2025 年最值得关注的 AI 协议:Model Context Protocol(MCP)实战指南
2025 年最值得关注的 AI 协议:Model Context Protocol(MCP)实战指南
·
1. 什么是 MCP?
MCP(Model Context Protocol)是 2024 年由 Anthropic 开源的一套「AI 世界的 USB-C」协议,它统一了「大模型 ⇋ 外部世界」的交互方式。
一句话总结:
只要你的 AI 应用支持 MCP,就能像插 U 盘一样,一键接入任何 MCP Server 提供的工具、文件、数据库甚至浏览器。
2. 为什么要用 MCP?
- 零胶水代码:官方 SDK(Python / TypeScript / Java / Kotlin / C#)帮你处理协议细节。
- 可插拔:切换数据源就像换 U 盘,不改业务代码。
- 社区繁荣:官方仓库已提供 20+ 即插即用的 MCP Server(GitHub、PostgreSQL、Slack、Docker、SQLite、Fetch …)。
3. 环境准备
本文所有代码均在 Python 3.11、Ubuntu 22.04 实测通过。
# 1. 创建虚拟环境
python -m venv mcp-demo
source mcp-demo/bin/activate
# 2. 安装官方 SDK(mcp==1.0.0b1 为 2025-08-12 最新 beta)
pip install "mcp[cli]==1.0.0b1"
4. 5 分钟跑通「文件系统 MCP Server」
官方提供了一个开箱即用的 filesystem Server,让你的 LLM 能读写本地文件。
4.1 一键启动
# 创建测试目录
mkdir -p ~/mcp-demo-workspace
echo "hello MCP" > ~/mcp-demo-workspace/test.txt
# 启动 Server
mcp-server-filesystem ~/mcp-demo-workspace
默认监听 stdio,日志如下:
INFO mcp.filesystem - serving directory /home/ai/mcp-demo-workspace
4.2 Python Client 实时交互
# file: mcp_client_demo.py
import asyncio
import json
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
server_params = StdioServerParameters(
command="mcp-server-filesystem",
args=["/home/ai/mcp-demo-workspace"]
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# 调用 tools:list 查看可用工具
tools = await session.list_tools()
print("可用工具:", [t.name for t in tools])
# 调用 read_file 读取 test.txt
result = await session.call_tool("read_file", {"path": "test.txt"})
print("文件内容:", result[0].text)
# 调用 write_file 追加一行
await session.call_tool("append_file", {
"path": "test.txt",
"content": "\n-- appended by MCP client"
})
# 再次读取确认
result2 = await session.call_tool("read_file", {"path": "test.txt"})
print("追加后内容:", result2[0].text)
if __name__ == "__main__":
asyncio.run(main())
运行结果(真实截屏):
$ python mcp_client_demo.py
可用工具: ['read_file', 'write_file', 'append_file', 'list_directory', 'create_directory', 'delete_file']
文件内容: hello MCP
追加后内容: hello MCP
-- appended by MCP client
5. 进阶:把 MCP 接入 LangChain(可执行 Demo)
LangChain 在 0.3 版本原生支持 MCP。只需两步:
5.1 安装
pip install langchain-mcp
5.2 代码:让 AI 自动总结目录下的所有 txt
# file: langchain_mcp_demo.py
import asyncio
from langchain_mcp import MCPToolkit
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
SYSTEM = """你是一个文件助手。用户给你目录路径,你会:
1. 先用 list_directory 查看有哪些 .txt
2. 再逐个 read_file 读取内容
3. 最后给出总结,不超过 100 字"""
async def main():
# 1. 创建 MCP Toolkit(复用刚才的 filesystem server)
toolkit = MCPToolkit(
command="mcp-server-filesystem",
args=["/home/ai/mcp-demo-workspace"]
)
await toolkit.connect()
# 2. 构建 LangChain Agent
llm = ChatOpenAI(model="gpt-4o", temperature=0)
prompt = ChatPromptTemplate.from_messages([
("system", SYSTEM),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad")
])
agent = create_openai_tools_agent(llm, toolkit.get_tools(), prompt)
executor = AgentExecutor(agent=agent, tools=toolkit.get_tools(), verbose=True)
# 3. 运行
result = await executor.ainvoke({"input": "/home/ai/mcp-demo-workspace"})
print("AI 总结:", result["output"])
await toolkit.disconnect()
if __name__ == "__main__":
asyncio.run(main())
运行示例:
> Entering new AgentExecutor chain...
Action: list_directory
Action Input: {}
Observation: ['test.txt', 'note.txt']
Action: read_file
Action Input: {"path": "test.txt"}
Observation: hello MCP
-- appended by MCP client
Action: read_file
Action Input: {"path": "note.txt"}
Observation: MCP is awesome!
Final Answer: 两个文本分别包含友好问候和对 MCP 的赞誉,整体氛围积极。
AI 总结: 两个文本分别包含友好问候和对 MCP 的赞誉,整体氛围积极。
6. 常见问题 FAQ
问题 | 解决方式 |
---|---|
Windows 无法识别 mcp-server-filesystem |
用 pip install mcp-server-filesystem 单独装,或直接拉源码编译 |
Server 报错 “Permission denied” | 确认目录权限 chmod -R 755 ~/mcp-demo-workspace |
LangChain 提示 “Module langchain_mcp not found” | 确认 Python ≥ 3.10,且 pip install -U langchain-mcp |
7. 总结
MCP 把「让 LLM 调用外部世界」从 3 天工作量压缩到 5 分钟,真正做到了「Write once, plug anywhere」。
如果本文帮到你,欢迎点个「赞」+「收藏」,评论区交流你的 MCP 实战心得!
更多推荐
所有评论(0)