一个简单的Python文件MCP服务器
代码先行
import asyncio
import json
import osfrom mcp.server import Server
from mcp.types import Resource, Tool, TextContent
from typing import Listapp = Server("file_list")@app.list_tools()
async def list_tools() -> List[Tool]:"""List available file tools."""return [Tool(name="list_files",description="List files in the given directory.",inputSchema={"type": "object","properties": {"text": {"type": "string","description": "The directory path to list files from."}},"required": ["text"]}),Tool(name="rename_file",description="rename the file name to a new name.",inputSchema={"type": "object","properties": {"old_name": {"type": "string","description": "the file's old name."},"new_name": {"type": "string","description": "the file's new name."}},"required": ["old_name", "new_name"]})]@app.call_tool()
async def list_files(name: str, path: dict) -> List[TextContent]:"""List files in the given directory."""try:directory = path['text']files = os.listdir(directory)return [{"type": "text","text": f"文件夹内包含的文件和文件夹有:{','.join(files)}"}]except Exception as e:raise RuntimeError(f"Error {name} in {path}: {str(e)}")@app.call_tool()
async def rename_file(name: str, path: dict) -> List[TextContent]:"""Rename a file."""old_name = path['old_name']new_name = path['new_name']os.rename(old_name, new_name)return [{"type": "text","text": f"文件 {old_name} 重命名为 {new_name} 成功。"}]async def main():"""Main entry point to run the MCP server."""from mcp.server.stdio import stdio_serverasync with stdio_server() as (read_stream, write_stream):try:await app.run(read_stream,write_stream,app.create_initialization_options())except Exception as e:raiseif __name__ == "__main__":asyncio.run(main())
核心点有三个
1.list_tools 这个是给AI展示有哪些工具可以调用的,具体工具的功能是什么,可以在这里面配置具体工具call_tools的入参数据类型,确保执行的健壮性
2.call_tool 这个是具体的实现方法,定义的名称与list_tools要一致,里面是一些具体的实现方法
3.main 这个是用来启动整个服务器的,主要是对标准数据输入输出流进行适配