使用Langchain调用集成模型上下文协议(MCP)服务

使用Langchain调用集成模型上下文协议(MCP)服务

前面分享了如何使用MCP的服务,并应用于Cusor、Claude Desktop等应用上。鉴于项目需要调用各种能力完成复杂的操作,通过热插拔的形式集成各种工具,如Manus。这里我们也可以直接调用基于MCP协议的各种服务,调用其各种各样工具能力,增强我们模型或应用的外延能力。

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

LLM应用程序的一个关键焦点领域一直是数据传递方面。将数据传递给LLM进行推理,这一直是RAG实现、微调的目标,现在也是MCP的目标。

MCP的主要目的是标准化LLM应用程序如何连接到不同系统,如下图所示:

使用Langchain调用集成模型上下文协议(MCP)服务

AI代理面临的挑战是向AI代理传递数据,或者换句话说,将AI代理/基于LLM的应用程序集成到外部数据源。

人们一直在尝试通过利用GUI、网络浏览器和网络搜索来实现某种程度的无缝集成。所有这些途径都有优点和缺点。

使用Langchain调用集成模型上下文协议(MCP)服务

MCP有潜力作为一个通用接口,可以将其视为AI的虚拟/软件版USB-C。它实现了LLMs/AI代理与外部manus 教程资源之间无缝、安全和可扩展的数据交换。MCP使用客户端-服务器架构,其中MCP主机(AI应用程序)与MCP服务器(数据/工具提供者)进行通信。开发人员可以使用MCP构建可重用、模块化的连接器,流行平台上已经提供了预构建的服务器,从而创建了一个社区驱动的生态系统。MCP的开源特性鼓励创新,允许开发人员扩展其功能,同时通过精细权限等功能维护安全性。最终,MCP旨在将AI代理从孤立的聊天机器人转变为具有上下文感知、可互操作的系统,深度集成到数字环境中。

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

按顺序运行以下代码:

pip install langchain-mcp-adapters

创建服务器

vim server.py,创建如下内容并运行:

# 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

运行客户端

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_ollama import ChatOllama import asyncio  model = ChatOllama(model='qwen2.5:72b')  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

按顺序运行以下代码:

pip install langchain-mcp-tools

运行客户端

vim remote_client.py.创建如下内容,并运行:

# Standard library imports import asyncio import logging import os import sys  # Third-party imports try: from dotenv import load_dotenv from langchain.chat_models import init_chat_model from langchain.schema import HumanMessage from langchain_ollama import ChatOllama from langgraph.prebuilt import create_react_agent except ImportError as e: print(f'\nError: Required package not found: {e}') print('Please ensure all required packages are installed\n') sys.exit(1)  # Local application imports from langchain_mcp_tools import convert_mcp_to_langchain_tools  # A very simple logger def init_logger() -> logging.Logger: logging.basicConfig( level=logging.INFO, # logging.DEBUG, format='\x1b[90m[%(levelname)s]\x1b[0m %(message)s' ) return logging.getLogger()  async def run() -> None: # Be sure to set ANTHROPIC_API_KEY and/or OPENAI_API_KEY as needed load_dotenv()  # Check the api key early to avoid showing a confusing long trace if not os.environ.get('ANTHROPIC_API_KEY'): raise Exception('ANTHROPIC_API_KEY env var needs to be set') # if not os.environ.get('OPENAI_API_KEY'): # raise Exception('OPENAI_API_KEY env var needs to be set')  try: mcp_configs = { 'filesystem': { 'command': 'npx', 'args': [ '-y', '@modelcontextprotocol/server-filesystem', '.' # path to a directory to allow access to ] }, 'fetch': { 'command': 'uvx', 'args': [ 'mcp-server-fetch' ] }, 'weather': { 'command': 'npx', 'args': [ '-y', '@h1deya/mcp-server-weather' ] }, } tools, cleanup = await convert_mcp_to_langchain_tools( mcp_configs, init_logger() ) llm = ChatOllama(model='qwen2.5:72b') agent = create_react_agent( llm, tools ) # query = 'Read the news headlines on bbc.com' # query = 'Read and briefly summarize the LICENSE file' query = "Tomorrow's weather in SF?" print('\x1b[33m') # color to yellow print(query) print('\x1b[0m') # reset the color messages = [HumanMessage(content=query)] result = await agent.ainvoke({'messages': messages}) # the last message should be an AIMessage response = result['messages'][-1].content print('\x1b[36m') # color to cyan print(response) print('\x1b[0m') # reset the color finally: if cleanup is not None: await cleanup() def main() -> None: asyncio.run(run())  if __name__ == '__main__': main()

如果不出意外将出现,与下面类似的输出结束:

{'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}})]}

MCP是一种将AI代理与提供上下文和记忆的信息和服务集成的便捷方式。

github.com/hideya/langc

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:Ai探索者,转载请注明出处:https://javaforall.net/245267.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月15日 下午7:59
下一篇 2026年3月15日 下午7:59


相关推荐

关注全栈程序员社区公众号