优秀的编程知识分享平台

网站首页 > 技术文章 正文

用python实现MCP server及调试(python写mc插件)

nanyue 2025-07-14 20:18:54 技术文章 2 ℃

更深入了解,请参考
https://github.com/modelcontextprotocol/python-sdk

一 环境安装及mcp server代码

用的是python3.13, nodejs v20.18.0。

pip install uv

pip install mcp

pip install fastmcp

编写FastMCPTest.py脚本:

from mcp.server.fastmcp import FastMCP
# Create an MCP server
mcp = FastMCP("mcp_test")

# Add an addition tool
@mcp.tool()
def add(a: int, b: int) -> int:
   return a + b

@mcp.tool()
def sub(a: int, b: int) -> int
   return a - b

#资源模板
@mcp.resource("greeting://{name}")
def get_byebye(name: str) -> str:
    return f"bye, {name}!"

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


stdio方式编写的MCP服务不需要单独运行,而是由MCP客户端通过python或者uv命令触发运行。stdio模式本地直接调用Python代码,SSE模式跨机器HTTP交互。

二调试


2.1使用 Inspector 做调试

npx -y @modelcontextprotocol/inspector uv run FastMCPTest.py

或者mcp dev FastMCPTest.py 启动Inspector。


打开浏览器http://127.0.0.1:6274

点击上图左边的”Connect” 连接上MCP Server。


2.2 测试Tools

2.3 测试资源模板


三 使用cherry studio 测试

3.1设置mcp 服务


参数见

--directory

D:\src\work\AITester

run

FastMCPTest.py


如果连接失败,检查mcp服务器的JSON内容是否正确。

保存后:

3.2 发起会话测试

发起会话,勾选fastmcptest服务


四 使用visual studio的cline测试

五 使用mcp client调用

5.1 Client代码

from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
from mcp.client.sse import sse_client #sse服务器对应的客户端必须import sse_client
# Create server parameters for stdio connection
server_params2 = StdioServerParameters(
 command="uv", # Executable
 args=["--directory","D:\\src\\work\\AITester","run","FastMCPTest.py"], # Optional command line arguments
 env=None, # Optional environment variables
)
# Create server parameters for stdio connection
server_params = StdioServerParameters(
 command="python", # Executable
 args=["FastMCPTest.py"], # Optional command line arguments
 env=None, # Optional environment variables
)
# Optional: create a sampling callback
async def handle_sampling_message(
 message: types.CreateMessageRequestParams,
) -> types.CreateMessageResult:
 return types.CreateMessageResult(
 role="assistant",
 content=types.TextContent(
 type="text",
 text="MCPTest计算差值",
 ),
 model="deepseek-v3-250324",
 stopReason="endTurn",
 )

async def stdio_run():
  async with stdio_client(server_params) as (read, write):
    async with ClientSession(
     read, write, sampling_callback=handle_sampling_message
 ) as session:
    # Initialize the connection
    await session.initialize()
 
   # List available resources
   resources = await session.list_resources()
   print(f"resources={resources}")
   # List available tools
   tools = await session.list_tools()
   print(f"tools={tools}")
   result = await session.call_tool("sub", arguments={"a": "104","b": "21"})
   print(result)
   print(result.content[0].text)

 # 运行 client_run() 异步函数
async def client_sse_run():
   # 1. 异步上下文管理器 (SSE 客户端)
   async with sse_client(url="http://127.0.0.1:8000/sse") as streams:
   # 2. 异步上下文管理器 (HTTP 会话)
   async with ClientSession(*streams) as session:
     # 3. 等待初始化完成
    await session.initialize()
    # 4. 等待获取工具列表
    tools = await session.list_tools()
    print(tools)
    # 5. 等待调用工具 "aoe" 并获取结果
    result = await session.call_tool("sub", arguments={"a": 4, "b": 5})
    print(result.content[0].text)

if __name__ == "__main__":
   import asyncio
   #asyncio.run(stdio_run())
   asyncio.run(client_sse_run())


5.2 stdio模式

直接python.exe mcpclient.py 即可。


5.3 sse模式

启动python FastMCPTest.py服务。

直接python.exe mcpclient.py触发调用sse

Tags:

最近发表
标签列表