LangChain + 模型上下文协议

MCP源于解决大型语言模型(LLM)应用的一个关键限制,即它们与外部数据源和工具隔离的问题。

LangChain + 模型上下文协议

MCP源于解决大型语言模型(LLM)应用的一个关键限制,即它们与外部数据源和工具隔离的问题。

LLM驱动的应用程序的一个主要关注点是数据交付。将数据传递给LLM进行推理,这是RAG实现、微调以及MCP的目标。

MCP的主要目的是标准化LLM驱动的应用程序连接到各种系统的机制,如下图所示:


1、消除自定义集成

将AI代理/LLM驱动的应用程序与外部数据源集成存在挑战。

已经有许多尝试通过利用GUI、网页浏览器和网络搜索来实现某种无缝集成。所有这些途径都有其优势和劣势。

MCP有潜力作为一个通用接口,可以将其视为AI的虚拟/软件版本USB-C。

它能够使LLM/AI代理与外部资源之间的数据交换变得无缝、安全和可扩展。

MCP采用客户端-服务器架构,其中MCP主机(AI应用程序)与MCP服务器(数据/工具提供者)通信。

开发者可以使用MCP构建可重用的模块化连接器,为流行的平台提供预构建的服务器,从而创建一个社区驱动的生态系统。

MCP的开源性质鼓励创新,允许开发者扩展其功能,同时通过细粒度权限等功能保持安全性。

最终,MCP旨在将AI代理从孤立的聊天机器人转变为与数字环境深度集成的上下文感知、互操作系统。

2、使用说明

Anthropic的模型上下文协议(MCP)是一个开源协议,用于连接LLM与上下文、工具和提示。它拥有越来越多的连接到各种工具或数据源的服务器。在这里,我们将展示如何将任何MCP服务器连接到LangGraph代理并使用MCP工具……

如果你像我一样,无论多么简单的原型工作都能带来极大的清晰感和理解力;至少在我自己的脑海中是这样的。

要开始,请打开终端应用程序……以下是在MacBook上找到它的位置

在终端窗口中,创建两个标签页;其中一个用于运行服务器,另一个用于运行客户端。

创建虚拟环境以安装和运行代码是一个好习惯;下面的命令创建名为MCP_Demo的虚拟环境。

python3 -m venv MCP_Demo

然后运行以下命令以激活(进入)虚拟环境:

source MCP_Demo/bin/activate

你会看到你的命令提示符更新为(MCP_Demo)

按顺序运行以下代码行:

pip install langchain-mcp-adapters
pip install langchain-mcp-adapters
export OPENAI_API_KEY=<your_api_key>

将文本<your_api_key>替换为你的OpenAI API密钥。

在其中一个终端标签页中,创建一个文本文件:vim server.py

并将以下Python代码粘贴进去:

# math_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

你不会看到任何输出,终端标签页看起来会是这样的:

现在我们将创建并运行客户端……

当一个标签页中的MCP服务器正在运行时,转到第二个标签页……

创建一个文件以粘贴客户端代码:vim 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)

使用命令python3 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}})]}

3、结束语

MCP 是一种方便的集成方式,可以将AI代理与提供上下文和记忆的信息和服务结合起来。


原文链接:Using LangChain With Model Context Protocol (MCP)

汇智网翻译整理,转载请标明出处