跳到内容

LangGraph服务器中的MCP端点

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

LangGraph服务器使用可流式HTTP传输实现MCP。这允许将LangGraph代理暴露为MCP工具,使其可与任何支持可流式HTTP且符合MCP的客户端一起使用。

MCP端点在LangGraph服务器/mcp路径可用。

要求

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

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

使用以下命令安装它们

pip install "langgraph-api>=0.2.3" "langgraph-sdk>=0.1.61"

使用概述

要启用MCP

  • 升级到使用langgraph-api>=0.2.3。如果您正在部署LangGraph平台,如果您创建新的修订版,这将自动为您完成。
  • MCP工具(代理)将自动暴露。
  • 连接到任何支持可流式HTTP且符合MCP的客户端。

客户端

使用符合MCP的客户端连接到LangGraph服务器。以下示例展示了如何使用不同的编程语言进行连接。

npm install @modelcontextprotocol/sdk

注意serverUrl替换为您的LangGraph服务器URL,并根据需要配置身份验证头。

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 = "https://:2024/mcp";

connectClient(serverUrl)
    .then(() => {
        console.log("Client connected successfully");
    })
    .catch(error => {
        console.error("Failed to connect client:", error);
    });

使用以下命令安装适配器

pip install langchain-mcp-adapters

以下是连接到远程MCP端点并将代理用作工具的示例

# Create server parameters for stdio connection
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:
            # Initialize the connection
            await session.initialize()

            # Load the remote graph as if it was a tool
            tools = await load_mcp_tools(session)

            # Create and run a react agent with the tools
            agent = create_react_agent("openai:gpt-4.1", tools)

            # Invoke the agent with a message
            agent_response = await agent.ainvoke({"messages": "What can the finance agent do for me?"})
            print(agent_response)

if __name__ == "__main__":
    asyncio.run(main())

将代理暴露为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参考:StateGraph | START | END

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工具

先决条件

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

要使用户范围的工具可用于您的LangGraph平台部署,请从实现以下代码片段开始

API参考:MultiServerMCPClient

from langchain_mcp_adapters.client import MultiServerMCPClient

def mcp_tools_node(state, config):
    user = config["configurable"].get("langgraph_auth_user")
         # e.g., 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_httpsse transport服务器的请求添加头。
  2. 您的MCP服务器URL。
  3. 从您的MCP服务器获取可用工具。

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

会话行为

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

身份验证

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

禁用MCP

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

{
  "http": {
    "disable_mcp": true
  }
}

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