1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| from mcp.server import Server, stdio_server
server = Server("file-system")
@server.list_tools() async def list_tools(): return [ { "name": "read_file", "description": "读取文件内容", "parameters": { "type": "object", "properties": { "path": {"type": "string", "description": "文件路径"} }, "required": ["path"] } }, { "name": "write_file", "description": "写入文件内容", "parameters": { "type": "object", "properties": { "path": {"type": "string"}, "content": {"type": "string"} }, "required": ["path", "content"] } }, { "name": "list_files", "description": "列出目录下的文件", "parameters": { "type": "object", "properties": { "dir": {"type": "string"} }, "required": ["dir"] } } ]
@server.call_tool() async def call_tool(name: str, arguments: dict): if name == "read_file": content = open(arguments["path"], encoding="utf-8").read() return {"content": [{"type": "text", "text": content}]} elif name == "write_file": with open(arguments["path"], "w", encoding="utf-8") as f: f.write(arguments["content"]) return {"content": [{"type": "text", "text": "写入成功"}]} elif name == "list_files": import os files = os.listdir(arguments["dir"]) return {"content": [{"type": "text", "text": "\n".join(files)}]}
if __name__ == "__main__": stdio_server.run(server)
|