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.choices0

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_calls0

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.content0.text

print("==== 最终的结果:",result)

六、使用大模型生成最终的结果,并且使用语言模型生成最终的结果

messages.append({

"role": "tool",

"content": tool_result.content0.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.choices0.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())

相关推荐
特立独行的猫A3 分钟前
我用仓颉写了个多平台发文工具:一份 Markdown,一条命令发六个平台
java·后端·python
进击的荆棘5 分钟前
MySQL——数据库基础
数据库·mysql
Decay__5 分钟前
22_MySQL 运维自动化平台 —— 部署编排 + 监控 + 巡检 + 告警 + 工单闭环一体化
运维·数据库·sql·mysql·架构
陆陆陆六17 分钟前
# 五个AI引擎的答案采集:反爬、去重与时间窗对齐的三个工程细节
python·net·ai答案采集
codeejun1 小时前
每日一Go·MySQL-11、覆盖索引 & 回表原理
javascript·数据库·mysql
.痞老板.1 小时前
java ee--计算机是如何工作的
java·开发语言·java-ee
奇树谦1 小时前
Qt Quick 图片加载与 GPU 纹理机制详解:QImage、QQuickTextureFactory、QSGTexture 与异步加载
开发语言·qt·系统架构
青梅味猪大肠1 小时前
【操作系统-60】临近适应算法
java·linux·开发语言·嵌入式硬件·算法·操作系统
CoderYanger1 小时前
Java EE 进阶:8.MyBatis 操作数据库(入门)(第一弹)
java·数据库·spring·面试·职场和发展·java-ee·mybatis
XLYcmy2 小时前
信息检索报告数字经济赋能城市低碳治理的路径研究——基于“传统数据库 + 生成式人工智能”双轮驱动的检索实践 检索实施与结果分析 Web of Science
数据库·ai·llm·prompt·ssci·deepseek·wos