news 2026/2/11 14:31:44

python mcp see

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
python mcp see

"""3.1 【stdio模式】mcp服务端开发"""
#导入mcp依赖包
from mcp.server.fastmcp import FastMCP
#创建mcp实例
mcp = FastMCP("Tool MCP Server")

@mcp.tool()
def add_tool(x:int,y:int):
"""
有两个数字相加的加法工具
:param x: 第一个数字
:param y: 第二个数字
:return: 两个数字的和
"""
return x+y

@mcp.tool()
def sub_tool(x:int,y:int):
"""
有两个数字相减的减法工具
:param x: 第一个数字
:param y: 第二个数字
:return: 两个数字的差
"""
return x-y

if __name__ == "__main__":
print(" MCP Server Start!")
#启动mcp服务:有两种协议,分别是stdio和tcp,stdio模式下,transport参数必须为stdio
mcp.run(transport="sse")


"""3.2 【stdio模式】mcp客户端开发—连接服务端"""
import asyncio
import json
from contextlib import AsyncExitStack

from mcp import StdioServerParameters, stdio_client, ClientSession
from mcp.client.sse import sse_client
from openai import OpenAI
import time


class MCPClient:

def __init__(self):
self.async_exit_stack = AsyncExitStack()
self.session = None
self.deepseek = OpenAI(
api_key="sk-304d80ba4865490283ec012fcdfa568a",
base_url="https://api.deepseek.com"
)


async def connect_to_server(self,url:str):
# 一 、创建stdio_client
client = sse_client(url=url)
transport = await self.async_exit_stack.enter_async_context(client)
print('----------------------transport---------------------------')
print(transport)
print('----------------------transport---------------------------')
read_stream, write_stream = transport
print('----------------read_stream, write_stream------------------')
print(read_stream,write_stream)
print('----------------read_stream, write_stream------------------')

# 二、创建会话client
client_session = ClientSession(read_stream, write_stream)
self.session = await self.async_exit_stack.enter_async_context(client_session)
# 三、初始化会话
await self.session.initialize()

async def execute(self,query:str):
# 一、获取server服务端中的工具列表
response = await self.session.list_tools()
list_tools = response.tools
print("responce",response)
print("打印出获取的工具列表:",list_tools)
#二、创建function calling 格式(大模型使用)、
tools =[
{
"type":"function",
"function":{
"name":tool.name,
"description":tool.description,
"parameters":tool.inputSchema
}
} for tool in list_tools
]
print('------------tools-------------------')
print(tools)
print('------------tools-------------------')

# 三、 创建messages,deepseek大模型的格式
messages = [
{
"role":"user",
"content":query
}
]
print ('--------------------message0-----------------')
print(messages)
print('--------------------message0-----------------')

# 四、调用deepseek大模型
print('---------------message1--------------------')
print(messages)
print('---------------message1--------------------')
deepseek_response = self.deepseek.chat.completions.create(
model="deepseek-chat",
messages=messages,
tools=tools
)
# 打印出大模型的决策结果
print("==== deepseek 响应持结果:",deepseek_response)
choice_result = deepseek_response.choices[0]
print('--------------choice_result---------------------')
print(choice_result)
print('--------------choice_result---------------------')


#第二次调用大模型的前置参数
messages.append(choice_result.message.model_dump())
print('----------------messages2----------------')
print(messages)
print('----------------messages2----------------')
tool_call = choice_result.message.tool_calls[0]

print(" tool_call:",tool_call)
print("大模型决策的最终结果,工具名称:",tool_call.function.name,",参数:",tool_call.function.arguments)
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)

print('------function_name,arguments-------------------')
print(function_name,arguments)
print('------function_name,arguments-------------------')

# 五、调用工具链
tool_result = await self.session.call_tool(
name = function_name,
arguments=arguments
)
print("==== 工具调用结果:",tool_result)
#最终的结果
result = tool_result.content[0].text
print("==== 最终的结果:",result)

# 六、使用大模型生成最终的结果,并且使用语言模型生成最终的结果
messages.append({
"role": "tool",
"content": tool_result.content[0].text,
"tool_call_id": tool_call.id
})

print('----------------messages3----------------')
print(messages)
print('----------------messages3----------------')
# 再次调用大模型
deepseek_response = self.deepseek.chat.completions.create(
model="deepseek-chat",
messages=messages,
tools=tools,
)
# 获取最终的结果
result = deepseek_response.choices[0].message.content
print("==== 最终的结果:", result)


#关闭资源
async def aclose(self):
await self.async_exit_stack.aclose()

async def main():
client = MCPClient()

await client.connect_to_server("http://127.0.0.1:8000/sse")
await client.execute("帮我计算一下2加3等于几?")


await client.aclose()

if __name__ == "__main__":
asyncio.run(main())

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/2/8 5:46:03

大数据领域 OLAP 的维度建模与业务需求匹配

大数据领域 OLAP 的维度建模与业务需求匹配关键词:大数据、OLAP、维度建模、业务需求匹配、数据仓库摘要:本文聚焦于大数据领域中 OLAP 的维度建模与业务需求匹配这一关键问题。首先介绍了研究背景,包括目的范围、预期读者等。接着阐述了维度…

作者头像 李华
网站建设 2026/2/8 3:09:30

谷歌浏览器护眼插件使用

电脑看久了眼睛很累,谷歌浏览器可以通过安装扩展插件的方式,让网页的颜色变成护眼模式,保护眼睛。安装插件具体操作:找到‘访问谷歌应用商店’(有可能打不开,打不开就要用魔法,只需要在第一次安…

作者头像 李华
网站建设 2026/2/4 12:03:33

飞算科技JavaAI引领行业智能化转型

在软件开发领域,Java作为应用场景广泛的主流编程语言,其工程开发环节正面临效率瓶颈凸显、代码质量波动、人力成本攀升等多重挑战。推动Java工程智能化升级,已成为行业实现高质量发展必须解决的核心课题。飞算数智科技(深圳&#…

作者头像 李华
网站建设 2026/2/8 1:53:20

COZE编程-起飞起飞起飞(一句话生成你的应用)

从零构建智能体、工作流与应用等等的方法描述你的需求:等等等等最终的智能体问:搜索过去2个月的招聘行业政策并分析影响评测说明:1.效果偏差,但是基本能否完成2.功能是真多3.市场反应真快其他主推的workflow生成:refly…

作者头像 李华
网站建设 2026/2/7 22:14:40

测试工具创新:驱动软件质量新纪元

创新为何至关重要 在数字化浪潮中,软件已渗透至各行各业,从金融交易到医疗设备,无不依赖高质量代码。然而,传统测试方法如手动测试和脚本化自动化已难以应对日益复杂的系统。测试工具创新通过引入智能化、集成化和用户友好化元素…

作者头像 李华