Posted on • Originally published at gentic.news
#ai #programming #opensource #machinelearningConnect LangGraph to MCP using MCPClient: call send_request() in your handler, and add retries. This fixes broken agent responses and keeps conversation flows resilient.
Key Takeaways
- Connect LangGraph to MCP using MCPClient: call send_request() in your handler, and add retries.
- This fixes broken agent responses and keeps conversation flows resilient.
The Problem: Your LangGraph Agent Won't Talk to MCP

你花了不少精力搭了一个LangGraph agent,对话流程设计得挺复杂。结果一上线,它直接哑了——日志里全是看不懂的错误,对用户输入毫无反应。问题出在哪?连接agent和MCP服务器的那根线断了,而MCP服务器恰恰是agent获取上下文和知识的关键。
这可不是什么罕见的小概率事件。MCP(Model Context Protocol)正在成为连接AI模型和外部工具的标准——Claude Code、Cursor,甚至Google都在用。所以,怎么正确地把这玩意儿接上,是每个Claude Code用户都得掌握的技能。好消息是,修复方法比你想的简单得多。
The Technique: Use MCPClient to Bridge the Gap
核心就是MCP API里的MCPClient类。它能建立与MCP服务器的连接,然后通过它发送请求来获取上下文和知识。来看一个最简化的模式:
import langgraph as lg
from mcp.client import MCPClient
# Create a new LangGraph agent
agent = lg.Agent()
# Create a new MCP client
mcp_client = MCPClient("https://example-mcp-server.com")
# Define a function to handle user inputs
def handle_input(input_text):
# Send a request to the MCP server to retrieve context and knowledge
response = mcp_client.send_request(input_text)
# Use the response to inform the agent's response
agent_response = agent.generate_response(response.context, response.knowledge)
return agent_response
这就是最核心的接线方式:每次用户输入都触发一次对MCP的请求,然后把返回的上下文和知识喂给agent,让它生成响应。
Why It Works
LangGraph agent天生擅长生成类人回复,但如果缺少外部上下文,它就像没头苍蝇——只能靠训练数据瞎编。MCP服务器就是那个提供上下文的地方:数据库记录、API返回、知识库,什么都能来。没有MCPClient这座桥,agent就相当于在摸黑飞行,对话流程自然就断了。
The Gotcha: Error Handling and Retries
很多人在这一步翻车。如果MCP服务器宕机或者响应超时,agent就取不到上下文,对话直接死掉。来源文章里专门提到了这个问题。
需要给MCP调用加上重试逻辑。下面是一个实用的模式:
import time
from mcp.client import MCPClient
def handle_input_with_retry(mcp_client, input_text, retries=3, delay=2):
for attempt in range(retries):
try:
response = mcp_client.send_request(input_text)
return response
except Exception as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt < retries - 1:
time.sleep(delay)
raise RuntimeError("MCP server unreachable after retries")
把这个函数集成到你的handle_input里,agent就能优雅地应对MCP的临时故障了。
Try It Now
- 安装MCP客户端:
pip install mcp(确保已经装好langgraph)。 - 复制上面的基本模式,把URL替换成你自己的MCP服务器地址。
- 加上重试逻辑(用上面那段代码)。
- 测试一下宕机场景:停掉MCP服务器,验证agent能优雅地重试而不是直接崩溃。
A Word on MCP Trends
MCP演进得很快。社区正在往极简方向走——减少服务器数量以降低上下文膨胀。2026-07-28版本的规范移除了会话和初始化握手,让连接变成无状态。这意味着你的MCPClient接线方式可能会越来越简单。另外要留意安全问题:2026年7月有11个CVE漏洞在7000+个MCP实例中被披露,用之前一定得验证一下服务器的STDIO传输是否安全。
Final Takeaway
把LangGraph连到MCP没什么魔法——就是直接调用MCPClient,加上正确的错误处理。做到这一步,你的agent就再也不会当哑巴了。
Source: dev.to
[Updated 04 Aug via devto_mcp]
