參考:https://www.bilibili.com/video/BV1nyVDzaE1x
編寫自己的tools.py
#### tools.py
from pathlib import Path
import osbase_dir = Path("./test")def read_file(name: str) -> str:"""Return file content. If not exist, return error message."""print(f"(read_file {name})")try:with open(base_dir / name, "r") as f:content = f.read()return contentexcept Exception as e:return f"An error occurred: {e}"def list_files() -> list[str]:print("(list_file)")file_list = []for item in base_dir.rglob("*"):if item.is_file():file_list.append(str(item.relative_to(base_dir)))return file_listdef rename_file(name: str, new_name: str) -> str:print(f"(rename_file {name} -> {new_name})")try:new_path = base_dir / new_nameif not str(new_path).startswith(str(base_dir)):return "Error: new_name is outside base_dir."os.makedirs(new_path.parent, exist_ok=True)os.rename(base_dir / name, new_path)return f"File '{name}' successfully renamed to '{new_name}'."except Exception as e:return f"An error occurred: {e}"def sing_a_song(name: str) -> str:print(f"Sing a song, {name}")if name:return f"Sing a song, {name}"else:return "Sing a song: love"import platform
import psutil
import subprocess
import jsondef get_host_info() -> str:"""get host informationReturns:str: the host information in JSON string"""info: dict[str, str] = {"system": platform.system(),"release": platform.release(),"machine": platform.machine(),"processor": platform.processor(),"memory_gb": str(round(psutil.virtual_memory().total / (1024 ** 3), 2)),}cpu_count = psutil.cpu_count(logical=True)if cpu_count is None:info["cpu_count"] = "-1"else:info["cpu_count"] = str(cpu_count)try:cpu_model = subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"]).decode().strip()info["cpu_model"] = cpu_modelexcept Exception:info["cpu_model"] = "Unknown"return json.dumps(info, indent=4)
mcp 服務 mcp_test.py
# main.py
from mcp.server.fastmcp import FastMCP
import toolsmcp = FastMCP("host info mcp")
mcp.add_tool(tools.get_host_info)
mcp.add_tool(tools.rename_file)
mcp.add_tool(tools.read_file)
mcp.add_tool(tools.sing_a_song)
mcp.add_tool(tools.list_files)@mcp.tool()
def foo():return ""def main():mcp.run("stdio") # scp 和agent在同一機器# mcp.run("sse") # http調用if __name__ == "__main__":main()
cursor配置mcp服務
我本地是這么運行的:
C:\Users\admin\miniconda3\envs\king\python.exe D:\bing\Work\Code\Pura\king\mcp_test.py
所以我的mcp.json文件這么寫:
{"mcpServers": {"hostInfoMcp": {"command": "C:\\Users\\admin\\miniconda3\\envs\\king\\python.exe","args": ["D:\\bing\\Work\\Code\\Pura\\king\\mcp_test.py"]}}
}
測試
簡單的mcp就完成了