Agent Build智能体搭建 Tutor教程
Map地图 / Module模块 6 / labs/m06_*

Tools and MCP工具与 MCP

Give the model typed actions, and serve them over a protocol any harness can call.给模型提供带类型的动作,并通过任何 Harness 都能调用的协议对外提供。

What it is and why it exists它是什么,为什么需要它

What是什么

A tool is a function with a name, a description, and a JSON schema for its arguments. The Model Context Protocol (MCP) is a standard way to serve tools from a separate process so any compatible client can list and call them.工具是一个带有名称、描述和参数 JSON schema 的函数。模型上下文协议(MCP)是一种标准方式,让工具由独立进程提供,任何兼容的客户端都能列出并调用它们。

Why为什么

Tools are how an agent reads data and acts. Serving them over MCP means the chat agent, a coding agent, and a managed platform share one implementation. Tool design also decides how often the model picks the wrong instrument.工具是智能体读取数据和执行操作的途径。通过 MCP 提供工具,聊天智能体、编程智能体和托管平台就能共用一套实现。工具的设计也决定了模型选错工具的频率。

How it works工作原理

Where it sits in the build order它在搭建顺序中的位置

Needs first前置模块

  • API and gatewayAPI 与网关Tool calling rides on the chat contract: schemas go in the request and tool calls come back in the response. Key scope decides who gets tools.工具调用建立在 chat 契约之上:schema 随请求发出,工具调用随响应返回。密钥的权限范围决定谁能用工具。Build out of order不按顺序搭建 Stand in with:可用以下替代: Call the tool functions directly from a script. No model is needed to build and test a tool.直接在脚本里调用工具函数。搭建和测试工具不需要模型。
  • RAG and knowledge graphRAG 与知识图谱The first tool wraps search. Its result shape and diagnostic come from the retrieval module.第一个工具封装的就是检索。它的结果结构和诊断信息来自检索模块。Build out of order不按顺序搭建 Stand in with:可用以下替代: A tool that reads a small CSV file. The lab includes one.一个读取小型 CSV 文件的工具。lab 里自带一个。

Unlocks解锁

  • Harness engineeringHarness 工程A loop with no tools is a chat proxy. You need a registry with at least one tool to exercise the tool path.没有工具的循环只是个聊天代理。至少要有一个带工具的注册表,才能走通工具路径。
  • Guardrails and verification护栏与验证The guard compares the answer with tool results. Tools must return values it can parse.护栏把回答与工具结果比对。工具必须返回它能解析的值。
  • SDKs and frameworksSDK 与框架Tools are what you carry between SDKs. Having them behind one registry and one MCP server makes the comparison a few lines per SDK.工具是你在各个 SDK 之间带着走的东西。把它们放在一个注册表和一个 MCP 服务后面,每个 SDK 的对比就只需要几行代码。

In the reference build在参考系统中

Path路径Role作用
apps/agent-server/tools/registry.pySchemas and the call_tool dispatcher.schema 和 call_tool 分发器。
apps/agent-server/mcp_client.pyConnects to external MCP servers and registers their tools.连接外部 MCP 服务并注册它们的工具。
apps/mcp-servers/brainbank/server.pyServes the knowledge and data tools to any MCP client.向任何 MCP 客户端提供知识和数据工具。
.mcp.jsonClient config: command, arguments, environment, timeout.客户端配置:命令、参数、环境变量、超时。

Process map流程图

One tool call, from the model's request to the tool message一次工具调用:从模型的请求到工具消息

  1. 1
    Model emits a tool call模型发出工具调用A name and a JSON string of arguments.一个名称和一段 JSON 字符串形式的参数。
  2. 2
    Look up by name按名称查找Unknown names return an error object listing known tools.未知的名称会返回一个错误对象,并列出已有的工具。
  3. 3
    Run执行Local function or MCP server. The caller cannot tell which.本地函数或 MCP 服务。调用方分辨不出是哪种。
  4. 4
    Catch everything捕获所有异常Exceptions become data the model can read.异常被转成模型可以读懂的数据。
  5. 5
    Cap and note截断并注明Long results are cut, with a note saying so.过长的结果会被截断,并注明已截断。
  6. 6
    Log记录日志Tool, arguments, duration, empty or error.工具名、参数、耗时、是否为空或出错。
  7. 7
    Tool message工具消息A role=tool message goes back into the conversation.一条 role=tool 的消息被放回对话。

Build steps搭建步骤

Follow them in order the first time. Each step names what it uses from earlier steps and what it leaves for later ones. Code is read from the lab files, and output is what the lab printed when it was run.第一次请按顺序做。每一步都写明它用到前面步骤的什么成果,又为后面的步骤留下什么。代码直接读取自 lab 文件,输出是 lab 实际运行时打印的内容。

  1. 1Decide the tool list on paper先在纸上确定工具清单
  2. 2Build the registry搭建注册表
  3. 3Write the tools, with diagnostics for empty results编写工具,并为空结果提供诊断
  4. 4Check errors, caps, and cost检查错误处理、截断和开销
  5. 5Serve the same tools over MCP通过 MCP 提供同一批工具
  6. 6Call the server the way a client does像客户端那样调用服务
  7. 7Register the server in each client在各个客户端里注册这个服务
01Decide the tool list on paper先在纸上确定工具清单
Why this step is here为什么这一步排在这里Every tool's schema is sent on every turn, and every extra tool is another way to answer with the wrong instrument. Decide the list before writing any of them.每个工具的 schema 每一轮都要发送,每多一个工具就多一种用错工具的可能。动手写之前先把清单定下来。
Uses用到Nothing from earlier steps.不依赖之前的任何步骤。

Do this操作

  1. Write the questions your agent must answer. Group them by the kind of data that answers them.写下智能体必须回答的问题,按回答它们所需的数据类型分组。
  2. One tool per group. The lab has two: documents and expense records.每组一个工具。lab 里有两个:文档和报销记录。
  3. For each tool write one sentence that says when to use it. That sentence becomes the description.为每个工具写一句话,说明何时使用它。这句话就是工具描述。
You are done when完成标志For any question on your list, exactly one tool is the obvious choice.对清单上的任何问题,都恰好有一个工具是显而易见的选择。
Produces产出A tool list: name, when to use, arguments.一份工具清单:名称、使用时机、参数。
Feeds供给
02Build the registry搭建注册表
Why this step is here为什么这一步排在这里The registry comes before the tools so every tool is born with a schema, a log record, and a size cap. Adding those later to tools that already exist is how some get missed.注册表先于工具,这样每个工具从一开始就有 schema、日志记录和大小上限。等工具都写好了再补,总会有漏掉的。
Uses用到

Do this操作

  1. A decorator builds the JSON schema from the function signature.用一个装饰器根据函数签名生成 JSON schema。
  2. `call()` never raises. Unknown tool, bad arguments, and exceptions all return an error object.`call()` 从不抛异常。未知工具、参数错误和运行异常都返回错误对象。
  3. `call_as_text()` produces the string for the tool message and cuts it at a limit with a note.`call_as_text()` 生成工具消息的字符串,超出上限时截断并注明。
  4. Every call appends a record: tool, arguments, milliseconds, empty, error.每次调用追加一条记录:工具、参数、毫秒数、是否为空、错误。
labs/m06_tools/registry.py · registry
class Registry:
    def __init__(self):
        self.tools: dict = {}          # name -> (schema, callable)
        self.log: list = []            # one record per call

    def tool(self, description: str, enums: Optional[dict] = None):
        """Decorator. Builds the JSON schema from the function signature."""
        def wrap(fn: Callable):
            props, required = {}, []
            hints = get_type_hints(fn)
            for name, p in inspect.signature(fn).parameters.items():
                props[name] = {"type": _PY_TO_JSON.get(hints.get(name), "string")}
                if enums and name in enums:
                    props[name]["enum"] = enums[name]
                if p.default is inspect.Parameter.empty:
                    required.append(name)
            schema = {"type": "function", "function": {
                "name": fn.__name__, "description": description,
                "parameters": {"type": "object", "properties": props, "required": required}}}
            self.tools[fn.__name__] = (schema, fn)
            return fn
        return wrap

    def schemas(self) -> list:
        return [schema for schema, _ in self.tools.values()]

    def schema_cost(self) -> int:
        """Rough tokens these schemas add to every single turn."""
        return len(json.dumps(self.schemas())) // 4

    def call(self, name: str, arguments: dict) -> dict:
        """Run a tool. Never raises: errors come back as data the model can read."""
        t0 = time.time()
        if name not in self.tools:
            result = {"error": f"unknown tool '{name}'", "known_tools": sorted(self.tools)}
        else:
            try:
                result = self.tools[name][1](**arguments)
            except TypeError as e:
                result = {"error": f"bad arguments: {e}"}
            except Exception as e:  # noqa: BLE001
                result = {"error": f"{type(e).__name__}: {e}"}
        self.log.append({"tool": name, "arguments": arguments, "ms": int((time.time() - t0) * 1000),
                         "empty": not result.get("rows", result.get("results", [1])),
                         "error": result.get("error")})
        return result

    def call_as_text(self, name: str, arguments: dict) -> str:
        """What goes into the role='tool' message: JSON, capped, with a note when cut."""
        text = json.dumps(self.call(name, arguments), default=str)
        if len(text) > MAX_RESULT_CHARS:
            text = text[:MAX_RESULT_CHARS] + f' ...[truncated, {len(text)} chars total; narrow the query]'
        return text
You are done when完成标志Calling a tool that does not exist returns an error with the list of known tools.调用不存在的工具时,返回带有已知工具列表的错误。
Produces产出`Registry`: schemas(), call(), call_as_text(), log.`Registry`:schemas()、call()、call_as_text()、log。
03Write the tools, with diagnostics for empty results编写工具,并为空结果提供诊断
Why this step is here为什么这一步排在这里Tools are written against the registry and wrap the modules below: search from retrieval, and a data source. The diagnostic is written now because the harness and the learner both depend on it.工具基于注册表编写,封装的是下层模块:来自检索模块的 search,以及一个数据源。诊断信息现在就要写,因为 Harness 和学习任务都依赖它。
Uses用到

Do this操作

  1. `search_policy` calls search and returns source, tier, section, text.`search_policy` 调用 search,返回来源、等级、章节、正文。
  2. `query_expenses` filters rows and returns rows, count, total.`query_expenses` 过滤数据行,返回行、数量、合计。
  3. When no rows match, test each filter: would dropping it alone return rows? Name that filter and list the values that exist.没有匹配的行时,逐个测试过滤条件:只去掉它是否就有结果?指出这个条件,并列出实际存在的取值。
labs/m06_tools/tools.py · tools
def build_registry(db: sqlite3.Connection) -> Registry:
    reg = Registry()
    expenses = load_expenses()

    @reg.tool("Search policy documents. Use for rules, limits, definitions and deadlines. "
              "Returns passages with their source file.", enums={"collection": ["POLICY"]})
    def search_policy(query: str, collection: str = "POLICY") -> dict:
        res = search(db, collection, query, top_k=3)
        out = {"results": [{"source": r["source"], "tier": r["tier"], "section": r["context"], "text": r["text"]} for r in res["results"]]}
        if "diagnostic" in res:
            out["diagnostic"] = res["diagnostic"]
        return out

    @reg.tool("Total and list expense records. Use for questions about what was actually spent. "
              "Filters are optional: category (lodging, meals, air), city, cost_center, month (YYYY-MM).")
    def query_expenses(category: str = "", city: str = "", cost_center: str = "", month: str = "") -> dict:
        filters = {"category": category, "city": city, "cost_center": cost_center, "month": month}
        active = {k: v for k, v in filters.items() if v}

        def keep(row, use):
            return all((row["date"].startswith(v) if k == "month" else row[k].lower() == v.lower())
                       for k, v in use.items())

        rows = [r for r in expenses if keep(r, active)]
        out = {"filters": active, "rows": rows, "count": len(rows),
               "total_usd": round(sum(r["amount_usd"] for r in rows), 2)}
        if not rows and active:
            # Which single filter, if dropped, would have returned rows?
            culprits = [k for k in active if any(keep(r, {a: b for a, b in active.items() if a != k}) for r in expenses)]
            known = {k: sorted({(r["date"][:7] if k == "month" else r[k]) for r in expenses}) for k in active}
            out["diagnostic"] = (f"{' and '.join(culprits) or 'the combination of filters'} emptied this result. "
                                 f"Values that exist: {known}")
        return out

    return reg
run
python3 -m labs.m06_tools.demo
Recorded output / 记录的输出 · m06.demo
2 schema: {'type': 'object', 'properties': {'category': {'type': 'string'}, 'city': {'type': 'string'}, 'cost_center': {'type': 'string'}, 'month': {'type': 'string'}}, 'required': []}
3 meals, CC-200: 2 rows, total 179.1
4 meals, 2026-07: 0 rows -> month emptied this result. Values that exist: {'category': ['air', 'lodging', 'meals'], 'month': ['2026-03', '2026-04', '2026-05', '2026-06']}
You are done when完成标志Line 4 names `month` as the filter that emptied the result and lists the months that exist.第 4 行指出是 `month` 这个条件导致结果为空,并列出实际存在的月份。
Produces产出`build_registry()`: two tools the agent can call.`build_registry()`:智能体可调用的两个工具。
04Check errors, caps, and cost检查错误处理、截断和开销
Why this step is here为什么这一步排在这里These are the properties the loop will rely on without checking. Verify them here, where a failure is one line of output and not a broken conversation.这些是循环会直接依赖而不再检查的特性。在这里验证,出问题只是一行输出;到了循环里,就是一次失败的对话。

Do this操作

  1. Read lines 5 and 6: an unknown tool and a bad argument both return data.看第 5、6 行:未知工具和错误参数都返回数据。
  2. Read line 1: the schema cost in tokens. This is charged on every turn.看第 1 行:schema 的 token 开销。这个开销每一轮都要付。
  3. Read line 8: the call log already separates ok, empty, and error.看第 8 行:调用日志已经区分了 ok、empty 和 error。
Recorded output / 记录的输出 · m06.demo
1 tools: ['search_policy', 'query_expenses'] | schema cost per turn ~ 198 tokens
5 unknown tool: {'error': "unknown tool 'delete_everything'", 'known_tools': ['query_expenses', 'search_policy']}
6 bad argument: {'error': "bad arguments: build_registry.<locals>.query_expenses() got an unexpected keyword argument 'year'"}
7 as tool message: 1795 chars (fits)
8 call log: [('query_expenses', 'ok'), ('query_expenses', 'empty'), ('delete_everything', 'error'), ('query_expenses', 'error'), ('query_expenses', 'ok')]
You are done when完成标志No call in the demo raised, and you know the per-turn schema cost.demo 中没有任何调用抛异常,并且你知道了每轮的 schema 开销。
Produces产出A measured schema cost and a call log format. Self-observation reads this log.一个实测的 schema 开销和一种调用日志格式。自我观察任务会读这份日志。
Feeds供给
05Serve the same tools over MCP通过 MCP 提供同一批工具
Why this step is here为什么这一步排在这里It follows the local tools because it wraps them. One implementation then serves every harness, which is what makes the rest of this curriculum portable.它排在本地工具之后,因为它是对本地工具的封装。这样一套实现就能服务所有 Harness,这也是整套课程可以移植的基础。

Do this操作

  1. Install the SDK: `pip install mcp`.安装 SDK:`pip install mcp`。
  2. Create a server object and register each tool with a decorator. The docstring is the description.创建服务对象,用装饰器注册每个工具。docstring 就是工具描述。
  3. Each MCP tool calls the registry, so caps and logging still apply.每个 MCP 工具都调用注册表,所以截断和日志依然生效。
  4. Note the import. SDK version 2 renamed the server class. The lab imports whichever exists.注意导入语句。SDK 第 2 版给服务类改了名。lab 会导入实际存在的那个。
labs/m06_tools/mcp_server.py · mcp
try:                                    # mcp 2.x renamed FastMCP to MCPServer
    from mcp.server.mcpserver import MCPServer as FastMCP
except ImportError:                     # mcp 1.x
    from mcp.server.fastmcp import FastMCP

from labs.m05_rag.demo import build
from labs.m06_tools.tools import build_registry

mcp = FastMCP("policy-desk")
_db, _ = build(fresh=False)
_reg = build_registry(_db)


@mcp.tool()
def search_policy(query: str) -> dict:
    """Search policy documents. Use for rules, limits, definitions and deadlines."""
    return _reg.call("search_policy", {"query": query})


@mcp.tool()
def query_expenses(category: str = "", city: str = "", cost_center: str = "", month: str = "") -> dict:
    """Total and list expense records. Filters are optional: category, city, cost_center, month (YYYY-MM)."""
    return _reg.call("query_expenses", {"category": category, "city": city, "cost_center": cost_center, "month": month})


if __name__ == "__main__":
    mcp.run()
You are done when完成标志`python3 -m labs.m06_tools.mcp_server` starts and waits for input without an error.`python3 -m labs.m06_tools.mcp_server` 能启动并等待输入,不报错。
Produces产出An MCP server any client can start from a command.一个任何客户端都能通过命令启动的 MCP 服务。
06Call the server the way a client does像客户端那样调用服务
Why this step is here为什么这一步排在这里Test the protocol path before handing the server to a client you do not control.在把服务交给你无法控制的客户端之前,先测试协议这条路径。
Uses用到

Do this操作

  1. Start the server as a subprocess over stdio.通过 stdio 以子进程方式启动服务。
  2. Initialize, list tools, call one, parse the result.初始化、列出工具、调用一个、解析结果。
labs/m06_tools/mcp_check.py · client
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client


async def main() -> None:
    params = StdioServerParameters(command=sys.executable, args=["-m", "labs.m06_tools.mcp_server"])
    async with stdio_client(params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            tools = await session.list_tools()
            print("tools over MCP:", [t.name for t in tools.tools])
            result = await session.call_tool("query_expenses", {"category": "lodging", "city": "Boston"})
            payload = json.loads(result.content[0].text)
            print("query_expenses(lodging, Boston):", payload["count"], "row, total", payload["total_usd"])
run
python3 -m labs.m06_tools.mcp_check
Recorded output / 记录的输出 · m06.mcp
tools over MCP: ['search_policy', 'query_expenses']
query_expenses(lodging, Boston): 1 row, total 219.0
You are done when完成标志Both tool names are listed and the call returns one row totaling 219.0.两个工具名都被列出,调用返回一行,合计 219.0。
Produces产出Proof the tools work over the protocol.工具可以通过协议正常工作的证据。
07Register the server in each client在各个客户端里注册这个服务Not executed in the labslab 中未执行
Why this step is here为什么这一步排在这里Last, because each client needs only a config entry pointing at a server that is already tested.放在最后,因为每个客户端只需要一条指向已测试服务的配置。

Do this操作

  1. Add an entry with a command, arguments, and working directory.添加一条配置,包含命令、参数和工作目录。
  2. Use an absolute path to the Python interpreter. Clients start servers with a minimal environment.Python 解释器要用绝对路径。客户端启动服务时环境变量很少。
  3. In the client, list tools and confirm both appear.在客户端里列出工具,确认两个都出现。
.mcp.json (Claude Code; Cursor uses the same shape in .cursor/mcp.json)
{
  "mcpServers": {
    "policy-desk": {
      "command": "/abs/path/to/venv/bin/python3",
      "args": ["-m", "labs.m06_tools.mcp_server"],
      "cwd": "/abs/path/to/aitutor"
    }
  }
}

Codex uses a TOML file with an `[mcp_servers.policy-desk]` table holding the same command and args. Check each client's current documentation for the file location.Codex 使用 TOML 文件,在 `[mcp_servers.policy-desk]` 表里写同样的 command 和 args。配置文件的位置请查各客户端当前的文档。

This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。

Checked on the reference machine在参考机器上的检查结果Not checked on a machine yet. On your own machine run the command below. It only reads, and it writes the result here when you add --write.还没有在机器上检查过。在你自己的机器上运行下面的命令。它只做读取操作;加上 --write 后会把结果写到这里。
run
python3 labs/machine/check.py --write
You are done when完成标志The client shows `search_policy` and `query_expenses` as available tools.客户端显示 `search_policy` 和 `query_expenses` 为可用工具。
Produces产出The same tools available in a coding agent or editor.同一批工具在编程智能体或编辑器里可用。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。

How it works with the other parts它如何与其他部分协作

What went wrong in the real build真实搭建中踩过的坑

2026-09

A confident explanation of data that existed对明明存在的数据给出了自信的“不存在”解释

What happened发生了什么
Asked about a purchase category, the agent got an empty result and explained at length why such purchases are not tracked. The data was there. The fiscal year filter was off by one.被问到某类采购时,智能体得到空结果,于是长篇解释为什么这类采购没有被记录。其实数据是有的,只是财年过滤条件差了一年。
Fix修复
Tools return a diagnostic naming the filter that emptied the result. The instructions forbid explaining absence.工具返回诊断信息,指出是哪个过滤条件导致为空。指令中禁止解释“为什么不存在”。
Lesson教训
An empty result means the filter matched nothing. It says nothing about the world.空结果只说明过滤条件没匹配到任何东西,并不说明现实中不存在。
2026-08

Twelve tools made the agent slower and more wrong十二个工具让智能体更慢、错得更多

What happened发生了什么
More tools meant more schema tokens on every turn and more ways to pick the wrong one.工具越多,每轮的 schema token 越多,选错工具的方式也越多。
Fix修复
Fewer tools, plus skills that say which tool answers which kind of question.减少工具数量,再用技能说明哪类问题用哪个工具。
Lesson教训
Tools add capability only when routing keeps up.只有路由跟得上,工具才能真正增加能力。
found while building the labs搭建 lab 时发现

The MCP SDK renamed its server classMCP SDK 给服务类改了名

What happened发生了什么
The lab was written against version 1 of the SDK. The installed version was 2, and the import failed.lab 是按 SDK 第 1 版写的,而安装的是第 2 版,导入失败。
Fix修复
Import whichever class exists, and run the client check in the test suite.导入实际存在的那个类,并把客户端检查纳入测试。
Lesson教训
Code you did not run is a guess, including code written from memory of a library.没跑过的代码只是猜测,凭记忆写的库调用也一样。

The same idea on other platforms同样的思路在其他平台上

Platform平台How this module maps本模块如何对应
DatabricksUnity Catalog functions are governed tools, and MCP servers are added in agent code with permissions granted in the bundle file. Unity Gateway governs access to MCP servers. A custom MCP server can be hosted as a Databricks App.Unity Catalog 函数是受管控的工具;MCP 服务在智能体代码中添加,权限在 bundle 文件里授予。Unity Gateway 管控对 MCP 服务的访问。自定义 MCP 服务可以作为 Databricks App 托管。
IBM watsonxOrchestrate tools are Python functions, OpenAPI specs, or MCP servers imported with the ADK. The MCP server from this module can be registered there.Orchestrate 的工具可以是 Python 函数、OpenAPI 规范,或通过 ADK 导入的 MCP 服务。本模块的 MCP 服务可以在那里注册。
CodexAdd MCP servers in the config file. Tools then appear to the agent. This is the direct route for reusing your own tools.在配置文件里添加 MCP 服务,工具就会出现在智能体中。这是复用你自己工具的最直接方式。
CursorAdd servers to the project MCP config. Same server, no code change.在项目的 MCP 配置里添加服务。同一个服务,无需改代码。
Claude Code / Agent SDKAdd servers to the project MCP file. The reference build shares one server between its chat agent and its coding agent this way.在项目的 MCP 文件里添加服务。参考系统就是这样让聊天智能体和编程智能体共用一个服务。
Another machineAn MCP server is a process speaking JSON-RPC over stdio or HTTP. It runs anywhere Python or Node runs.MCP 服务是一个通过 stdio 或 HTTP 使用 JSON-RPC 通信的进程。有 Python 或 Node 的地方就能运行。

Step-by-step guides per platform各平台的分步指南

Explain it back讲给自己听

Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。

A tool returns an empty list. What may the agent conclude?工具返回了空列表。智能体可以得出什么结论?
A strong answer参考答案Only that this filter matched nothing. It may report what it searched. It may not explain why the data cannot exist. The diagnostic names the filter to relax.只能得出“这个过滤条件没有匹配到任何东西”。它可以说明自己查了什么,但不可以解释数据为什么不存在。诊断信息会指出该放宽哪个条件。
Why does the registry come before the tools?为什么注册表先于工具?
A strong answer参考答案So every tool gets a schema, error handling, a size cap, and a log record from the start. Those are the properties the loop relies on.这样每个工具从一开始就有 schema、错误处理、大小上限和日志记录。循环依赖的正是这些特性。
Why serve tools over MCP when the harness could import them?Harness 明明可以直接导入工具,为什么还要通过 MCP 提供?
A strong answer参考答案One implementation then serves every harness. Moving to another platform means registering the server, with no rewrite.这样一套实现就能服务所有 Harness。迁移到其他平台只需要注册服务,不用重写。
Why must a tool never raise?为什么工具绝不能抛异常?
A strong answer参考答案An exception ends the request. An error object goes back to the model, which can correct its arguments and try again within the round budget.异常会终止整个请求。而错误对象会返回给模型,模型可以修正参数,在轮次预算内重试。

Terms术语

SchemaSchemaThe JSON description of a tool's arguments that is sent to the model.发送给模型的、描述工具参数的 JSON。
Diagnostic诊断信息A field in an empty result that names what emptied it.空结果里的一个字段,说明是什么导致结果为空。
MCPMCPModel Context Protocol. A standard for serving tools from a separate process.模型上下文协议。由独立进程提供工具的一种标准。

From the live build来自实时构建

Recent changes and files the sync job filed under this module. These lines are in English as written in the build.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。

Ask the tutor about this module就本模块向导师提问