Practical LangGraph Guide to Integrating MCP and Managing Tool Selection
A Juejin guide describes integrating Model Context Protocol (MCP) with LangGraph for Agent projects, recommending local stdio connections during development and environment variables such as MCP_URL to separate local and deployed resources. It recommends module-level lazy-loaded connections with cached tool listings, domain-specific graph routing, result truncation, graceful degradation, and progressive disclosure or retrieval to limit tool-selection errors as the available tool count grows. The author also warns about container-only DNS addresses, missing Node.js in some images, browser-dependent OAuth, and credentials leaking into images.
The guide offers concrete architecture and tool-governance patterns for developers connecting MCP services to LangGraph, although its recommendations come from a single author and have not been independently verified.
最近在 Agent 项目中接入了 MCP(Model Context Protocol),踩了不少坑。今天就以 LangGraph 为例,聊聊 MCP 接入的架构设计、环境切换以及当 MCP 工具越来越多时,如何防止大模型“注意力涣散”。
一、 本地开发与线上部署怎么选?
在本地开发时,强烈推荐使用 stdio 模式直起,而不是去连 Docker 或线上环境。
- 优势:改完代码重启即生效,不用 build 镜像;不依赖
docker network和端口映射;协议层完全一致。 - 避坑:不要本地直连线上容器地址(如
http://mcp-xxx:8765),这是 Docker 内部 DNS,本地解析不了。 - 环境隔离:MCP 连的是它所在环境的数据库。本地
stdio连本地库,线上连线上库。建议用环境变量(如MCP_URL)区分,并且在线上使用docker-compose时,务必用environment覆盖.env,因为environment优先级更高。
二、 代码设计与架构建议
- 依赖与连接:使用
langchain-mcp-adapters,做成模块级懒加载单例。首次用到时建连并缓存list_tools(),不要每次请求都去握手。 - 工具过滤:服务端可能给了 12 个工具,但 Agent 端只留 4~5 个核心的。模型选错的概率与工具数量成正比。
- 图结构设计:不要把所有工具直接绑给 Supervisor(主管节点),这会导致路由逻辑混乱。建议采用
supervisor -> research | data | writer的结构,把data做成一个小型的 ReAct 循环。 - 结果截断与降级:对于查询类工具,结果最多返回 500 行,截断到 20~30 行并转成 Markdown 表格,防止 token 爆炸。如果 MCP 挂掉,
data节点要优雅降级(返回“服务暂不可用”),绝不能拖垮主流程导致 500。