参考:https://www.bilibili.com/video/BV1nyVDzaE1x
编写自己的tools.py
python
#### tools.py
from pathlib import Path
import os
base_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 content
except 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_list
def rename_file(name: str, new_name: str) -> str:
print(f"(rename_file {name} -> {new_name})")
try:
new_path = base_dir / new_name
if 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 json
def get_host_info() -> str:
"""get host information
Returns:
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_model
except Exception:
info["cpu_model"] = "Unknown"
return json.dumps(info, indent=4)
mcp 服务 mcp_test.py
python
# main.py
from mcp.server.fastmcp import FastMCP
import tools
mcp = 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服务
我本地是这么运行的:
powershell
C:\Users\admin\miniconda3\envs\king\python.exe D:\bing\Work\Code\Pura\king\mcp_test.py
所以我的mcp.json文件这么写:
bash
{
"mcpServers": {
"hostInfoMcp": {
"command": "C:\\Users\\admin\\miniconda3\\envs\\king\\python.exe",
"args": [
"D:\\bing\\Work\\Code\\Pura\\king\\mcp_test.py"
]
}
}
}
测试

简单的mcp就完成了