MCP - 使用 fastmcp 编写 Client 调用 MCP Serverr - Streamable HTTP (三)
同样,MCP Server,可以运行在:
- 本地进程间管道(stdin/stdout)通信:Stdio
- 通过 HTTP 长链接通信:SSE 、 Streamable HTTP
本文讲解如果使用 fastmcp 如何跟 MCP Server(Streamable HTTP) 创建链接并调用 tools。这里都是手动调用 tools 没有使用任何大模型。
1、创建 client.py 并粘贴如下代码:
import asyncio
from fastmcp import Client
# 使用 config 配置方式
config = {
"mcpServers": {
"server": {
"url": "http://127.0.0.1:3002/weather",
"transport": "streamable-http"
}
}
}
# 初始化客户端
client = Client(config)
async def main():
async with client:
print("===== 调用 tools 列表查询 =====")
tools = await client.list_tools()
print(tools)
print("===== 调用工具 get_weather =====")
output = await client.call_tool("get_weather", {"city": "Tokyo"})
extracted_text = output.content[0].text
print(extracted_text)
if __name__ == "__main__":
asyncio.run(main())
代码中的 await client.call_tool("get_weather", {"city": "Tokyo"}) 需要根据 list_tools 后的结果修改,如下图

2、运行
2.1、启动 server
根据文章 https://www.cnblogs.com/rslai/p/19092832 介绍启动 server 端,运行成功如下图:

2.2、运行 client
重新启动一个终端,执行如下命令:
python client.py
运行后如下图:
- 右侧运行后可以看到,执行了两条命令。一个,查询所有 tools 列表。二,执行工具 get_weather
- 左侧可以看到 client 调用后服务器请求

源代码: mcp_client_http.zip

浙公网安备 33010602011771号