# 第 13 周：先把查询做成只读工具

> 用官方 MCP SDK 的独立客户端和服务进程实跑维修工单只读工具，关联请求与服务审计，核对允许、未知身份、跨车间和参数拒绝；保留生产认证未测的边界。

原文：https://cs-wude-fde-learning.pages.dev/course/week-13-read-only-mcp/
维护者：[wude](https://cs-wude-fde-learning.pages.dev/about/)
内容更新：2026-11-05

> 现场练习 13 / 设备维修工单。所有组织、数据与业务情节均为模拟材料。

## 协议接通，不代表业务安全

MCP 是 Model Context Protocol。先读 [官方架构文档](https://modelcontextprotocol.io/docs/learn/architecture)，选择与你语言和版本匹配的 SDK。本站起步包只有业务函数，没有 MCP 传输层。

## 实验：只暴露一项查询

设计 `get_workorder_manual`，输入只包含业务所需的工单标识，不允许调用方自报主管角色。服务端根据可信会话取身份，再调用业务核心。

输出使用明确状态与允许公开的来源信息，错误时不给内部栈、密钥或受限资料。只读工具不应偷偷写业务状态；运行日志与业务副作用要分清。

先用真实 MCP 客户端或调试工具完成调用，再测试未知身份、跨车间工单和错误参数。普通函数测试不能代替协议联调。

## 工具提示不能替代服务端权限

`readOnlyHint` 和 `destructiveHint` 是 MCP `ToolAnnotations` 中的风险提示，字段名使用这里的驼峰写法。声明 `readOnlyHint: true` 不会自动禁止写操作，`destructiveHint: false` 也不会授予访问工单或执行操作的权限。客户端可以参考这些提示安排交互，但不能靠它们强制执行服务端授权；来自不可信服务端的提示也不能直接当成保证。参见[官方工具注解说明](https://blog.modelcontextprotocol.io/posts/2026-03-16-tool-annotations/)。

在工具合同中写清工单标识的必填项、类型和额外字段处理规则。服务端仍须验证参数、从可信会话取得身份、检查工单所属车间，并限制可返回的字段。不要接受参数中自报的角色或车间作为授权依据，也不要因为工具标了“只读”就跳过检查。

## 一个只读查询找到了两位技师，谁能独立接单？

假设这张维修教学工单要求同一人既熟悉硫化机（`tire_curing_press`），又掌握电气系统（`electrical_systems`）。查询返回两个编号。能不能把第一个编号填进工单的负责人栏？

微软 Repair Planner 的[练习说明](https://github.com/microsoft/agentic-factory-hack/blob/26b906d3e2e3f073ced52bd15ee2ae6c150625fe/challenge-2/README.md)给出了查询方法的骨架。打开同版本[示例实现](https://github.com/microsoft/agentic-factory-hack/blob/26b906d3e2e3f073ced52bd15ee2ae6c150625fe/challenge-2/example-solution/RepairPlanner/Services/CosmosDbService.cs)，查找 `QueryAvailableTechniciansBySkillsAsync`。在无部门筛选的情况下，它先取可用人员；有技能条件时，保留至少命中一项的人，再按命中项数等条件排序。这里要分别核对“出现在候选中”和“一个人具备本单要求的全部技能”。

[预览六条教学人员的技能摘录](https://cs-wude-fde-learning.pages.dev/downloads/repair-skills/technicians-skills.json)，将[technicians-skills.json 下载到本地](https://cs-wude-fde-learning.pages.dev/downloads/repair-skills/technicians-skills.json)，再保存[离线核对脚本](https://cs-wude-fde-learning.pages.dev/downloads/repair-skills/check-skills.py)，放在同一目录。摘录只保留[微软样例](https://github.com/microsoft/agentic-factory-hack/blob/26b906d3e2e3f073ced52bd15ee2ae6c150625fe/challenge-0/data/technicians.json)中的编号、可用标记和技能；复用摘录时请一并保存[微软 MIT 许可与版权声明](https://cs-wude-fde-learning.pages.dev/downloads/repair-skills/LICENSE.txt)。用 Python 3 运行以下命令，每次使用新报告文件名：

```sh
python3 check-skills.py technicians-skills.json split.json tire_curing_press electrical_systems
python3 check-skills.py technicians-skills.json single.json tire_curing_press hydraulic_systems
python3 check-skills.py technicians-skills.json unavailable.json load_cell_calibration
python3 check-skills.py technicians-skills.json unspecified.json
```

| 打开的报告 | 候选与缺项 | 工单交接写什么 |
| --- | --- | --- |
| `split.json` | tech-001 缺电气系统，tech-004 缺硫化机；`singlePersonAll` 为 `[]` | 两人各会一项，单人满足数为零；保留缺项，请负责人员确认是否允许组队。 |
| `single.json` | tech-001 同时命中硫化机和液压系统 | 标记为单人技能匹配，交给派工人员复核。 |
| `unavailable.json` | tech-003 的技能包含称重传感器校准，但样例把此人标为不可用，候选为空 | 记录本次可用名单无匹配，保留与“全员都不会”之间的区别。 |
| `unspecified.json` | 技能要求为空，五位可用人员均返回；本练习把 `singlePersonAll` 留为 `null` | 先补齐工单需求，再判断谁能独立承接。 |

交一条包含**工单要求、候选编号、每人缺少的技能、可否单人承接**的记录，并注明所用报告名。脚本按编号排列，便于核对每人的集合；上游的完整排序、部门筛选和数据库异常处理均可回到 C# 源码查看。这里复算公开样例的成功读取路径，未连接人员系统，也没有创建派工记录。

<h3 id="fit-repair-window" lang="en" tabindex="-1">Can the entire repair fit in one maintenance window?</h3>

A planner needs one window ID for an uninterrupted repair. Microsoft's [scheduling example](https://github.com/microsoft/agentic-factory-hack/blob/26b906d3e2e3f073ced52bd15ee2ae6c150625fe/challenge-3/agents/maintenance_scheduler_agent.py#L126-L133) reads a single maintenance window from a proposal. For this exercise, a repair may finish exactly when a window closes. It may not switch windows halfway through.

Save Microsoft's [maintenance-windows.json](https://raw.githubusercontent.com/microsoft/agentic-factory-hack/26b906d3e2e3f073ced52bd15ee2ae6c150625fe/challenge-0/data/maintenance-windows.json) under that exact name ([MIT license](https://github.com/microsoft/agentic-factory-hack/blob/26b906d3e2e3f073ced52bd15ee2ae6c150625fe/LICENSE)). Download the [offline window checker](https://cs-wude-fde-learning.pages.dev/downloads/fit-repair-window.py) into the same folder. With Python 3.8 or newer, run these commands there. The checker verifies the snapshot before reading its 17 teaching windows. Once both files are saved, you can disconnect.

```sh
python3 fit-repair-window.py 2026-01-05T04:00Z 180 split.json
python3 fit-repair-window.py 2026-01-05T03:00Z 180 night.json
python3 fit-repair-window.py 2026-01-05T05:00Z 60 choice.json
```

Open each JSON and compare these decisions.

- **04:00–07:00 UTC.** The night and early windows each overlap 120 minutes. Together they cover all 180 distinct minutes, but neither contains the whole repair. Leave the window ID open and ask for another start.
- **03:00–06:00 UTC.** The previous night's window, `mw-2026-01-04-night`, contains the job through its 06:00 close. Record that ID for review.
- **05:00–06:00 UTC.** Both the night window and `mw-2026-01-05-early` contain the same hour. Give the planner both IDs as alternatives for one repair.

Keep the start and end in UTC, the intersecting source IDs and their bounds, and all eligible IDs in your handoff. Try a new start or duration with a fresh report name. This checks time coverage in a fixed sample. A real booking also needs current availability and authorization.

## 通过协议边界验证四条路径

[下载只读 MCP 实验包](https://cs-wude-fde-learning.pages.dev/downloads/readonly-mcp-lab.zip)并解压到新目录。包里有客户端、服务端、锁文件、说明及起步包的原版 `lab.mjs`。在含 `package-lock.json` 的解压目录中运行：

```sh
npm ci --ignore-scripts --no-audit --no-fund
node client.mjs first-run
```

需要 Node.js 22.13+ 和 npm。首次安装要联网获取锁定的公开依赖；安装后，实验只通过本机标准输入输出通信，无须模型、账号或密钥。成功时终端显示 `passed | first-run/run.json`。再跑一次请换一个未使用的目录名，保留第一次记录。

客户端先发 `initialize`，再以 `tools/list` 发现唯一工具 `get_workorder_manual`，随后实际发出 `tools/call`。以下四类用了六次工具调用。打开自己的 `run.json`，在**同一会话**用请求 `id` 找到同号响应与审计 `requestId`；不同服务进程会重复使用请求号。

| 调用者与输入 | 客户端应取得 | 服务端对应记录 |
| --- | --- | --- |
| 固定 `tech-a` 查同车间 `T-101` | `found`；唯一来源是 `MAN-01` 第 2 版，只返回来源编号和版本 | `fixtureKnown: true`，`queryCalls: 1` |
| 用未知身份夹具另起服务，查同一工单 | `denied`；没有工单、手册或内部原因字段 | `fixtureKnown: false`，业务查询 1 次 |
| 固定 `tech-a` 查另一车间的 `T-201` | 同样只得到 `denied` | `fixtureKnown: true`，业务查询 1 次 |
| 工单编号缺失、编号为数值、或额外传入 `sessionId: "lead-a"` | 三次分别得到 JSON-RPC 参数错误 `-32602` | 每次都是 `input-rejected`，业务查询 0 次 |

**交给接手人两条记录。** 选一条 `denied` 和一条参数错误，记下服务进程号、请求号、实际返回、审计决定及调用数。再从各会话的 `server-close` 行核对退出码和信号。成功记录也保留 Node、SDK、协商的协议版本及材料摘要。找不到相配的响应或审计时，标明哪一侧缺件。

本机实跑使用 [TypeScript SDK 1.32.2 对应的 stdio 客户端源码](https://github.com/modelcontextprotocol/typescript-sdk/blob/3b73021a0a2272c0c04c3917bcdb03398b3ec63f/src/client/stdio.ts)，协商的协议为 2025-11-25。[stdio 传输约定](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#stdio) · [工具发现和调用](https://modelcontextprotocol.io/specification/2025-11-25/server/tools#protocol-messages)。服务端的审计经标准错误输出。身份是启动服务时选定的教学夹具；本实验没有验证真实用户登录、远程 HTTP、完整 MCP 能力或 Windows 环境。

## 参数不合约时，业务查询有没有被调用？

下面新增的只是**页面内作者编写的本地参数门**：身份固定在闭包中的 `tech-a`，输入必须是普通 JSON 对象，恰有一个自有字段 `ticketId`，且值严格符合 `^T-[0-9]{3}$`。这是本练习自定格式，不是原业务核心或 MCP 通用 ID 规范；原业务测试中的 `T-END` 等标识不受这个新增门约束。额外字段整次拒绝，不删除后再调用核心。

在[公开起步包](https://cs-wude-fde-learning.pages.dev/projects/)解压后的四文件目录中，用 Node.js 22+ 运行。计数包裹的确实是 `lab.query`，每个案例开始前清零；只调用查询和状态读取，没有批准预览或关闭操作。

本页 `<<` 首尾包装适用于 Bash / zsh；其他终端可按[保存为 .mjs 文件运行](https://cs-wude-fde-learning.pages.dev/projects/#run-lesson-file)操作，一个原代码块对应一个新文件，保留块内身份、日期与断言。

```bash
node --input-type=module <<'JS'
import assert from 'node:assert/strict';
import { createLab, fixtures } from './lab.mjs';
const originalFixtures = structuredClone(fixtures);
const lab = createLab();
const beforeState = ['T-101', 'T-102'].map(id => lab.readStatus('tech-a', id));
let calls = 0;
const countedQuery = (sessionId, ticketId) => {
  calls += 1;
  return lab.query(sessionId, ticketId);
};
function makeGate(query) {
  const fixedSession = 'tech-a';
  return args => {
    if (args === null || typeof args !== 'object' || Array.isArray(args)
      || Object.getPrototypeOf(args) !== Object.prototype
      || Reflect.ownKeys(args).length !== 1 || !Object.hasOwn(args, 'ticketId')) {
      return { status: 'input-rejected' };
    }
    const field = Object.getOwnPropertyDescriptor(args, 'ticketId');
    if (!Object.hasOwn(field, 'value') || typeof field.value !== 'string'
      || !/^T-[0-9]{3}$/.test(field.value)) return { status: 'input-rejected' };
    return query(fixedSession, field.value);
  };
}
const gate = makeGate(countedQuery);
const sources = fixtures.manuals.filter(m => m.workshop === 'A' && m.id === 'MAN-01'
  && m.version === 2 && m.section === 'inspection');
assert.equal(sources.length, 1);
const found = { status: 'found', sources: structuredClone(sources) };
const unavailable = { status: 'unavailable', sources: [] };
const denied = { status: 'denied' }, rejected = { status: 'input-rejected' };
const cases = [
  ['valid-101', { ticketId: 'T-101' }, found, 1],
  ['valid-102', { ticketId: 'T-102' }, unavailable, 1],
  ['cross-201', { ticketId: 'T-201' }, denied, 1],
  ['unknown-999', { ticketId: 'T-999' }, denied, 1],
  ['null', null, rejected, 0],
  ['array', [], rejected, 0],
  ['empty-object', {}, rejected, 0],
  ['numeric-id', { ticketId: 101 }, rejected, 0],
  ['blank-id', { ticketId: '   ' }, rejected, 0],
  ['extra-role', { ticketId: 'T-101', role: 'lead' }, rejected, 0],
  ['extra-session', { ticketId: 'T-101', sessionId: 'lead-a' }, rejected, 0],
  ['extra-workshop', { ticketId: 'T-101', workshop: 'B' }, rejected, 0],
  ['session-swap-102', { ticketId: 'T-102', sessionId: 'lead-a' }, rejected, 0],
  ['local-format', { ticketId: 'T-END' }, rejected, 0],
  ['trailing-newline', { ticketId: 'T-101\n' }, rejected, 0],
];
const originalCases = structuredClone(cases);
for (const [caseId, args, expected, expectedCalls] of cases) {
  calls = 0;
  const actual = gate(args);
  assert.deepEqual(actual, expected);
  assert.equal(calls, expectedCalls);
  console.log(JSON.stringify({ caseId, status: actual.status, calls }));
}
assert.deepEqual(cases, originalCases);
assert.deepEqual(fixtures, originalFixtures);
assert.deepEqual(['T-101', 'T-102'].map(id => lab.readStatus('tech-a', id)), beforeState);
JS
```

预期前四例各调用核心一次：T-101 返回完整适用 v2，T-102 返回 `unavailable`，跨车间 T-201 和格式合法但不存在的 T-999 都返回 `denied`。其余案例均为 `input-rejected` 且 `calls: 0`。特别是 `session-swap-102`，不能忽略其 `sessionId` 后继续查询，更不能接受它切换到主管身份。格式合法只允许进入业务判断，不证明资源存在或访问获权；零调用由完整结果和真实计数断言验证，不靠打印自证。

输出只保留 caseId、结果类别与调用数，不记录原参数或手册全文。`input-rejected` 是作者的本地返回约定，不是 MCP 标准 JSON-RPC 错误、`isError` 或自动审计记录；固定教学会话也不是真实认证。该门不替代业务授权或[第 7 周的输出字段合同](https://cs-wude-fde-learning.pages.dev/course/week-07-frontline-task-permissions/)。这段函数练习只检查本地参数门。需要协议侧的请求、响应与服务端记录时，运行本页上方的只读 MCP 实验包。

## 交付物

工具合同、SDK 与协议版本、实际启动步骤、一次客户端联调记录和授权测试。

## 验收与返工

完整结果必须跨过真实协议边界。尚未接通就标为“接口设计”，不能把示例 JSON 当成已运行服务器。

---

[← 上一周](https://cs-wude-fde-learning.pages.dev/course/week-12-cited-rag-evaluation/index.md) · [学习地图](https://cs-wude-fde-learning.pages.dev/roadmap/index.md) · [下一周 →](https://cs-wude-fde-learning.pages.dev/course/week-14-approved-write-action/index.md)
