refactor: streamline the course to 17 lessons

This commit is contained in:
Haoran
2026-08-12 03:02:42 +08:00
parent ab35e59672
commit 7e2f2fd99b
250 changed files with 12179 additions and 18653 deletions

207
s14_mcp_plugin/README.ja.md Normal file
View File

@@ -0,0 +1,207 @@
# s14: MCP Tools — 外部ツールの発見と呼び出し
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
[s04](../s04_hooks/) → `s14` → [s15](../s15_integrated_harness/) → s16 → s17
> **Harness レイヤー**MCP Tools — service に接続し、tool を発見して Agent Loop に追加する。
---
## 課題
これまでの基本ツールは `code.py` に直接書かれている。documentation system と deployment platform を接続するために `search_docs``deploy_status``trigger_deploy` を追加することはできるが、service が増えるたびに tool definition、parameter schema、call handler を追加する必要がある。
MCP はこの責務を分ける。server は tool list と invocation endpoint を提供する。Harness は接続、model-facing name、permission check を担当し、発見した tool を model に渡す。
---
## ソリューション
![MCP Architecture](images/mcp-architecture.ja.svg)
本章は s04 の 5 つの基本ツールと Hooks から始め、次の 3 つを追加する:
- `MCPClient` は server が返した tool definition と call handler を保持する。
- `connect_mcp` は 1 つの server に接続して tool list を取得する。
- `assemble_tool_pool` は基本ツールと接続済み server の MCP tool を 1 つの tool pool にまとめる。
`docs``deploy` は、`tools/list``tools/call`、dynamic tool pool を示すための in-process mock server である。本章では実際の MCP transport は実装しない。
---
## 仕組み
### 1. 基本の Agent Loop は変わらない
各 model call の前に現在の tool pool を組み立てる:
```python
def agent_loop(messages: list):
while True:
tools, handlers = assemble_tool_pool()
response = client.messages.create(
model=MODEL,
system=assemble_system_prompt(),
messages=messages,
tools=tools,
max_tokens=8000,
)
...
```
新しい server を接続すると、次の `assemble_tool_pool()` がその tool を model input に追加する。実行結果は従来通り `tool_result` として messages に追加される。
### 2. MCPClient は発見結果と呼び出し入口を保持する
```python
class MCPClient:
def register(self, tool_defs, handlers):
self.tools = list(tool_defs)
self._handlers = dict(handlers)
def call_tool(self, tool_name, args):
handler = self._handlers.get(tool_name)
if not handler:
return f"MCP error: unknown tool '{tool_name}'"
try:
return str(handler(**args))
except Exception as error:
return f"MCP error: {type(error).__name__}: {error}"
```
`register()` は発見した tool list、`call_tool()` は invocation boundary を表す。error は Agent Loop を終了させず model へ返す。
### 3. connect_mcp は接続と発見だけを行う
```python
def connect_mcp(name: str) -> str:
if name in mcp_clients:
return f"MCP server '{name}' already connected"
factory = MOCK_SERVERS.get(name)
if not factory:
return f"Unknown server '{name}'"
server = factory()
mcp_clients[name] = server
...
```
開始時、model が見るのは 5 つの基本ツールと `connect_mcp` だけである。`connect_mcp(name="docs")` の後、Harness は docs client を保持し、次の model call に次の tool が加わる:
```text
mcp__docs__search
mcp__docs__get_version
```
### 4. prefix で別 server の同名 tool を区別する
複数の server が `search``status` を提供することがある。Harness は次の名前を使う:
```text
mcp__{server}__{tool}
```
`normalize_mcp_name()` は model tool name に使えない文字を underscore に置き換える。tool pool の組み立て時には、正規化後の名前衝突と 64 文字制限も確認する:
```python
prefixed = f"mcp__{safe_server}__{safe_tool}"
if prefixed in origins:
raise ValueError("MCP tool name collision after normalization")
```
そのため `docs.one/get.version``docs_one/get_version` が同じ名前へ暗黙に変換されることはない。
### 5. tool definition と handler を同時に追加する
```python
tools.append({
"name": prefixed,
"description": tool_def.get("description", ""),
"input_schema": schema,
})
handlers[prefixed] = (
lambda *, client=server, tool=raw_name, **kwargs:
client.call_tool(tool, kwargs)
)
```
model は prefix 付きの名前を見る。handler は server の元の tool name で `MCPClient` を呼ぶ。default argument が現在の client と tool を保持するため、loop 内の lambda がすべて最後の tool を参照することはない。
### 6. permission は host が決める
MCP server は `readOnlyHint``destructiveHint` を返せるが、それらは server 由来の hint であり authorization ではない。本章では host-side policy を使う:
```python
MCP_HOST_POLICY = {
("docs", "search"): "allow",
("docs", "get_version"): "allow",
("deploy", "status"): "allow",
("deploy", "trigger"): "confirm",
}
```
`permission_hook()` は正規化された tool name からこの policy を調べる。設定されていない外部ツールは、default で user confirmation を必要とする。description に `readOnly` と書かれていても自動許可されない。
### 7. 入力 error は tool boundary 内に留める
model は required argument を省略したり、server が受け付けない field を送ることがある。`execute_tool()``MCPClient.call_tool()` は error を捕捉し、error `tool_result` を返す:
```text
MCP error: TypeError: <lambda>() missing 1 required argument: 'query'
```
lesson script を終了せず、model は次の turn で argument を修正できる。
---
## s04 からの変更
| コンポーネント | s04 | s14 |
|---|---|---|
| 基本ツール | 5 つの固定ツール | 変更なし |
| ツールソース | `code.py` 内の定義 | 基本ツールと発見した MCP tool |
| ツールプール | 固定 `TOOLS` | 各 turn に `assemble_tool_pool()` で組み立て |
| 外部ツール名 | なし | `mcp__{server}__{tool}` |
| Permission | Shell と path check | host-side MCP policy を追加 |
| MCP transport | なし | in-process mock server で boundary を示す |
本章には Task、Background、Cron、Team、Worktree を持ち込まない。これらは s15 Integrated Harness で MCP と合流する。
---
## 試してみる
```sh
cd learn-claude-code
python s14_mcp_plugin/code.py
```
入力:
```text
docs server に接続し、agent hooks を検索して、現在の documentation API version を教えてください。
```
典型的な tool trace
```text
connect_mcp(name="docs")
mcp__docs__search(query="agent hooks")
mcp__docs__get_version()
```
続けて入力:
```text
deploy server に接続して web service の status を確認してください。deployment は trigger しないでください。
```
`status` は host policy によりそのまま実行され、`trigger` は user confirmation を必要とする。
---
## 次の章
ここでは MCP は独立した course branch である。s15 Integrated Harness は基本ツール、Hooks、Skills、Context、Memory、Task、Background、Cron、Teams、MCP を 1 つの runtime にまとめる。
<!-- translation-sync: zh@v9, en@v9, ja@v9 -->

207
s14_mcp_plugin/README.md Normal file
View File

@@ -0,0 +1,207 @@
# s14: MCP Tools — Discover and Invoke External Tools
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
[s04](../s04_hooks/) → `s14` → [s15](../s15_integrated_harness/) → s16 → s17
> **Harness layer**: MCP Tools — connect to services, discover tools, and add them to the agent loop.
---
## The Problem
The base tools in earlier chapters are written directly in `code.py`. We could integrate a documentation system and deployment platform by adding `search_docs`, `deploy_status`, and `trigger_deploy`, but every service would require another set of tool definitions, parameter schemas, and call handlers.
MCP separates those responsibilities. A server provides a tool list and invocation endpoint. The harness connects to it, assigns model-facing names, applies permission checks, and gives the discovered tools to the model.
---
## The Solution
![MCP Architecture](images/mcp-architecture.en.svg)
This chapter starts from s04's five base tools and hooks, then adds three parts:
- `MCPClient` stores the tool definitions and call handlers returned by a server.
- `connect_mcp` connects to one server and obtains its tool list.
- `assemble_tool_pool` combines the base tools with tools from every connected server.
The `docs` and `deploy` servers are in-process stand-ins for `tools/list`, `tools/call`, and a dynamic tool pool. This chapter does not implement a real MCP transport.
---
## How It Works
### 1. The base agent loop stays the same
Before each model call, the harness assembles the current tool pool:
```python
def agent_loop(messages: list):
while True:
tools, handlers = assemble_tool_pool()
response = client.messages.create(
model=MODEL,
system=assemble_system_prompt(),
messages=messages,
tools=tools,
max_tokens=8000,
)
...
```
After a new server connects, the next `assemble_tool_pool()` call adds its tools to the model input. Tool results are still appended to messages as `tool_result` blocks.
### 2. MCPClient stores discovery results and call handlers
```python
class MCPClient:
def register(self, tool_defs, handlers):
self.tools = list(tool_defs)
self._handlers = dict(handlers)
def call_tool(self, tool_name, args):
handler = self._handlers.get(tool_name)
if not handler:
return f"MCP error: unknown tool '{tool_name}'"
try:
return str(handler(**args))
except Exception as error:
return f"MCP error: {type(error).__name__}: {error}"
```
`register()` represents the discovered tool list. `call_tool()` represents the invocation boundary. Errors return to the model instead of terminating the agent loop.
### 3. connect_mcp only connects and discovers
```python
def connect_mcp(name: str) -> str:
if name in mcp_clients:
return f"MCP server '{name}' already connected"
factory = MOCK_SERVERS.get(name)
if not factory:
return f"Unknown server '{name}'"
server = factory()
mcp_clients[name] = server
...
```
Initially, the model sees the five base tools and `connect_mcp`. After `connect_mcp(name="docs")`, the harness stores the docs client. The next model call also sees:
```text
mcp__docs__search
mcp__docs__get_version
```
### 4. Prefixes separate tools from different servers
Several servers may expose `search` or `status`. The harness uses:
```text
mcp__{server}__{tool}
```
`normalize_mcp_name()` replaces characters outside the model tool-name alphabet with underscores. Tool-pool assembly also checks normalized-name collisions and the 64-character limit:
```python
prefixed = f"mcp__{safe_server}__{safe_tool}"
if prefixed in origins:
raise ValueError("MCP tool name collision after normalization")
```
As a result, `docs.one/get.version` and `docs_one/get_version` cannot silently map to the same name.
### 5. Tool definitions and handlers enter the pool together
```python
tools.append({
"name": prefixed,
"description": tool_def.get("description", ""),
"input_schema": schema,
})
handlers[prefixed] = (
lambda *, client=server, tool=raw_name, **kwargs:
client.call_tool(tool, kwargs)
)
```
The model sees the prefixed name. The handler calls `MCPClient` with the server's original tool name. Default arguments capture the current client and tool so every lambda does not point to the last item in the loop.
### 6. The host decides permissions
An MCP server may provide `readOnlyHint` or `destructiveHint`, but those hints come from the server and are not authorization. This chapter uses a host-side policy:
```python
MCP_HOST_POLICY = {
("docs", "search"): "allow",
("docs", "get_version"): "allow",
("deploy", "status"): "allow",
("deploy", "trigger"): "confirm",
}
```
`permission_hook()` looks up this policy using the normalized tool name. An unconfigured external tool requires confirmation by default. A description containing `readOnly` does not make a tool trusted.
### 7. Input errors stay at the tool boundary
The model may omit a required argument or send a field the server does not accept. Both `execute_tool()` and `MCPClient.call_tool()` catch those errors and return an error `tool_result`:
```text
MCP error: TypeError: <lambda>() missing 1 required argument: 'query'
```
The model can correct its arguments on the next turn without terminating the lesson script.
---
## What Changed from s04
| Component | s04 | s14 |
|---|---|---|
| Base tools | Five fixed tools | Unchanged |
| Tool source | Definitions in `code.py` | Base tools plus discovered MCP tools |
| Tool pool | Fixed `TOOLS` | Built each turn by `assemble_tool_pool()` |
| External tool names | None | `mcp__{server}__{tool}` |
| Permission | Shell and path checks | Adds a host-side MCP policy |
| MCP transport | None | In-process server stand-ins demonstrate the boundary |
This chapter does not carry Task, Background, Cron, Team, or Worktree. They join MCP in the s15 Integrated Harness.
---
## Try It Out
```sh
cd learn-claude-code
python s14_mcp_plugin/code.py
```
Enter:
```text
Connect to the docs server, search for agent hooks, and tell me the current documentation API version.
```
A typical tool trace is:
```text
connect_mcp(name="docs")
mcp__docs__search(query="agent hooks")
mcp__docs__get_version()
```
Then enter:
```text
Connect to the deploy server and check the web service status. Do not trigger a deployment.
```
`status` runs under the host policy. `trigger` requires user confirmation.
---
## What's Next
MCP is still an independent course branch here. s15 Integrated Harness combines the base tools, hooks, skills, context, memory, tasks, background work, cron, teams, and MCP in one runtime.
<!-- translation-sync: zh@v9, en@v9, ja@v9 -->

207
s14_mcp_plugin/README.zh.md Normal file
View File

@@ -0,0 +1,207 @@
# s14: MCP Tools — 发现并调用外部工具
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
[s04](../s04_hooks/) → `s14` → [s15](../s15_integrated_harness/) → s16 → s17
> **Harness 层**MCP Tools — 连接服务、发现工具,并把它们加入 Agent 的工具循环。
---
## 问题
前面的基础工具都直接写在 `code.py` 里。接入文档系统和部署平台时,我们还可以继续手写 `search_docs``deploy_status``trigger_deploy`,但每增加一个服务,都要重新维护工具定义、参数格式和调用代码。
MCP 把这部分拆成两个角色server 提供工具列表和调用入口Harness 负责连接、命名、权限检查,并把发现的工具交给模型。
---
## 解决方案
![MCP Architecture](images/mcp-architecture.svg)
本章从 s04 的五个基础工具和 Hooks 出发,增加三个部分:
- `MCPClient` 保存 server 返回的工具定义和调用入口。
- `connect_mcp` 连接一个 server并取得它的工具列表。
- `assemble_tool_pool` 把基础工具与已经连接的 MCP 工具组装到同一个工具池。
课程里的 `docs``deploy` 是进程内模拟 server用来展示 `tools/list``tools/call` 和动态工具池。真实 MCP transport 不在本章实现。
---
## 工作原理
### 1. 基础 Agent Loop 不需要改变
每轮调用模型前Harness 组装当前工具池:
```python
def agent_loop(messages: list):
while True:
tools, handlers = assemble_tool_pool()
response = client.messages.create(
model=MODEL,
system=assemble_system_prompt(),
messages=messages,
tools=tools,
max_tokens=8000,
)
...
```
连接新 server 后,下一轮 `assemble_tool_pool()` 会把新工具加入模型输入。工具执行后,结果仍作为 `tool_result` 追加到 messages。
### 2. MCPClient 保存发现结果和调用入口
```python
class MCPClient:
def register(self, tool_defs, handlers):
self.tools = list(tool_defs)
self._handlers = dict(handlers)
def call_tool(self, tool_name, args):
handler = self._handlers.get(tool_name)
if not handler:
return f"MCP error: unknown tool '{tool_name}'"
try:
return str(handler(**args))
except Exception as error:
return f"MCP error: {type(error).__name__}: {error}"
```
`register()` 对应课程里的工具发现结果,`call_tool()` 对应调用入口。错误会返回给模型,不会直接结束 Agent Loop。
### 3. connect_mcp 只负责连接和发现
```python
def connect_mcp(name: str) -> str:
if name in mcp_clients:
return f"MCP server '{name}' already connected"
factory = MOCK_SERVERS.get(name)
if not factory:
return f"Unknown server '{name}'"
server = factory()
mcp_clients[name] = server
...
```
开始时,模型只看到五个基础工具和 `connect_mcp`。调用 `connect_mcp(name="docs")`Harness 保存 docs client。下一轮模型调用会看到
```text
mcp__docs__search
mcp__docs__get_version
```
### 4. 前缀区分不同 server 的同名工具
多个 server 都可能提供 `search``status`。Harness 使用:
```text
mcp__{server}__{tool}
```
`normalize_mcp_name()` 把不适合模型工具名的字符替换为下划线。组装工具池时还会检查规范化后的名称冲突和 64 字符长度限制:
```python
prefixed = f"mcp__{safe_server}__{safe_tool}"
if prefixed in origins:
raise ValueError("MCP tool name collision after normalization")
```
因此 `docs.one/get.version``docs_one/get_version` 不会悄悄映射到同一个名字。
### 5. 工具定义和 handler 一起加入工具池
```python
tools.append({
"name": prefixed,
"description": tool_def.get("description", ""),
"input_schema": schema,
})
handlers[prefixed] = (
lambda *, client=server, tool=raw_name, **kwargs:
client.call_tool(tool, kwargs)
)
```
模型看到带前缀的名字handler 仍使用 server 原始工具名调用 `MCPClient`。默认参数保存当前 client 和 tool避免循环里的 lambda 全部指向最后一个工具。
### 6. 权限由宿主配置决定
MCP server 可以提供 `readOnlyHint``destructiveHint`,但这些信息来自 server不能直接作为授权依据。本章使用宿主侧策略
```python
MCP_HOST_POLICY = {
("docs", "search"): "allow",
("docs", "get_version"): "allow",
("deploy", "status"): "allow",
("deploy", "trigger"): "confirm",
}
```
`permission_hook()` 根据规范化后的工具名查询这份策略。未配置的外部工具默认需要用户确认;即使 description 写着 `readOnly`,也不会自动放行。
### 7. 工具输入错误留在工具边界内
模型可能漏传参数,也可能传入 server 不接受的字段。`execute_tool()``MCPClient.call_tool()` 都会捕获异常,并返回错误 `tool_result`
```text
MCP error: TypeError: <lambda>() missing 1 required argument: 'query'
```
模型可以在下一轮修正参数,而不是让课程脚本直接退出。
---
## 相对 s04 的变化
| 组件 | s04 | s14 |
|---|---|---|
| 基础工具 | 五个固定工具 | 保持不变 |
| 工具来源 | `code.py` 中的定义 | 基础工具加动态发现的 MCP 工具 |
| 工具池 | 固定 `TOOLS` | 每轮由 `assemble_tool_pool()` 组装 |
| 外部工具名 | 无 | `mcp__{server}__{tool}` |
| 权限 | Shell 和路径检查 | 增加宿主侧 MCP 策略 |
| MCP transport | 无 | 使用进程内模拟 server 展示协议边界 |
本章不带入 Task、Background、Cron、Team 或 Worktree。它们会在 s15 的 Integrated Harness 中与 MCP 合并。
---
## 试一下
```sh
cd learn-claude-code
python s14_mcp_plugin/code.py
```
输入:
```text
连接 docs server搜索 agent hooks并告诉我当前文档 API 版本。
```
一次典型工具轨迹是:
```text
connect_mcp(name="docs")
mcp__docs__search(query="agent hooks")
mcp__docs__get_version()
```
再输入:
```text
连接 deploy server查看 web 服务状态,不要触发部署。
```
`status` 会按宿主策略直接执行;`trigger` 需要用户确认。
---
## 接下来
目前MCP 还是一条独立的课程分支。s15 Integrated Harness 会把基础工具、Hooks、Skills、Context、Memory、Task、Background、Cron、Teams 和 MCP 放进同一个运行时。
<!-- translation-sync: zh@v9, en@v9, ja@v9 -->

529
s14_mcp_plugin/code.py Normal file
View File

@@ -0,0 +1,529 @@
#!/usr/bin/env python3
"""
s14: MCP Tools - discover external tools and add them to the agent loop.
Run: python s14_mcp_plugin/code.py
Need: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY
connect_mcp("docs")
|
v
+------------------+ tools/list +------------------+
| Agent Harness | <----------------- | MCP server |
| | | docs |
| built-in tools | tools/call | |
| + MCP tools | -----------------> | search |
+--------+---------+ | get_version |
| +------------------+
v
+-----------------------------------------------+
| bash | read | write | edit | glob | connect |
| mcp__docs__search | mcp__docs__get_version |
+-----------------------------------------------+
"""
import glob
import os
import re
import subprocess
from pathlib import Path
try:
import readline
readline.parse_and_bind("set bind-tty-special-chars off")
except ImportError:
pass
from anthropic import Anthropic
from dotenv import load_dotenv
load_dotenv(override=True)
if os.getenv("ANTHROPIC_BASE_URL"):
os.environ.pop("ANTHROPIC_AUTH_TOKEN", None)
WORKDIR = Path.cwd()
client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL"))
MODEL = os.environ["MODEL_ID"]
BASE_SYSTEM = (
f"You are a coding agent at {WORKDIR}. Use built-in and connected MCP "
"tools to solve tasks. Call connect_mcp before using a server."
)
# -- From s04: base tools --
def run_bash(command: str) -> str:
try:
result = subprocess.run(
command,
shell=True,
cwd=WORKDIR,
capture_output=True,
text=True,
timeout=120,
)
output = (result.stdout + result.stderr).strip()
output = output[:50000] if output else "(no output)"
if result.returncode:
return f"Error: command exited with status {result.returncode}\n{output}"
return output
except subprocess.TimeoutExpired:
return "Error: Timeout (120s)"
except OSError as exc:
return f"Error: {type(exc).__name__}: {exc}"
def run_read(path: str, limit: int | None = None) -> str:
try:
lines = (WORKDIR / path).resolve().read_text(encoding="utf-8").splitlines()
if limit and limit < len(lines):
lines = lines[:limit] + [f"... ({len(lines) - limit} more lines)"]
return "\n".join(lines)
except Exception as exc:
return f"Error: {exc}"
def run_write(path: str, content: str) -> str:
try:
target = (WORKDIR / path).resolve()
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
return f"Wrote {len(content)} bytes to {path}"
except Exception as exc:
return f"Error: {exc}"
def run_edit(path: str, old_text: str, new_text: str) -> str:
try:
target = (WORKDIR / path).resolve()
content = target.read_text(encoding="utf-8")
count = content.count(old_text)
if count != 1:
return f"Error: Expected 1 occurrence, found {count}"
target.write_text(content.replace(old_text, new_text), encoding="utf-8")
return f"Edited {path}"
except Exception as exc:
return f"Error: {exc}"
def run_glob(pattern: str) -> str:
try:
matches = [
match
for match in glob.glob(pattern, root_dir=WORKDIR)
if (WORKDIR / match).resolve().is_relative_to(WORKDIR.resolve())
]
return "\n".join(matches[:200]) if matches else "(no matches)"
except Exception as exc:
return f"Error: {exc}"
BASE_TOOLS = [
{"name": "bash", "description": "Run a shell command.",
"input_schema": {"type": "object",
"properties": {"command": {"type": "string"}},
"required": ["command"]}},
{"name": "read_file", "description": "Read file contents.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"},
"limit": {"type": "integer"}},
"required": ["path"]}},
{"name": "write_file", "description": "Write content to a file.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"},
"content": {"type": "string"}},
"required": ["path", "content"]}},
{"name": "edit_file", "description": "Replace exact text once.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"},
"old_text": {"type": "string"},
"new_text": {"type": "string"}},
"required": ["path", "old_text", "new_text"]}},
{"name": "glob", "description": "Find files by glob pattern.",
"input_schema": {"type": "object",
"properties": {"pattern": {"type": "string"}},
"required": ["pattern"]}},
]
BASE_HANDLERS = {
"bash": run_bash,
"read_file": run_read,
"write_file": run_write,
"edit_file": run_edit,
"glob": run_glob,
}
# -- New in s14: MCP discovery and dispatch --
class MCPClient:
"""Small in-process stand-in for MCP tools/list and tools/call."""
def __init__(self, name: str):
self.name = name
self.tools: list[dict] = []
self._handlers: dict[str, callable] = {}
def register(self, tool_defs: list[dict], handlers: dict[str, callable]):
names = [tool.get("name") for tool in tool_defs]
if any(not isinstance(name, str) or not name for name in names):
raise ValueError("Every MCP tool needs a non-empty name")
if len(set(names)) != len(names):
raise ValueError(f"Duplicate MCP tool name on server {self.name!r}")
missing = [name for name in names if name not in handlers]
if missing:
raise ValueError(f"Missing MCP handlers: {', '.join(missing)}")
self.tools = list(tool_defs)
self._handlers = dict(handlers)
def call_tool(self, tool_name: str, args: dict) -> str:
handler = self._handlers.get(tool_name)
if not handler:
return f"MCP error: unknown tool '{tool_name}'"
try:
return str(handler(**args))
except Exception as exc:
return f"MCP error: {type(exc).__name__}: {exc}"
mcp_clients: dict[str, MCPClient] = {}
mcp_tool_policies: dict[str, str] = {}
_DISALLOWED_CHARS = re.compile(r"[^a-zA-Z0-9_-]")
# Authorization comes from host configuration, never server descriptions.
MCP_HOST_POLICY = {
("docs", "search"): "allow",
("docs", "get_version"): "allow",
("deploy", "status"): "allow",
("deploy", "trigger"): "confirm",
}
def normalize_mcp_name(name: str) -> str:
"""Replace characters outside the model tool-name alphabet."""
normalized = _DISALLOWED_CHARS.sub("_", name)
if not normalized:
raise ValueError("MCP names cannot normalize to an empty string")
return normalized
def _mock_server_docs() -> MCPClient:
server = MCPClient("docs")
server.register(
tool_defs=[
{
"name": "search",
"description": "Search the documentation.",
"inputSchema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"],
},
"annotations": {"readOnlyHint": True},
},
{
"name": "get_version",
"description": "Get the documentation API version.",
"inputSchema": {"type": "object", "properties": {}},
"annotations": {"readOnlyHint": True},
},
],
handlers={
"search": lambda query: f"[docs] Found 3 results for '{query}'",
"get_version": lambda: "[docs] API v2.1.0",
},
)
return server
def _mock_server_deploy() -> MCPClient:
server = MCPClient("deploy")
server.register(
tool_defs=[
{
"name": "trigger",
"description": "Trigger a deployment.",
"inputSchema": {
"type": "object",
"properties": {"service": {"type": "string"}},
"required": ["service"],
},
"annotations": {"destructiveHint": True},
},
{
"name": "status",
"description": "Check deployment status.",
"inputSchema": {
"type": "object",
"properties": {"service": {"type": "string"}},
"required": ["service"],
},
"annotations": {"readOnlyHint": True},
},
],
handlers={
"trigger": lambda service: f"[deploy] Triggered: {service}",
"status": lambda service: f"[deploy] {service}: running (v1.4.2)",
},
)
return server
MOCK_SERVERS = {
"docs": _mock_server_docs,
"deploy": _mock_server_deploy,
}
def connect_mcp(name: str) -> str:
if name in mcp_clients:
return f"MCP server '{name}' already connected"
factory = MOCK_SERVERS.get(name)
if not factory:
return f"Unknown server '{name}'. Available: {', '.join(MOCK_SERVERS)}"
server = factory()
mcp_clients[name] = server
names = ", ".join(tool["name"] for tool in server.tools)
print(f" [mcp] connected: {name} -> {names}")
return (
f"Connected to MCP server '{name}'. "
f"Discovered {len(server.tools)} tools: {names}"
)
def run_connect_mcp(name: str) -> str:
return connect_mcp(name)
CONNECT_TOOL = {
"name": "connect_mcp",
"description": "Connect to an MCP server and discover its tools.",
"input_schema": {
"type": "object",
"properties": {"name": {"type": "string", "enum": ["docs", "deploy"]}},
"required": ["name"],
},
}
BUILTIN_TOOLS = [*BASE_TOOLS, CONNECT_TOOL]
BUILTIN_HANDLERS = {**BASE_HANDLERS, "connect_mcp": run_connect_mcp}
def assemble_tool_pool() -> tuple[list[dict], dict[str, callable]]:
"""Combine built-in tools with every connected server tool."""
global mcp_tool_policies
tools = list(BUILTIN_TOOLS)
handlers = dict(BUILTIN_HANDLERS)
policies: dict[str, str] = {}
origins = {
tool["name"]: f"built-in tool {tool['name']!r}"
for tool in tools
}
for server_name, server in mcp_clients.items():
safe_server = normalize_mcp_name(server_name)
for tool_def in server.tools:
raw_name = tool_def["name"]
safe_tool = normalize_mcp_name(raw_name)
prefixed = f"mcp__{safe_server}__{safe_tool}"
if len(prefixed) > 64:
raise ValueError(f"MCP tool name is longer than 64 characters: {prefixed}")
origin = f"MCP tool {server_name!r}/{raw_name!r}"
if prefixed in origins:
raise ValueError(
"MCP tool name collision after normalization: "
f"{prefixed!r} maps both {origins[prefixed]} and {origin}"
)
schema = tool_def.get("inputSchema", {})
if not isinstance(schema, dict) or schema.get("type", "object") != "object":
raise ValueError(f"Invalid input schema for {origin}")
origins[prefixed] = origin
tools.append({
"name": prefixed,
"description": tool_def.get("description", ""),
"input_schema": schema,
})
handlers[prefixed] = (
lambda *, client=server, tool=raw_name, **kwargs:
client.call_tool(tool, kwargs)
)
policies[prefixed] = MCP_HOST_POLICY.get(
(server_name, raw_name), "confirm"
)
mcp_tool_policies = policies
return tools, handlers
def assemble_system_prompt() -> str:
if not mcp_clients:
return BASE_SYSTEM
return BASE_SYSTEM + "\n\nConnected MCP servers: " + ", ".join(mcp_clients)
# -- From s04: hooks and permission checks --
HOOKS = {"UserPromptSubmit": [], "PreToolUse": [], "PostToolUse": [], "Stop": []}
DENY_LIST = ["rm -rf /", "sudo", "shutdown", "reboot", "mkfs", "dd if="]
DESTRUCTIVE = ["rm ", "> /etc/", "chmod 777"]
def register_hook(event: str, callback):
HOOKS[event].append(callback)
def trigger_hooks(event: str, *args):
for callback in HOOKS[event]:
result = callback(*args)
if result is not None:
return result
return None
def permission_hook(block):
if block.name == "bash":
command = block.input.get("command", "")
for pattern in DENY_LIST:
if pattern in command:
return f"Permission denied by deny list: {pattern}"
if any(keyword in command for keyword in DESTRUCTIVE):
print(f"\n[permission] {block.name}({block.input})")
if input("Allow? [y/N] ").strip().lower() not in {"y", "yes"}:
return "Permission denied by user"
if block.name in {"read_file", "write_file", "edit_file"}:
raw_path = block.input.get("path", "")
if not (WORKDIR / raw_path).resolve().is_relative_to(WORKDIR.resolve()):
print(f"\n[permission] {block.name}({block.input})")
if input("Allow? [y/N] ").strip().lower() not in {"y", "yes"}:
return "Permission denied by user"
if block.name.startswith("mcp__"):
policy = mcp_tool_policies.get(block.name, "confirm")
if policy != "allow":
print(f"\n[permission] External tool {block.name}({block.input})")
if input("Allow? [y/N] ").strip().lower() not in {"y", "yes"}:
return "Permission denied by user"
return None
def log_hook(block):
preview = str(list(block.input.values())[:2])[:60]
print(f"[hook] {block.name}({preview})")
return None
def large_output_hook(block, output):
if len(str(output)) > 100000:
print(f"[hook] Large output from {block.name}: {len(str(output))} chars")
return None
def context_hook(query: str):
print(f"[hook] UserPromptSubmit: working in {WORKDIR}")
return None
def summary_hook(messages: list):
tool_count = sum(
1
for message in messages
for block in (
message.get("content")
if isinstance(message.get("content"), list)
else []
)
if isinstance(block, dict) and block.get("type") == "tool_result"
)
print(f"[hook] Stop: session used {tool_count} tool calls")
return None
register_hook("UserPromptSubmit", context_hook)
register_hook("PreToolUse", permission_hook)
register_hook("PreToolUse", log_hook)
register_hook("PostToolUse", large_output_hook)
register_hook("Stop", summary_hook)
def execute_tool(block, handlers: dict[str, callable]) -> str:
blocked = trigger_hooks("PreToolUse", block)
if blocked:
return str(blocked)
handler = handlers.get(block.name)
if not handler:
return f"Unknown tool: {block.name}"
try:
output = str(handler(**block.input))
except Exception as exc:
output = f"Error: {type(exc).__name__}: {exc}"
trigger_hooks("PostToolUse", block, output)
return output
# -- Agent loop with a dynamic tool pool --
def agent_loop(messages: list):
while True:
try:
tools, handlers = assemble_tool_pool()
response = client.messages.create(
model=MODEL,
system=assemble_system_prompt(),
messages=messages,
tools=tools,
max_tokens=8000,
)
except Exception as exc:
messages.append({
"role": "assistant",
"content": [{
"type": "text",
"text": f"[Error] {type(exc).__name__}: {exc}",
}],
})
trigger_hooks("Stop", messages)
return
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
trigger_hooks("Stop", messages)
return
results = []
for block in response.content:
if block.type != "tool_use":
continue
print(f"> {block.name}")
output = execute_tool(block, handlers)
print(output[:300])
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": output,
})
messages.append({"role": "user", "content": results})
if __name__ == "__main__":
print("s14: MCP tools")
print("Enter a question, press Enter to send. Type q to quit.\n")
history = []
while True:
try:
query = input("s14 >> ")
except (EOFError, KeyboardInterrupt):
break
if query.strip().lower() in {"q", "exit", ""}:
break
trigger_hooks("UserPromptSubmit", query)
history.append({"role": "user", "content": query})
agent_loop(history)
for block in history[-1].get("content", []):
if getattr(block, "type", None) == "text":
print(block.text)
elif isinstance(block, dict) and block.get("type") == "text":
print(block.get("text", ""))
print()

View File

@@ -0,0 +1,112 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 460" font-family="system-ui, -apple-system, sans-serif">
<defs>
<linearGradient id="header" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#1e3a5f"/><stop offset="100%" stop-color="#dc2626"/>
</linearGradient>
<marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#555"/>
</marker>
<marker id="arrow-rose" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#dc2626"/>
</marker>
<marker id="arrow-rose-left" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M 10 0 L 0 5 L 10 10 z" fill="#dc2626"/>
</marker>
</defs>
<rect width="760" height="460" fill="#fafbfc" rx="8"/>
<!-- Title -->
<rect x="0" y="0" width="760" height="44" fill="url(#header)" rx="8"/>
<rect x="0" y="36" width="760" height="8" fill="url(#header)"/>
<text x="380" y="28" fill="#fff" font-size="15" font-weight="700" text-anchor="middle">MCP Tools — Discovery + Dynamic Tool Pool</text>
<!-- Legend -->
<rect x="40" y="56" width="12" height="10" rx="2" fill="#f0f4ff" stroke="#2563eb" stroke-width="1"/>
<text x="58" y="66" fill="#2563eb" font-size="10" font-weight="600">s04 Base Loop</text>
<rect x="160" y="56" width="12" height="10" rx="2" fill="#fff1f2" stroke="#dc2626" stroke-width="1"/>
<text x="178" y="66" fill="#dc2626" font-size="10" font-weight="600">s14 New</text>
<!-- ===== Row 1: Lead Loop (s13 preserved) ===== -->
<rect x="20" y="90" width="70" height="40" rx="8" fill="#eef2ff" stroke="#4f46e5" stroke-width="1.5"/>
<text x="55" y="114" fill="#4f46e5" font-size="8" font-weight="600" text-anchor="middle">turn</text>
<line x1="90" y1="110" x2="104" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="107" y="90" width="70" height="40" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="142" y="114" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">messages</text>
<line x1="177" y1="110" x2="191" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="194" y="86" width="80" height="48" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="234" y="114" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">prompt</text>
<line x1="274" y1="110" x2="288" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="291" y="86" width="70" height="48" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="326" y="114" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">LLM</text>
<line x1="361" y1="110" x2="375" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="378" y="76" width="356" height="72" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="556" y="94" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">TOOL DISPATCH (dynamic pool)</text>
<text x="394" y="109" fill="#2563eb" font-size="7.5">bash · read · write · edit · glob</text>
<text x="394" y="121" fill="#7c3aed" font-size="7.5" font-weight="700">connect_mcp</text>
<text x="394" y="133" fill="#b45309" font-size="7.5" font-weight="700">mcp__server__tool from connected servers</text>
<text x="394" y="145" fill="#dc2626" font-size="7.5" font-weight="700">★ connect_mcp + dynamic mcp__server__tool tools</text>
<!-- Loop back -->
<path d="M 734 110 L 748 110 L 748 150 L 55 150 L 55 130" fill="none" stroke="#94a3b8" stroke-width="1" marker-end="url(#arrow)" stroke-dasharray="5,4"/>
<!-- ===== Row 2: MCP Architecture (s14 new) ===== -->
<rect x="30" y="172" width="700" height="215" rx="8" fill="#fff1f2" stroke="#dc2626" stroke-width="2"/>
<text x="380" y="194" fill="#991b1b" font-size="11" font-weight="700" text-anchor="middle">MCP Architecture (s14 new: standard protocol + dynamic external tools)</text>
<!-- Agent Side -->
<rect x="50" y="210" width="255" height="140" rx="6" fill="#fff" stroke="#dc2626" stroke-width="1.5"/>
<text x="177" y="230" fill="#991b1b" font-size="10" font-weight="700" text-anchor="middle">Agent Side (MCPClient)</text>
<rect x="65" y="240" width="225" height="24" rx="4" fill="#fef2f2" stroke="#fca5a5" stroke-width="0.5"/>
<text x="177" y="256" fill="#475569" font-size="8" text-anchor="middle">connect_mcp → discover → register tools</text>
<rect x="65" y="272" width="225" height="24" rx="4" fill="#fef2f2" stroke="#fca5a5" stroke-width="0.5"/>
<text x="177" y="288" fill="#475569" font-size="8" text-anchor="middle">assemble_tool_pool assembles builtin + mcp</text>
<rect x="65" y="304" width="225" height="24" rx="4" fill="#fef2f2" stroke="#fca5a5" stroke-width="0.5"/>
<text x="177" y="320" fill="#475569" font-size="8" text-anchor="middle">handler → call_tool("search", args)</text>
<!-- Communication arrows -->
<line x1="305" y1="262" x2="435" y2="262" stroke="#dc2626" stroke-width="1.5" marker-end="url(#arrow-rose)"/>
<text x="370" y="256" fill="#dc2626" font-size="7" font-weight="600" text-anchor="middle">tools/list</text>
<line x1="435" y1="296" x2="305" y2="296" stroke="#dc2626" stroke-width="1.5" marker-end="url(#arrow-rose)"/>
<text x="370" y="312" fill="#dc2626" font-size="7" font-weight="600" text-anchor="middle">tools/call + response</text>
<!-- MCP Servers -->
<rect x="438" y="210" width="275" height="140" rx="6" fill="#fff" stroke="#ca8a04" stroke-width="1.5"/>
<text x="575" y="230" fill="#854d0e" font-size="10" font-weight="700" text-anchor="middle">MCP Servers (External Services)</text>
<rect x="453" y="240" width="245" height="28" rx="4" fill="#fefce8" stroke="#facc15" stroke-width="0.5"/>
<text x="575" y="258" fill="#854d0e" font-size="9" font-weight="600" text-anchor="middle">docs server: search · get_version</text>
<rect x="453" y="276" width="245" height="28" rx="4" fill="#fefce8" stroke="#facc15" stroke-width="0.5"/>
<text x="575" y="294" fill="#854d0e" font-size="9" font-weight="600" text-anchor="middle">deploy server: trigger · status</text>
<rect x="453" y="312" width="245" height="28" rx="4" fill="#fefce8" stroke="#facc15" stroke-width="0.5"/>
<text x="575" y="330" fill="#854d0e" font-size="9" font-weight="600" text-anchor="middle">This lesson uses in-process server stand-ins</text>
<!-- Naming convention -->
<rect x="50" y="360" width="660" height="20" rx="4" fill="#fef3c7" stroke="#d97706" stroke-width="1"/>
<text x="380" y="374" fill="#92400e" font-size="8" text-anchor="middle">Tool naming: mcp__{server}__{tool} → e.g. mcp__docs__search · mcp__deploy__trigger · prevents name collisions across servers</text>
<!-- ===== Row 3: Bottom notes ===== -->
<rect x="30" y="400" width="700" height="22" rx="4" fill="#f8fafc" stroke="#e2e8f0" stroke-width="1"/>
<rect x="50" y="408" width="12" height="10" rx="2" fill="#f0f4ff" stroke="#2563eb" stroke-width="1"/>
<text x="70" y="418" fill="#475569" font-size="10">s04: base tools + hooks + permission</text>
<rect x="420" y="408" width="12" height="10" rx="2" fill="#fff1f2" stroke="#dc2626" stroke-width="1"/>
<text x="440" y="418" fill="#475569" font-size="10">s14: MCP + dynamic tool pool</text>
<!-- ===== Final note ===== -->
<rect x="30" y="430" width="700" height="22" rx="4" fill="#fff1f2" stroke="#dc2626" stroke-width="1"/>
<text x="380" y="444" fill="#991b1b" font-size="9" font-weight="600" text-anchor="middle">Next: s15 combines tools, permissions, teams, worktrees, MCP, and more into one while True loop.</text>
</svg>

After

Width:  |  Height:  |  Size: 7.7 KiB

View File

@@ -0,0 +1,112 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 460" font-family="system-ui, -apple-system, sans-serif">
<defs>
<linearGradient id="header" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#1e3a5f"/><stop offset="100%" stop-color="#dc2626"/>
</linearGradient>
<marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#555"/>
</marker>
<marker id="arrow-rose" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#dc2626"/>
</marker>
<marker id="arrow-rose-left" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M 10 0 L 0 5 L 10 10 z" fill="#dc2626"/>
</marker>
</defs>
<rect width="760" height="460" fill="#fafbfc" rx="8"/>
<!-- Title -->
<rect x="0" y="0" width="760" height="44" fill="url(#header)" rx="8"/>
<rect x="0" y="36" width="760" height="8" fill="url(#header)"/>
<text x="380" y="28" fill="#fff" font-size="14" font-weight="700" text-anchor="middle">MCP Tools — Tool Discovery + Dynamic Tool Pool</text>
<!-- Legend -->
<rect x="40" y="56" width="12" height="10" rx="2" fill="#f0f4ff" stroke="#2563eb" stroke-width="1"/>
<text x="58" y="66" fill="#2563eb" font-size="10" font-weight="600">s04 Base Loop</text>
<rect x="130" y="56" width="12" height="10" rx="2" fill="#fff1f2" stroke="#dc2626" stroke-width="1"/>
<text x="148" y="66" fill="#dc2626" font-size="10" font-weight="600">s14 新規</text>
<!-- ===== Row 1: Lead Loop ===== -->
<rect x="20" y="90" width="70" height="40" rx="8" fill="#eef2ff" stroke="#4f46e5" stroke-width="1.5"/>
<text x="55" y="114" fill="#4f46e5" font-size="8" font-weight="600" text-anchor="middle">turn</text>
<line x1="90" y1="110" x2="104" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="107" y="90" width="70" height="40" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="142" y="114" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">messages</text>
<line x1="177" y1="110" x2="191" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="194" y="86" width="80" height="48" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="234" y="114" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">prompt</text>
<line x1="274" y1="110" x2="288" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="291" y="86" width="70" height="48" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="326" y="114" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">LLM</text>
<line x1="361" y1="110" x2="375" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="378" y="76" width="356" height="72" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="556" y="94" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">TOOL DISPATCHdynamic pool</text>
<text x="394" y="109" fill="#2563eb" font-size="7.5">bash · read · write · edit · glob</text>
<text x="394" y="121" fill="#7c3aed" font-size="7.5" font-weight="700">connect_mcp</text>
<text x="394" y="133" fill="#b45309" font-size="7.5" font-weight="700">接続済み server の mcp__server__tool</text>
<text x="394" y="145" fill="#dc2626" font-size="7.5" font-weight="700">★ connect_mcp + 動的 mcp__server__tool ツール</text>
<!-- Loop back -->
<path d="M 734 110 L 748 110 L 748 150 L 55 150 L 55 130" fill="none" stroke="#94a3b8" stroke-width="1" marker-end="url(#arrow)" stroke-dasharray="5,4"/>
<!-- ===== Row 2: MCP Architecture ===== -->
<rect x="30" y="172" width="700" height="215" rx="8" fill="#fff1f2" stroke="#dc2626" stroke-width="2"/>
<text x="380" y="194" fill="#991b1b" font-size="11" font-weight="700" text-anchor="middle">MCP アーキテクチャs14 新規:標準プロトコル + 外部ツール動的統合)</text>
<!-- Agent Side -->
<rect x="50" y="210" width="255" height="140" rx="6" fill="#fff" stroke="#dc2626" stroke-width="1.5"/>
<text x="177" y="230" fill="#991b1b" font-size="10" font-weight="700" text-anchor="middle">Agent 側MCPClient</text>
<rect x="65" y="240" width="225" height="24" rx="4" fill="#fef2f2" stroke="#fca5a5" stroke-width="0.5"/>
<text x="177" y="256" fill="#475569" font-size="8" text-anchor="middle">connect_mcp → discover → ツール登録</text>
<rect x="65" y="272" width="225" height="24" rx="4" fill="#fef2f2" stroke="#fca5a5" stroke-width="0.5"/>
<text x="177" y="288" fill="#475569" font-size="8" text-anchor="middle">assemble_tool_pool builtin + mcp 組み立て</text>
<rect x="65" y="304" width="225" height="24" rx="4" fill="#fef2f2" stroke="#fca5a5" stroke-width="0.5"/>
<text x="177" y="320" fill="#475569" font-size="8" text-anchor="middle">handler → call_tool("search", args)</text>
<!-- Communication arrows -->
<line x1="305" y1="262" x2="435" y2="262" stroke="#dc2626" stroke-width="1.5" marker-end="url(#arrow-rose)"/>
<text x="370" y="256" fill="#dc2626" font-size="7" font-weight="600" text-anchor="middle">tools/list</text>
<line x1="435" y1="296" x2="305" y2="296" stroke="#dc2626" stroke-width="1.5" marker-end="url(#arrow-rose)"/>
<text x="370" y="312" fill="#dc2626" font-size="7" font-weight="600" text-anchor="middle">tools/call + response</text>
<!-- MCP Servers -->
<rect x="438" y="210" width="275" height="140" rx="6" fill="#fff" stroke="#ca8a04" stroke-width="1.5"/>
<text x="575" y="230" fill="#854d0e" font-size="10" font-weight="700" text-anchor="middle">MCP Servers外部サービス</text>
<rect x="453" y="240" width="245" height="28" rx="4" fill="#fefce8" stroke="#facc15" stroke-width="0.5"/>
<text x="575" y="258" fill="#854d0e" font-size="9" font-weight="600" text-anchor="middle">docs server: search · get_version</text>
<rect x="453" y="276" width="245" height="28" rx="4" fill="#fefce8" stroke="#facc15" stroke-width="0.5"/>
<text x="575" y="294" fill="#854d0e" font-size="9" font-weight="600" text-anchor="middle">deploy server: trigger · status</text>
<rect x="453" y="312" width="245" height="28" rx="4" fill="#fefce8" stroke="#facc15" stroke-width="0.5"/>
<text x="575" y="330" fill="#854d0e" font-size="9" font-weight="600" text-anchor="middle">本章は in-process mock server を使用</text>
<!-- Naming convention -->
<rect x="50" y="360" width="660" height="20" rx="4" fill="#fef3c7" stroke="#d97706" stroke-width="1"/>
<text x="380" y="374" fill="#92400e" font-size="8" text-anchor="middle">ツール命名: mcp__{server}__{tool} → 例: mcp__docs__search · mcp__deploy__trigger · サーバー間の名前衝突を防止</text>
<!-- ===== Row 3: Bottom notes ===== -->
<rect x="30" y="400" width="700" height="22" rx="4" fill="#f8fafc" stroke="#e2e8f0" stroke-width="1"/>
<rect x="50" y="408" width="12" height="10" rx="2" fill="#f0f4ff" stroke="#2563eb" stroke-width="1"/>
<text x="70" y="418" fill="#475569" font-size="10">s04: base tools + hooks + permission</text>
<rect x="420" y="408" width="12" height="10" rx="2" fill="#fff1f2" stroke="#dc2626" stroke-width="1"/>
<text x="440" y="418" fill="#475569" font-size="10">s14: MCP + dynamic tool pool</text>
<!-- ===== Final note ===== -->
<rect x="30" y="430" width="700" height="22" rx="4" fill="#fff1f2" stroke="#dc2626" stroke-width="1"/>
<text x="380" y="444" fill="#991b1b" font-size="9" font-weight="600" text-anchor="middle">次の s15tools、permissions、teams、worktree、MCP などを 1 つの while True ループに統合。</text>
</svg>

After

Width:  |  Height:  |  Size: 7.7 KiB

View File

@@ -0,0 +1,112 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 460" font-family="system-ui, -apple-system, sans-serif">
<defs>
<linearGradient id="header" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#1e3a5f"/><stop offset="100%" stop-color="#dc2626"/>
</linearGradient>
<marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#555"/>
</marker>
<marker id="arrow-rose" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#dc2626"/>
</marker>
<marker id="arrow-rose-left" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M 10 0 L 0 5 L 10 10 z" fill="#dc2626"/>
</marker>
</defs>
<rect width="760" height="460" fill="#fafbfc" rx="8"/>
<!-- Title -->
<rect x="0" y="0" width="760" height="44" fill="url(#header)" rx="8"/>
<rect x="0" y="36" width="760" height="8" fill="url(#header)"/>
<text x="380" y="28" fill="#fff" font-size="15" font-weight="700" text-anchor="middle">MCP Tools — 工具发现 + 动态工具池</text>
<!-- Legend -->
<rect x="40" y="56" width="12" height="10" rx="2" fill="#f0f4ff" stroke="#2563eb" stroke-width="1"/>
<text x="58" y="66" fill="#2563eb" font-size="10" font-weight="600">s04 基础循环</text>
<rect x="140" y="56" width="12" height="10" rx="2" fill="#fff1f2" stroke="#dc2626" stroke-width="1"/>
<text x="158" y="66" fill="#dc2626" font-size="10" font-weight="600">s14 新增</text>
<!-- ===== Row 1: Lead Loop (s13 preserved) ===== -->
<rect x="20" y="90" width="70" height="40" rx="8" fill="#eef2ff" stroke="#4f46e5" stroke-width="1.5"/>
<text x="55" y="114" fill="#4f46e5" font-size="8" font-weight="600" text-anchor="middle">turn</text>
<line x1="90" y1="110" x2="104" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="107" y="90" width="70" height="40" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="142" y="114" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">messages</text>
<line x1="177" y1="110" x2="191" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="194" y="86" width="80" height="48" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="234" y="114" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">prompt</text>
<line x1="274" y1="110" x2="288" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="291" y="86" width="70" height="48" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="326" y="114" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">LLM</text>
<line x1="361" y1="110" x2="375" y2="110" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="378" y="76" width="356" height="72" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="556" y="94" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">TOOL DISPATCH动态工具池</text>
<text x="394" y="109" fill="#2563eb" font-size="7.5">bash · read · write · edit · glob</text>
<text x="394" y="121" fill="#7c3aed" font-size="7.5" font-weight="700">connect_mcp</text>
<text x="394" y="133" fill="#b45309" font-size="7.5" font-weight="700">已连接 server 的 mcp__server__tool</text>
<text x="394" y="145" fill="#dc2626" font-size="7.5" font-weight="700">★ connect_mcp + 动态 mcp__server__tool 工具</text>
<!-- Loop back -->
<path d="M 734 110 L 748 110 L 748 150 L 55 150 L 55 130" fill="none" stroke="#94a3b8" stroke-width="1" marker-end="url(#arrow)" stroke-dasharray="5,4"/>
<!-- ===== Row 2: MCP Architecture (s14 new) ===== -->
<rect x="30" y="172" width="700" height="215" rx="8" fill="#fff1f2" stroke="#dc2626" stroke-width="2"/>
<text x="380" y="194" fill="#991b1b" font-size="11" font-weight="700" text-anchor="middle">MCP 架构s14 新增:标准协议 + 外部工具动态接入)</text>
<!-- Agent Side -->
<rect x="50" y="210" width="255" height="140" rx="6" fill="#fff" stroke="#dc2626" stroke-width="1.5"/>
<text x="177" y="230" fill="#991b1b" font-size="10" font-weight="700" text-anchor="middle">Agent Side (MCPClient)</text>
<rect x="65" y="240" width="225" height="24" rx="4" fill="#fef2f2" stroke="#fca5a5" stroke-width="0.5"/>
<text x="177" y="256" fill="#475569" font-size="8" text-anchor="middle">connect_mcp → discover → 注册工具</text>
<rect x="65" y="272" width="225" height="24" rx="4" fill="#fef2f2" stroke="#fca5a5" stroke-width="0.5"/>
<text x="177" y="288" fill="#475569" font-size="8" text-anchor="middle">assemble_tool_pool 组装 builtin + mcp</text>
<rect x="65" y="304" width="225" height="24" rx="4" fill="#fef2f2" stroke="#fca5a5" stroke-width="0.5"/>
<text x="177" y="320" fill="#475569" font-size="8" text-anchor="middle">handler → call_tool("search", args)</text>
<!-- Communication arrows -->
<line x1="305" y1="262" x2="435" y2="262" stroke="#dc2626" stroke-width="1.5" marker-end="url(#arrow-rose)"/>
<text x="370" y="256" fill="#dc2626" font-size="7" font-weight="600" text-anchor="middle">tools/list</text>
<line x1="435" y1="296" x2="305" y2="296" stroke="#dc2626" stroke-width="1.5" marker-end="url(#arrow-rose)"/>
<text x="370" y="312" fill="#dc2626" font-size="7" font-weight="600" text-anchor="middle">tools/call + response</text>
<!-- MCP Servers -->
<rect x="438" y="210" width="275" height="140" rx="6" fill="#fff" stroke="#ca8a04" stroke-width="1.5"/>
<text x="575" y="230" fill="#854d0e" font-size="10" font-weight="700" text-anchor="middle">MCP Servers (外部服务)</text>
<rect x="453" y="240" width="245" height="28" rx="4" fill="#fefce8" stroke="#facc15" stroke-width="0.5"/>
<text x="575" y="258" fill="#854d0e" font-size="9" font-weight="600" text-anchor="middle">docs server: search · get_version</text>
<rect x="453" y="276" width="245" height="28" rx="4" fill="#fefce8" stroke="#facc15" stroke-width="0.5"/>
<text x="575" y="294" fill="#854d0e" font-size="9" font-weight="600" text-anchor="middle">deploy server: trigger · status</text>
<rect x="453" y="312" width="245" height="28" rx="4" fill="#fefce8" stroke="#facc15" stroke-width="0.5"/>
<text x="575" y="330" fill="#854d0e" font-size="9" font-weight="600" text-anchor="middle">本章使用进程内模拟 server</text>
<!-- Naming convention -->
<rect x="50" y="360" width="660" height="20" rx="4" fill="#fef3c7" stroke="#d97706" stroke-width="1"/>
<text x="380" y="374" fill="#92400e" font-size="8" text-anchor="middle">工具命名: mcp__{server}__{tool} → 例: mcp__docs__search · mcp__deploy__trigger · 避免不同 server 的工具名冲突</text>
<!-- ===== Row 3: Bottom notes ===== -->
<rect x="30" y="400" width="700" height="22" rx="4" fill="#f8fafc" stroke="#e2e8f0" stroke-width="1"/>
<rect x="50" y="408" width="12" height="10" rx="2" fill="#f0f4ff" stroke="#2563eb" stroke-width="1"/>
<text x="70" y="418" fill="#475569" font-size="10">s04: 基础工具 + Hooks + Permission</text>
<rect x="420" y="408" width="12" height="10" rx="2" fill="#fff1f2" stroke="#dc2626" stroke-width="1"/>
<text x="440" y="418" fill="#475569" font-size="10">s14: MCP + dynamic tool pool</text>
<!-- ===== Final note ===== -->
<rect x="30" y="430" width="700" height="22" rx="4" fill="#fff1f2" stroke="#dc2626" stroke-width="1"/>
<text x="380" y="444" fill="#991b1b" font-size="9" font-weight="600" text-anchor="middle">下一章 s15把工具、权限、团队、worktree、MCP 等机制合回同一个 while True 循环。</text>
</svg>

After

Width:  |  Height:  |  Size: 7.7 KiB