tool-search-exposure.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. import { describe, expect, it } from "vitest";
  2. import { type Model, type ModelToolContract } from "@zcode/contracts";
  3. import { createTestRuntimeModel } from "./test-runtime-model.js";
  4. import { buildToolExposure, buildToolSearchAnnouncement } from "../src/tool/search/exposure.js";
  5. import { createToolRegistry } from "../src/tool/registry.js";
  6. import { toolSearchToolEntry } from "../src/tool/handlers/tool-search.js";
  7. import { deferredToolCallEntry } from "../src/tool/handlers/deferred-tool-call.js";
  8. import { taskOutputToolEntry } from "../src/tool/handlers/task-output.js";
  9. import { readToolEntry } from "../src/tool/handlers/read.js";
  10. import { todoReadToolEntry } from "../src/tool/handlers/todo.js";
  11. import type { RuntimeMessageEntry } from "../src/agent/message-history.js";
  12. import { collectDiscoveredTools, parseToolSearchHiddenNames } from "../src/tool/search/history.js";
  13. const model = (enabled: boolean): Model => ({
  14. ...createTestRuntimeModel({
  15. generateText: async () => ({ text: "", finishReason: "stop", usage: {} }),
  16. }),
  17. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: enabled } },
  18. });
  19. it("keeps enabled search call/result pairing when every reference in a result becomes unavailable", () => {
  20. const registry = createToolRegistry();
  21. [toolSearchToolEntry, todoReadToolEntry, taskOutputToolEntry].forEach((entry) =>
  22. registry.register(entry),
  23. );
  24. const tools = registry.toContracts();
  25. const entries: RuntimeMessageEntry[] = [
  26. {
  27. message: {
  28. role: "assistant",
  29. content: "",
  30. toolCalls: [
  31. { id: "search-removed", name: "ToolSearch", input: { query: "select:TodoRead" } },
  32. ],
  33. },
  34. },
  35. {
  36. message: {
  37. role: "tool",
  38. toolName: "ToolSearch",
  39. toolCallId: "search-removed",
  40. content: [{ type: "tool_reference", toolName: "TodoRead" }],
  41. },
  42. },
  43. ];
  44. const before = structuredClone(entries);
  45. const projected = buildToolExposure({
  46. mode: "native" as const,
  47. model: model(true),
  48. registry,
  49. entries,
  50. tools: tools.filter((tool) => tool.name !== "TodoRead"),
  51. });
  52. expect(projected.enabled).toBe(true);
  53. expect(projected.context.catalog.map((tool) => tool.name)).toEqual(["ToolSearch", "TaskOutput"]);
  54. expect(projected.tools.map((tool) => tool.name)).toEqual(["ToolSearch"]);
  55. expect(projected.entries).toHaveLength(2);
  56. expect(projected.entries[0]).toEqual(entries[0]);
  57. expect(projected.entries[1]).toMatchObject({
  58. message: {
  59. role: "tool",
  60. toolName: "ToolSearch",
  61. toolCallId: "search-removed",
  62. content: [{ type: "text", text: "[Tool references removed - tools no longer available]" }],
  63. },
  64. });
  65. expect(entries).toEqual(before);
  66. expect([...collectDiscoveredTools(entries)]).toEqual(["TodoRead"]);
  67. const restored = buildToolExposure({
  68. mode: "native" as const,
  69. model: model(true),
  70. registry,
  71. entries,
  72. tools,
  73. });
  74. expect(restored.entries).toEqual(before);
  75. expect(restored.tools.find((tool) => tool.name === "TodoRead")).toMatchObject({
  76. deferLoading: true,
  77. });
  78. });
  79. it("projects current definitions and removes inaccessible references without changing raw history", () => {
  80. const registry = createToolRegistry();
  81. [toolSearchToolEntry, todoReadToolEntry, readToolEntry].forEach((entry) =>
  82. registry.register(entry),
  83. );
  84. const tools = registry.toContracts();
  85. const entries: RuntimeMessageEntry[] = [
  86. {
  87. message: {
  88. role: "tool",
  89. toolName: "ToolSearch",
  90. toolCallId: "real",
  91. content: [{ type: "tool_reference", toolName: "TodoRead" }],
  92. },
  93. },
  94. ];
  95. const on = buildToolExposure({
  96. mode: "native" as const,
  97. model: model(true),
  98. tools,
  99. registry,
  100. entries,
  101. });
  102. expect(on.tools.find((tool) => tool.name === "TodoRead")?.deferLoading).toBe(true);
  103. const off = buildToolExposure({
  104. mode: "off" as const,
  105. model: model(false),
  106. tools,
  107. registry,
  108. entries: [
  109. ...entries,
  110. buildToolSearchAnnouncement({
  111. mode: "native" as const,
  112. model: model(true),
  113. tools,
  114. registry,
  115. entries,
  116. })!,
  117. ],
  118. });
  119. expect(off.tools.map((tool) => tool.name)).toEqual(["TodoRead", "Read"]);
  120. expect(off.entries).toHaveLength(1);
  121. expect(JSON.stringify(off)).not.toContain('"tool_reference"');
  122. const changed = tools.map((tool) =>
  123. tool.name === "TodoRead"
  124. ? { ...tool, description: "new schema", inputSchema: { type: "object", required: ["new"] } }
  125. : tool,
  126. ) as ModelToolContract[];
  127. expect(
  128. buildToolExposure({
  129. mode: "native" as const,
  130. model: model(true),
  131. tools: changed,
  132. registry,
  133. entries,
  134. }).tools.find((tool) => tool.name === "TodoRead")?.description,
  135. ).toBe("new schema");
  136. const denied = buildToolExposure({
  137. mode: "native" as const,
  138. model: model(true),
  139. tools: tools.filter((tool) => tool.name !== "TodoRead"),
  140. registry,
  141. entries,
  142. });
  143. expect(denied.enabled).toBe(false);
  144. expect(denied.context.catalog.map((tool) => tool.name)).not.toContain("TodoRead");
  145. expect(entries[0]?.message.content).toEqual([{ type: "tool_reference", toolName: "TodoRead" }]);
  146. });
  147. it("collects announcements from retained history independently of request projection", () => {
  148. const registry = createToolRegistry();
  149. [toolSearchToolEntry, todoReadToolEntry, readToolEntry].forEach((entry) =>
  150. registry.register(entry),
  151. );
  152. const input = {
  153. mode: "native" as const,
  154. model: model(true),
  155. tools: registry.toContracts(),
  156. registry,
  157. entries: [],
  158. };
  159. const announcement = buildToolSearchAnnouncement(input)!;
  160. expect(announcement.content)
  161. .toBe(`The following deferred tools are now available via ToolSearch. Their schemas are NOT loaded — calling them directly will fail with InputValidationError. Use ToolSearch with query "select:<name>[,<name>...]" to load tool schemas before calling them:
  162. TodoRead`);
  163. expect(announcement.metadata?.toolSearchAnnouncement).toEqual({
  164. addedNames: ["TodoRead"],
  165. removedNames: [],
  166. readdedNames: [],
  167. });
  168. expect(input.entries).toEqual([]);
  169. const entries = [announcement];
  170. expect(buildToolSearchAnnouncement({ ...input, entries })).toBeUndefined();
  171. expect(
  172. buildToolSearchAnnouncement({ ...input, mode: "off" as const, model: model(false) }),
  173. ).toBeUndefined();
  174. expect(
  175. buildToolSearchAnnouncement({
  176. ...input,
  177. tools: input.tools.filter((t) => t.name !== "ToolSearch"),
  178. }),
  179. ).toBeUndefined();
  180. const projected = buildToolExposure({ ...input, entries });
  181. expect(projected.entries).toEqual(entries);
  182. expect(projected).not.toHaveProperty("announcement");
  183. expect(buildToolExposure(input).entries).toEqual([]);
  184. });
  185. it("rebuilds complete name listings from retained deltas, including a readded-only suffix", () => {
  186. const registry = createToolRegistry();
  187. [toolSearchToolEntry, todoReadToolEntry, taskOutputToolEntry].forEach((t) =>
  188. registry.register(t),
  189. );
  190. const tools = registry.toContracts();
  191. const collect = (entries: RuntimeMessageEntry[], names = ["TodoRead", "TaskOutput"]) =>
  192. buildToolSearchAnnouncement({
  193. mode: "native" as const,
  194. model: model(true),
  195. registry,
  196. entries,
  197. tools: tools.filter((t) => t.name === "ToolSearch" || names.includes(t.name)),
  198. });
  199. const first = collect([], ["TodoRead"])!;
  200. const second = collect([first])!;
  201. expect(second.metadata?.toolSearchAnnouncement).toEqual({
  202. addedNames: ["TaskOutput"],
  203. removedNames: [],
  204. readdedNames: [],
  205. });
  206. expect(second.content).not.toContain("TodoRead");
  207. const rebuilt = collect([second])!;
  208. expect(rebuilt.metadata?.toolSearchAnnouncement).toEqual({
  209. addedNames: ["TodoRead"],
  210. removedNames: [],
  211. readdedNames: [],
  212. });
  213. expect(rebuilt.content).toContain("\nTodoRead");
  214. expect(collect([second, rebuilt])).toBeUndefined();
  215. const removed = collect([first, second], ["TaskOutput"])!;
  216. expect(removed.metadata?.toolSearchAnnouncement).toEqual({
  217. addedNames: [],
  218. removedNames: ["TodoRead"],
  219. readdedNames: [],
  220. });
  221. const readded = collect([first, second, removed])!;
  222. expect(readded.metadata?.toolSearchAnnouncement).toEqual({
  223. addedNames: ["TodoRead"],
  224. removedNames: [],
  225. readdedNames: ["TodoRead"],
  226. });
  227. expect(readded.content).toBe(
  228. `1 deferred tool is available again in this session (announced earlier in this conversation): TodoRead. Load via ToolSearch as before.`,
  229. );
  230. expect(collect([first, second, removed, readded])).toBeUndefined();
  231. const readdedSuffix = collect([readded])!;
  232. expect(readdedSuffix.metadata?.toolSearchAnnouncement).toEqual({
  233. addedNames: ["TaskOutput", "TodoRead"],
  234. removedNames: [],
  235. readdedNames: [],
  236. });
  237. expect(readdedSuffix.content).toContain("\nTaskOutput\nTodoRead");
  238. expect(collect([readded, readdedSuffix])).toBeUndefined();
  239. });
  240. it.each([30, 31])("renders removal of %i names at the listing threshold", (count) => {
  241. const registry = createToolRegistry();
  242. const names = Array.from(
  243. { length: count },
  244. (_, i) => `mcp__demo__tool${String(i).padStart(2, "0")}`,
  245. );
  246. [toolSearchToolEntry, todoReadToolEntry].forEach((entry) => registry.register(entry));
  247. for (const name of names) {
  248. registry.register({ ...todoReadToolEntry, metadata: { ...todoReadToolEntry.metadata, name } });
  249. }
  250. const tools = registry.toContracts();
  251. const first = buildToolSearchAnnouncement({
  252. mode: "native" as const,
  253. model: model(true),
  254. tools,
  255. registry,
  256. entries: [],
  257. })!;
  258. const removed = buildToolSearchAnnouncement({
  259. mode: "native" as const,
  260. model: model(true),
  261. registry,
  262. tools: tools.filter((tool) => !names.includes(tool.name)),
  263. entries: [first],
  264. })!;
  265. const expected =
  266. count === 30
  267. ? `The following deferred tools are no longer available. Do not search for them — ToolSearch will return no match:\n${names.join("\n")}`
  268. : "31 deferred tools are no longer available: mcp__demo__* (31). Do not search for them — ToolSearch will return no match.";
  269. expect(removed.content).toBe(`${expected}
  270. This is ambient context — do not narrate it to the user unless they ask or it is directly relevant to their request.`);
  271. expect(removed.metadata?.toolSearchAnnouncement?.removedNames).toEqual(names);
  272. });
  273. it("separates added, grouped readded and removed announcement paragraphs", () => {
  274. const registry = createToolRegistry();
  275. const names = ["mcp__demo__read", "mcp__demo__write", "mcp__other__read", "TaskOutput"];
  276. registry.register(toolSearchToolEntry);
  277. for (const name of [...names, "TodoRead"]) {
  278. registry.register({ ...todoReadToolEntry, metadata: { ...todoReadToolEntry.metadata, name } });
  279. }
  280. const priorNames = [...names, "Gone"];
  281. const entries: RuntimeMessageEntry[] = [
  282. {
  283. message: { role: "user", content: "prior listing" },
  284. metadata: {
  285. source: "legacy_synthetic",
  286. toolSearchAnnouncement: { addedNames: priorNames, readdedNames: [], removedNames: [] },
  287. },
  288. },
  289. {
  290. message: { role: "user", content: "prior removal" },
  291. metadata: {
  292. source: "legacy_synthetic",
  293. toolSearchAnnouncement: { addedNames: [], readdedNames: [], removedNames: names },
  294. },
  295. },
  296. ];
  297. const announcement = buildToolSearchAnnouncement({
  298. mode: "native" as const,
  299. model: model(true),
  300. registry,
  301. tools: registry.toContracts(),
  302. entries,
  303. })!;
  304. expect(announcement.content)
  305. .toBe(`The following deferred tools are now available via ToolSearch. Their schemas are NOT loaded — calling them directly will fail with InputValidationError. Use ToolSearch with query "select:<name>[,<name>...]" to load tool schemas before calling them:
  306. TodoRead
  307. 3 deferred tools are available again (MCP server reconnected — names announced earlier in this conversation): mcp__demo__* (2), mcp__other__*. Load via ToolSearch as before.
  308. 1 deferred tool is available again in this session (announced earlier in this conversation): TaskOutput. Load via ToolSearch as before.
  309. The following deferred tools are no longer available in this session. Do not search for them — ToolSearch will return no match:
  310. Gone
  311. This is ambient context — do not narrate it to the user unless they ask or it is directly relevant to their request.`);
  312. expect(
  313. buildToolSearchAnnouncement({
  314. mode: "native" as const,
  315. model: model(true),
  316. registry,
  317. tools: registry.toContracts(),
  318. entries: [...entries, announcement],
  319. }),
  320. ).toBeUndefined();
  321. });
  322. it("does not announce deletion when a deferred tool becomes resident", () => {
  323. const registry = createToolRegistry();
  324. [toolSearchToolEntry, todoReadToolEntry, taskOutputToolEntry].forEach((t) =>
  325. registry.register(t),
  326. );
  327. const tools = registry.toContracts();
  328. const input = { mode: "native" as const, model: model(true), registry, tools, entries: [] };
  329. const first = buildToolSearchAnnouncement(input)!;
  330. registry.register(
  331. { ...todoReadToolEntry, metadata: { ...todoReadToolEntry.metadata, alwaysLoad: true } },
  332. { silentDuplicateWarning: true },
  333. );
  334. expect(buildToolSearchAnnouncement({ ...input, entries: [first] })).toBeUndefined();
  335. registry.register(todoReadToolEntry, { silentDuplicateWarning: true });
  336. expect(buildToolSearchAnnouncement({ ...input, entries: [first] })).toBeUndefined();
  337. });
  338. it("disables deferral when ToolSearch is outside the allowed scope and honors alwaysLoad", () => {
  339. const registry = createToolRegistry();
  340. registry.register({
  341. ...todoReadToolEntry,
  342. metadata: { ...todoReadToolEntry.metadata, alwaysLoad: true },
  343. });
  344. registry.register(toolSearchToolEntry);
  345. const exposed = buildToolExposure({
  346. mode: "native" as const,
  347. model: model(true),
  348. tools: registry.toContracts(),
  349. registry,
  350. entries: [],
  351. });
  352. expect(exposed.reason).toBe("no_deferred_tools");
  353. expect(exposed.tools[0]?.name).toBe("TodoRead");
  354. const scoped = buildToolExposure({
  355. mode: "native" as const,
  356. model: model(true),
  357. tools: [todoReadToolEntry].map((entry) => ({
  358. name: entry.metadata.name,
  359. inputSchema: entry.inputSchema,
  360. })),
  361. entries: [],
  362. });
  363. expect(scoped.enabled).toBe(false);
  364. });
  365. describe("removal reasons", () => {
  366. const AMBIENT =
  367. "This is ambient context — do not narrate it to the user unless they ask or it is directly relevant to their request.";
  368. // removed 离开工具目录;hidden 仍在 registry,只是本轮不在 tools 里。
  369. function announceThenRemove(removed: string[], hidden: string[] = []) {
  370. const registry = createToolRegistry();
  371. [toolSearchToolEntry, todoReadToolEntry].forEach((entry) => registry.register(entry));
  372. // mcp__demo__keep 始终留在本轮,ToolSearch 保持开启。
  373. for (const name of [...removed, "mcp__demo__keep"]) {
  374. registry.register({
  375. ...todoReadToolEntry,
  376. metadata: { ...todoReadToolEntry.metadata, name },
  377. });
  378. }
  379. const first = buildToolSearchAnnouncement({
  380. mode: "native" as const,
  381. model: model(true),
  382. tools: registry.toContracts(),
  383. registry,
  384. entries: [],
  385. })!;
  386. for (const name of removed) registry.unregister(name);
  387. return buildToolSearchAnnouncement({
  388. mode: "native" as const,
  389. model: model(true),
  390. tools: registry.toContracts().filter((tool) => !hidden.includes(tool.name)),
  391. registry,
  392. entries: [first],
  393. })!;
  394. }
  395. it("names an MCP disconnect by the mcp__ name prefix", () => {
  396. // 只看名称前缀,不读取连接状态;非 MCP 名称不写成断开。
  397. const removed = announceThenRemove(["mcp__my_server__read", "mcp__other__read", "TaskOutput"]);
  398. expect(removed.content)
  399. .toBe(`The following deferred tools are no longer available (their MCP server disconnected). Do not search for them — ToolSearch will return no match:
  400. mcp__my_server__read
  401. mcp__other__read
  402. The following deferred tools are no longer available in this session. Do not search for them — ToolSearch will return no match:
  403. TaskOutput
  404. ${AMBIENT}`);
  405. // 原因只进入文案,增量事实不变。
  406. expect(removed.metadata?.toolSearchAnnouncement?.removedNames).toEqual([
  407. "TaskOutput",
  408. "mcp__my_server__read",
  409. "mcp__other__read",
  410. ]);
  411. });
  412. it("summarizes more than 30 tools of a disconnected server", () => {
  413. const names = Array.from(
  414. { length: 31 },
  415. (_, i) => `mcp__demo__tool${String(i).padStart(2, "0")}`,
  416. );
  417. expect(announceThenRemove(names).content).toBe(
  418. `31 deferred tools are no longer available (MCP server disconnected): mcp__demo__* (31). Do not search for them — ToolSearch will return no match.
  419. ${AMBIENT}`,
  420. );
  421. });
  422. it("keeps the neutral text for a tool that is only hidden in this turn", () => {
  423. expect(announceThenRemove([], ["TodoRead"]).content)
  424. .toBe(`The following deferred tools are no longer available. Do not search for them — ToolSearch will return no match:
  425. TodoRead
  426. ${AMBIENT}`);
  427. });
  428. // 请求投影每次按 metadata 重新渲染;隐藏名称不记下来时,同一条公告在请求里会变成"会话内不可用"。
  429. it("renders the hidden names in every request and after cold resume", () => {
  430. const announcement = announceThenRemove([], ["TodoRead"]);
  431. expect(announcement.metadata?.toolSearchHiddenNames).toEqual(["TodoRead"]);
  432. const registry = createToolRegistry();
  433. [toolSearchToolEntry, deferredToolCallEntry, todoReadToolEntry].forEach((entry) =>
  434. registry.register(entry),
  435. );
  436. registry.register({
  437. ...todoReadToolEntry,
  438. metadata: { ...todoReadToolEntry.metadata, name: "mcp__demo__keep" },
  439. });
  440. const tools = registry.toContracts().filter((tool) => tool.name !== "TodoRead");
  441. // 冷恢复只剩持久化的 metadata 原样回来。
  442. const resumed = parseToolSearchHiddenNames(
  443. JSON.parse(JSON.stringify(announcement.metadata!.toolSearchHiddenNames)),
  444. announcement.metadata!.toolSearchAnnouncement!,
  445. );
  446. const restored: RuntimeMessageEntry = {
  447. ...announcement,
  448. metadata: { ...announcement.metadata!, toolSearchHiddenNames: resumed },
  449. };
  450. for (const entry of [announcement, restored]) {
  451. for (const mode of ["native", "local"] as const) {
  452. const projected = buildToolExposure({
  453. mode,
  454. model: model(true),
  455. tools,
  456. registry,
  457. entries: [entry],
  458. });
  459. const searchName = mode === "local" ? "LocalToolSearch" : "ToolSearch";
  460. expect(projected.entries.find((item) => item.kind === "attachment")?.content)
  461. .toBe(`The following deferred tools are no longer available. Do not search for them — ${searchName} will return no match:
  462. TodoRead
  463. ${AMBIENT}`);
  464. }
  465. }
  466. });
  467. });