mcp-lesson 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mcp_lesson-0.1.0/PKG-INFO +11 -0
- mcp_lesson-0.1.0/README.md +0 -0
- mcp_lesson-0.1.0/pyproject.toml +23 -0
- mcp_lesson-0.1.0/pyproject.toml.orig +23 -0
- mcp_lesson-0.1.0/src/mcp_lesson/.ipynb_checkpoints/__init__-checkpoint.py +1 -0
- mcp_lesson-0.1.0/src/mcp_lesson/.ipynb_checkpoints/__main__-checkpoint.py +2 -0
- mcp_lesson-0.1.0/src/mcp_lesson/.ipynb_checkpoints/server_weather-checkpoint.py +88 -0
- mcp_lesson-0.1.0/src/mcp_lesson/__init__.py +1 -0
- mcp_lesson-0.1.0/src/mcp_lesson/__main__.py +2 -0
- mcp_lesson-0.1.0/src/mcp_lesson/client3.py +126 -0
- mcp_lesson-0.1.0/src/mcp_lesson/server_weather.py +88 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: mcp-lesson
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Add your description here
|
|
5
|
+
Requires-Dist: httpx>=0.29.0
|
|
6
|
+
Requires-Dist: mcp>=2.3.0
|
|
7
|
+
Requires-Dist: openai>=3.60.0
|
|
8
|
+
Requires-Dist: python-dotenv>=1.2.4
|
|
9
|
+
Requires-Python: >=3.12
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
File without changes
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "mcp-lesson"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Add your description here"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"httpx>=0.29.0",
|
|
9
|
+
"mcp>=2.3.0",
|
|
10
|
+
"openai>=3.60.0",
|
|
11
|
+
"python-dotenv>=1.2.4",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
mcp-lesson = "mcp_lesson:main"
|
|
16
|
+
|
|
17
|
+
[[tool.uv.index]]
|
|
18
|
+
url = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
|
19
|
+
default = true
|
|
20
|
+
|
|
21
|
+
[build-system]
|
|
22
|
+
requires = ["uv_build>=0.13.10,<0.14.0"]
|
|
23
|
+
build-backend = "uv_build"
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "mcp-lesson"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Add your description here"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"httpx>=0.29.0",
|
|
9
|
+
"mcp>=2.3.0",
|
|
10
|
+
"openai>=3.60.0",
|
|
11
|
+
"python-dotenv>=1.2.4",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
mcp-lesson = "mcp_lesson:main"
|
|
16
|
+
|
|
17
|
+
[[tool.uv.index]]
|
|
18
|
+
url = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
|
19
|
+
default = true
|
|
20
|
+
|
|
21
|
+
[build-system]
|
|
22
|
+
requires = ["uv_build>=0.13.10,<0.14.0"]
|
|
23
|
+
build-backend = "uv_build"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .server_weather import main
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import httpx
|
|
3
|
+
from typing import Any
|
|
4
|
+
from mcp.server.mcpserver import MCPServer
|
|
5
|
+
|
|
6
|
+
mcp = MCPServer("weather")
|
|
7
|
+
|
|
8
|
+
#from mcp.server.fastmcp import FastMCP
|
|
9
|
+
# 初始化 MCP 服务器
|
|
10
|
+
#mcp = FastMCP("WeatherServer")
|
|
11
|
+
|
|
12
|
+
# OpenWeather API 配置
|
|
13
|
+
OPENWEATHER_API_BASE = "https://api.openweathermap.org/data/2.5/weather"
|
|
14
|
+
API_KEY = "3a221d0cbb0c70a0c97ddee240dc18a6" # 请替换为你自己的 OpenWeather API Key
|
|
15
|
+
USER_AGENT = "weather-app/1.0"
|
|
16
|
+
|
|
17
|
+
async def fetch_weather(city: str) -> dict[str, Any] | None:
|
|
18
|
+
"""
|
|
19
|
+
从 OpenWeather API 获取天气信息。
|
|
20
|
+
:param city: 城市名称(需使用英文,如 Beijing)
|
|
21
|
+
:return: 天气数据字典;若出错返回包含 error 信息的字典
|
|
22
|
+
"""
|
|
23
|
+
params = {
|
|
24
|
+
"q": city,
|
|
25
|
+
"appid": API_KEY,
|
|
26
|
+
"units": "metric",
|
|
27
|
+
"lang": "zh_cn"
|
|
28
|
+
}
|
|
29
|
+
headers = {"User-Agent": USER_AGENT}
|
|
30
|
+
async with httpx.AsyncClient() as client:
|
|
31
|
+
try:
|
|
32
|
+
response = await client.get(OPENWEATHER_API_BASE, params=params,
|
|
33
|
+
headers=headers, timeout=30.0)
|
|
34
|
+
response.raise_for_status()
|
|
35
|
+
return response.json() # 返回字典类型
|
|
36
|
+
except httpx.HTTPStatusError as e:
|
|
37
|
+
return {"error": f"HTTP 错误: {e.response.status_code}"}
|
|
38
|
+
except Exception as e:
|
|
39
|
+
return {"error": f"请求失败: {str(e)}"}
|
|
40
|
+
|
|
41
|
+
def format_weather(data: dict[str, Any] | str) -> str:
|
|
42
|
+
"""
|
|
43
|
+
将天气数据格式化为易读文本。
|
|
44
|
+
:param data: 天气数据(可以是字典或 JSON 字符串)
|
|
45
|
+
:return: 格式化后的天气信息字符串
|
|
46
|
+
"""
|
|
47
|
+
# 如果传入的是字符串,则先转换为字典
|
|
48
|
+
if isinstance(data, str):
|
|
49
|
+
try:
|
|
50
|
+
data = json.loads(data)
|
|
51
|
+
except Exception as e:
|
|
52
|
+
return f"无法解析天气数据: {e}"
|
|
53
|
+
# 如果数据中包含错误信息,直接返回错误提示
|
|
54
|
+
if "error" in data:
|
|
55
|
+
return f"{data['error']}"
|
|
56
|
+
# 提取数据时做容错处理
|
|
57
|
+
city = data.get("name", "未知")
|
|
58
|
+
country = data.get("sys", {}).get("country", "未知")
|
|
59
|
+
temp = data.get("main", {}).get("temp", "N/A")
|
|
60
|
+
humidity = data.get("main", {}).get("humidity", "N/A")
|
|
61
|
+
wind_speed = data.get("wind", {}).get("speed", "N/A")
|
|
62
|
+
# weather 可能为空列表,因此用 [0] 前先提供默认字典
|
|
63
|
+
weather_list = data.get("weather", [{}])
|
|
64
|
+
description = weather_list[0].get("description", "未知")
|
|
65
|
+
return (
|
|
66
|
+
f"城市{city}, {country}\n"
|
|
67
|
+
f"温度: {temp}°C\n"
|
|
68
|
+
f"湿度: {humidity}%\n"
|
|
69
|
+
f"风速: {wind_speed} m/s\n"
|
|
70
|
+
f"天气: {description}\n")
|
|
71
|
+
|
|
72
|
+
@mcp.tool()
|
|
73
|
+
async def query_weather(city: str) -> str:
|
|
74
|
+
"""
|
|
75
|
+
输入指定城市的英文名称,返回今日天气查询结果。
|
|
76
|
+
:param city: 城市名称(需使用英文)
|
|
77
|
+
:return: 格式化后的天气信息
|
|
78
|
+
"""
|
|
79
|
+
data = await fetch_weather(city)
|
|
80
|
+
return format_weather(data)
|
|
81
|
+
|
|
82
|
+
def main():
|
|
83
|
+
mcp.run(transport='stdio')
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
if __name__ == "__main__":
|
|
87
|
+
main()
|
|
88
|
+
#mcp.run(transport='stdio')
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .server_weather import main
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import os
|
|
3
|
+
import json
|
|
4
|
+
from typing import Optional
|
|
5
|
+
from contextlib import AsyncExitStack
|
|
6
|
+
from openai import OpenAI
|
|
7
|
+
from dotenv import load_dotenv
|
|
8
|
+
from mcp import ClientSession, StdioServerParameters
|
|
9
|
+
from mcp.client.stdio import stdio_client
|
|
10
|
+
|
|
11
|
+
load_dotenv()
|
|
12
|
+
|
|
13
|
+
class MCPClient:
|
|
14
|
+
def __init__(self):
|
|
15
|
+
"""初始化 MCP 客户端"""
|
|
16
|
+
self.exit_stack = AsyncExitStack()
|
|
17
|
+
self.openai_api_key = os.getenv("OPENAI_API_KEY") # 读取Key
|
|
18
|
+
self.base_url = os.getenv("BASE_URL") # 读取 URL
|
|
19
|
+
self.model = os.getenv("MODEL") # 读取 model
|
|
20
|
+
if not self.openai_api_key:
|
|
21
|
+
raise ValueError("未找到 OpenAI API Key")
|
|
22
|
+
self.client = OpenAI(api_key=self.openai_api_key, base_url=self.base_url)
|
|
23
|
+
|
|
24
|
+
self.session: Optional[ClientSession] = None
|
|
25
|
+
self.exit_stack = AsyncExitStack()
|
|
26
|
+
|
|
27
|
+
async def connect_to_server(self, server_script_path: str):
|
|
28
|
+
"""连接到 MCP 服务器并列出可用工具"""
|
|
29
|
+
is_python = server_script_path.endswith('.py')
|
|
30
|
+
is_js = server_script_path.endswith('.js')
|
|
31
|
+
## 判断服务器脚本是 Python 还是 Node.js,选择对应的运行命令
|
|
32
|
+
if not (is_python or is_js):
|
|
33
|
+
raise ValueError("服务器脚本必须是 .py 或 .js 文件")
|
|
34
|
+
command = "python" if is_python else "node"
|
|
35
|
+
## 告诉 MCP 客户端如何启动服务器
|
|
36
|
+
server_params = StdioServerParameters(
|
|
37
|
+
command=command,
|
|
38
|
+
args=[server_script_path],
|
|
39
|
+
env=None
|
|
40
|
+
)
|
|
41
|
+
# 启动 MCP 服务器并建立通信
|
|
42
|
+
stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
|
|
43
|
+
self.stdio, self.write = stdio_transport
|
|
44
|
+
self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
|
|
45
|
+
await self.session.initialize()
|
|
46
|
+
# 向 MCP 服务器请求所有已注册的工具(用 @mcp.tool() 标记)
|
|
47
|
+
response = await self.session.list_tools()
|
|
48
|
+
tools = response.tools
|
|
49
|
+
print("\n已连接到服务器,支持以下工具:", [tool.name for tool in tools])
|
|
50
|
+
|
|
51
|
+
## 这个本质就是Function call
|
|
52
|
+
async def process_query(self, query: str) -> str:
|
|
53
|
+
"""
|
|
54
|
+
使用大模型处理查询并调用可用的 MCP 工具 (Function Calling)
|
|
55
|
+
"""
|
|
56
|
+
messages = [{"role": "user", "content": query}]
|
|
57
|
+
response = await self.session.list_tools()
|
|
58
|
+
available_tools = [{
|
|
59
|
+
"type": "function",
|
|
60
|
+
"function": {
|
|
61
|
+
"name": tool.name,
|
|
62
|
+
"description": tool.description,
|
|
63
|
+
"input_schema": tool.input_schema
|
|
64
|
+
}
|
|
65
|
+
} for tool in response.tools]
|
|
66
|
+
# print(available_tools)
|
|
67
|
+
response = self.client.chat.completions.create(
|
|
68
|
+
model=self.model,
|
|
69
|
+
messages=messages,
|
|
70
|
+
tools=available_tools)
|
|
71
|
+
# 处理返回的内容
|
|
72
|
+
content = response.choices[0]
|
|
73
|
+
if content.finish_reason == "tool_calls":
|
|
74
|
+
# 如何是需要使用工具,就解析工具
|
|
75
|
+
tool_call = content.message.tool_calls[0]
|
|
76
|
+
tool_name = tool_call.function.name
|
|
77
|
+
tool_args = json.loads(tool_call.function.arguments)
|
|
78
|
+
# 执行工具
|
|
79
|
+
result = await self.session.call_tool(tool_name, tool_args)
|
|
80
|
+
print(f"\n\n[Calling tool {tool_name} with args {tool_args}]\n\n")
|
|
81
|
+
# 将模型返回的调用哪个工具数据和工具执行完成后的数据都存入messages中
|
|
82
|
+
messages.append(content.message.model_dump())
|
|
83
|
+
messages.append({
|
|
84
|
+
"role": "tool",
|
|
85
|
+
"content": result.content[0].text,
|
|
86
|
+
"tool_call_id": tool_call.id,})
|
|
87
|
+
|
|
88
|
+
# 将上面的结果再返回给大模型用于生产最终的结果
|
|
89
|
+
response = self.client.chat.completions.create(
|
|
90
|
+
model=self.model,
|
|
91
|
+
messages=messages,
|
|
92
|
+
)
|
|
93
|
+
return response.choices[0].message.content
|
|
94
|
+
return content.message.content
|
|
95
|
+
|
|
96
|
+
async def chat_loop(self):
|
|
97
|
+
"""运行交互式聊天循环"""
|
|
98
|
+
print("\n 智能助手客户端已启动!输入 'quit' 退出")
|
|
99
|
+
while True:
|
|
100
|
+
try:
|
|
101
|
+
query = input("\n用户: ").strip()
|
|
102
|
+
if query.lower() == 'quit':
|
|
103
|
+
break
|
|
104
|
+
response = await self.process_query(query) # 发送用户输入到 OpenAIAPI
|
|
105
|
+
print(f"\n天气预报智能助手: {response}")
|
|
106
|
+
except Exception as e:
|
|
107
|
+
print(f"\n发生错误: {str(e)}")
|
|
108
|
+
|
|
109
|
+
async def cleanup(self):
|
|
110
|
+
"""清理资源"""
|
|
111
|
+
await self.exit_stack.aclose()
|
|
112
|
+
|
|
113
|
+
async def main():
|
|
114
|
+
if len(sys.argv) < 2:
|
|
115
|
+
print("Usage: python client.py <path_to_server_script>")
|
|
116
|
+
sys.exit(1)
|
|
117
|
+
client = MCPClient()
|
|
118
|
+
try:
|
|
119
|
+
await client.connect_to_server(sys.argv[1])
|
|
120
|
+
await client.chat_loop()
|
|
121
|
+
finally:
|
|
122
|
+
await client.cleanup()
|
|
123
|
+
|
|
124
|
+
if __name__ == "__main__":
|
|
125
|
+
import sys
|
|
126
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import httpx
|
|
3
|
+
from typing import Any
|
|
4
|
+
from mcp.server.mcpserver import MCPServer
|
|
5
|
+
|
|
6
|
+
mcp = MCPServer("weather")
|
|
7
|
+
|
|
8
|
+
#from mcp.server.fastmcp import FastMCP
|
|
9
|
+
# 初始化 MCP 服务器
|
|
10
|
+
#mcp = FastMCP("WeatherServer")
|
|
11
|
+
|
|
12
|
+
# OpenWeather API 配置
|
|
13
|
+
OPENWEATHER_API_BASE = "https://api.openweathermap.org/data/2.5/weather"
|
|
14
|
+
API_KEY = "3a221d0cbb0c70a0c97ddee240dc18a6" # 请替换为你自己的 OpenWeather API Key
|
|
15
|
+
USER_AGENT = "weather-app/1.0"
|
|
16
|
+
|
|
17
|
+
async def fetch_weather(city: str) -> dict[str, Any] | None:
|
|
18
|
+
"""
|
|
19
|
+
从 OpenWeather API 获取天气信息。
|
|
20
|
+
:param city: 城市名称(需使用英文,如 Beijing)
|
|
21
|
+
:return: 天气数据字典;若出错返回包含 error 信息的字典
|
|
22
|
+
"""
|
|
23
|
+
params = {
|
|
24
|
+
"q": city,
|
|
25
|
+
"appid": API_KEY,
|
|
26
|
+
"units": "metric",
|
|
27
|
+
"lang": "zh_cn"
|
|
28
|
+
}
|
|
29
|
+
headers = {"User-Agent": USER_AGENT}
|
|
30
|
+
async with httpx.AsyncClient() as client:
|
|
31
|
+
try:
|
|
32
|
+
response = await client.get(OPENWEATHER_API_BASE, params=params,
|
|
33
|
+
headers=headers, timeout=30.0)
|
|
34
|
+
response.raise_for_status()
|
|
35
|
+
return response.json() # 返回字典类型
|
|
36
|
+
except httpx.HTTPStatusError as e:
|
|
37
|
+
return {"error": f"HTTP 错误: {e.response.status_code}"}
|
|
38
|
+
except Exception as e:
|
|
39
|
+
return {"error": f"请求失败: {str(e)}"}
|
|
40
|
+
|
|
41
|
+
def format_weather(data: dict[str, Any] | str) -> str:
|
|
42
|
+
"""
|
|
43
|
+
将天气数据格式化为易读文本。
|
|
44
|
+
:param data: 天气数据(可以是字典或 JSON 字符串)
|
|
45
|
+
:return: 格式化后的天气信息字符串
|
|
46
|
+
"""
|
|
47
|
+
# 如果传入的是字符串,则先转换为字典
|
|
48
|
+
if isinstance(data, str):
|
|
49
|
+
try:
|
|
50
|
+
data = json.loads(data)
|
|
51
|
+
except Exception as e:
|
|
52
|
+
return f"无法解析天气数据: {e}"
|
|
53
|
+
# 如果数据中包含错误信息,直接返回错误提示
|
|
54
|
+
if "error" in data:
|
|
55
|
+
return f"{data['error']}"
|
|
56
|
+
# 提取数据时做容错处理
|
|
57
|
+
city = data.get("name", "未知")
|
|
58
|
+
country = data.get("sys", {}).get("country", "未知")
|
|
59
|
+
temp = data.get("main", {}).get("temp", "N/A")
|
|
60
|
+
humidity = data.get("main", {}).get("humidity", "N/A")
|
|
61
|
+
wind_speed = data.get("wind", {}).get("speed", "N/A")
|
|
62
|
+
# weather 可能为空列表,因此用 [0] 前先提供默认字典
|
|
63
|
+
weather_list = data.get("weather", [{}])
|
|
64
|
+
description = weather_list[0].get("description", "未知")
|
|
65
|
+
return (
|
|
66
|
+
f"城市{city}, {country}\n"
|
|
67
|
+
f"温度: {temp}°C\n"
|
|
68
|
+
f"湿度: {humidity}%\n"
|
|
69
|
+
f"风速: {wind_speed} m/s\n"
|
|
70
|
+
f"天气: {description}\n")
|
|
71
|
+
|
|
72
|
+
@mcp.tool()
|
|
73
|
+
async def query_weather(city: str) -> str:
|
|
74
|
+
"""
|
|
75
|
+
输入指定城市的英文名称,返回今日天气查询结果。
|
|
76
|
+
:param city: 城市名称(需使用英文)
|
|
77
|
+
:return: 格式化后的天气信息
|
|
78
|
+
"""
|
|
79
|
+
data = await fetch_weather(city)
|
|
80
|
+
return format_weather(data)
|
|
81
|
+
|
|
82
|
+
def main():
|
|
83
|
+
mcp.run(transport='stdio')
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
if __name__ == "__main__":
|
|
87
|
+
main()
|
|
88
|
+
#mcp.run(transport='stdio')
|