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

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

MCP的火爆带来了很多的优质MCP服务,怎么将这些优质的MCP服务快速的集成到agent的能力上,除了官方的简单适配器外,我发现了一个宝藏Python库:mcpstore

mcpstore已经发布到PyPI上,使用pip install mcpstore就可以直接使用,作者设计的非常直观人性化,没有复杂的名称,还采用了链式调用,非常的直观。

store = MCPStore.setup_store()

store.for_store().add_service({"name": "mcpstore-wiki", "url": "https://mcpstore.wiki/mcp"})

tools = store.for_store().for_langchain().list_tools()

几行代码就可以直接使用tools了,这个tools列表是完全兼容langchain的,可以和我们已经通过@tool定义好的方法直接使用列表加法添加,作者还提供了一个可以直接运行的例子:

from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from mcpstore import MCPStore
store = MCPStore.setup_store()
store.for_store().add_service({"name":"mcpstore-wiki","url":"https://mcpstore.wiki/mcp"})
tools = store.for_store().for_langchain().list_tools()
# 如果要添加本地化的启动比较慢的服务 可以尝试time.sleep(5)一会
llm = ChatOpenAI(
    temperature=0, model="deepseek-chat",
    openai_api_key="sk-****",
    openai_api_base="httpss://api.deepseek.com"
)
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个助手,回答的时候带上表情"),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}"),
])
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
query = "北京的天气怎么样?"
print(f"\n   🤔: {query}")
response = agent_executor.invoke({"input": query})
print(f"   🤖 : {response['output']}")

只需要替换模型就可以直接使用了,本人亲测还是好用的。

🏪 Store设计思路

作者的思路是通过维护一个mcp.json文件作为一个**“store”**的开店基础,也就是说可以直接拿现在的通用的json文件直接生成一个store,每个store会维护好注册在他身上的这些服务,如果想要使用,直接use_tool就行,非常直观。

🔗 链式设计

另一个直观的点是,作者考虑到,一个store可能要维护过多的MCP服务,所以他设计了两个链:

  • store.for_store()
  • store.for_agent("agent_id")

其中for_store后面的方法就是操作store的for_agent的后面的方法就是操作一个agent的,所以如果某个agent只需要部分的MCP服务,可以直接给他量身定制一套MCP服务们,store会复杂维护心跳和更新,并且保证更加迅速的响应和记录,下面是作者的展示:

store = MCPStore.setup_store()

agent_id1 = "my-knowledge-agent"
knowledge_agent_context = store.for_agent(agent_id1).add_service(
    {"name": "mcpstore-wiki", "url": "https://mcpstore.wiki/mcp"}
)

agent_id2 = "my-development-agent"
dev_agent_context = store.for_agent(agent_id2).add_service(
    {"name": "mcpstore-demo", "url": "https://mcpstore.wiki/mcp"}
)

# 各Agent的工具集完全隔离,互不影响
knowledge_tools = store.for_agent(agent_id1).list_tools()
dev_tools = store.for_agent(agent_id2).list_tools()

🎨 可视化管理界面

对于你的store,作者的GitHub上有一个开源的Vue项目,可以通过简单的几行代码开启API模式,搭配Vue可以有一个前端点点点的维护store:

image-20250721212359929

可以通过 mcpstore run api 快速启动API模式,或者通过一段简单的代码:

from mcpstore import MCPStore
prod_store = MCPStore.setup_store()
prod_store.start_api_server(
    host='0.0.0.0',
    port=18200
)

快速启动后端,clone项目之后npm run dev即可运行Vue的前端。

也可以通过 https://www.mcpstore.wiki/web_demo/dashboard 来快速体验

🔧 灵活的服务注册

对于服务的增删改查,作者尽可能的兼容各种各样的格式,保证用户可以不需要太过于专注格式,只要不冲突并且关键的配置对就行,所以支持市面上常见的字典和列表等等格式,主流的Client的json配置文件都可以直接使用,非常方便。

📄 自动加载配置文件

注册 mcp.json 配置文件中的所有服务:

store.for_store().add_service()

不传递任何参数,add_service自动查找并加载项目根目录下的 mcp.json 文件,该文件兼容主流格式

🌐 远程服务注册

通过 URL 添加远程 MCP 服务:

store.for_store().add_service({
    "name": "mcpstore-wiki",
    "url": "https://mcpstore.wiki/mcp",
    "transport": "streamable-https"
})
  • transport: 可选字段,可以自动推断传输协议 (streamable-https, sse)

💻 本地服务进程

启动本地 MCP 服务进程:

# Python 服务
store.for_store().add_service({
    "name": "local_assistant",
    "command": "python",
    "args": ["./assistant_server.py"],
    "env": {"DEBUG": "true", "API_KEY": "your_key"},
    "working_dir": "/path/to/service"
})

# Node.js 服务
store.for_store().add_service({
    "name": "node_service",
    "command": "node",
    "args": ["server.js", "--port", "8080"],
    "env": {"NODE_ENV": "production"}
})

# 可执行文件
store.for_store().add_service({
    "name": "binary_service",
    "command": "./mcp_server",
    "args": ["--config", "config.json"]
})

📄 标准配置格式

使用标准 MCP 配置格式:

store.for_store().add_service({
  "mcpServers": {
    "mcpstore-wiki": {
      "url": "https://mcpstore.wiki/mcp"
    },
    "howtocook": {
      "command": "npx",
      "args": [
        "-y",
        "howtocook-mcp"
      ]
    }
  }
})

🎯 选择性注册

从现有配置中选择特定服务注册:

# 注册指定的服务
store.for_store().add_service(['mcpstore-wiki', 'howtocook'])

# 注册单个服务
store.for_store().add_service(['howtocook'])

📁 外部文件配置

从外部 JSON 文件读取配置:

store.for_store().add_service(json_file="./demo_config.json")

JSON 文件格式示例

{
  "mcpServers": {
    "mcpstore-wiki": {
      "url": "https://mcpstore.wiki/mcp"
    },
    "howtocook": {
      "command": "npx",
      "args": [
        "-y",
        "howtocook-mcp"
      ]
    }
  }
}

以及 add_service 支持的其他格式 📝:

{
    "name": "mcpstore-wiki",
    "url": "https://mcpstore.wiki/mcp"
}

🎯 总结

总之,该项目更新比较频繁,感觉作者也在全力做一个直观好用的MCP管理包,对于Langchain集成MCP服务或许是一个不错的选择。

LangChain调用MCP服务有多种方法,以下为你详细介绍: - **实现MCP调用流程**:可通过模拟一个简单的算术计算器,基于MCP Server运行,并使用MCP Client进行调用,最终集成DeepSeek大模型完成整个MCP调用流程。还提供了Python示例代码以供参考[^1]。 - **开发自定义MCP Server与Client调用**:通过LangChain开发自定义MCP Server,利用langgraph.prebuilt提供的预定义代理(Agent)模板结合DeepSeek实现MCP Client的调用[^2]。 - **使用标准MCP配置格式**:使用如下标准MCP配置格式添加服务,如本地服务进程配置示例: ```python store.for_store().add_service({ "mcpServers": { "mcpstore-wiki": { "url": "https://mcpstore.wiki/mcp" }, "howtocook": { "command": "npx", "args": [ "-y", "howtocook-mcp" ] } } }) ``` [^4] - **利用MCPStore进行配置**:mcpstore已发布到PyPI上,可使用`pip install mcpstore`直接安装使用。其设计直观人性化,采用链式调用。示例代码如下: ```python store = MCPStore.setup_store() store.for_store().add_service({"name": "mcpstore-wiki", "url": "https://mcpstore.wiki/mcp"}) tools = store.for_store().for_langchain().list_tools() ``` [^5] MCP有潜力作为一个通用接口,实现了LLMs/AI代理与外部资源之间无缝、安全和可扩展的数据交换。它使用客户端 - 服务器架构,开发人员可使用MCP构建可重用、模块化的连接器,流行平台上也提供了预构建的服务器,形成了社区驱动的生态系统。其开源特性鼓励创新,同时通过精细权限等功能维护安全性,旨在将AI代理从孤立的聊天机器人转变为具有上下文感知、可互操作的系统,深度集成到数字环境中[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值