Files
gitmost/packages/mcp/test/unit/tool-timing.test.mjs
T
agent_coder 7cb3199d09 refactor(mcp)!: BREAKING — все имена MCP-тулов snake_case → camelCase (унификация с in-app) (#412)
Один логический тул жил под двумя именами: внешний MCP snake_case
(edit_page_text), in-app camelCase (editPageText) — дублирование доков, путаница
при переносе промптов/скиллов, помеха шарингу спек (#294). Решение владельца:
единый camelCase везде, включая внешний MCP. После этого mcpName === inAppKey.

- tool-specs.ts: mcpName ВЫВЕДЕН из ключа спеки (mcpName == inAppKey) для всех
  43 shared-спек — раньше divergent snake, теперь равен ключу (проверено: mcpName
  читается только структурно — цикл регистрации, генератор <tool_inventory>,
  TOOL_FAMILY). +5 inline-регистраций (tableGet/updateComment/deleteComment/
  docmostTransform; search без изменений). Рантайм: 47 тулов, все camelCase, ноль
  подчёркиваний.
- Контракт-конвенция ИНВЕРТИРОВАНА: shared-tool-specs.contract.spec
  `mcpName === toSnake(inAppKey)` → `mcpName === inAppKey`; tool-specs.test
  и tool-inventory.test обновлены.
- ROUTING_PROSE/TOOL_FAMILY/INLINE_MCP_INVENTORY (server-instructions.ts) →
  camelCase (105 замен). ai-chat.prompt/guard уже на in-app camelCase-ключах —
  без изменений (guard прошёл). comment-signal EXCLUDED_TOOLS схлопнут с
  дублей snake+camel до camelCase.
- Некоторое неочевидное: assertUnambiguousMatch(op: "patch_node"|"delete_node")
  в prosemirror-markdown/node-ops — op интерполируется в model-facing ошибку;
  литерал-юнион + call-sites → "patchNode"|"deleteNode".
- Все snake-имена в описаниях/error-строках/комментах/тестах/доках → camelCase
  (whole-token, longest-match-first). CHANGELOG: BREAKING-таблица 46 строк +
  миграция (allowlists mcp__gitmost-*__get_node→__getNode, промпты/скиллы,
  .mcp.json, метрики по tool-label); релизится вместе с #411.
  Внутренние имена методов (PageService.updatePageContent и т.п.) НЕ тронуты —
  переименованы только ИМЕНА ТУЛОВ.

Гейт: mcp node --test 677/677; tsc -p apps/server чисто; jest ai-chat-tools.
service + shared-tool-specs.contract + tool-tiers + ai-chat.prompt +
comment-signal-inapp → 323. Второй линк breaking-окна (#411→ЭТОТ→#413→#415).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 19:10:38 +03:00

68 lines
2.4 KiB
JavaScript

import { test } from "node:test";
import assert from "node:assert/strict";
import { timeToolHandler } from "../../build/index.js";
// #402 — the registerTool wrapper times every tool through a single choke point
// and feeds the host's dependency-neutral onMetric sink. These assert the
// timing contract without a live transport (the factory monkeypatches
// server.registerTool with exactly this helper).
test("times a tool and preserves the handler's return value", async () => {
const calls = [];
const onMetric = (name, value, labels) => calls.push({ name, value, labels });
const handler = async (arg) => ({ ok: true, echo: arg });
const wrapped = timeToolHandler("getPage", handler, onMetric);
const result = await wrapped("hello");
// Return value passes through untouched.
assert.deepEqual(result, { ok: true, echo: "hello" });
// Exactly one sample, correct name/labels, numeric non-negative duration.
assert.equal(calls.length, 1);
assert.equal(calls[0].name, "mcp_tool_duration_seconds");
assert.deepEqual(calls[0].labels, { tool: "getPage" });
assert.equal(typeof calls[0].value, "number");
assert.ok(calls[0].value >= 0, "duration must be non-negative seconds");
});
test("standalone (no onMetric) is a transparent pass-through", async () => {
const handler = async (a, b) => a + b;
const wrapped = timeToolHandler("noop_tool", handler, undefined);
// No throw, result unchanged, and nothing to observe.
const result = await wrapped(2, 3);
assert.equal(result, 5);
});
test("still observes on throw, then rethrows the original error", async () => {
const calls = [];
const onMetric = (name, value, labels) => calls.push({ name, value, labels });
const boom = new Error("handler failed");
const handler = async () => {
throw boom;
};
const wrapped = timeToolHandler("boom_tool", handler, onMetric);
await assert.rejects(() => wrapped(), (err) => err === boom);
// Observed exactly once despite the throw.
assert.equal(calls.length, 1);
assert.equal(calls[0].name, "mcp_tool_duration_seconds");
assert.deepEqual(calls[0].labels, { tool: "boom_tool" });
});
test("standalone still rethrows the original error (no swallow, no observe)", async () => {
const boom = new Error("standalone failure");
const wrapped = timeToolHandler(
"boom_standalone",
async () => {
throw boom;
},
undefined,
);
await assert.rejects(() => wrapped(), (err) => err === boom);
});