tool-search.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { ToolSearchCandidate } from "@zcode/contracts";
  3. import { searchTools } from "../src/tool/search/search.js";
  4. import { collectDiscoveredTools, projectToolReferences } from "../src/tool/search/history.js";
  5. import { buildToolExposure, resolveToolSearchMode } from "../src/tool/search/exposure.js";
  6. import { createToolRegistry } from "../src/tool/registry.js";
  7. import { toolSearchToolEntry } from "../src/tool/handlers/tool-search.js";
  8. import { webFetchToolEntry } from "../src/tool/handlers/webfetch.js";
  9. import { webSearchToolEntry } from "../src/tool/handlers/websearch.js";
  10. import { todoWriteToolEntry } from "../src/tool/handlers/todo.js";
  11. import { enterPlanModeToolEntry, exitPlanModeToolEntry } from "../src/tool/handlers/plan-mode.js";
  12. import { taskOutputToolEntry } from "../src/tool/handlers/task-output.js";
  13. import { taskStopToolEntry } from "../src/tool/handlers/task-stop.js";
  14. import { sendMessageToolEntry } from "../src/tool/handlers/send-message.js";
  15. import {
  16. cronCreateToolEntry,
  17. cronListToolEntry,
  18. cronDeleteToolEntry,
  19. cronPauseSelfToolEntry,
  20. } from "../src/tool/handlers/cron.js";
  21. import { createTestRuntimeModel } from "./test-runtime-model.js";
  22. const catalog = [
  23. { name: "Read", aliases: ["read_file"], deferred: false, description: "Read files" },
  24. { name: "WebFetch", deferred: true, description: "Fetch content from a URL" },
  25. { name: "mcp__slack__send_message", deferred: true, description: "Send messages" },
  26. { name: "mcp__slack__search", deferred: true, description: "Search messages" },
  27. { name: "mcp__comms__send", deferred: true, description: "Send to slack" },
  28. ];
  29. describe("ToolSearch semantics", () => {
  30. it("searches built-in hints through the real scoped request catalog", () => {
  31. const registry = createToolRegistry();
  32. [
  33. toolSearchToolEntry,
  34. webFetchToolEntry,
  35. webSearchToolEntry,
  36. todoWriteToolEntry,
  37. enterPlanModeToolEntry,
  38. exitPlanModeToolEntry,
  39. taskOutputToolEntry,
  40. taskStopToolEntry,
  41. sendMessageToolEntry,
  42. cronCreateToolEntry,
  43. cronListToolEntry,
  44. cronDeleteToolEntry,
  45. cronPauseSelfToolEntry,
  46. ].forEach((entry) => registry.register(entry));
  47. const tools = registry.toContracts();
  48. const exposed = buildToolExposure({
  49. model: {
  50. ...createTestRuntimeModel({
  51. generateText: async () => ({ text: "", finishReason: "stop", usage: {} }),
  52. }),
  53. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  54. },
  55. tools,
  56. registry,
  57. entries: [],
  58. });
  59. for (const tool of exposed.context.catalog.filter((t) => t.deferred))
  60. expect(tool.searchHint, tool.name).toBeTruthy();
  61. for (const [query, name] of [
  62. ["logs", "TaskOutput"],
  63. ["cancel", "CronDelete"],
  64. ["active", "CronList"],
  65. ["pause", "CronPauseSelf"],
  66. ]) {
  67. expect(searchTools(query!, exposed.context.catalog)).toContain(name);
  68. expect(searchTools(`+${query}`, exposed.context.catalog)).toContain(name);
  69. }
  70. expect(searchTools("+cancel cron", exposed.context.catalog)).toEqual(["CronDelete"]);
  71. expect(searchTools("+logs absent", exposed.context.catalog)).toEqual(["TaskOutput"]);
  72. const scoped = exposed.context.catalog.filter((t) => t.name !== "CronDelete");
  73. expect(searchTools("+cancel cron", scoped)).not.toContain("CronDelete");
  74. });
  75. it("selects canonical tools and aliases without truncating direct selection", () => {
  76. expect(searchTools("select:WebFetch,read_file,WebFetch,missing", catalog, 1)).toEqual([
  77. "WebFetch",
  78. "Read",
  79. ]);
  80. expect(searchTools("select:read", catalog)).toEqual([]);
  81. expect(searchTools("read_file", catalog)).toEqual([]);
  82. expect(searchTools("read", catalog)).toEqual(["Read"]);
  83. });
  84. it("searches deferred tools by prefix and weighted name/description matches", () => {
  85. expect(searchTools("mcp__slack__", catalog, 1)).toEqual(["mcp__slack__send_message"]);
  86. expect(searchTools("slack send", catalog)[0]).toBe("mcp__slack__send_message");
  87. expect(searchTools("+slack send", catalog)).toContain("mcp__comms__send");
  88. expect(searchTools("files", catalog)).toEqual([]);
  89. expect(searchTools("nonexistent", catalog)).toEqual([]);
  90. });
  91. it("uses genuine results and the selected compact checkpoint, not ordinary calls", () => {
  92. const entries = [
  93. {
  94. message: { role: "user" as const, content: "summary" },
  95. metadata: {
  96. source: "legacy_synthetic" as const,
  97. compactBoundary: { boundaryId: "boundary", preCompactDiscoveredTools: ["WebFetch"] },
  98. },
  99. },
  100. {
  101. message: {
  102. role: "assistant" as const,
  103. content: "",
  104. toolCalls: [{ id: "read", name: "Read", input: {} }],
  105. },
  106. },
  107. {
  108. message: {
  109. role: "tool" as const,
  110. toolCallId: "search",
  111. toolName: "ToolSearch",
  112. content: [{ type: "tool_reference" as const, toolName: "mcp__slack__search" }],
  113. },
  114. },
  115. ];
  116. expect([...collectDiscoveredTools(entries)]).toEqual(["WebFetch", "mcp__slack__search"]);
  117. const before = structuredClone(entries);
  118. const off = projectToolReferences(entries, "off", []).entries;
  119. expect(off[2]?.message.content).toEqual([
  120. { type: "text", text: "[Tool references removed - tool search not enabled]" },
  121. ]);
  122. expect(off[2]?.message.toolCallId).toBe("search");
  123. expect(entries).toEqual(before);
  124. });
  125. it("tokenizes explicit MCP server and tool metadata even when the public name is opaque", () => {
  126. const tools: ToolSearchCandidate[] = [
  127. {
  128. name: "OpaqueTool",
  129. deferred: true,
  130. mcp: { serverName: "Team.Slack", toolName: "send_message" },
  131. },
  132. {
  133. name: "ResidentTool",
  134. deferred: false,
  135. mcp: { serverName: "Team.Slack", toolName: "send_message" },
  136. },
  137. { name: "PlainTool", deferred: true },
  138. ];
  139. expect(searchTools("+team +slack +send +message", tools)).toEqual(["OpaqueTool"]);
  140. expect(searchTools("opaque", tools)).toEqual([]);
  141. expect(searchTools("OpaqueTool", tools)).toEqual(["OpaqueTool"]);
  142. });
  143. it("requires every required term while allowing name, hint and description to satisfy them", () => {
  144. const tools: ToolSearchCandidate[] = [
  145. { name: "SlackReports", deferred: true, description: "report" },
  146. { name: "SendReports", deferred: true, description: "report" },
  147. { name: "HintMatch", deferred: true, searchHint: "slack send", description: "report" },
  148. { name: "SlackSend", deferred: true, description: "report" },
  149. { name: "DescriptionMatch", deferred: true, description: "slack send report" },
  150. { name: "MixedMatch", deferred: true, searchHint: "slack", description: "send report" },
  151. ];
  152. expect(searchTools("+slack +send report", tools)).toEqual([
  153. "SlackSend",
  154. "HintMatch",
  155. "MixedMatch",
  156. "DescriptionMatch",
  157. ]);
  158. expect(searchTools("+slack +send +absent report", tools)).toEqual([]);
  159. });
  160. it.each([
  161. ["foo.bar", "fooXbar"],
  162. ["a[b]c", "abc"],
  163. ["a+b", "aaab"],
  164. ["a(b)c", "abc"],
  165. ["a|b", "a b"],
  166. ["a\\b", "a b"],
  167. ])("matches %s literally in search hints and descriptions", (query, lookalike) => {
  168. const tools = [
  169. { name: "LiteralDescription", deferred: true, description: `Supports ${query} syntax` },
  170. { name: "PatternLookalike", deferred: true, description: `Supports ${lookalike} syntax` },
  171. { name: "LiteralHint", deferred: true, searchHint: `Supports ${query} syntax` },
  172. ];
  173. expect(searchTools(query, tools)).toEqual(["LiteralHint", "LiteralDescription"]);
  174. expect(searchTools(`+${query}`, tools)).toEqual(["LiteralHint", "LiteralDescription"]);
  175. });
  176. it("ranks MCP names, builtin names, partial names, hints and descriptions before truncation", () => {
  177. const tools = [
  178. { name: "DescriptionOnly", deferred: true, description: "lookup" },
  179. { name: "HintOnly", deferred: true, searchHint: "lookup" },
  180. { name: "HintAndDescription", deferred: true, searchHint: "lookup", description: "lookup" },
  181. { name: "Lookupish", deferred: true },
  182. { name: "LookupFiles", deferred: true },
  183. { name: "mcp__lookup__files", deferred: true },
  184. ];
  185. expect(searchTools("lookup", tools, 10)).toEqual([
  186. "mcp__lookup__files",
  187. "LookupFiles",
  188. "Lookupish",
  189. "HintAndDescription",
  190. "HintOnly",
  191. "DescriptionOnly",
  192. ]);
  193. expect(searchTools("lookup", tools, 3)).toEqual([
  194. "mcp__lookup__files",
  195. "LookupFiles",
  196. "Lookupish",
  197. ]);
  198. });
  199. it("preserves unrelated text and removes only unavailable references", () => {
  200. const entries = [
  201. {
  202. message: {
  203. role: "tool" as const,
  204. content: [
  205. { type: "text" as const, text: "diagnostic" },
  206. { type: "tool_reference" as const, toolName: "removed" },
  207. { type: "tool_reference" as const, toolName: "WebFetch" },
  208. ],
  209. },
  210. },
  211. ];
  212. expect(
  213. projectToolReferences(entries, "native", [{ name: "WebFetch", inputSchema: {} }]).entries[0]
  214. ?.message.content,
  215. ).toEqual([entries[0]!.message.content[0], entries[0]!.message.content[2]]);
  216. });
  217. it("defaults off and selects an explicit mode from actual Model capabilities", () => {
  218. const base = createTestRuntimeModel({
  219. generateText: async () => ({ text: "", finishReason: "stop", usage: {} }),
  220. });
  221. const supported = {
  222. ...base,
  223. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: false } },
  224. };
  225. expect(resolveToolSearchMode(supported)).toBe("off");
  226. expect(resolveToolSearchMode(supported, "auto")).toBe("local");
  227. expect(resolveToolSearchMode(supported, "native")).toBe("native");
  228. const codingPlan = {
  229. ...supported,
  230. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  231. };
  232. expect(resolveToolSearchMode(codingPlan)).toBe("off");
  233. expect(resolveToolSearchMode(codingPlan, "auto")).toBe("native");
  234. expect(() => resolveToolSearchMode(base, "native")).toThrow(/Anthropic Messages/);
  235. expect(() =>
  236. resolveToolSearchMode(
  237. { ...base, properties: { ...base.properties, supportsToolCall: false } },
  238. "local",
  239. ),
  240. ).toThrow(/supports tool calls/);
  241. });
  242. });
  243. // 回归:搜索执行时连接可能已就绪,不能继续使用发请求时的旧目录。
  244. describe("ToolSearch live MCP directory", () => {
  245. const ready = { name: "mcp__slow__ping", deferred: true };
  246. async function run(
  247. query: string,
  248. latest: () => unknown,
  249. wait: (...args: unknown[]) => Promise<void> = async () => {},
  250. ) {
  251. return toolSearchToolEntry.handler({ query, max_results: 5 }, {
  252. toolSearch: {
  253. enabled: true,
  254. mode: "native",
  255. catalog: [],
  256. discovered: new Set(),
  257. readLatest: latest,
  258. waitForPending: wait,
  259. },
  260. } as never);
  261. }
  262. it("reads tools that became ready after request preparation", async () => {
  263. const result = await run("select:mcp__slow__ping", () => ({
  264. catalog: [ready],
  265. pending: [],
  266. failed: [],
  267. }));
  268. expect(result).toMatchObject({ matches: [ready.name] });
  269. });
  270. it("waits for missing select names even with a partial match", async () => {
  271. const other = { name: "mcp__other__ping", deferred: true };
  272. let settled = false;
  273. const waits: unknown[] = [];
  274. const result = await run(
  275. `select:${other.name},${ready.name}`,
  276. () => ({
  277. catalog: settled ? [other, ready] : [other],
  278. pending: settled ? [] : ["slow"],
  279. failed: [],
  280. }),
  281. async (names) => {
  282. waits.push(names);
  283. settled = true;
  284. },
  285. );
  286. expect(waits).toEqual([["slow"]]);
  287. expect(result).toMatchObject({ matches: [other.name, ready.name] });
  288. });
  289. it.each([
  290. ["digital artwork", ["images"]],
  291. ["git artwork", []],
  292. ["select:mcp__unconfigured", []],
  293. ["select:mcp__images-extra", []],
  294. ])("distinguishes whole server names from keyword substrings: %s", async (query, expected) => {
  295. const wait = vi.fn(async (..._args: unknown[]) => {});
  296. await run(
  297. query as string,
  298. () => ({
  299. catalog: [
  300. {
  301. name: "mcp__git__status",
  302. deferred: true,
  303. mcp: { serverName: "git", toolName: "status" },
  304. },
  305. ],
  306. pending: ["images"],
  307. failed: [],
  308. }),
  309. wait,
  310. );
  311. expect(wait.mock.calls.map((args) => args[0])).toEqual(expected.length ? [expected] : []);
  312. });
  313. it("returns an existing pending tool without waiting", async () => {
  314. let waited = false;
  315. const result = await run(
  316. "ping",
  317. () => ({ catalog: [ready], pending: ["slow"], failed: [] }),
  318. async () => {
  319. waited = true;
  320. },
  321. );
  322. expect(waited).toBe(false);
  323. expect(result).toMatchObject({ matches: [ready.name] });
  324. });
  325. it("does not wait for unrelated servers and reports failure facts", async () => {
  326. let waited = false;
  327. const result = await run(
  328. "select:mcp__failed__ping",
  329. () => ({ catalog: [], pending: ["slow"], failed: [{ name: "failed", error: "offline" }] }),
  330. async () => {
  331. waited = true;
  332. },
  333. );
  334. expect(waited).toBe(false);
  335. expect(result).toMatchObject({
  336. matches: [],
  337. failed_mcp_servers: [{ name: "failed", error: "offline" }],
  338. });
  339. });
  340. });