服务端


from mcp.server.fastmcp import FastMCP
from pywin.framework.toolmenu import tools

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):
    """
    计算两个数只差,y是不能为0的
    :param x: 第一个整数
    :param y: 第二个整数
    :return: 两个整数只差
    """
    return x-y

if __name__ == '__main__':
    mcp.run(transport="sse")

客户端:

from openai import OpenAI
import asyncio
from mcp import ClientSession
from mcp.client.sse import sse_client
import json
ali = OpenAI(
            api_key="sk-3ad75cfac6b********f8d3d473b2a",
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
        )

SERVER_URL = "http://127.0.0.1:8000/sse"

async def main():
    # 2. 建立 SSE 长连接
    async with sse_client(url=SERVER_URL) as (read, write):
        # 3. 创建 MCP 会话
        async with ClientSession(read, write) as session:
            await session.initialize()

            # 4. 枚举服务器提供的工具
            toolsResult = await session.list_tools()
            tools = [
                {"type": "function",
                 "function": {
                     "name": tool.name,
                     "description": tool.description,
                     "parameters": tool.inputSchema
                 }
                 } for tool in toolsResult.tools
            ]
            print(tools)
            messages = [
                {
                    "role": "user",
                    "content": "我想知道五加八等于多少"
                }
            ]
            model_response = ali.chat.completions.create(
                model="qwen-turbo",
                messages=messages,
                tools=tools,
            )
            tool_result = await session.call_tool(
                name=model_response.choices[0].message.tool_calls[0].function.name,
                arguments=json.loads(model_response.choices[0].message.tool_calls[0].function.arguments)
            )
            print(tool_result)

asyncio.run(main())
toolsResult:
ListToolsResult(meta=None, nextCursor=None, tools=[Tool(name='add_tool', title=None, description='\n    计算两数之和\n    :param x: 第一个整数\n    :param y: 第二个整数\n    :return: 两数之和\n    ', inputSchema={'properties': {'x': {'title': 'X', 'type': 'integer'}, 'y': {'title': 'Y', 'type': 'integer'}}, 'required': ['x', 'y'], 'title': 'add_toolArguments', 'type': 'object'}, outputSchema=None, annotations=None, meta=None), Tool(name='sub_tool', title=None, description='\n    计算两个数只差,y是不能为0的\n    :param x: 第一个整数\n    :param y: 第二个整数\n    :return: 两个整数只差\n    ', inputSchema={'properties': {'x': {'title': 'X', 'type': 'integer'}, 'y': {'title': 'Y', 'type': 'integer'}}, 'required': ['x', 'y'], 'title': 'sub_toolArguments', 'type': 'object'}, outputSchema=None, annotations=None, meta=None)])

tools:

[{'type': 'function',
  'function': {'name': 'add_tool',
   'description': '\n    计算两数之和\n    :param x: 第一个整数\n    :param y: 第二个整数\n    :return: 两数之和\n    ',
   'parameters': {'properties': {'x': {'title': 'X', 'type': 'integer'},
     'y': {'title': 'Y', 'type': 'integer'}},
    'required': ['x', 'y'],
    'title': 'add_toolArguments',
    'type': 'object'}}},
 {'type': 'function',
  'function': {'name': 'sub_tool',
   'description': '\n    计算两个数只差,y是不能为0的\n    :param x: 第一个整数\n    :param y: 第二个整数\n    :return: 两个整数只差\n    ',
   'parameters': {'properties': {'x': {'title': 'X', 'type': 'integer'},
     'y': {'title': 'Y', 'type': 'integer'}},
    'required': ['x', 'y'],
    'title': 'sub_toolArguments',
    'type': 'object'}}}]

model_response:

ChatCompletion(id='chatcmpl-f0824309-6685-48f0-a61f-54fbedb1a68c', choices=[Choice(finish_reason='tool_calls', index=0, logprobs=None, message=ChatCompletionMessage(content='', refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=[ChatCompletionMessageFunctionToolCall(id='call_24daf68301a34104980a02', function=Function(arguments='{"x": 5, "y": 8}', name='add_tool'), type='function', index=0)]))], created=1763368514, model='qwen-turbo', object='chat.completion', service_tier=None, system_fingerprint=None, usage=CompletionUsage(completion_tokens=25, prompt_tokens=357, total_tokens=382, completion_tokens_details=None, prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cached_tokens=0)))

tool_result:

CallToolResult(meta=None, content=[TextContent(type='text', text='13', annotations=None, meta=None)], structuredContent=None, isError=False)

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐