前言2026年AI Agent已经成为开发者必备技能而MCPModel Context Protocol则是连接大模型与外部工具的核心协议。截至2026年7月MCP生态已拥有超过3000个开源Server实现成为连接LLM与现实世界数据的标准协议。本文带你从零开始用Python搭建一个完整的MCP Server让AI模型能调用你的自定义工具。一、MCP是什么MCPModel Context Protocol是Anthropic推出的开放标准协议为AI应用提供统一方式连接外部数据源和工具。你可以把MCP理解为AI世界的USB接口——任何工具只要实现MCP协议就能被任何支持MCP的AI模型调用。核心架构AI模型(Claude/GPT) ←→ MCP Client ←→ MCP Server ←→ 你的工具/数据组件作用示例MCP Host运行AI模型的宿主Claude Desktop、CursorMCP Client协议客户端连接Server内置于Host中MCP Server暴露工具和数据文件系统、数据库、APITransport通信层stdio、SSE、HTTP二、环境准备# 安装MCP Python SDKpipinstallmcp# 或使用uv推荐uv init mcp-democdmcp-demo uvaddmcp## 三、实战搭建天气查询MCP Server ### 3.1 最小化Serverfrommcp.serverimportServerfrommcp.server.stdioimportstdio_serverimportmcp.typesastypesimporthttpximportjson appServer(weather-server)app.list_tools()asyncdeflist_tools()-list[types.Tool]:return[types.Tool(nameget_weather,description获取指定城市的天气信息,inputSchema{type:object,properties:{city:{type:string,description:城市名称如上海、北京}},required:[city]})]app.call_tool()asyncdefcall_tool(name:str,arguments:dict)-list[types.TextContent]:ifnameget_weather:cityarguments.get(city,未知)# 调用免费天气APIasyncwithhttpx.AsyncClient()asclient:respawaitclient.get(fhttps://wttr.in/{city},params{format:j1},timeout10)dataresp.json()currentdata.get(current_condition,[{}])[0]result{city:city,温度:f{current.get(temp_C)}°C,天气:current.get(weatherDesc,[{}])[0].get(value),湿度:f{current.get(humidity)}%,风速:f{current.get(windspeedKmph)}km/h}return[types.TextContent(typetext,textjson.dumps(result,ensure_asciiFalse,indent2))]asyncdefmain():asyncwithstdio_server()as(read_stream,write_stream):awaitapp.run(read_stream,write_stream)if__name____main__:importasyncio asyncio.run(main())### 3.2 配置到Claude Desktop在Claude Desktop的配置文件中添加{mcpServers:{weather:{command:python,args:[path/to/weather_server.py]}}}配置文件位置Windows:%APPDATA%\Claude\claude_desktop_config.jsonmacOS:~/Library/Application Support/Claude/claude_desktop_config.json重启Claude Desktop后就可以直接问上海今天天气怎么样AI会自动调用你的MCP Server。## 四、进阶数据库查询Serverimportsqlite3frommcp.serverimportServerimportmcp.typesastypes appServer(db-server)defget_db():connsqlite3.connect(products.db)conn.row_factorysqlite3.Rowreturnconnapp.list_tools()asyncdeflist_tools()-list[types.Tool]:return[types.Tool(namequery_products,description查询商品数据库支持按名称、价格范围筛选,inputSchema{type:object,properties:{keyword:{type:string,description:商品名称关键词},min_price:{type:number,description:最低价格},max_price:{type:number,description:最高价格},limit:{type:integer,description:返回条数,default:10}}}),types.Tool(nameget_product_stats,description获取商品统计信息总数、平均价格等,inputSchema{type:object,properties:{}})]app.call_tool()asyncdefcall_tool(name:str,arguments:dict)-list[types.TextContent]:dbget_db()try:ifnamequery_products:sqlSELECT * FROM products WHERE 11params[]ifarguments.get(keyword):sql AND name LIKE ?params.append(f%{arguments[keyword]}%)ifarguments.get(min_price):sql AND price ?params.append(arguments[min_price])ifarguments.get(max_price):sql AND price ?params.append(arguments[max_price])limitarguments.get(limit,10)sqlf LIMIT{limit}rowsdb.execute(sql,params).fetchall()results[dict(row)forrowinrows]return[types.TextContent(typetext,textjson.dumps(results,ensure_asciiFalse,indent2))]elifnameget_product_stats:rowdb.execute(SELECT COUNT(*) as total, AVG(price) as avg_price, MIN(price) as min_price, MAX(price) as max_price FROM products).fetchone()return[types.TextContent(typetext,textjson.dumps(dict(row),ensure_asciiFalse,indent2))]finally:db.close()## 五、MCP的三大资源类型MCP Server可以暴露三种资源### 5.1 Tools工具AI可以调用的函数如查询数据库、调用API。### 5.2 Resources资源AI可以读取的数据如文件内容、数据库表。app.list_resources()asyncdeflist_resources()-list[types.Resource]:return[types.Resource(urifile:///config.json,name配置文件,description应用配置,mimeTypeapplication/json)]app.read_resource()asyncdefread_resource(uri:str)-str:ifurifile:///config.json:withopen(config.json)asf:returnf.read()## 5.3 Prompts提示词预设的对Y模板用户可以更接週择使用。app.list_prompts()asyncdeflist_prompts()-list[types.Prompt]:return[types.Prompt(namecode-review,description代码殡查助手,arguments[types.PromptArgument(namelanguage,description编程语,requiredTrue)])]app.get_prompt()asyncdefget_prompt(name:str,arguments:dict)-types.GetPromptResult:ifnamecode-review:langarguments.get(language,Python)returntypes.GetPromptResult(messages[types.PromptMessage(roleuser,contenttypes.TextContent(typetext,textf诵审查以下{lang}代码关注安全性、性能和可读性\\n\\nF{lang.lower()}\\n# 粘贴代8\\n〦))])## 公、调试技巧 ### 6.1 使用MCP Inspectornpx modelcontextprotocol/inspector python weather_server.py这会启动一个Web界面可以可视化测试所有工具和资源。### 6.2 日志调试importlogging logging.basicConfig(levellogging.DEBUG)loggerlogging.getLogger(mcp-server)app.call_tool()asyncdefcall_tool(name:str,arguments:dict):logger.info(fTool called:{name}with{arguments})# ...## 七、部署与发布 ### 7.1 打包为命令行工具# pyproject.toml [project.scripts] weather-mcp weather_server:mainpipinstall-e.# 现在可以直接运行weather-mcp### 7.2 发布到PyPIpython-mbuild twine upload dist/*### 7.3 发布到MCP Hub将你的Server提交到 mcphub.io让全球开发者都能使用。## 八、变现机会学会MCP开发后可以通过以下方式变现定制MCP Server为企业开发连接内部系统的MCP Server单价2000-10000元SaaS化MCP服务搭建MCP Server云平台按调用次数收费技术专栏在CSDN写MCP系列教程积累粉丝后开付费专栏开源赞助优质MCP Server项目可获GitHub Sponsors赞助培训课程录制MCP开发实战课程在网易云课堂等平台售卖总结MCP是2026年AI开发最热门的方向之一。掌握MCP开发你就能让任何AI模型使用你构建的工具打开AI应用开发的全新可能。专栏后续会更新MCPRAG实战、MCP安全防护、MCP多Server编排、企业级MCP部署等内容欢迎关注有问题欢迎评论区交流需要定制MCP Server开发可以私信。