-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweather_mcp_client.py
More file actions
123 lines (106 loc) · 4.54 KB
/
Copy pathweather_mcp_client.py
File metadata and controls
123 lines (106 loc) · 4.54 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#!/usr/bin/env python3
"""Minimal prompt-driven official MCP client for the weather server example."""
from __future__ import annotations
import asyncio
import json
import os
import sys
from typing import Any
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
SERVER_SCRIPT = ROOT / "examples" / "weather_mcp_server.py"
try:
from mcp.client.session import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client
except ModuleNotFoundError as exc: # pragma: no cover
raise RuntimeError("Install the optional MCP dependency first: pip install 'zero-context-protocol-sdk[mcp]'") from exc
try:
from openai import OpenAI
except ModuleNotFoundError as exc: # pragma: no cover
raise RuntimeError("Install the optional OpenAI dependency first: pip install 'zero-context-protocol-sdk[openai]'") from exc
def _model_client() -> OpenAI:
api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("DEEPSEEK_API_KEY")
if not api_key:
raise RuntimeError("Set OPENAI_API_KEY or DEEPSEEK_API_KEY before running this example.")
return OpenAI(
api_key=api_key,
base_url=os.environ.get("OPENAI_BASE_URL", "https://api.deepseek.com"),
)
def _tool_spec(tool: Any) -> dict[str, Any]:
return {
"type": "function",
"function": {
"name": tool.name,
"description": tool.description or "",
"parameters": tool.inputSchema,
"strict": True,
},
}
async def run(query: str) -> dict[str, object]:
async with stdio_client(
StdioServerParameters(
command=sys.executable,
args=[str(SERVER_SCRIPT)],
cwd=str(ROOT),
)
) as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
tools = await session.list_tools()
llm = _model_client()
model = os.environ.get("OPENAI_MODEL", "deepseek-chat")
messages: list[dict[str, Any]] = [
{
"role": "system",
"content": "You are a helpful weather assistant. Use tools when the user asks about weather. Keep the final answer concise.",
},
{
"role": "user",
"content": query,
},
]
tool_specs = [_tool_spec(tool) for tool in tools.tools]
tool_log: list[dict[str, Any]] = []
for _ in range(4):
response = llm.chat.completions.create(
model=model,
messages=messages,
tools=tool_specs,
tool_choice="auto",
)
message = response.choices[0].message
assistant_payload = message.model_dump(exclude_none=True)
messages.append(assistant_payload)
tool_calls = message.tool_calls or []
if not tool_calls:
return {
"tool_names": [tool.name for tool in tools.tools],
"tool_log": tool_log,
"answer": message.content,
}
for tool_call in tool_calls:
arguments = json.loads(tool_call.function.arguments or "{}")
result = await session.call_tool(tool_call.function.name, arguments)
payload: Any = result.structured_content
if payload is None and result.content:
payload = {"content": [block.text for block in result.content]}
tool_log.append({"name": tool_call.function.name, "arguments": arguments, "result": payload})
messages.append(
{
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(payload, ensure_ascii=False),
}
)
return {
"tool_names": [tool.name for tool in tools.tools],
"tool_log": tool_log,
"answer": "Model did not finish within the maximum number of tool rounds.",
}
def main() -> None:
query = " ".join(sys.argv[1:]) or "请查询 Hangzhou 当前天气,并用一句话总结。"
print(json.dumps(asyncio.run(run(query)), ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()