tool-search-wire.test.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. import { createAnthropic } from "@ai-sdk/anthropic";
  2. import { generateText } from "ai";
  3. import { expect, it } from "vitest";
  4. import { toAiSdkMessages } from "../src/model/transform.js";
  5. import { toAiSdkTools } from "../src/model/tool-transform.js";
  6. import { toolSearchHeaders } from "../src/model/tool-search.js";
  7. import { createSessionId, type Model } from "@zcode/contracts";
  8. import { createTestAgentRuntime } from "../../core/tests/test-agent-runtime.js";
  9. import { createTestModelFactory } from "../../core/tests/test-runtime-model.js";
  10. import { createTestSessionEventStore } from "../../core/tests/test-event-store.js";
  11. it.each([
  12. { stripMedia: false, large: false },
  13. { stripMedia: true, large: false },
  14. { stripMedia: false, large: true },
  15. { stripMedia: true, large: true },
  16. ])(
  17. "serializes native references and schemas (stripMedia=$stripMedia, large=$large)",
  18. async ({ stripMedia, large }) => {
  19. const names = large
  20. ? Array.from({ length: 2_000 }, (_, i) =>
  21. `mcp__demo__lookup_${String(i).padStart(4, "0")}_`.padEnd(64, "x"),
  22. )
  23. : ["WebFetch"];
  24. let body: any;
  25. let headers: Headers | undefined;
  26. const provider = createAnthropic({
  27. apiKey: "test",
  28. fetch: async (_url, init) => {
  29. body = JSON.parse(String(init?.body));
  30. headers = new Headers(init?.headers);
  31. return new Response(
  32. JSON.stringify({ error: { type: "invalid_request_error", message: "capture" } }),
  33. { status: 400, headers: { "content-type": "application/json" } },
  34. );
  35. },
  36. });
  37. const options = { stripMedia, providerKind: "anthropic" as const, toolSearchEnabled: true };
  38. await expect(
  39. generateText({
  40. model: provider("test"),
  41. maxRetries: 0,
  42. headers: toolSearchHeaders({ "anthropic-beta": "existing-beta" }, true),
  43. tools: toAiSdkTools(
  44. names.map((name) => ({ name, inputSchema: { type: "object" }, deferLoading: true })),
  45. options,
  46. ),
  47. messages: toAiSdkMessages(
  48. [
  49. {
  50. role: "assistant",
  51. content: "",
  52. toolCalls: [
  53. {
  54. id: "search-1",
  55. name: "ToolSearch",
  56. input: { query: `select:${names.join(",")}` },
  57. },
  58. ],
  59. },
  60. {
  61. role: "tool",
  62. toolCallId: "search-1",
  63. toolName: "ToolSearch",
  64. content: [
  65. { type: "text", text: "before" },
  66. ...names.map((toolName) => ({ type: "tool_reference" as const, toolName })),
  67. { type: "text", text: "after" },
  68. ],
  69. },
  70. ],
  71. options,
  72. ),
  73. }),
  74. ).rejects.toBeDefined();
  75. expect(
  76. body.tools.map((tool: { name: string; defer_loading: boolean }) => ({
  77. name: tool.name,
  78. defer_loading: tool.defer_loading,
  79. })),
  80. ).toEqual(names.map((name) => ({ name, defer_loading: true })));
  81. expect(body.messages[1].content[0].content).toEqual([
  82. { type: "text", text: "before" },
  83. ...names.map((tool_name) => ({ type: "tool_reference", tool_name })),
  84. { type: "text", text: "after" },
  85. ]);
  86. expect(headers?.get("anthropic-beta")).toContain("advanced-tool-use-2025-11-20");
  87. expect(headers?.get("anthropic-beta")).toContain("existing-beta");
  88. },
  89. );
  90. it("keeps one announcement in native Anthropic bodies through continuation and the next input", async () => {
  91. const bodies: Array<{
  92. messages: unknown[];
  93. tools: Array<{ name: string; description: string; input_schema: unknown }>;
  94. }> = [];
  95. const provider = createAnthropic({
  96. apiKey: "test",
  97. fetch: async (_url, init) => {
  98. bodies.push(JSON.parse(String(init?.body)));
  99. return new Response(
  100. JSON.stringify({ error: { type: "invalid_request_error", message: "capture" } }),
  101. { status: 400, headers: { "content-type": "application/json" } },
  102. );
  103. },
  104. });
  105. const factory = createTestModelFactory({
  106. async generateText(request) {
  107. const options = {
  108. providerKind: "anthropic" as const,
  109. toolSearchEnabled: request.toolSearchEnabled,
  110. };
  111. await expect(
  112. generateText({
  113. model: provider("test"),
  114. maxRetries: 0,
  115. headers: toolSearchHeaders(undefined, request.toolSearchEnabled),
  116. tools: toAiSdkTools(request.tools, options),
  117. messages: toAiSdkMessages(request.messages, options),
  118. }),
  119. ).rejects.toBeDefined();
  120. return { text: "response", finishReason: bodies.length <= 3 ? "length" : "stop", usage: {} };
  121. },
  122. });
  123. const wrap = (model: Model): Model => ({
  124. ...model,
  125. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  126. bind: (options) => wrap(model.bind(options)),
  127. });
  128. const runtime = createTestAgentRuntime(
  129. createSessionId("toolsearch-continuation-wire"),
  130. {
  131. toolSearch: { mode: "native" },
  132. modelStreaming: "off",
  133. titleGeneration: { enabled: false },
  134. toolAllowlist: ["ToolSearch", "WebFetch"],
  135. },
  136. { eventStore: createTestSessionEventStore(), modelFactory: (input) => wrap(factory(input)) },
  137. );
  138. await runtime.executeTurn("start");
  139. await runtime.executeTurn("next input");
  140. expect(bodies).toHaveLength(5);
  141. for (const body of bodies) {
  142. expect(
  143. JSON.stringify(body.messages).split(
  144. "The following deferred tools are now available via ToolSearch.",
  145. ),
  146. ).toHaveLength(2);
  147. expect(body.tools.map((tool) => tool.name)).toEqual(["ToolSearch"]);
  148. expect(body.tools[0]?.description)
  149. .toBe(`Fetches full schema definitions for deferred tools so they can be called.
  150. Deferred tools appear by name in <system-reminder> messages. Until fetched, only the name is known — there is no parameter schema, so the tool cannot be invoked. This tool takes a query, matches it against the deferred tool list, and returns the matched tools' complete JSONSchema definitions inside a <functions> block. Once a tool's schema appears in that result, it is callable exactly like any tool defined at the top of the prompt.
  151. Result format: each matched tool appears as one <function>{"description": "...", "name": "...", "parameters": {...}}</function> line inside the <functions> block — the same encoding as the tool list at the top of this prompt.
  152. Query forms:
  153. - "select:Read,Edit,Grep" — fetch these exact tools by name
  154. - "notebook jupyter" — keyword search, up to max_results best matches
  155. - "+slack send" — require "slack" in the name, rank by remaining terms`);
  156. expect(body.tools[0]?.input_schema).toMatchObject({
  157. required: ["query", "max_results"],
  158. properties: {
  159. query: {
  160. description:
  161. 'Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search.',
  162. },
  163. max_results: {
  164. description: "Maximum number of results to return (default: 5)",
  165. default: 5,
  166. },
  167. },
  168. });
  169. }
  170. });