使用 uv 创建项目和依赖
1
2
3
4
5
uv init mcp-client-demo
uv add "mcp[cli]"
pip install mcp
编写 mcp_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="python", # Executable
args=[
"mcp_demo1.py"
],# Optional command line arguments
env=None # Optional environment variables
)
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the connection
await session.initialize()
# List available tools
tools = await session.list_tools()
print("Tools:", tools)
# call a tool
score = await session.call_tool(name="get_weather",arguments={"city": "上海"})
print("weather: ", score)
if __name__ == "__main__":
import asyncio
asyncio.run(run())
运行代码,可以看到输出
