Skip to content

MCP

安装依赖

bash
pip install mcp[fastmcp]

用 Python 造一个 MCP 服务

任何一个函数都可以被作为MCP的Tool。

python
# mcp_stdio.py
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("My Python MCP") # 创建服务实例

# 1. 注册一个计算工具
@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

# 2. 注册一个动态资源 (类似API端点)
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
    """Get a greeting"""
    return f"Hello, {name}!"

# 3. 连接外部工具文件
import tool
mcp.add_tool(tool.test_tool) # 将外部文件中的函数注册进来

if __name__ == "__main__":
    mcp.run(transport="stdio") # 启动标准输入输出服务

启动服务

bash
python mcp_stdio.py

在编辑器中配置服务

在CursorSetting中配置

json
{
  "name": "My Python MCP",
  "type": "stdio",
  "command": "python",
  "arguments": [
    "path/to/your/mcp_stdio.py"
  ]
}

Released under the MIT License.