Python MCP服务器示例:30分钟搭建
想把自己的数据或工具开放给Claude等AI助手。
MCP Server Example in Python: Build Your First Model Context Protocol Server in 30 Minutes
Building an MCP server in Python in 2026 is a solved problem: the official SDK (mcp) handles the protocol, and you just write plain functions. This tutorial builds a working server that exposes a tool, then connects it to Claude Desktop.
Step 1: Install
pip install "mcp[cli]"
Step 2: The Server (about 20 lines)
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Weather Demo")
@mcp.tool()
def get_weather(city: str) -> str:
# In production, call a real weather API here
return "Weather in " + city + ": 22C, partly cloudy"
if __name__ == "__main__":
mcp.run()
That is a complete server. One decorator, one run call.
Step 3: Test It
python server.py
# in another terminal:
mcp dev server.py
The mcp dev command opens an inspector UI where you can call get_weather and see the result.
Step 4: Connect to Claude Desktop
Add to claude_desktop_config.json:
{
"mcpServers": {
"weather": {
"command": "python",
"args": ["C:/path/to/server.py"]
}
}
}
Restart Claude Desktop. Claude can now call get_weather("Tokyo") and use the result in conversation.
What the FastMCP Layer Does For You
| Concern | Handled by |
|---|---|
| JSON-RPC transport | SDK (stdio or SSE/HTTP) |
| Tool discovery | SDK introspection |
| Input validation | Pydantic models |
| Error handling | SDK error codes |
FAQ
FastMCP or raw SDK? FastMCP for new projects - it is the official high-level API and cuts boilerplate by 80%.
Can I expose a REST API as MCP? Yes, wrap the REST calls inside a @mcp.tool() function; the LLM then calls your tool, which calls the API.
Is there a TypeScript version? Yes, the official SDK is first-class in TypeScript too. Python and TS cover the vast majority of servers.
