了解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 以执行数学运算。
运作原理
- 启动数学服务器:The
math_server.py作为MCP服务器运行,提供两个工具:add(a, b)和multiply(a, b). - 初始化Stdio连接:客户端创建一个子流程,通过以下方式与数学服务器通信 stdio传输.
- 加载可用工具:客户端获取可用工具(
add,multiply)从服务器。 - 调用AI模型:人工智能模型,
GPT-4o,使用LangGraph的 ReAct(推理+代理)代理 决定如何求解给定的数学表达式。 - 执行计算:模型生成工具调用,调用
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 96MCP通信流程(序列图)
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.py 和 weather_server.py.
运作原理
- 初始化多个服务器:客户端连接到 数学 服务器使用
stdio和那个 天气 服务器通过 SSE(服务器发送事件). - 从多个服务器加载工具:AI模型可以从两个服务器访问工具。
- 并行处理:客户端现在可以在同一执行中从不同的服务器调用工具。
- 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.pyMCP架构使开发人员能够构建与多种服务高效交互的强大AI驱动应用程序。 🚀
______________________________________________________________________

