随着大语言模型的兴起,如何安全、高效、模块化地调用模型以外的外部工具函数(Tool) ,成为构建智能体系统的关键能力之一。OpenAI 提供了Function Calling 这一种高层封装(详情可见 基于 OpenAI Function Calling 的工具调用实践解析交互流程),而 MCP(Message Control Protocol)进一步提供了一种底层通信协议和标准化架构,支持双向消息、工具注册与执行、Agent 编排等高级能力。
本文将带领读者理解 MCP 的核心思想,并通过 Stdio 模式 实现一个本地交互式的 Agent-Tool 系统,其具备跨进程通信、动态工具发现、远程调用与安全隔离等优势。
一、什么是 MCP?
MCP(Message Control Protocol)是一个为 AI 工具链和智能体系统设计的 轻量级通信协议,支持:
- 多语言之间的数据交互
- LLM 与工具函数的解耦
- 可插拔式工具发现、注册与调用
- 支持 Stdio、SSE、Streamable HTTP三种传输机制
其目标是让 AI 系统具备"调用任何工具"的能力,并提供统一的接口定义与消息传输规范。
二、什么是 Stdio 模式?
Stdio
模式是 MCP 最轻量的通信方式,底层通过标准输入输出(stdin/stdout)进行通信。优势包括:
- 无需网络环境,完全本地化运行
- 进程隔离,避免工具崩溃影响主程序
- 更适合开发、测试、调试小型工具代理系统
- 性能稳定、通信延迟极低
非常适合构建一类"本地 LLM + 工具执行"的 AI 智能体系统,或将 Python 工具封装成标准 Agent。
三、示例项目结构
bash
project/
├── stdio_server.py # MCP 服务端,注册工具
└── stdio_client.py # MCP 客户端,调用工具
MCP 服务端(工具注册者)
python
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("MyServer")
@mcp.tool()
def say_hello(name: str) -> str:
return f"Hello, {name}! Nice to meet you!"
@mcp.tool()
def add(a: int, b: int) -> int:
return a + b
if __name__ == "__main__":
mcp.run(transport="stdio")
关键解析:
FastMCP("MyServer")
:初始化一个 MCP Server,内部会维护工具注册表@mcp.tool()
:将本地函数注册为 MCP 工具,自动暴露名称、描述、参数结构等元数据mcp.run(transport="stdio")
:开启服务,监听标准输入/输出流,等待客户端请求
MCP 客户端(工具调用方)
python
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
# Define server parameters
server_params = StdioServerParameters(
command="python", # The command to run your server
args=["stdio_server.py"], # The arguments to pass to the command
)
# Connection to the server
async with stdio_client(server_params) as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
# Initialize the connection
await session.initialize()
# List avaliable tools
tools_result = await session.list_tools()
print("Available tools:")
for tool in tools_result.tools:
print(f"- {tool.name}: {tool.description}")
# Call our calculator tool
result = await session.call_tool("add", arguments={"a": 1, "b": 2})
print(f"1 + 2 = {result.content[0].text}")
if __name__ == "__main__":
asyncio.run(main())
关键解析:
StdioServerParameters
:用于描述目标 Server 的启动方式(命令 + 参数)stdio_client(...)
:打开一个异步上下文环境,与 Server 通过标准 IO 建立连接ClientSession
:抽象出的"客户端会话",支持工具列举、函数调用等 APIcall_tool(name, arguments)
:直接远程调用 MCP Server 上注册的某个工具
交互流程时序图

四、MCP 与 Function Calling 的对比
功能 | OpenAI Function Calling | MCP |
---|---|---|
工具注册 | JSON Schema 注册函数 | Python 装饰器注册 |
参数交互 | 模型生成 JSON 参数 | 客户端直接指定参数 |
执行隔离 | 模型内执行 | 可进程级别隔离(Stdio) |
通信机制 | 内部封装 | 可选 Stdio、SSE、Streamable HTTP |
场景适配 | LLM 调用链 | 通用代理工具框架,适合 Agent |
小结:Function Calling 更高层、针对 LLM 推理流程;而 MCP 更底层,更通用、组件化,更适合做 Tool Registry + Agent 系统。
五、总结
MCP 提供了一种强大而灵活的协议,可以帮助我们将任意 Python 工具函数注册为结构化、可调用的服务端组件 。通过 Stdio
模式,我们实现了本地进程间通信的高效工具系统,读者可在此基础上进一步拓展为:
- 本地 LLM Agent + 工具系统
- 与 LangGraph 等框架整合的流程图智能体
- 支持多语言互通的插件机制
如果你正准备构建一个智能体执行平台,那么MCP 将会是一个非常值得探索的选项。