模型上下文协议 (MCP) 是由 Anthropic 开发的开源协议,专注于安全且可解释的生成式 AI 系统。
MCP 的出现是为了解决大型语言模型(
LLM)应用程序的一个关键限制,即它们与外部数据源和工具的隔离。
MCP 的主要目的是标准化基于 LLM 的应用程序如何连接到不同的系统 ,如下图所示:
AI Agent的挑战在于传输给Agent数据,换句话说,基于
AI Agent/LLM 的应用程序集成到外部数据源。
MCP 可以用作通用接口,将其视为 AI 的 USB-C,在
LLMs/AI Agent和外部资源之间实现无缝、安全和可扩展的数据交换。
MCP 使用客户端-服务器架构,其中 MCP 主机(AI 应用程序)与 MCP 服务器(数据/工具提供商)。
开发人员也可以使用 MCP 构建可重用的模块化连接器,并为流行的平台提供预定义的服务器,从而创建一个社区驱动的生态系统。
MCP 的开源性质鼓励创新,允许开发人员扩展其功能,同时通过精细权限等功能维护安全性。
最终,MCP 旨在将 AI Agent从孤立的聊天机器人转变为深度集成到数字环境中的上下文感知、可互作的系统。
下面演示一下如何使用Langchain完成MCP全流程:
在终端开两个窗口,一个用于运行服务器,另一个用于运行客户端。并且最好创建一个python虚拟环境来运行。
首先,创建一个名为MCP_Demo虚拟环境
python3 -m venv MCP\_Demo
然后,激活该虚拟环境
source MCP\_Demo/bin/activate
再安装相关包和Openai API Key
pip install langchain-mcp-adapters
export OPENAI_API_KEY=<your_api_key>
最后,在其中一个终端创建一个文本文件:vim server.py,并把下面代码粘贴到该文件中。
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")
关闭文本文件,使用以下命令启动并运行服务器:
python3 math\_server.py
此时,终端不显示任何内容
在另一个终端创建一个文本文件client.py用于客户端
# Create server parameters for stdio connection
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI
import asyncio
model = ChatOpenAI(model="gpt-4o")
server_params = StdioServerParameters(
command="python",
# Make sure to update to the full absolute path to your math_server.py file
args=["math_server.py"],
)
async def run_agent():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the connection
await session.initialize()
# Get tools
tools = await load_mcp_tools(session)
# Create and run the agent
agent = create_react_agent(model, tools)
agent_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
return agent_response
# Run the async function
if __name__ == "__main__":
result = asyncio.run(run_agent())
print(result)
使用运行客户端:python client.py
{'messages':
[HumanMessage(content="what's (3 + 5) x 12?",
additional_kwargs={}, response_metadata={},
id='87a8b6b6-9add-4da7-aea5-1b197c0fc0f5'),
AIMessage(content='',
additional_kwargs={'tool_calls': [{'id': 'call_1eyRzR7WpKzhMXG4ZFQAJtUD',
'function':
{'arguments': '{"a": 3, "b": 5}', 'name': 'add'},
'type': 'function'},
{'id': 'call_q82CX807NC3T6nHMrhoHT46E',
'function':
{'arguments': '{"a": 8, "b": 12}', 'name': 'multiply'},
'type': 'function'}],
'refusal': None},
response_metadata={'token_usage':
{'completion_tokens': 51,
'prompt_tokens': 77,
'total_tokens': 128,
'completion_tokens_details':
{'accepted_prediction_tokens': 0,
'audio_tokens': 0,
'reasoning_tokens': 0,
'rejected_prediction_tokens': 0},
'prompt_tokens_details':
{'audio_tokens': 0,
'cached_tokens': 0}},
'model_name': 'gpt-4o-2024-08-06',
'system_fingerprint': 'fp_eb9dce56a8',
'finish_reason': 'tool_calls',
'logprobs': None},
id='run-13c01640-f92b-48b7-9340-c2ad983eb1c8-0',
tool_calls=[{'name': 'add', 'args': {'a': 3, 'b': 5},
'id': 'call_1eyRzR7WpKzhMXG4ZFQAJtUD',
'type': 'tool_call'}, {'name': 'multiply',
'args': {'a': 8, 'b': 12},
'id': 'call_q82CX807NC3T6nHMrhoHT46E',
'type': 'tool_call'}],
usage_metadata={'input_tokens': 77,
'output_tokens': 51,
'total_tokens': 128,
'input_token_details': {'audio': 0,
'cache_read': 0},
'output_token_details': {'audio': 0,
'reasoning': 0}}),
ToolMessage(content='8',
name='add',
id='f8e0aba5-7a62-44c6-92a3-5fe3b07c9bd5',
tool_call_id='call_1eyRzR7WpKzhMXG4ZFQAJtUD'),
ToolMessage(content='96',
name='multiply',
id='66b9bbd9-b99a-402f-b26c-df83f5a69fa3',
tool_call_id='call_q82CX807NC3T6nHMrhoHT46E'),
AIMessage(content='The result of \\((3 + 5) \\times 12\\) is 96.',
additional_kwargs={'refusal': None},
response_metadata={'token_usage': {'completion_tokens': 22,
'prompt_tokens': 143,
'total_tokens': 165,
'completion_tokens_details': {'accepted_prediction_tokens': 0,
'audio_tokens': 0,
'reasoning_tokens': 0,
'rejected_prediction_tokens': 0},
'prompt_tokens_details': {'audio_tokens': 0,
'cached_tokens': 0}},
'model_name': 'gpt-4o-2024-08-06',
'system_fingerprint': 'fp_eb9dce56a8',
'finish_reason': 'stop',
'logprobs': None},
id='run-6c00a336-7d52-4917-9186-b282a5984b10-0',
usage_metadata={'input_tokens': 143,
'output_tokens': 22,
'total_tokens': 165,
'input_token_details': {'audio': 0, 'cache_read': 0},
'output_token_details': {'audio': 0,
'reasoning': 0}})]}