前言
- 模型上下文协议(Model Context Protocol,MCP),是由Anthropic推出的开源协议,旨在实现大语言模型与外部数据源和工具的集成,用来在大模型和数据源之间建立安全双向的连接。
本文代码技术栈
Python 3.11.8 FastMCP 2.10.3
MCP 的传输机制
- Standard Input/Output (stdio)
- Streamable HTTP
- Server-Sent Events (SSE)(已被官方弃用)
- 本文使用
stdio
和Streamable HTTP
FastMCP stdio 示例
- MCP Server 代码
stdio_server.py
from fastmcp import FastMCP
mcp = FastMCP(name="StdioServer")
@mcp.tool
def hello(name: str) -> str:
return f"Hello, {name}!"
@mcp.tool
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
@mcp.tool
def multiply(a: float, b: float) -> float:
"""Multiplies two numbers."""
return a * b
if __name__ == "__main__":
mcp.run(transport="stdio")
- MCP Client 代码 stdio_client.py
import asyncio
from fastmcp import Client
from fastmcp.client.transports import StdioTransport
transport = StdioTransport(
command="D:/Python3Project/test_mcp/.venv/Scripts/python.exe",
args=["D:/Python3Project/test_mcp/stdio_server.py"]
)
async def main():
async with Client(transport) as client:
tools = await client.list_tools()
print(f"Available tools: {tools}")
result = await client.call_tool("add", {"a": 5, "b": 3})
print(f"Result: {result}")
if __name__ == "__main__":
asyncio.run(main())
stdio
模式下,由client
启动server
,不用单独运行server
,Windows cmd 运行结果如下,注意用其他终端可能报错RuntimeError: Client failed to connect: Connection closed
Available tools: [Tool(name='hello', title=None, description=None, inputSchema={'properties': {'name': {'title': 'Name', 'type': 'string'}}, 'required': ['name'], 'type': 'object'}, outputSchema={'properties': {'result': {'title': 'Result', 'type': 'string'}}, 'required': ['result'], 'title': '_WrappedResult', 'type': 'object', 'x-fastmcp-wrap-result': True}, annotations=None, meta=None), Tool(name='add', title=None, description='Add two numbers', inputSchema={'properties': {'a': {'title': 'A', 'type': 'integer'}, 'b': {'title': 'B', 'type': 'integer'}}, 'required': ['a', 'b'], 'type': 'object'}, outputSchema={'properties': {'result': {'title': 'Result', 'type': 'integer'}}, 'required': ['result'], 'title': '_WrappedResult', 'type': 'object', 'x-fastmcp-wrap-result': True}, annotations=None, meta=None), Tool(name='multiply', title=None, description='Multiplies two numbers.', inputSchema={'properties': {'a': {'title': 'A', 'type': 'number'}, 'b': {'title': 'B', 'type': 'number'}}, 'required': ['a', 'b'], 'type': 'object'}, outputSchema={'properties': {'result': {'title': 'Result', 'type': 'number'}}, 'required': ['result'], 'title': '_WrappedResult', 'type': 'object', 'x-fastmcp-wrap-result': True}, annotations=None, meta=None)]
Result: CallToolResult(content=[TextContent(type='text', text='8', annotations=None, meta=None)], structured_content={'result': 8}, data=8, is_error=False)
相关阅读
本文出自 qbit snap