intermediate
⏱ 15 分钟
mcp
从 0 写一个 MCP Server:让你的 Agent 能操作数据库
手把手教你写第一个 MCP Server,让 Cursor/Claude Desktop 都能直接操作你的 MySQL。
MCP Server 开发
MCP(Model Context Protocol)是 Anthropic 主导的 Agent 工具标准。写一个 MCP Server 只需 50 行代码。
## 完整代码
```python
from mcp.server import Server, stdio
app = Server("mysql-mcp")
@app.list_tools()
async def list_tools():
return [{
"name": "query",
"description": "Execute SQL query",
"inputSchema": {
"type": "object",
"properties": {"sql": {"type": "string"}}
}
}]
@app.call_tool()
async def call_tool(name, args):
if name == "query":
# execute SQL
return [{"type": "text", "text": result}]
if __name__ == "__main__":
stdio.run(app)
```
## 接入 Claude Desktop
编辑 `~/Library/Application Support/Claude/claude_desktop_config.json`:
```json
{
"mcpServers": {
"mysql": {"command": "python", "args": ["mysql_mcp.py"]}
}
}
```
重启 Claude Desktop,你就能说"查询 users 表最近 100 行"了。