网站首页 > 技术文章 正文
更深入了解,请参考
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') #ssestdio方式编写的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
猜你喜欢
- 2025-09-18 GPU集群扩展:Ray Serve与Celery的技术选型与应用场景分析
- 2025-09-18 【不背八股】2.操作系统-进程、线程、协程的基本理解
- 2025-09-18 两张图看透Android Handler使用与机制
- 2025-09-18 Spring Boot 3.x 日志配置与 Logback 集成指南
- 2025-09-18 解锁C++异步之力:高效并发编程指南
- 2025-09-18 Flutter框架分析(八)-Platform Channel
- 2025-09-18 原来你是这样打印日志的,怪不得天天背锅……
- 2025-09-18 .NET Aspire 9.4 发布了 CLI GA、交互式仪表板和高级部署功能
- 2025-09-18 27.8K!一把梭 LLM:LiteLLM 带你用一套接口召唤 100+ 大模型
- 2025-09-18 Rust异步编程神器:用Tokio轻松创建定时任务
- 最近发表
-
- 聊一下 gRPC 的 C++ 异步编程_grpc 异步流模式
- [原创首发]安全日志管理中心实战(3)——开源NIDS之suricata部署
- 超详细手把手搭建在ubuntu系统的FFmpeg环境
- Nginx运维之路(Docker多段构建新版本并增加第三方模
- 92.1K小星星,一款开源免费的远程桌面,让你告别付费远程控制!
- Go 人脸识别教程_piwigo人脸识别
- 安卓手机安装Termux——搭建移动服务器
- ubuntu 安装开发环境(c/c++ 15)_ubuntu安装c++编译器
- Rust开发环境搭建指南:从安装到镜像配置的零坑实践
- Windows系统安装VirtualBox构造本地Linux开发环境
- 标签列表
-
- cmd/c (90)
- c++中::是什么意思 (84)
- 标签用于 (71)
- 主键只能有一个吗 (77)
- c#console.writeline不显示 (95)
- pythoncase语句 (88)
- es6includes (74)
- sqlset (76)
- apt-getinstall-y (100)
- node_modules怎么生成 (87)
- chromepost (71)
- flexdirection (73)
- c++int转char (80)
- mysqlany_value (79)
- static函数和普通函数 (84)
- el-date-picker开始日期早于结束日期 (76)
- js判断是否是json字符串 (75)
- c语言min函数头文件 (77)
- asynccallback (87)
- localstorage.removeitem (77)
- vector线程安全吗 (73)
- java (73)
- js数组插入 (83)
- mac安装java (72)
- 无效的列索引 (74)
