MCP Python SDK

python 3.10+

安装MCP

1 pip install "mcp[cli]"

安装node.js

 1 # 下载并安装 nvm:
 2 curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
 3 # 代替重启 shell
 4 \. "$HOME/.nvm/nvm.sh"
 5 # 下载并安装 Node.js:
 6 nvm install 24
 7 # 验证 Node.js 版本:
 8 node -v # Should print "v24.19.0".
 9 # 验证 npm 版本:
10 npm -v # Should print "11.17.0".

服务器示例代码

 1 from mcp.server import MCPServer
 2 
 3 mcp = MCPServer("Demo")
 4 
 5 
 6 @mcp.tool()
 7 def add(a: int, b: int) -> int:
 8     """Add two numbers."""
 9     return a + b
10 
11 
12 @mcp.resource("greeting://{name}")
13 def greeting(name: str) -> str:
14     """Greet someone by name."""
15     return f"Hello, {name}!"
16 
17 '''
18 如果不要
19 if __name__ == "__main__":
20     mcp.run()
21 则在命令行里
22 mcp dev server.py
23 
24 mcp dev server.py --with mcp-inspector
25 
26 '''
27 
28 # if __name__ == "__main__":
29 #     mcp.run()
30 
31 '''
32 python server.py
33 '''

清理

1 rm -rf ~/.cache/mcp
2 npm cache clean --force
3 rm -rf ~/.npm/_npx
4 rm -rf /tmp/mcp-*

运行

1 mcp dev server.py

结果

 1 (envXYJ) thbytwo@thbytwopower:~/testCode/xuyuanji/test$ mcp dev server.py
 2 Need to install the following packages:
 3 @modelcontextprotocol/inspector@2.0.0
 4 Ok to proceed? (y) y
 5 npm warn ERESOLVE overriding peer dependency
 6 npm warn deprecated lodash.isequal@4.5.0: This package is deprecated. Use require('node:util').isDeepStrictEqual instead.
 7 npm warn deprecated @modelcontextprotocol/server-legacy@2.0.0-beta.5: This package is a frozen copy of v1's SSE transport and OAuth Authorization Server helpers for migration purposes only. Use StreamableHTTP from @modelcontextprotocol/server and a dedicated OAuth server in production. Will not receive new features.
 8 Starting MCP inspector...
 9 
10 MCP Inspector Web is up and running at:
11    http://localhost:6274?MCP_INSPECTOR_API_TOKEN=3747836967c52406c064359bd2fec797703b22e45e4d3150f9c105a02fba0063
12 
13    Sandbox (MCP Apps): http://localhost:44199/sandbox
14 
15    Auth token: 3747836967c52406c064359bd2fec797703b22e45e4d3150f9c105a02fba0063
16 
17 Opening browser...

 

这里因为用的conda没有用uv,导致无法使用弹出的页面。点击开关会报错。

客户端示例代码

客户端程序:client_stdio.py

 1 import asyncio
 2 from mcp import ClientSession, StdioServerParameters
 3 from mcp.client.stdio import stdio_client
 4 
 5 async def main():
 6     server_params = StdioServerParameters(
 7         command="python",
 8         args=["server.py"]
 9     )
10     async with stdio_client(server_params) as (read, write):
11         async with ClientSession(read, write) as session:
12             await session.initialize()
13 
14             # 测试工具 add
15             res = await session.call_tool("add", arguments={"a": 10, "b": 20})
16             print("add(10,20) =", res.content[0].text)
17 
18             # 测试资源 greeting
19             res = await session.read_resource("greeting://MCPTest")
20             print("greeting://MCPTest =", res.contents[0].text)
21 
22 asyncio.run(main())
23 
24 
25 '''
26 服务器
27 
28 使用下面的代码:
29 if __name__ == "__main__":
30     mcp.run()
31 
32 运行结果:
33 thbytwo@thbytwopower:~/testCode/xuyuanji$  conda activate envXYJ
34 (envXYJ) thbytwo@thbytwopower:~/testCode/xuyuanji$ cd test/
35 (envXYJ) thbytwo@thbytwopower:~/testCode/xuyuanji/test$ mcp dev server.py --with mcp-inspector
36 Starting MCP inspector...
37 
38 MCP Inspector Web is up and running at:
39    http://localhost:6274?MCP_INSPECTOR_API_TOKEN=43d13ea49bb62f0fad7ab56d782362e7e30416b6672898267bff4d19faf1067b
40 
41    Sandbox (MCP Apps): http://localhost:42967/sandbox
42 
43    Auth token: 43d13ea49bb62f0fad7ab56d782362e7e30416b6672898267bff4d19faf1067b
44 
45 Opening browser...
46 '''
47 
48 '''
49 客户端
50 
51 运行结果:
52 thbytwo@thbytwopower:~/testCode/xuyuanji$  conda activate envXYJ
53 (envXYJ) thbytwo@thbytwopower:~/testCode/xuyuanji$ cd test/
54 (envXYJ) thbytwo@thbytwopower:~/testCode/xuyuanji/test$ python client_stdio.py 
55 add(10,20) = 30
56 greeting://MCPTest = Hello, MCPTest!
57 (envXYJ) thbytwo@thbytwopower:~/testCode/xuyuanji/test$ 
58 
59 '''

 

客户端程序2:client_sse.py

 1 import asyncio
 2 from mcp import ClientSession
 3 from mcp.client.sse import sse_client
 4 
 5 async def main():
 6     # 连接 SSE 服务器
 7     async with sse_client(url="http://127.0.0.1:8800/sse") as (read, write):
 8         async with ClientSession(read, write) as session:
 9             await session.initialize()
10 
11             # 测试工具 add
12             res = await session.call_tool("add", arguments={"a": 10, "b": 20})
13             print("add(10, 20) =", res.content[0].text)
14 
15             # 测试资源 greeting
16             res = await session.read_resource("greeting://MCPTest")
17             print("greeting://MCPTest =", res.contents[0].text)
18 
19 asyncio.run(main())
20 
21 '''
22 服务器
23 
24 使用下面的代码:
25 if __name__ == "__main__":
26     mcp.run(transport="sse", host="0.0.0.0", port=8800)
27 在vscode里点击运行
28 
29 运行结果:
30 (envXYJ) thbytwo@thbytwopower:~/testCode/xuyuanji$ /home/thbytwo/miniforge3/envs/envXYJ/bin/python /home/thbytwo/testCode/xuyuanji/test/server.py
31 INFO:     Started server process [16860]
32 INFO:     Waiting for application startup.
33 INFO:     Application startup complete.
34 INFO:     Uvicorn running on http://127.0.0.1:8800 (Press CTRL+C to quit)
35 INFO:     127.0.0.1:39174 - "GET /sse HTTP/1.1" 200 OK
36 INFO:     127.0.0.1:39186 - "POST /messages/?session_id=8172f8010a6b42e9b1d7aa5f51490156 HTTP/1.1" 202 Accepted
37 INFO:     127.0.0.1:39186 - "POST /messages/?session_id=8172f8010a6b42e9b1d7aa5f51490156 HTTP/1.1" 202 Accepted
38 INFO:     127.0.0.1:39186 - "POST /messages/?session_id=8172f8010a6b42e9b1d7aa5f51490156 HTTP/1.1" 202 Accepted
39 INFO:     127.0.0.1:39186 - "POST /messages/?session_id=8172f8010a6b42e9b1d7aa5f51490156 HTTP/1.1" 202 Accepted
40 INFO:     127.0.0.1:39186 - "POST /messages/?session_id=8172f8010a6b42e9b1d7aa5f51490156 HTTP/1.1" 202 Accepted
41 '''
42 
43 
44 '''
45 客户端
46 
47 运行结果:
48 thbytwo@thbytwopower:~/testCode/xuyuanji$  conda activate envXYJ
49 (envXYJ) thbytwo@thbytwopower:~/testCode/xuyuanji$ cd test/
50 (envXYJ) thbytwo@thbytwopower:~/testCode/xuyuanji/test$ python client_sse.py 
51 add(10, 20) = 30
52 greeting://MCPTest = Hello, MCPTest!
53 (envXYJ) thbytwo@thbytwopower:~/testCode/xuyuanji/test$ 
54 '''

 

三种启动方式对比

(未验证)

方式命令需要代码中的 mcp.run()?热重载适用场景
mcp dev mcp dev server.py 不需要 ✅ 有 本地开发调试(仅 stdio)
mcp run mcp run --transport sse --port 8800 server.py 不能有 ❌ 无 生产环境 SSE 部署
python python server.py 必须有 ❌ 无 需要自定义 host/port 的 SSE 部署

mcp run 的命令行参数里没有 --host,它只提供了 --port。如果想绑定 0.0.0.0(允许外部访问),只能用代码方式(即保留 mcp.run(transport="sse", host="0.0.0.0", port=8800) 并用 python server.py 启动)。

也可以删掉 server.py 中的 mcp.run(),然后用 mcp run --transport sse --port 8800 server.py 启动