tool-search.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import { describe, expect, it } 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. } from "../src/tool/handlers/cron.js";
  20. import { createTestRuntimeModel } from "./test-runtime-model.js";
  21. const catalog = [
  22. { name: "Read", aliases: ["read_file"], deferred: false, description: "Read files" },
  23. { name: "WebFetch", deferred: true, description: "Fetch content from a URL" },
  24. { name: "mcp__slack__send_message", deferred: true, description: "Send messages" },
  25. { name: "mcp__slack__search", deferred: true, description: "Search messages" },
  26. { name: "mcp__comms__send", deferred: true, description: "Send to slack" },
  27. ];
  28. describe("ToolSearch semantics", () => {
  29. it("searches built-in hints through the real scoped request catalog", () => {
  30. const registry = createToolRegistry();
  31. [
  32. toolSearchToolEntry,
  33. webFetchToolEntry,
  34. webSearchToolEntry,
  35. todoWriteToolEntry,
  36. enterPlanModeToolEntry,
  37. exitPlanModeToolEntry,
  38. taskOutputToolEntry,
  39. taskStopToolEntry,
  40. sendMessageToolEntry,
  41. cronCreateToolEntry,
  42. cronListToolEntry,
  43. cronDeleteToolEntry,
  44. ].forEach((entry) => registry.register(entry));
  45. const tools = registry.toContracts();
  46. const exposed = buildToolExposure({
  47. model: {
  48. ...createTestRuntimeModel({
  49. generateText: async () => ({ text: "", finishReason: "stop", usage: {} }),
  50. }),
  51. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  52. },
  53. tools,
  54. registry,
  55. entries: [],
  56. });
  57. for (const tool of exposed.context.catalog.filter((t) => t.deferred))
  58. expect(tool.searchHint, tool.name).toBeTruthy();
  59. for (const [query, name] of [
  60. ["checklist", "TodoWrite"],
  61. ["cancel", "CronDelete"],
  62. ["active", "CronList"],
  63. ]) {
  64. expect(searchTools(query!, exposed.context.catalog)).toContain(name);
  65. expect(searchTools(`+${query}`, exposed.context.catalog)).toContain(name);
  66. }
  67. expect(searchTools("+cancel cron", exposed.context.catalog)).toEqual(["CronDelete"]);
  68. expect(searchTools("+checklist absent", exposed.context.catalog)).toEqual(["TodoWrite"]);
  69. const scoped = exposed.context.catalog.filter((t) => t.name !== "CronDelete");
  70. expect(searchTools("+cancel cron", scoped)).not.toContain("CronDelete");
  71. });
  72. it("selects canonical tools and aliases without truncating direct selection", () => {
  73. expect(searchTools("select:WebFetch,read_file,WebFetch,missing", catalog, 1)).toEqual([
  74. "WebFetch",
  75. "Read",
  76. ]);
  77. expect(searchTools("select:read", catalog)).toEqual([]);
  78. expect(searchTools("read_file", catalog)).toEqual([]);
  79. expect(searchTools("read", catalog)).toEqual(["Read"]);
  80. });
  81. it("searches deferred tools by prefix and weighted name/description matches", () => {
  82. expect(searchTools("mcp__slack__", catalog, 1)).toEqual(["mcp__slack__send_message"]);
  83. expect(searchTools("slack send", catalog)[0]).toBe("mcp__slack__send_message");
  84. expect(searchTools("+slack send", catalog)).toContain("mcp__comms__send");
  85. expect(searchTools("files", catalog)).toEqual([]);
  86. expect(searchTools("nonexistent", catalog)).toEqual([]);
  87. });
  88. it("uses genuine results and the selected compact checkpoint, not ordinary calls", () => {
  89. const entries = [
  90. {
  91. message: { role: "user" as const, content: "summary" },
  92. metadata: {
  93. source: "legacy_synthetic" as const,
  94. compactBoundary: { boundaryId: "boundary", preCompactDiscoveredTools: ["WebFetch"] },
  95. },
  96. },
  97. {
  98. message: {
  99. role: "assistant" as const,
  100. content: "",
  101. toolCalls: [{ id: "read", name: "Read", input: {} }],
  102. },
  103. },
  104. {
  105. message: {
  106. role: "tool" as const,
  107. toolCallId: "search",
  108. toolName: "ToolSearch",
  109. content: [{ type: "tool_reference" as const, toolName: "mcp__slack__search" }],
  110. },
  111. },
  112. ];
  113. expect([...collectDiscoveredTools(entries)]).toEqual(["WebFetch", "mcp__slack__search"]);
  114. const before = structuredClone(entries);
  115. const off = projectToolReferences(entries, "off", []).entries;
  116. expect(off[2]?.message.content).toEqual([
  117. { type: "text", text: "[Tool references removed - tool search not enabled]" },
  118. ]);
  119. expect(off[2]?.message.toolCallId).toBe("search");
  120. expect(entries).toEqual(before);
  121. });
  122. it("tokenizes explicit MCP server and tool metadata even when the public name is opaque", () => {
  123. const tools: ToolSearchCandidate[] = [
  124. {
  125. name: "OpaqueTool",
  126. deferred: true,
  127. mcp: { serverName: "Team.Slack", toolName: "send_message" },
  128. },
  129. {
  130. name: "ResidentTool",
  131. deferred: false,
  132. mcp: { serverName: "Team.Slack", toolName: "send_message" },
  133. },
  134. { name: "PlainTool", deferred: true },
  135. ];
  136. expect(searchTools("+team +slack +send +message", tools)).toEqual(["OpaqueTool"]);
  137. expect(searchTools("opaque", tools)).toEqual([]);
  138. expect(searchTools("OpaqueTool", tools)).toEqual(["OpaqueTool"]);
  139. });
  140. it("requires every required term while allowing name, hint and description to satisfy them", () => {
  141. const tools: ToolSearchCandidate[] = [
  142. { name: "SlackReports", deferred: true, description: "report" },
  143. { name: "SendReports", deferred: true, description: "report" },
  144. { name: "HintMatch", deferred: true, searchHint: "slack send", description: "report" },
  145. { name: "SlackSend", deferred: true, description: "report" },
  146. { name: "DescriptionMatch", deferred: true, description: "slack send report" },
  147. { name: "MixedMatch", deferred: true, searchHint: "slack", description: "send report" },
  148. ];
  149. expect(searchTools("+slack +send report", tools)).toEqual([
  150. "SlackSend",
  151. "HintMatch",
  152. "MixedMatch",
  153. "DescriptionMatch",
  154. ]);
  155. expect(searchTools("+slack +send +absent report", tools)).toEqual([]);
  156. });
  157. it.each([
  158. ["foo.bar", "fooXbar"],
  159. ["a[b]c", "abc"],
  160. ["a+b", "aaab"],
  161. ["a(b)c", "abc"],
  162. ["a|b", "a b"],
  163. ["a\\b", "a b"],
  164. ])("matches %s literally in search hints and descriptions", (query, lookalike) => {
  165. const tools = [
  166. { name: "LiteralDescription", deferred: true, description: `Supports ${query} syntax` },
  167. { name: "PatternLookalike", deferred: true, description: `Supports ${lookalike} syntax` },
  168. { name: "LiteralHint", deferred: true, searchHint: `Supports ${query} syntax` },
  169. ];
  170. expect(searchTools(query, tools)).toEqual(["LiteralHint", "LiteralDescription"]);
  171. expect(searchTools(`+${query}`, tools)).toEqual(["LiteralHint", "LiteralDescription"]);
  172. });
  173. it("ranks MCP names, builtin names, partial names, hints and descriptions before truncation", () => {
  174. const tools = [
  175. { name: "DescriptionOnly", deferred: true, description: "lookup" },
  176. { name: "HintOnly", deferred: true, searchHint: "lookup" },
  177. { name: "HintAndDescription", deferred: true, searchHint: "lookup", description: "lookup" },
  178. { name: "Lookupish", deferred: true },
  179. { name: "LookupFiles", deferred: true },
  180. { name: "mcp__lookup__files", deferred: true },
  181. ];
  182. expect(searchTools("lookup", tools, 10)).toEqual([
  183. "mcp__lookup__files",
  184. "LookupFiles",
  185. "Lookupish",
  186. "HintAndDescription",
  187. "HintOnly",
  188. "DescriptionOnly",
  189. ]);
  190. expect(searchTools("lookup", tools, 3)).toEqual([
  191. "mcp__lookup__files",
  192. "LookupFiles",
  193. "Lookupish",
  194. ]);
  195. });
  196. it("preserves unrelated text and removes only unavailable references", () => {
  197. const entries = [
  198. {
  199. message: {
  200. role: "tool" as const,
  201. content: [
  202. { type: "text" as const, text: "diagnostic" },
  203. { type: "tool_reference" as const, toolName: "removed" },
  204. { type: "tool_reference" as const, toolName: "WebFetch" },
  205. ],
  206. },
  207. },
  208. ];
  209. expect(
  210. projectToolReferences(entries, "native", [{ name: "WebFetch", inputSchema: {} }]).entries[0]
  211. ?.message.content,
  212. ).toEqual([entries[0]!.message.content[0], entries[0]!.message.content[2]]);
  213. });
  214. it("defaults off and selects an explicit mode from actual Model capabilities", () => {
  215. const base = createTestRuntimeModel({
  216. generateText: async () => ({ text: "", finishReason: "stop", usage: {} }),
  217. });
  218. const supported = {
  219. ...base,
  220. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: false } },
  221. };
  222. expect(resolveToolSearchMode(supported)).toBe("off");
  223. expect(resolveToolSearchMode(supported, "auto")).toBe("local");
  224. expect(resolveToolSearchMode(supported, "native")).toBe("native");
  225. const codingPlan = {
  226. ...supported,
  227. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  228. };
  229. expect(resolveToolSearchMode(codingPlan)).toBe("off");
  230. expect(resolveToolSearchMode(codingPlan, "auto")).toBe("native");
  231. expect(() => resolveToolSearchMode(base, "native")).toThrow(/Anthropic Messages/);
  232. expect(() =>
  233. resolveToolSearchMode(
  234. { ...base, properties: { ...base.properties, supportsToolCall: false } },
  235. "local",
  236. ),
  237. ).toThrow(/supports tool calls/);
  238. });
  239. });