| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348 |
- import { describe, expect, it, vi } from "vitest";
- import type { ToolSearchCandidate } from "@zcode/contracts";
- import { searchTools } from "../src/tool/search/search.js";
- import { collectDiscoveredTools, projectToolReferences } from "../src/tool/search/history.js";
- import { buildToolExposure, resolveToolSearchMode } from "../src/tool/search/exposure.js";
- import { createToolRegistry } from "../src/tool/registry.js";
- import { toolSearchToolEntry } from "../src/tool/handlers/tool-search.js";
- import { webFetchToolEntry } from "../src/tool/handlers/webfetch.js";
- import { webSearchToolEntry } from "../src/tool/handlers/websearch.js";
- import { todoWriteToolEntry } from "../src/tool/handlers/todo.js";
- import { enterPlanModeToolEntry, exitPlanModeToolEntry } from "../src/tool/handlers/plan-mode.js";
- import { taskOutputToolEntry } from "../src/tool/handlers/task-output.js";
- import { taskStopToolEntry } from "../src/tool/handlers/task-stop.js";
- import { sendMessageToolEntry } from "../src/tool/handlers/send-message.js";
- import {
- cronCreateToolEntry,
- cronListToolEntry,
- cronDeleteToolEntry,
- cronPauseSelfToolEntry,
- } from "../src/tool/handlers/cron.js";
- import { createTestRuntimeModel } from "./test-runtime-model.js";
- const catalog = [
- { name: "Read", aliases: ["read_file"], deferred: false, description: "Read files" },
- { name: "WebFetch", deferred: true, description: "Fetch content from a URL" },
- { name: "mcp__slack__send_message", deferred: true, description: "Send messages" },
- { name: "mcp__slack__search", deferred: true, description: "Search messages" },
- { name: "mcp__comms__send", deferred: true, description: "Send to slack" },
- ];
- describe("ToolSearch semantics", () => {
- it("searches built-in hints through the real scoped request catalog", () => {
- const registry = createToolRegistry();
- [
- toolSearchToolEntry,
- webFetchToolEntry,
- webSearchToolEntry,
- todoWriteToolEntry,
- enterPlanModeToolEntry,
- exitPlanModeToolEntry,
- taskOutputToolEntry,
- taskStopToolEntry,
- sendMessageToolEntry,
- cronCreateToolEntry,
- cronListToolEntry,
- cronDeleteToolEntry,
- cronPauseSelfToolEntry,
- ].forEach((entry) => registry.register(entry));
- const tools = registry.toContracts();
- const exposed = buildToolExposure({
- model: {
- ...createTestRuntimeModel({
- generateText: async () => ({ text: "", finishReason: "stop", usage: {} }),
- }),
- requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
- },
- tools,
- registry,
- entries: [],
- });
- for (const tool of exposed.context.catalog.filter((t) => t.deferred))
- expect(tool.searchHint, tool.name).toBeTruthy();
- for (const [query, name] of [
- ["logs", "TaskOutput"],
- ["cancel", "CronDelete"],
- ["active", "CronList"],
- ["pause", "CronPauseSelf"],
- ]) {
- expect(searchTools(query!, exposed.context.catalog)).toContain(name);
- expect(searchTools(`+${query}`, exposed.context.catalog)).toContain(name);
- }
- expect(searchTools("+cancel cron", exposed.context.catalog)).toEqual(["CronDelete"]);
- expect(searchTools("+logs absent", exposed.context.catalog)).toEqual(["TaskOutput"]);
- const scoped = exposed.context.catalog.filter((t) => t.name !== "CronDelete");
- expect(searchTools("+cancel cron", scoped)).not.toContain("CronDelete");
- });
- it("selects canonical tools and aliases without truncating direct selection", () => {
- expect(searchTools("select:WebFetch,read_file,WebFetch,missing", catalog, 1)).toEqual([
- "WebFetch",
- "Read",
- ]);
- expect(searchTools("select:read", catalog)).toEqual([]);
- expect(searchTools("read_file", catalog)).toEqual([]);
- expect(searchTools("read", catalog)).toEqual(["Read"]);
- });
- it("searches deferred tools by prefix and weighted name/description matches", () => {
- expect(searchTools("mcp__slack__", catalog, 1)).toEqual(["mcp__slack__send_message"]);
- expect(searchTools("slack send", catalog)[0]).toBe("mcp__slack__send_message");
- expect(searchTools("+slack send", catalog)).toContain("mcp__comms__send");
- expect(searchTools("files", catalog)).toEqual([]);
- expect(searchTools("nonexistent", catalog)).toEqual([]);
- });
- it("uses genuine results and the selected compact checkpoint, not ordinary calls", () => {
- const entries = [
- {
- message: { role: "user" as const, content: "summary" },
- metadata: {
- source: "legacy_synthetic" as const,
- compactBoundary: { boundaryId: "boundary", preCompactDiscoveredTools: ["WebFetch"] },
- },
- },
- {
- message: {
- role: "assistant" as const,
- content: "",
- toolCalls: [{ id: "read", name: "Read", input: {} }],
- },
- },
- {
- message: {
- role: "tool" as const,
- toolCallId: "search",
- toolName: "ToolSearch",
- content: [{ type: "tool_reference" as const, toolName: "mcp__slack__search" }],
- },
- },
- ];
- expect([...collectDiscoveredTools(entries)]).toEqual(["WebFetch", "mcp__slack__search"]);
- const before = structuredClone(entries);
- const off = projectToolReferences(entries, "off", []).entries;
- expect(off[2]?.message.content).toEqual([
- { type: "text", text: "[Tool references removed - tool search not enabled]" },
- ]);
- expect(off[2]?.message.toolCallId).toBe("search");
- expect(entries).toEqual(before);
- });
- it("tokenizes explicit MCP server and tool metadata even when the public name is opaque", () => {
- const tools: ToolSearchCandidate[] = [
- {
- name: "OpaqueTool",
- deferred: true,
- mcp: { serverName: "Team.Slack", toolName: "send_message" },
- },
- {
- name: "ResidentTool",
- deferred: false,
- mcp: { serverName: "Team.Slack", toolName: "send_message" },
- },
- { name: "PlainTool", deferred: true },
- ];
- expect(searchTools("+team +slack +send +message", tools)).toEqual(["OpaqueTool"]);
- expect(searchTools("opaque", tools)).toEqual([]);
- expect(searchTools("OpaqueTool", tools)).toEqual(["OpaqueTool"]);
- });
- it("requires every required term while allowing name, hint and description to satisfy them", () => {
- const tools: ToolSearchCandidate[] = [
- { name: "SlackReports", deferred: true, description: "report" },
- { name: "SendReports", deferred: true, description: "report" },
- { name: "HintMatch", deferred: true, searchHint: "slack send", description: "report" },
- { name: "SlackSend", deferred: true, description: "report" },
- { name: "DescriptionMatch", deferred: true, description: "slack send report" },
- { name: "MixedMatch", deferred: true, searchHint: "slack", description: "send report" },
- ];
- expect(searchTools("+slack +send report", tools)).toEqual([
- "SlackSend",
- "HintMatch",
- "MixedMatch",
- "DescriptionMatch",
- ]);
- expect(searchTools("+slack +send +absent report", tools)).toEqual([]);
- });
- it.each([
- ["foo.bar", "fooXbar"],
- ["a[b]c", "abc"],
- ["a+b", "aaab"],
- ["a(b)c", "abc"],
- ["a|b", "a b"],
- ["a\\b", "a b"],
- ])("matches %s literally in search hints and descriptions", (query, lookalike) => {
- const tools = [
- { name: "LiteralDescription", deferred: true, description: `Supports ${query} syntax` },
- { name: "PatternLookalike", deferred: true, description: `Supports ${lookalike} syntax` },
- { name: "LiteralHint", deferred: true, searchHint: `Supports ${query} syntax` },
- ];
- expect(searchTools(query, tools)).toEqual(["LiteralHint", "LiteralDescription"]);
- expect(searchTools(`+${query}`, tools)).toEqual(["LiteralHint", "LiteralDescription"]);
- });
- it("ranks MCP names, builtin names, partial names, hints and descriptions before truncation", () => {
- const tools = [
- { name: "DescriptionOnly", deferred: true, description: "lookup" },
- { name: "HintOnly", deferred: true, searchHint: "lookup" },
- { name: "HintAndDescription", deferred: true, searchHint: "lookup", description: "lookup" },
- { name: "Lookupish", deferred: true },
- { name: "LookupFiles", deferred: true },
- { name: "mcp__lookup__files", deferred: true },
- ];
- expect(searchTools("lookup", tools, 10)).toEqual([
- "mcp__lookup__files",
- "LookupFiles",
- "Lookupish",
- "HintAndDescription",
- "HintOnly",
- "DescriptionOnly",
- ]);
- expect(searchTools("lookup", tools, 3)).toEqual([
- "mcp__lookup__files",
- "LookupFiles",
- "Lookupish",
- ]);
- });
- it("preserves unrelated text and removes only unavailable references", () => {
- const entries = [
- {
- message: {
- role: "tool" as const,
- content: [
- { type: "text" as const, text: "diagnostic" },
- { type: "tool_reference" as const, toolName: "removed" },
- { type: "tool_reference" as const, toolName: "WebFetch" },
- ],
- },
- },
- ];
- expect(
- projectToolReferences(entries, "native", [{ name: "WebFetch", inputSchema: {} }]).entries[0]
- ?.message.content,
- ).toEqual([entries[0]!.message.content[0], entries[0]!.message.content[2]]);
- });
- it("defaults off and selects an explicit mode from actual Model capabilities", () => {
- const base = createTestRuntimeModel({
- generateText: async () => ({ text: "", finishReason: "stop", usage: {} }),
- });
- const supported = {
- ...base,
- requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: false } },
- };
- expect(resolveToolSearchMode(supported)).toBe("off");
- expect(resolveToolSearchMode(supported, "auto")).toBe("local");
- expect(resolveToolSearchMode(supported, "native")).toBe("native");
- const codingPlan = {
- ...supported,
- requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
- };
- expect(resolveToolSearchMode(codingPlan)).toBe("off");
- expect(resolveToolSearchMode(codingPlan, "auto")).toBe("native");
- expect(() => resolveToolSearchMode(base, "native")).toThrow(/Anthropic Messages/);
- expect(() =>
- resolveToolSearchMode(
- { ...base, properties: { ...base.properties, supportsToolCall: false } },
- "local",
- ),
- ).toThrow(/supports tool calls/);
- });
- });
- // 回归:搜索执行时连接可能已就绪,不能继续使用发请求时的旧目录。
- describe("ToolSearch live MCP directory", () => {
- const ready = { name: "mcp__slow__ping", deferred: true };
- async function run(
- query: string,
- latest: () => unknown,
- wait: (...args: unknown[]) => Promise<void> = async () => {},
- ) {
- return toolSearchToolEntry.handler({ query, max_results: 5 }, {
- toolSearch: {
- enabled: true,
- mode: "native",
- catalog: [],
- discovered: new Set(),
- readLatest: latest,
- waitForPending: wait,
- },
- } as never);
- }
- it("reads tools that became ready after request preparation", async () => {
- const result = await run("select:mcp__slow__ping", () => ({
- catalog: [ready],
- pending: [],
- failed: [],
- }));
- expect(result).toMatchObject({ matches: [ready.name] });
- });
- it("waits for missing select names even with a partial match", async () => {
- const other = { name: "mcp__other__ping", deferred: true };
- let settled = false;
- const waits: unknown[] = [];
- const result = await run(
- `select:${other.name},${ready.name}`,
- () => ({
- catalog: settled ? [other, ready] : [other],
- pending: settled ? [] : ["slow"],
- failed: [],
- }),
- async (names) => {
- waits.push(names);
- settled = true;
- },
- );
- expect(waits).toEqual([["slow"]]);
- expect(result).toMatchObject({ matches: [other.name, ready.name] });
- });
- it.each([
- ["digital artwork", ["images"]],
- ["git artwork", []],
- ["select:mcp__unconfigured", []],
- ["select:mcp__images-extra", []],
- ])("distinguishes whole server names from keyword substrings: %s", async (query, expected) => {
- const wait = vi.fn(async (..._args: unknown[]) => {});
- await run(
- query as string,
- () => ({
- catalog: [
- {
- name: "mcp__git__status",
- deferred: true,
- mcp: { serverName: "git", toolName: "status" },
- },
- ],
- pending: ["images"],
- failed: [],
- }),
- wait,
- );
- expect(wait.mock.calls.map((args) => args[0])).toEqual(expected.length ? [expected] : []);
- });
- it("returns an existing pending tool without waiting", async () => {
- let waited = false;
- const result = await run(
- "ping",
- () => ({ catalog: [ready], pending: ["slow"], failed: [] }),
- async () => {
- waited = true;
- },
- );
- expect(waited).toBe(false);
- expect(result).toMatchObject({ matches: [ready.name] });
- });
- it("does not wait for unrelated servers and reports failure facts", async () => {
- let waited = false;
- const result = await run(
- "select:mcp__failed__ping",
- () => ({ catalog: [], pending: ["slow"], failed: [{ name: "failed", error: "offline" }] }),
- async () => {
- waited = true;
- },
- );
- expect(waited).toBe(false);
- expect(result).toMatchObject({
- matches: [],
- failed_mcp_servers: [{ name: "failed", error: "offline" }],
- });
- });
- });
|