MCP - 使用 fastmcp 编写 Client 调用 MCP Serverr - Stdio(五)
在 MCP - 使用 fastmcp 编写 Client 调用 MCP Serverr - Streamable HTTP (三) 中讲解了如何写 MCP Serverr - Streamable HTTP 的 Client 。
下文将介绍如何写 MCP Serverr - Stdio 的 Client 。
1、server.py 文件将 mcp.run(transport="sse") 改为 mcp.run() ,如下图:
2、添加 client.py 代码如下:
# -*- coding: utf-8 -*-
import asyncio
from fastmcp import Client
async def test_stdio_client():
# 使用stdio传输方式连接
async with Client("server.py") as client:
print("===== 调用 tools 列表查询 =====")
tools = await client.list_tools()
print(tools)
print("===== 调用工具 get_weather =====")
result = await client.call_tool("get_weather", {"city": "Tokyo"})
extracted_text = result.content[0].text
print(extracted_text)
print("===== 调用 resources 列表查询 =====")
resources = await client.list_resources()
print(resources)
print("===== 读取城市列表资源 =====")
cities = await client.read_resource("weather://cities")
print(cities)
async def main():
await test_stdio_client()
if __name__ == "__main__":
asyncio.run(main())
3、运行 client.py
python client.py
运行后如图
源代码: https://pan.baidu.com/s/1-wOUPqHntgzsuNjfwcS4dQ?pwd=xjhq 提取码: xjhq

浙公网安备 33010602011771号