Skip to content
LangSmith 文档版本 跟随上游 源快照 63594004 更新于 2026-10-18

Agent Server 中的 MCP 端点

Model Context Protocol (MCP) 是一种开放协议,用于以模型无关的格式描述工具和数据源,使 LLM 能够通过结构化 API 发现和使用它们。

Agent Server 使用 Streamable HTTP 传输实现 MCP。这允许将 LangGraph agents 暴露为 MCP 工具,使其可与任何支持 Streamable HTTP 的 MCP 兼容客户端一起使用。

MCP 端点位于 Agent Server 上的 /mcp。

Managed Deep Agents 部署运行在 Agent Server 上,因此它们暴露相同的 /mcp 端点。有关 Managed Deep Agents 的 URL 发现和身份标头,请参阅将 MCP 客户端连接到托管 deep agent。

你可以设置自定义身份验证中间件,以通过 MCP 服务器对用户进行身份验证,从而访问 LangSmith 部署中的用户范围工具。

此流程的示例架构:

sequenceDiagram
  %% Actors
  participant ClientApp as Client
  participant AuthProv  as Auth Provider
  participant LangGraph as Agent Server
  participant SecretStore as Secret Store
  participant MCPServer as MCP Server

  %% Platform login / AuthN
  ClientApp  ->> AuthProv: 1. Login (username / password)
  AuthProv   -->> ClientApp: 2. Return token
  ClientApp  ->> LangGraph: 3. Request with token

  Note over LangGraph: 4. Validate token (@auth.authenticate)
  LangGraph  -->> AuthProv: 5. Fetch user info
  AuthProv   -->> LangGraph: 6. Confirm validity

  %% Fetch user tokens from secret store
  LangGraph  ->> SecretStore: 6a. Fetch user tokens
  SecretStore -->> LangGraph: 6b. Return tokens

  Note over LangGraph: 7. Apply access control (@auth.on.*)

  %% MCP round-trip
  Note over LangGraph: 8. Build MCP client with user token
  LangGraph  ->> MCPServer: 9. Call MCP tool (with header)
  Note over MCPServer: 10. MCP validates header and runs tool
  MCPServer  -->> LangGraph: 11. Tool response

  %% Return to caller
  LangGraph  -->> ClientApp: 12. Return resources / tool output

要求

要使用 MCP,请确保已安装以下依赖项:

  • langgraph-api >= 0.2.3
  • langgraph-sdk >= 0.1.61

使用以下命令安装它们:

bash
pip install "langgraph-api>=0.2.3" "langgraph-sdk>=0.1.61"
bash
uv add "langgraph-api>=0.2.3" "langgraph-sdk>=0.1.61"

用法概述

要启用 MCP:

  • 升级以使用 langgraph-api>=0.2.3。如果你正在部署 LangSmith,创建新修订版时会自动完成此操作。
  • MCP 工具(agents)将自动暴露。
  • 使用任何支持 Streamable HTTP 的 MCP 兼容客户端进行连接。

客户端

使用 MCP 兼容客户端连接到 Agent Server。以下示例展示如何使用不同编程语言进行连接。

bash
npm install @modelcontextprotocol/sdk

Note 将 serverUrl 替换为你的 Agent Server URL,并根据需要配置身份验证标头。

js
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";

// Connects to the LangGraph MCP endpoint
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);
    });

将 agent 暴露为 MCP 工具

部署后,你的 agent 将显示为 MCP 端点中的工具, 使用以下配置:

  • 工具名称:agent 的名称。
  • 工具描述:agent 的描述。
  • 工具输入模式:agent 的输入模式。

设置名称和描述

你可以在 langgraph.json 中设置 agent 的名称和描述:

json
{
    "graphs": {
        "my_agent": {
            "path": "./my_agent/agent.py:graph",
            "description": "A description of what the agent does"
        }
    },
    "env": ".env"
}

部署后,你可以使用 LangGraph SDK 更新名称和描述。

Schema

定义清晰、最小的输入和输出模式,以避免向 LLM 暴露不必要的内部复杂性。

默认的 MessagesState 使用 AnyMessage,它支持许多消息类型,但对于直接暴露给 LLM 来说过于通用。

相反,请定义使用显式类型化输入和输出结构的自定义 agent 或工作流。

例如,回答文档问题的工作流可能如下所示:

python
from langgraph.graph import StateGraph, START, END
from typing_extensions import TypedDict

# Define input schema
class InputState(TypedDict):
    question: str

# Define output schema
class OutputState(TypedDict):
    answer: str

# Combine input and output
class OverallState(InputState, OutputState):
    pass

# Define the processing node
def answer_node(state: InputState):
    # Replace with actual logic and do something useful
    return {"answer": "bye", "question": state["question"]}

# Build the graph with explicit schemas
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()

# Run the graph
print(graph.invoke({"question": "hi"}))

有关更多详情,请参阅低级概念指南。

在部署中使用用户范围的 MCP 工具

TIP

先决条件 你已添加自己的自定义身份验证中间件,它会填充 langgraph_auth_user 对象,使其可通过可配置上下文供图中的每个节点访问。

要使 LangSmith 部署能够使用用户范围工具,请先实现类似以下代码片段:

python
from langchain_mcp_adapters.client import MultiServerMCPClient

def mcp_tools_node(state, config):
    user = config["configurable"].get("langgraph_auth_user")
         , user["github_token"], user["email"], etc.

    client = MultiServerMCPClient({
        "github": {
            "transport": "streamable_http", # (1)
            "url": "https://my-github-mcp-server/mcp", # (2)
            "headers": {
                "Authorization": f"Bearer {user['github_token']}"
            }
        }
    })
    tools = await client.get_tools() # (3)

    # Your tool-calling logic here

    tool_messages = ...
    return {"messages": tool_messages}
  1. MCP 仅支持向发往 streamable_http 和 sse transport 服务器的请求添加标头。
  2. 你的 MCP 服务器 URL。
  3. 从你的 MCP 服务器获取可用工具。

这也可以通过在运行时重建图来为新运行使用不同的配置

会话行为

当前的 LangGraph MCP 实现不支持会话。每个 /mcp 请求都是无状态且独立的。

身份认证

/mcp 端点使用与 LangGraph API 其余部分相同的身份验证。有关设置详情,请参阅身份验证指南。

禁用 MCP

要禁用 MCP 端点,请在 langgraph.json 配置文件中将 disable_mcp 设置为 true:

json
{
  "$schema": "https://langgra.ph/schema.json",
  "http": {
    "disable_mcp": true
  }
}

这将阻止服务器暴露 /mcp 端点。


BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。