
第31课核心知识点梳理MCP 工具与智能小秘书案例一、什么是 MCPModel Context ProtocolMCP模型上下文协议是一个开放的标准化协议旨在解决 AI 大语言模型与外部工具、数据源之间的连接碎片化问题。在传统的 AI Agent 开发中开发者需要为每个外部服务编写专用的适配器导致系统维护成本高、扩展性差。MCP 提供了一个统一的规范MCP 核心设计说明统一工具描述格式通过标准的 Tool Schema 定义工具的输入参数、输出格式和执行方式跨语言客户端/服务端实现支持 stdio 管道、HTTP SSE 等多种通信方式服务发现机制通过注册中心实现 MCP Server 的动态加载版本兼容性保障协议标准化避免 API 变更导致的集成问题采用 MCP 后新工具接入时间从平均 72 小时缩短至 15 分钟以内。二、为什么需要 MCP工具链碎片化每个外部系统需要定制 API 连接代码维护成本高昂多模型协同支持不同厂商 LLM 的无缝切换避免技术锁定开发效率跃升标准化协议使集成成本降低 68%开发周期缩短 42%三、LangGraph 与 MCP 的两种集成模式LangGraph 与 MCP 的融合有两种模式各自适用于不同的场景。集成模式说明适用场景客户端集成模式将 MCP Server 暴露的工具集作为 LangGraph 工作流中的原子节点Agent 可通过统一接口调用外部服务调用外部 NLP 服务、访问向量数据库、集成第三方 API服务端封装模式将现有 LangGraph 工作流暴露为 MCP 服务供其他系统调用复用已有流程、构建可组合的工作流服务下面通过完整的案例演示这两种模式。 星系案例智能小秘书系统构建一个支持多工具调用的智能小秘书系统集成数学计算和天气查询两大能力通过 MCP 协议统一管理。案例整体架构图工具执行层标准化工具层LangGraph 智能体用户层HTTP SSE 通信stdio 通信MCP 调用MCP 调用用户输入ReAct Agent状态管理与推理Math MCP Serveradd / multiplyWeather MCP Serverget_weather加法工具乘法工具天气工具目录结构mcp_intelligent_secretary/ ├── math_server.py # 数学计算 MCP Server (stdio) ├── weather_server.py # 天气查询 MCP Server (HTTP/SSE) ├── agent_client.py # LangGraph Agent 客户端 └── .env # 环境配置步骤一安装依赖pipinstalllangchain-mcp-adapters langgraph langchain-openai mcp httpx python-dotenv步骤二数学计算 MCP Serverstdio 通信# math_server.pyimportasynciofrommcp.serverimportServerfrommcp.server.stdioimportstdio_serverfrommcp.typesimportTool,TextContentimportjson appServer(math-server)app.list_tools()asyncdeflist_tools():return[Tool(nameadd,description计算两个数的和,inputSchema{type:object,properties:{a:{type:number,description:第一个数},b:{type:number,description:第二个数}},required:[a,b]}),Tool(namemultiply,description计算两个数的乘积,inputSchema{type:object,properties:{a:{type:number,description:第一个数},b:{type:number,description:第二个数}},required:[a,b]}),]app.call_tool()asyncdefcall_tool(name:str,arguments:dict):ifnameadd:resultarguments[a]arguments[b]return[TextContent(typetext,textstr(result))]elifnamemultiply:resultarguments[a]*arguments[b]return[TextContent(typetext,textstr(result))]raiseValueError(fUnknown tool:{name})asyncdefmain():asyncwithstdio_server()as(read_stream,write_stream):awaitapp.run(read_stream,write_stream,app.create_initialization_options())if__name____main__:asyncio.run(main())步骤三天气查询 MCP ServerHTTP SSE 通信# weather_server.pyimportasyncioimportjsonfrommcp.serverimportServerfrommcp.server.sseimportSseServerTransportfrommcp.typesimportTool,TextContentfromstarlette.applicationsimportStarlettefromstarlette.routingimportRouteimportuvicorn appServer(weather-server)sseSseServerTransport(/messages)app.list_tools()asyncdeflist_tools():return[Tool(nameget_weather,description查询指定城市的天气信息,inputSchema{type:object,properties:{city:{type:string,description:城市名称如北京、上海、广州}},required:[city]})]app.call_tool()asyncdefcall_tool(name:str,arguments:dict):ifnameget_weather:cityarguments[city]# 模拟天气查询weather_data{北京:晴朗25°C空气质量良好,上海:多云22°C湿度适中,广州:阵雨28°C注意带伞}resultweather_data.get(city,f晴转多云20°C)return[TextContent(typetext,textf{city}天气{result})]raiseValueError(fUnknown tool:{name})# Starlette 应用支持 SSEasyncdefhandle_sse(request):asyncwithsse.connect_sse(request.scope,request.receive,request._send)asstreams:awaitapp.run(streams[0],streams[1],app.create_initialization_options())routes[Route(/sse,endpointhandle_sse),Route(/messages,endpointsse.handle_post_message,methods[POST]),]starlette_appStarlette(routesroutes)if__name____main__:uvicorn.run(starlette_app,host127.0.0.1,port8000)步骤四LangGraph Agent 客户端# agent_client.pyimportasyncioimportosfromdotenvimportload_dotenvfromlangchain_openaiimportChatOpenAIfromlangchain_mcp_adapters.clientimportMultiServerMCPClientfromlanggraph.prebuiltimportcreate_react_agentfromlanggraph.checkpoint.memoryimportMemorySaver load_dotenv()ifos.nament:importsysimportasyncioifsys.platformwin32:asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())# 初始化 LLMllmChatOpenAI(modelqwen-plus,temperature0.7,api_keyos.getenv(DASHSCOPE_API_KEY),base_urlos.getenv(DASHSCOPE_BASE_URL),)asyncdefmain():# 配置多个 MCP Servermcp_servers{math:{command:python,args:[math_server.py],transport:stdio,},weather:{url:http://127.0.0.1:8000/sse,transport:sse,},}# 创建 MCP 客户端并获取工具asyncwithMultiServerMCPClient(mcp_servers)asclient:toolsawaitclient.get_tools()print(f✅ 加载了{len(tools)}个 MCP 工具:)fortoolintools:print(f -{tool.name}:{tool.description})# 创建 LangGraph Agentagentcreate_react_agent(modelllm,toolstools,prompt你是一个智能小秘书可以帮助用户进行数学计算和查询天气。)# 交互对话print(\n 智能小秘书已启动输入 quit 退出\n)config{configurable:{thread_id:user_001}}whileTrue:user_inputinput(用户: )ifuser_input.lower()quit:breakresponseawaitagent.ainvoke({messages:[(user,user_input)]},configconfig)print(f助手:{response[messages][-1].content}\n)if__name____main__:asyncio.run(main())启动顺序# 终端1启动数学 MCP Serverpython math_server.py# 终端2启动天气 MCP Serverpython weather_server.py# 终端3启动 Agentpython agent_client.py 对话测试效果✅ 加载了 3 个 MCP 工具: - add: 计算两个数的和 - multiply: 计算两个数的乘积 - get_weather: 查询指定城市的天气信息 智能小秘书已启动输入 quit 退出 用户: 3 5 等于多少 助手: 3 5 8。 用户: 把这个结果乘以 4然后告诉我 助手: 8 × 4 32。 用户: 北京今天天气怎么样 助手: 北京天气晴朗25°C空气质量良好。 关键代码解析1.MultiServerMCPClient统一管理多个 MCP Server支持 stdio 和 SSE 两种通信方式。2.client.get_tools()自动发现注册的工具将 MCP Tool 转换为 LangChain Tool 对象。3.create_react_agentLangGraph 预置的 ReAct Agent自动处理工具调用循环。 高频面试题汇总一、MCP 基础概念题面试问题核心回答要点什么是 MCP为什么需要它MCPModel Context Protocol是开放协议解决 LLM 与外部工具集成的碎片化问题。需解释传统开发痛点定制 API 适配器和 MCP 价值工具接入时间从 72 小时→15 分钟MCP 1.0 和 2.0 的主要区别MCP 2.0 增强版本兼容性、改进动态服务发现机制、引入闭环反馈与可视化编排MCP 与 Function Calling 的区别Function Calling 是模型专有特性由模型在运行时决定调用哪个函数MCP 是协议层标准化提供统一工具描述解耦工具实现与模型MCP Server 的两种通信方式stdio标准输入输出适合本地子进程SSEServer-Sent Events适合远程 HTTP 调用二、LangGraph MCP 集成题面试问题核心回答要点LangGraph 与 MCP 如何集成两种模式客户端集成模式工具节点化服务端封装模式工作流暴露为服务如何实现多 MCP Server 并行调用用 MultiServerMCPClient 统一管理内部通过 asyncio.gather 并发执行MCP 工具调用失败如何处理在 Agent 中实现重试策略和降级方案支持同步/异步混合调用自动适配三、工程实战题面试问题核心回答要点开发 MCP Server 的关键步骤创建 Server 实例、定义 list_tools 返回工具 Schema、实现 call_tool 处理请求、配置传输层stdio/SSEMCP 工具如何定义输入输出通过 inputSchemaJSON Schema定义参数类型和必填项Tool 对象含 name、description、inputSchemaMCP Server 如何实现服务发现通过注册中心机制实现动态加载客户端通过 MultiServerMCPClient 配置 endpointsAgent 如何自动选择合适的 MCP 工具LangGraph ReAct Agent 根据工具 description 调用 LLM 判断MCP 提供统一 Tool Schema 支持动态路由 总结MCP LangGraph 的三大核心价值能力解耦将 AI 能力封装为独立节点“一次开发多处调用”标准化集成通过统一接口规范实现不同厂商 LLM 与工具的灵活组合闭环反馈LangGraph 的状态管理与 MCP 反馈机制形成智能闭环系统MCP 是一个开放标准你可以扩展更多自定义的 MCP Server 来集成任何外部 API 或服务并根据实际业务需求定制工具 Schema。通过本次实践你可以直观理解 MCP 如何让 Agent 从“只会聊天”进阶到“会动手执行任务”的智能助手。