MCP Server for Local File Access

English Summary

Introduction

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.

Demonstration

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.

Implemented Tools

  1. List Files: Lists all files and folders in a specified directory
  2. Read File: Reads and returns the content of a specified file

Implementation

The implementation requires three main packages:

  • Input/OS for handling system file paths
  • Path Lib for path management
  • FastMCP as the main package

The code creates a FastMCP app and implements:

  • A function to list files in a directory
  • A function to read file contents using UTF-8 encoding with error handling
  • A resource that provides directory listings

Testing

After saving the code, run the MCP dev server using mcp-dev-server.py, open the test webpage, and test both tools:

  • List Files tool shows all files in the specified directory
  • Read File tool displays the content of a selected file
  • Resource List shows directory contents in a more structured way

中文摘要

介紹

無論是在日常應用或大語言模型的應用中,能夠讀取本地資料對整體應用都有非常大的加值。本教程展示如何實作一個可以讀取目錄以及檔案內容的MCP Server。

演示

演示使用D:\Demo15\Samples目錄結構,其中包含三個文字檔:intro.txt、Node1.txt和README.txt。通過MCP Cloud界面展示如何列出目錄和讀取檔案內容。

實作工具

  1. List Files:列出指定目錄下的所有檔案以及資料夾
  2. Read File:讀取指定檔案的內容

實作細節

實作需要三個主要套件:

  • Input/OS用於處理系統檔案路徑
  • Path Lib用於路徑管理
  • FastMCP作為主要套件

程式碼創建一個FastMCP應用並實現:

  • 列出目錄內所有檔案的函式
  • 使用UTF-8編碼讀取檔案內容的函式,包含錯誤處理
  • 提供目錄清單的Resource

測試

保存程式碼後,使用mcp-dev-server.py運行MCP開發伺服器,打開測試網頁,並測試兩個工具:

  • List Files工具顯示指定目錄中的所有檔案
  • Read File工具顯示所選檔案的內容
  • Resource List以更結構化的方式顯示目錄內容

Server.py Source Code

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()