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())

相关推荐
我叫黑大帅9 分钟前
如何通过 Python 实现招聘平台自动投递
后端·python·面试
其实防守也摸鱼34 分钟前
CTF密码学综合教学指南--第九章
开发语言·网络·python·安全·网络安全·密码学·ctf
砚底藏山河37 分钟前
Python量化开发:2026最佳实时股票数据API接口推荐与对比
开发语言·windows·python
倔强的石头_1 小时前
kingbase备份与恢复实战(六)—— 备份自动化与保留策略:Windows任务计划+日志追溯
数据库
AlunYegeer1 小时前
JAVA,以后端的视角理解前端。在全栈的路上迈出第一步。
java·开发语言·前端
研究点啥好呢2 小时前
专为求职者开发的“面馆”!!!摆脱面试焦虑!!!
python·面试·开源·reactjs·求职招聘·fastapi
轻刀快马2 小时前
别被 ORM 框架宠坏了:从一场“订单消失”悬案,看懂 MySQL 为什么要强推 InnoDB
数据库·mysql
hixiong1232 小时前
C# OpenvinoSharp使用DINOv2模型进行图像相似度计算
开发语言·c#
DFT计算杂谈2 小时前
自动化脚本一键绘制三元化合物相图
java·运维·服务器·开发语言·前端·python·自动化
EW Frontier3 小时前
6G ISAC新范式:基于智能漏波天线的Wi‑Fi通感一体化系统设计与实测【附MATLAB+python代码】
开发语言·python·matlab·music·isac·doa·wi‑fi