MCP 端点¶
模型上下文协议(Model Context Protocol,简称 MCP) 是一种开放协议,用于以与模型无关的格式描述工具和数据源,使大型语言模型(LLMs)能够通过结构化的 API 发现并使用这些工具和数据源。
LangGraph Server 使用 Streamable HTTP 传输方式 实现 MCP。这使得 LangGraph 的 代理(agents) 可以作为 MCP 工具(tools) 暴露出来,从而可以被任何支持 Streamable HTTP 的 MCP 兼容客户端使用。
MCP 端点位于:
在 LangGraph Server 上。
要求¶
要使用 MCP,请确保已安装以下依赖项:
langgraph-api >= 0.2.3
langgraph-sdk >= 0.1.61
使用以下命令进行安装:
将代理作为 MCP 工具公开¶
部署后,您的代理将作为工具出现在 MCP 端点中, 具有以下配置:
- 工具名称:代理的名称。
- 工具描述:代理的描述。
- 工具输入模式:代理的输入模式。
设置名称和描述¶
您可以在 langgraph.json
中设置代理的名称和描述:
{
"graphs": {
"my_agent": {
"path": "./my_agent/agent.py:graph",
"description": "A description of what the agent does"
}
},
"env": ".env"
}
部署后,您可以使用 LangGraph SDK 更新名称和描述。
模式¶
定义清晰、简化的输入和输出模式,以避免向 LLM 暴露不必要的内部复杂性。
默认的 MessagesState 使用 AnyMessage
,它支持许多消息类型,但对直接暴露给 LLM 来说过于通用。
相反,定义 自定义代理或工作流,它们使用明确类型的输入和输出结构。
例如,一个回答文档问题的工作流可能如下所示:
API Reference: StateGraph | START | END
from langgraph.graph import StateGraph, START, END
from typing_extensions import TypedDict
# 定义输入模式
class InputState(TypedDict):
question: str
# 定义输出模式
class OutputState(TypedDict):
answer: str
# 合并输入和输出
class OverallState(InputState, OutputState):
pass
# 定义处理节点
def answer_node(state: InputState):
# 替换为实际逻辑并执行有用的操作
return {"answer": "bye", "question": state["question"]}
# 使用显式模式构建图
builder = StateGraph(OverallState, input_schema=InputState, output_schema=OutputState)
builder.add_node(answer_node)
builder.add_edge(START, "answer_node")
builder.add_edge("answer_node", END)
graph = builder.compile()
# 运行图
print(graph.invoke({"question": "hi"}))
有关更多详细信息,请参阅 低级概念指南。
使用概览¶
要启用 MCP:
- 升级以使用 langgraph-api>=0.2.3。如果你正在部署 LangGraph 平台,当你创建新版本时,这将自动为你完成。
- MCP 工具(代理)将被自动暴露。
- 使用任何支持 Streamable HTTP 的 MCP 兼容客户端进行连接。
客户端¶
使用一个 MCP 兼容的客户端连接到 LangGraph 服务器。以下示例展示了如何使用不同的编程语言进行连接。
注意 将
serverUrl
替换为你的 LangGraph 服务器 URL,并根据需要配置认证头。
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
// 连接到 LangGraph MCP 端点
async function connectClient(url) {
const baseUrl = new URL(url);
const client = new Client({
name: 'streamable-http-client',
version: '1.0.0'
});
const transport = new StreamableHTTPClientTransport(baseUrl);
await client.connect(transport);
console.log("Connected using Streamable HTTP transport");
console.log(JSON.stringify(await client.listTools(), null, 2));
return client;
}
const serverUrl = "http://localhost:2024/mcp";
connectClient(serverUrl)
.then(() => {
console.log("Client connected successfully");
})
.catch(error => {
console.error("Failed to connect client:", error);
});
使用以下命令安装适配器:
下面是一个连接到远程 MCP 端点并使用代理作为工具的示例:
# 创建用于 stdio 连接的服务器参数
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
import asyncio
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent
server_params = {
"url": "https://mcp-finance-agent.xxx.us.langgraph.app/mcp",
"headers": {
"X-Api-Key":"lsv2_pt_your_api_key"
}
}
async def main():
async with streamablehttp_client(**server_params) as (read, write, _):
async with ClientSession(read, write) as session:
# 初始化连接
await session.initialize()
# 加载远程图,就像它是一个工具一样
tools = await load_mcp_tools(session)
# 创建并运行带有工具的 react 代理
agent = create_react_agent("openai:gpt-4.1", tools)
# 使用消息调用代理
agent_response = await agent.ainvoke({"messages": "What can the finance agent do for me?"})
print(agent_response)
if __name__ == "__main__":
asyncio.run(main())
会话行为¶
当前的 LangGraph MCP 实现不支持会话。每个 /mcp
请求都是无状态且独立的。
认证¶
/mcp
端点使用与 LangGraph API 其余部分相同的认证方式。有关设置详情,请参考 认证指南。
禁用 MCP¶
要禁用 MCP 端点,请在你的 langgraph.json
配置文件中将 disable_mcp
设置为 true
:
这将阻止服务器暴露 /mcp
端点。