> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Server 中的 MCP 端点

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

[Agent Server](/langsmith/agent-server) 使用 [可流式 HTTP 传输](https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/transports/#streamable-http) 实现了 MCP。这使得 LangGraph **智能体** 可以作为 **MCP 工具** 暴露，从而能被任何支持可流式 HTTP 的 MCP 兼容客户端使用。

MCP 端点位于 [Agent Server](/langsmith/agent-server) 的 `/mcp` 路径。

您可以设置 [自定义认证中间件](/langsmith/custom-auth) 来使用 MCP 服务器对用户进行身份验证，以获取对 LangSmith 部署中用户作用域工具的访问权限。

此流程的示例架构：

```mermaid theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
sequenceDiagram
  %% 参与者
  participant ClientApp as 客户端
  participant AuthProv  as 认证提供者
  participant LangGraph as Agent Server
  participant SecretStore as 密钥存储
  participant MCPServer as MCP 服务器

  %% 平台登录 / 身份验证
  ClientApp  ->> AuthProv: 1. 登录（用户名 / 密码）
  AuthProv   -->> ClientApp: 2. 返回令牌
  ClientApp  ->> LangGraph: 3. 携带令牌请求

  Note over LangGraph: 4. 验证令牌 (@auth.authenticate)
  LangGraph  -->> AuthProv: 5. 获取用户信息
  AuthProv   -->> LangGraph: 6. 确认有效性

  %% 从密钥存储获取用户令牌
  LangGraph  ->> SecretStore: 6a. 获取用户令牌
  SecretStore -->> LangGraph: 6b. 返回令牌

  Note over LangGraph: 7. 应用访问控制 (@auth.on.*)

  %% MCP 往返
  Note over LangGraph: 8. 使用用户令牌构建 MCP 客户端
  LangGraph  ->> MCPServer: 9. 调用 MCP 工具（携带请求头）
  Note over MCPServer: 10. MCP 验证请求头并运行工具
  MCPServer  -->> LangGraph: 11. 工具响应

  %% 返回给调用者
  LangGraph  -->> ClientApp: 12. 返回资源 / 工具输出
```

## 要求

要使用 MCP，请确保已安装以下依赖项：

* `langgraph-api >= 0.2.3`
* `langgraph-sdk >= 0.1.61`

使用以下命令安装：

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install "langgraph-api>=0.2.3" "langgraph-sdk>=0.1.61"
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add "langgraph-api>=0.2.3" "langgraph-sdk>=0.1.61"
  ```
</CodeGroup>

## 使用概述

要启用 MCP：

* 升级到使用 langgraph-api>=0.2.3。如果您正在部署 LangSmith，创建新修订版时会自动完成此操作。
* MCP 工具（智能体）将自动暴露。
* 使用任何支持可流式 HTTP 的 MCP 兼容客户端进行连接。

### 客户端

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

<Tabs>
  <Tab title="JavaScript/TypeScript">
    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    npm install @modelcontextprotocol/sdk
    ```

    > **注意**
    > 将 `serverUrl` 替换为您的 Agent Server URL，并根据需要配置认证请求头。

    ```js theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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("已使用可流式 HTTP 传输连接");
        console.log(JSON.stringify(await client.listTools(), null, 2));
        return client;
    }

    const serverUrl = "http://localhost:2024/mcp";

    connectClient(serverUrl)
        .then(() => {
            console.log("客户端连接成功");
        })
        .catch(error => {
            console.error("连接客户端失败:", error);
        });
    ```
  </Tab>

  <Tab title="Python">
    使用以下命令安装适配器：

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    pip install langchain-mcp-adapters
    ```

    以下是如何连接到远程 MCP 端点并将智能体用作工具的示例：

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    # 为标准输入输出连接创建服务器参数
    from mcp import ClientSession
    from mcp.client.streamable_http import streamablehttp_client
    import asyncio

    from langchain_mcp_adapters.tools import load_mcp_tools
    from langchain.agents import create_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_agent("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())
    ```
  </Tab>
</Tabs>

## 将智能体暴露为 MCP 工具

部署后，您的智能体将作为工具出现在 MCP 端点中，配置如下：

* **工具名称**：智能体的名称。
* **工具描述**：智能体的描述。
* **工具输入模式**：智能体的输入模式。

### 设置名称和描述

您可以在 `langgraph.json` 中设置智能体的名称和描述：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
    "graphs": {
        "my_agent": {
            "path": "./my_agent/agent.py:graph",
            "description": "描述该智能体的功能"
        }
    },
    "env": ".env"
}
```

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

### 模式

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

默认的 [MessagesState](/oss/python/langgraph/graph-api#messagesstate) 使用 `AnyMessage`，它支持多种消息类型，但对于直接暴露给 LLM 来说过于通用。

相反，应定义使用显式类型化输入和输出结构的**自定义智能体或工作流**。

例如，一个回答文档问题的工作流可能如下所示：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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"}))
```

更多详情，请参阅 [底层概念指南](/oss/python/langgraph/graph-api#state)。

## 在您的部署中使用用户作用域的 MCP 工具

<Tip>
  **先决条件**
  您已添加了自己的 [自定义认证中间件](/langsmith/custom-auth)，该中间件填充了 `langgraph_auth_user` 对象，使其可通过可配置上下文在图的每个节点中访问。
</Tip>

要使您的 LangSmith 部署能够使用用户作用域的工具，请从实现类似以下的代码片段开始：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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"], 等等。

    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)

    # 您的工具调用逻辑写在这里

    tool_messages = ...
    return {"messages": tool_messages}
```

1. MCP 仅支持向 `streamable_http` 和 `sse` `transport` 服务器发出的请求添加请求头。
2. 您的 MCP 服务器 URL。
3. 从您的 MCP 服务器获取可用工具。

*这也可以通过 [在运行时重建您的图](/langsmith/graph-rebuild) 来实现，以便为新运行使用不同的配置*

## 会话行为

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

## 认证

`/mcp` 端点使用与 LangGraph API 其余部分相同的认证。有关设置详情，请参阅 [认证指南](/langsmith/auth)。

## 禁用 MCP

要禁用 MCP 端点，请在您的 `langgraph.json` 配置文件中将 `disable_mcp` 设置为 `true`：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  "$schema": "https://langgra.ph/schema.json",
  "http": {
    "disable_mcp": true
  }
}
```

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

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\langsmith\server-mcp.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
