第十章补充:天气 MCP 案例与 Tool 统一抽象

创建时间:2026-09-15 18:41:05 +08:00
更新时间:2026-09-15 18:41:05 +08:00
来源:Hello-Agents Chapter 10 官方 14_weather_mcp_server.py、14_weather_agent.py + 当前已检查的 MCPTool / MCPWrappedTool / ToolRegistry 实现
状态:源码总结完成;天气案例尚未在本地真实运行,不标记为已复现

本附录只解决两个问题:① 最后的天气案例里,Agent 使用 MCP 到底是怎么“注册 → 发现 → 展开 → 调用”的;② 为什么 MemoryTool / RAGTool / MCPTool / TerminalTool / NoteTool 都能被 Agent 当成 Tool,但底层职责完全不同。


1. 天气案例先看结论:实际上有“两次注册”

官方最后的天气案例不是 @mcp.tool() + ReActAgent 的写法,而是:

1
2
Server 端:MCPServer.add_tool(...)
Agent 端:SimpleAgent + MCPTool + get_expanded_tools() + add_tool(...)

所以它有两个不同层次的“注册”:

注册位置 注册对象 注册后谁能发现 作用
Weather MCP Server get_weather 等 Python 函数 MCP Client 把本地函数暴露成远程 MCP Tool
SimpleAgent / ToolRegistry MCPWrappedTool Agent / LLM 把远程 MCP Tool 适配成本地 Agent Tool

最值得记住:

1
2
3
4
5
Server 端注册
= Python Function → Remote MCP Tool

Agent 端注册
= Remote MCP Tool → Local HelloAgents Tool

2. Server 端:把天气函数注册为 MCP Tool

官方 14_weather_mcp_server.py 先创建服务:

1
2
3
4
weather_server = MCPServer(
name="weather-server",
description="真实天气查询服务"
)

然后定义三个普通 Python 函数:

1
2
3
get_weather(city)
list_supported_cities()
get_server_info()

最后显式注册:

1
2
3
weather_server.add_tool(get_weather)
weather_server.add_tool(list_supported_cities)
weather_server.add_tool(get_server_info)

并通过:

1
weather_server.run()

启动服务。

因此这一阶段的数据结构可以理解为:

1
2
3
4
Weather MCP Server Tool Registry
├── get_weather → Python get_weather()
├── list_supported_cities → Python list_supported_cities()
└── get_server_info → Python get_server_info()

get_weather() 内部最终调用:

1
2
3
4
5
6
7
get_weather(city)
↓
get_weather_data(city)
↓
requests.get("https://wttr.in/<city>?format=j1")
↓
真实天气 JSON

设计模式:Registry / Command-like Capability Registration

项目 说明
模式 / 架构思想 Registry + Command-like Capability Registration
代码位置 weather_server.add_tool(get_weather) 等
解决的问题 Server 如何通过字符串 Tool Name 找到真正的 Python Callable
好处 新增 Tool 只需注册函数;Client 可以动态 list_tools()
代价 / 边界 Tool Name 冲突、Schema 版本、权限和副作用治理仍需额外处理

3. Agent 端:MCPTool 不是最终的天气工具,而是“协议入口”

官方 14_weather_agent.py:

1
2
3
4
5
6
7
assistant = SimpleAgent(
name="天气助手",
llm=llm,
system_prompt="""你是天气助手,可以查询城市天气。
使用 mcp_get_weather 工具查询天气,支持中文城市名。
"""
)

然后创建:

1
2
3
4
5
6
7
8
server_script = os.path.join(
os.path.dirname(__file__),
"14_weather_mcp_server.py"
)

weather_tool = MCPTool(
server_command=["python", server_script]
)

这里的 weather_tool 不能简单等价于 get_weather。它更像:

1
2
MCPTool
= “我知道如何连接这个 MCP Server,并发现 / 调用它的能力”

MCPTool 初始化时做了什么

当前检查到的实现中,MCPTool.__init__() 会执行:

1
2
3
4
5
6
7
8
9
10
11
MCPTool(...)
↓
_discover_tools()
↓
创建 MCPClient
↓
通过 server_command 启动 / 连接 Server
↓
client.list_tools()
↓
保存 Remote Tool Schema 到 _available_tools

因此天气 Server 会返回类似:

1
2
3
get_weather
list_supported_cities
get_server_info

这一步叫:

1
Capability Discovery

它和“注册给 Agent”还不是一回事。


4. 为什么还要 get_expanded_tools()

官方天气 Agent 明确写:

1
2
3
4
5
6
7
expanded_tools = weather_tool.get_expanded_tools()

if not expanded_tools:
raise RuntimeError(...)

for expanded_tool in expanded_tools:
assistant.add_tool(expanded_tool)

get_expanded_tools() 会遍历 _available_tools,为每一个远程 MCP Tool 创建一个 MCPWrappedTool:

1
2
3
4
5
Remote MCP Tool Schema
↓
MCPWrappedTool
↓
HelloAgents Tool

默认 MCPTool 名称是:

1
mcp

自动展开时前缀为:

1
mcp_

所以:

1
2
3
4
5
Remote Tool              Agent Local Tool
----------- ----------------
get_weather → mcp_get_weather
list_supported_cities → mcp_list_supported_cities
get_server_info → mcp_get_server_info

这就是为什么官方 system prompt 会写:

1
使用 mcp_get_weather 工具查询天气

5. 时序图一:初始化、工具发现与 Agent 注册

这张图专门看“Agent 运行之前,天气 MCP Tool 是怎么进入 ToolRegistry 的”。这是把前面绘制的概念图按官方最终天气源码校正后的版本。

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
sequenceDiagram
participant A as SimpleAgent
participant M as MCPTool
participant C as MCPClient
participant T as Stdio Transport
participant S as Weather MCP Server
participant W as MCPWrappedTool
participant R as ToolRegistry

Note over S: Python 启动 server 脚本时<br/>创建 MCPServer 并 add_tool 三个函数

A->>M: MCPTool(server_command=[python, 14_weather_mcp_server.py])
M->>M: __init__() → _discover_tools()
M->>C: 创建 MCPClient(server_command)
C->>T: 建立 stdio Client/Server 通道
T->>S: 启动 weather_server.run()
M->>C: list_tools()
C->>S: MCP list_tools 请求
S-->>C: get_weather / list_supported_cities / get_server_info
C-->>M: Remote Tool Schemas
M->>M: 保存到 _available_tools

A->>M: get_expanded_tools()
loop 每个 Remote Tool Schema
M->>W: 创建 MCPWrappedTool(tool_info, prefix="mcp_")
W-->>A: 返回本地 Tool 对象
A->>R: add_tool(expanded_tool)
R->>R: register_tool(name → Tool)
end

Note over R: 最终包含<br/>mcp_get_weather<br/>mcp_list_supported_cities<br/>mcp_get_server_info

这张图最重要的三个节点

1
2
3
4
5
6
7
8
① list_tools()
= 远程能力发现

② get_expanded_tools()
= Remote Tool Schema → Local Tool Adapter

③ assistant.add_tool()
= 真正注册进 Agent ToolRegistry

因此不要把:

1
MCPTool(...)

直接理解成:

1
“一个天气查询函数”

更准确是:

1
“一个 MCP Server 的连接 / 发现 / 调用入口”

6. 时序图二:用户查询北京天气时的完整调用链

这张图专门看“工具已经注册后,一次真实 Agent Tool Call 怎么穿过 MCP 到达天气函数”。

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
sequenceDiagram
actor U as User
participant A as SimpleAgent / LLM
participant R as ToolRegistry
participant W as MCPWrappedTool<br/>mcp_get_weather
participant M as MCPTool
participant C as MCPClient
participant T as Stdio Transport
participant S as Weather MCP Server
participant API as wttr.in

U->>A: 北京今天天气怎么样?
A->>A: 根据 Tool 描述判断需要 mcp_get_weather
A->>R: 获取 / 执行 mcp_get_weather
R-->>A: MCPWrappedTool
A->>W: run({city: "北京"})

W->>W: 构造 MCP 调用参数
Note over W: action=call_tool<br/>tool_name=get_weather<br/>arguments={city: 北京}
W->>M: mcp_tool.run(mcp_params)

M->>C: 创建 MCPClient / 进入 async with
C->>T: 建立 stdio 通道
T->>S: 启动 / 连接 Weather MCP Server
M->>C: call_tool("get_weather", {city:"北京"})
C->>S: MCP call_tool 请求

S->>S: Registry 查找 get_weather
S->>API: GET wttr.in/Beijing?format=j1
API-->>S: 天气 JSON
S->>S: 格式化 temperature / humidity / condition ...
S-->>C: MCP Tool Result
C-->>M: Result
M-->>W: Result
W-->>A: Tool Observation

A->>A: LLM 根据天气结果生成自然语言回答
A-->>U: 返回北京天气信息

一个很值得注意的实现边界

当前检查到的 MCPTool 实现里:

1
2
3
4
5
6
7
8
9
发现阶段:_discover_tools()
→ 创建一次 MCPClient
→ list_tools
→ 退出 client session

运行阶段:MCPTool.run()
→ 再创建一次 MCPClient
→ call_tool
→ 退出 client session

因此它更接近“按操作建立 Client Session”,并不是默认长期复用同一条持久连接。

好处:生命周期简单、失败隔离清楚。
代价:频繁调用时可能增加进程启动 / 握手 / 网络连接开销。生产实现应继续考虑 Connection Pool、Persistent Session、Timeout、Cancel 与重连策略。


7. MCPWrappedTool 为什么是关键 Adapter

Agent 调用的是:

1
mcp_get_weather(city="北京")

但 MCP Server 真正认识的是:

1
get_weather

MCPWrappedTool.run() 会把本地 Agent 参数:

1
{"city": "北京"}

转换成:

1
2
3
4
5
6
7
{
"action": "call_tool",
"tool_name": "get_weather",
"arguments": {
"city": "北京"
}
}

再交给 MCPTool.run()。

因此它解决的是:

1
2
3
HelloAgents Tool Contract
≠
MCP Protocol Contract

设计模式:Adapter

项目 说明
模式 Adapter Pattern
代码位置 MCPWrappedTool.run()
Adapter 输入 Agent 本地 Tool 调用参数
Adapter 输出 action / tool_name / arguments MCP 调用结构
解决的问题 LLM / Agent 不需要理解 call_tool 协议结构
好处 Remote MCP Tool 对 Agent 来说像普通 Tool
代价 / 边界 多一层 Wrapper;协议高级能力可能被普通 Tool 接口压平

8. 统一理解:MemoryTool / RAGTool / MCPTool 都是 Tool,但不是“同一种能力”

最重要的结论:

Tool 是 Agent Runtime 的统一能力抽象;Memory、RAG、Shell、Note、MCP、A2A 只是这个抽象背后的不同能力来源。

其中需要修正一个说法:

1
2
3
4
5
6
7
MemoryTool / RAGTool / TerminalTool / NoteTool
→ 主要是框架内部能力封装
→ 并不存在一个与它们一一对应的“Memory 协议 / RAG 协议”

MCPTool / A2ATool
→ 更偏协议桥接 Tool
→ 背后真正存在 MCP / A2A 通信边界

Tool 横向对比

Tool Agent 看见的统一身份 核心职责 底层主要连接什么 是否跨协议边界 典型设计角色
MemoryTool Tool 写入 / 查询 Agent 记忆 Working / Episodic / Semantic Memory、存储系统 否 Facade / Service-like
RAGTool Tool 检索外部知识 Embedding、Retriever、Vector DB、RAG Pipeline 否 Facade / Pipeline Entry
TerminalTool Tool JIT 查看 / 操作运行环境 subprocess、workspace、文件系统 否 Facade + Capability Boundary
NoteTool Tool 保存可持久化项目状态 Markdown / Index / Note Store 否 Repository / Facade-like
MCPTool Tool 接入 MCP Server、发现和调用能力 MCPClient、Transport、MCP Server 是:MCP Adapter / Facade / Gateway-like
MCPWrappedTool Tool 把一个 Remote MCP Tool 变成本地 Tool MCPTool 间接:MCP Adapter
A2ATool Tool 把 Remote Agent 能力接进 Tool System A2AClient / Remote Agent 是:A2A Adapter / Proxy-like

两类 Tool

1
2
3
4
5
6
7
8
9
10
11
第一类:业务 / 数据能力 Tool
MemoryTool / RAGTool / TerminalTool / NoteTool

含义:
“我把一种具体能力封装成 Agent Tool。”

第二类:协议桥接 Tool
MCPTool / A2ATool

含义:
“我把另一个协议世界里的能力适配进 Agent Tool System。”

所以一个 MCPTool 背后甚至可以展开多个真正给 LLM 选择的 MCPWrappedTool。


9. Tool 统一抽象 UML

说明:这是跨 Chapter 8–10 的框架概念 UML。 MCPTool / MCPWrappedTool 的关系已由当前检查到的实现支持;Memory / RAG / Terminal / Note 部分用于统一理解前面章节的 Tool 抽象,不把未重新核验的方法签名写成精确源码事实。

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
classDiagram
class Tool {
<<Agent capability abstraction>>
+name
+description
+run(...)
}

class ToolRegistry {
+register_tool(tool)
+get_tool(name)
+execute_tool(name, input)
}

class MemoryTool
class RAGTool
class TerminalTool
class NoteTool
class MCPTool {
+get_expanded_tools()
+run(parameters)
}
class MCPWrappedTool {
-mcp_tool
-mcp_tool_name
+run(params)
}
class A2ATool

class MemorySystem {
<<memory backend>>
}
class RAGPipeline {
<<retrieval backend>>
}
class RuntimeEnvironment {
<<filesystem / subprocess>>
}
class NoteStore {
<<persistent notes>>
}
class MCPClient {
+list_tools()
+call_tool()
}
class MCPServer
class A2AClient
class RemoteAgent

Tool <|-- MemoryTool
Tool <|-- RAGTool
Tool <|-- TerminalTool
Tool <|-- NoteTool
Tool <|-- MCPTool
Tool <|-- MCPWrappedTool
Tool <|-- A2ATool

ToolRegistry o-- Tool : registers / dispatches

MemoryTool --> MemorySystem : facade
RAGTool --> RAGPipeline : facade
TerminalTool --> RuntimeEnvironment : capability boundary
NoteTool --> NoteStore : repository-like

MCPWrappedTool --> MCPTool : adapts
MCPTool --> MCPClient : protocol client
MCPClient --> MCPServer : MCP

A2ATool --> A2AClient : adapts
A2AClient --> RemoteAgent : A2A

UML 对应的设计模式总结

模式 / 架构思想 代码 / 模块位置 解决的问题 好处 代价 / 边界
Tool Abstraction / Polymorphism 所有 Tool 子类 Agent 不应依赖每种能力的底层实现 Agent Runtime 统一发现、描述、执行能力 过度统一会产生抽象泄漏
Registry Pattern ToolRegistry 通过 Tool Name 动态查找 / 执行对象 动态扩展、解耦 Agent 与具体 Tool 名称冲突、版本治理、权限治理
Facade / Service-like MemoryTool、RAGTool 等 隐藏复杂存储 / 检索子系统 Agent 只使用简单 Tool API 底层高级能力可能被隐藏
Adapter MCPWrappedTool Agent Tool API 与 MCP Tool API 不一致 LLM 无感调用 Remote Tool 多一层转换、Debug 链路更长
Gateway / Facade-like MCPTool 隐藏 MCPClient / Transport / Discovery 一个入口管理一个 MCP Server 能力集 连接生命周期、网络错误、Auth、Timeout 更复杂
Proxy-like A2ATool Remote Agent 不在本地 Runtime 远端 Agent 可以表现成本地 Tool Task / Streaming / 协商语义可能被压平

10. 把 Chapter 7–10 串起来

1
2
3
4
5
6
7
8
9
10
11
Chapter 7
Tool = Agent 的统一能力接口
↓
Chapter 8
Memory / RAG 也被包装成 Tool
↓
Chapter 9
Terminal / Note 等 Tool 动态获取 Context / 保存项目状态
↓
Chapter 10
跨进程 / 跨服务能力继续通过 MCP / A2A 接入 Tool System

最后形成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
                       Agent
│
ToolRegistry
│
┌──────────┬────────┼───────────┬────────────┐
▼ ▼ ▼ ▼ ▼
MemoryTool RAGTool TerminalTool NoteTool MCPWrappedTool
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
Memory Retriever OS/FS Notes MCPTool
│
▼
MCPClient
│
▼
Transport
│
▼
MCP Server

最终一句话:

Tool 不是“某一种工具”,而是 Agent Runtime 对“可调用能力”的统一抽象。它背后可以是 Python 函数、Memory、RAG、Shell、数据库、远程 MCP Server,甚至另一个 Agent;MCP / A2A 的特殊之处,是把这个统一 Tool 抽象继续延伸到跨进程、跨服务、跨 Agent 的协议边界。


当前实践状态

  • 已基于官方天气 Server / Agent 源码梳理两次注册机制。
  • 已梳理 MCPTool → _discover_tools → get_expanded_tools → MCPWrappedTool → Agent ToolRegistry。
  • 已绘制“初始化 / 注册”时序图。
  • 已绘制“运行时调用”时序图。
  • 已整理跨章节 Tool UML 与对比表。
  • 尚未在本地实际跑通 14_weather_mcp_server.py。
  • 尚未记录一次真实 mcp_get_weather Tool Trace。
  • 尚未做 Timeout / wttr.in 网络失败 / Server 启动失败等 Failure Injection。