简单容易理解的MCP client实现

上篇文章介绍了简单容易理解的MCP server实现-CSDN博客 ,市面上很多应用可以调用别人写的MCP,如cherry-studio/Claude Desktop/ Cline等。但毕竟只能UI上操作。作为程序员自然通过程序调用的方式,使应用更加千变万化。

我们基于上篇的server,来实现client,通过大模型调用server的function

import os
from typing import List,Dict, Any
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
import asyncio
from langchain_mcp_adapters.client import MultiServerMCPClient

# 定义远程天气MCP 服务
weather_mcp_server_config ={
	"url":"http://127.0.0.1:8000/sse",
	"transport":"sse"
}

# 定义本地计算MCP 服务
math_mcp_server_config ={
	"command": "python",
	"args": ["mcp_local_server.py"],
	"transport":"stdio"
}

from langchain_modelscope import ModelScopeChatEndpoint
llm = ModelScopeChatEndpoint(model="Qwen/Qwen2.5-Coder-32B-Instruct")

prompt= ChatPromptTemplate.from_messages([
	('system','你是一个智能助手,尽可能的调用工具回答用户的问题'),
	MessagesPlaceholder(variable_name='chat_history', optional=True),
	('human','{input}'),
	MessagesPlaceholder(variable_name='agent_scratchpad', optional=True)
])

async def execute_workflow(user_input: str) -> Any:
	"""执行工作流的函数"""
	inputs ={"input": user_input}
	client = MultiServerMCPClient(
		{
			"math": math_mcp_server_config,  #添加多个MCP服务
			"weather": weather_mcp_server_config
		}
	)
	all_tools = await client.get_tools()
	print(all_tools)
	agent = create_tool_calling_agent(llm, all_tools, prompt)
	executor = AgentExecutor(agent=agent, tools=all_tools)
	response = await executor.ainvoke(input=inputs)
	result = response["output"]
	print(result)
	return result

if __name__ == '__main__':
	asyncio.run(execute_workflow("北京天气怎样?"))
	asyncio.run(execute_workflow("帮我计算计算两个数字20和12的密集是多少?")) # 保证调用本地mcp的语句

 大模型我们还用免费的modelscope(表扬阿里提供了AI学习成长环境),环境变量自己设好。运行前,把server运行起来。一个远程sse服务和本地stdio的配置已写在代码里。同样可以配置更多别人写的server。大模型运行时将判断是否调用服务 

上面可以看到所有服务的tools的功能会提前拉出来。

理解了实现了以后,是不是感觉现在可以随意调用别人的MCP了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值