Token导航 LogoToken导航TokenDH.com
Langgraph MCP Integration logo
搜索检索stdio官方级别未说明来源级核验

Langgraph MCP Integration

MCP Server

MCP architecture demo with single-server \u0026 multi-server clients using LangGraph, AI-driven tool calls, and async communication.

工具数

2

提示词数

0

GitHub Stars

0

资源数

0
Python数学计算搜索

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

commitbyrajat

提供方

commitbyrajat

最后核验

2026/5/18 03:32

运行时

Python

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

python server/weather_server.py

详细介绍

了解MCP架构:单服务器与多服务器客户端

现代人工智能驱动的应用程序需要高效且可扩展的架构来与多个外部服务交互。这 多客户端协议(MCP) 提供了一个强大的框架来与各种工具服务器通信,实现了人工智能模型和外部计算之间的无缝交互。在这个博客中,我们将通过比较MCP架构来探索其优势 单一服务器多服务器 客户。

数学服务器(math_server.py)

数学服务器 充当MCP工具服务器,提供加法和乘法等基本数学运算。它监听传入的请求,处理工具调用,并返回结果。

代码分解

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Math")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

@mcp.tool()
def multiply(a: int, b: int) -> int:
    """Multiply two numbers"""
    return a * b

if __name__ == "__main__":
    mcp.run(transport="stdio")
  • 定义一个名为的MCP服务器 数学.
  • 寄存器 add(a, b)multiply(a, b) 作为可用的工具。
  • 与跑步 标准输入输出 传输,允许通过标准输入/输出进行通信。

单服务器客户端

A. 单服务器客户端 连接到一个MCP服务器,该服务器公开了一组用于计算的工具。让我们分析一下 single_server_client.py 脚本,与 math_server.py 以执行数学运算。

运作原理

  1. 启动数学服务器:The math_server.py 作为MCP服务器运行,提供两个工具: add(a, b)multiply(a, b).
  2. 初始化Stdio连接:客户端创建一个子流程,通过以下方式与数学服务器通信 stdio传输.
  3. 加载可用工具:客户端获取可用工具(add, multiply)从服务器。
  4. 调用AI模型:人工智能模型, GPT-4o,使用LangGraph的 ReAct(推理+代理)代理 决定如何求解给定的数学表达式。
  5. 执行计算:模型生成工具调用,调用 add(3,5) 首先,然后 multiply(8,12),最后返回计算出的答案。

代码分解(single_server_client.py)

server_params = StdioServerParameters(
    command="python",
    args=["server/math_server.py"],
)

async with stdio_client(server_params) as (read, write):
    async with ClientSession(read, write) as session:
        await session.initialize()
        tools = await load_mcp_tools(session)
        agent = create_react_agent(model, tools)
        events = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})

输出打印:

----------------------------------------------------------------------------
The result is 96

MCP通信流程(序列图)

sequenceDiagram
    participant Client as Client Script
    participant LangGraph as LangGraph React Agent
    participant ClientSession as MCP ClientSession
    participant stdio as stdio Transport Layer
    participant MathServer as Math Server Process
    participant Tools as Math Tools (add/multiply)
    participant LLM as GPT-4o Model

    Note over Client: Starts execution with asyncio.run()
    Client->>MathServer: Launch as subprocess with stdio parameters
    
    Client->>stdio: Create stdio client connection
    stdio-->>Client: Return read/write streams
    
    Client->>ClientSession: Initialize session
    ClientSession->>stdio: Send initialize message
    stdio->>MathServer: Forward initialize request
    MathServer-->>stdio: Return server capabilities
    stdio-->>ClientSession: Return initialization response
    ClientSession-->>Client: Session initialized
    
    Client->>ClientSession: load_mcp_tools()
    ClientSession->>stdio: Request available tools
    stdio->>MathServer: Forward tools request
    MathServer->>Tools: Discover registered tools (add, multiply)
    Tools-->>MathServer: Return tool descriptions
    MathServer-->>stdio: Return tool descriptions
    stdio-->>ClientSession: Return tool descriptions
    ClientSession-->>Client: Return langchain-compatible tools
    
    Client->>LangGraph: Create React agent with model and tools
    LangGraph-->>Client: Return agent instance
    
    Client->>LangGraph: agent.ainvoke("what's (3 + 5) x 12?")
    LangGraph->>LLM: Generate reasoning and tool calls
    
    Note over LLM: Decides to use add(3, 5) first
    LLM-->>LangGraph: Return reasoning and add(3, 5) tool call
    
    LangGraph->>ClientSession: Call add(3, 5)
    ClientSession->>stdio: Send tool execution request
    stdio->>MathServer: Forward tool execution request
    MathServer->>Tools: Execute add(3, 5)
    Tools-->>MathServer: Return result (8)
    MathServer-->>stdio: Return tool execution result
    stdio-->>ClientSession: Return tool execution result
    ClientSession-->>LangGraph: Return add result (8)
    
    LangGraph->>LLM: Generate next reasoning step with add result
    
    Note over LLM: Decides to use multiply(8, 12) next
    LLM-->>LangGraph: Return reasoning and multiply(8, 12) tool call
    
    LangGraph->>ClientSession: Call multiply(8, 12)
    ClientSession->>stdio: Send tool execution request
    stdio->>MathServer: Forward tool execution request
    MathServer->>Tools: Execute multiply(8, 12)
    Tools-->>MathServer: Return result (96)
    MathServer-->>stdio: Return tool execution result
    stdio-->>ClientSession: Return tool execution result
    ClientSession-->>LangGraph: Return multiply result (96)
    
    LangGraph->>LLM: Generate final answer with all results
    LLM-->>LangGraph: Return final answer "The result is 96"
    LangGraph-->>Client: Return complete event trace and answer
    
    Client->>Client: Print final answer

天气服务器(weather_server.py)

天气服务器 是另一个提供实时天气信息的MCP工具服务器。它监听传入的天气查询,并用最新的天气数据进行响应。

启动服务器的命令:

python server/weather_server.py

代码分解

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Weather")

@mcp.tool()
async def get_weather(location: str) -> str:
    """Get weather for location."""
    return "It's always sunny in New York"

if __name__ == "__main__":
    mcp.run(transport="sse")
  • 定义一个名为的MCP服务器 天气.
  • 寄存器 get_weather(location) 作为一种可用的工具。
  • 与跑步 SSE(服务器发送事件) 传输,允许实时事件流。

多服务器客户端

A. 多服务器客户端 可以同时与多个MCP服务器交互。这 multi_server_client.py 脚本通过与两者通信来演示这一点 math_server.pyweather_server.py.

运作原理

  1. 初始化多个服务器:客户端连接到 数学 服务器使用 stdio 和那个 天气 服务器通过 SSE(服务器发送事件).
  2. 从多个服务器加载工具:AI模型可以从两个服务器访问工具。
  3. 并行处理:客户端现在可以在同一执行中从不同的服务器调用工具。
  4. AI驱动的响应:该模型使用多个MCP服务器处理数学表达式和天气查询。

代码分解(multi_server_client.py)

async with MultiServerMCPClient(
    {
        "math": {
            "command": "python",
            "args": ["server/math_server.py"],
            "transport": "stdio",
        },
        "weather": {
            "url": "http://localhost:8000/sse",
            "transport": "sse",
        },
    }
) as client:
    agent = create_react_agent(model, client.get_tools())
    math_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
    weather_response = await agent.ainvoke({"messages": "what is the weather in nyc?"})

多服务器客户端响应

多服务器客户端的输出如下:

{
  "math_response": "The result of (3 + 5) x 12 is 96.",
  "weather_response": "The weather in NYC is currently sunny."
}

MCP架构的好处

  • 可扩展性:可轻松扩展到多种服务。
  • 并行执行:允许对不同服务器进行并发查询。
  • 灵活的沟通:支持多个传输层(stdio, sse等等)。
  • 人工智能集成:将AI模型与外部计算服务无缝连接。

代码设置和执行

要克隆并执行代码,请执行以下步骤:

git clone https://github.com/commitbyrajat/langgraph-mcp-integration.git
cd langgraph-mcp-integration
rye sync  # Sync dependencies
rye run python server/weather_server.py &
rye run python client/single_server_client.py
rye run python client/multi_server_client.py

MCP架构使开发人员能够构建与多种服务高效交互的强大AI驱动应用程序。 🚀

______________________________________________________________________

目录标签

目录标签

Python数学计算搜索research-and-datamathgptmath-solvermath-assistantAI通信框架本地部署多服务器交互天气查询并行处理

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

none

运行时(runtime,运行环境)

Python

工具数量(toolCount,工具数)

2

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdionone部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP