The ability to read local files is a significant value-add for both everyday applications and large language model applications. This tutorial demonstrates implementing an MCP Server that can read directory listings and file contents.
The demonstration uses a sample directory structure in D:\Demo15\Samples containing three text files: intro.txt, Node1.txt, and README.txt. The MCP Cloud interface is used to show both directory listing and file content retrieval.
The implementation requires three main packages:
The code creates a FastMCP app and implements:
After saving the code, run the MCP dev server using mcp-dev-server.py, open the test
webpage, and test both tools:
無論是在日常應用或大語言模型的應用中,能夠讀取本地資料對整體應用都有非常大的加值。本教程展示如何實作一個可以讀取目錄以及檔案內容的MCP Server。
演示使用D:\Demo15\Samples目錄結構,其中包含三個文字檔:intro.txt、Node1.txt和README.txt。通過MCP Cloud界面展示如何列出目錄和讀取檔案內容。
實作需要三個主要套件:
程式碼創建一個FastMCP應用並實現:
保存程式碼後,使用mcp-dev-server.py運行MCP開發伺服器,打開測試網頁,並測試兩個工具:
import os
from pathlib import Path
from mcp.server import FastMCP
app = FastMCP("本地檔案系統 MCP Server")
# 工具:列出指定目錄下的所有檔案和資料夾
@app.tool()
def list_files(path: str) -> list[str]:
"""
列出指定目錄下的所有檔案和資料夾。
"""
try:
p = Path(path).resolve()
if p.is_dir():
return [f.name for f in p.iterdir()]
else:
return [f"錯誤:指定的路徑不是目錄。"]
except Exception as e:
return [f"錯誤:{str(e)}"]
# 工具:讀取指定檔案的內容
@app.tool()
def read_file(path: str) -> str:
"""
讀取指定檔案的內容並返回。
"""
try:
p = Path(path).resolve()
if p.is_file():
return p.read_text(encoding='utf-8')
else:
return "錯誤:指定的路徑不是檔案。"
except Exception as e:
return f"錯誤:{str(e)}"
# 資源:提供指定目錄的檔案清單
@app.resource("fs://{drive}/{path}")
def resource_list_files(drive: str, path: str) -> dict:
try:
# 組合完整的 Windows 路徑,例如 'D:/demo15/samples'
full_path = Path(f"{drive}:/{path}").resolve()
if not full_path.exists():
return {
"path": str(full_path),
"error": "指定的路徑不存在。"
}
if not full_path.is_dir():
return {
"path": str(full_path),
"error": "指定的路徑不是目錄。"
}
files = [f.name for f in full_path.iterdir()]
return {
"path": str(full_path),
"files": files
}
except Exception as e:
return {
"path": f"{drive}:/{path}",
"error": f"發生錯誤:{str(e)}"
}
if __name__ == "__main__":
app.run()