Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

feat(mcp): make an ambiguous symbol resolvable, and bound what one tool returns

KageBinary5ed752e17f54
diff --git a/ix-cli/src/cli/__tests__/mcp-tool-params.test.ts b/ix-cli/src/cli/__tests__/mcp-tool-params.test.ts
new file mode 100644
index 00000000..470c5101
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/mcp-tool-params.test.ts
@@ -0,0 +1,125 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
+import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { capRecordStream, createIxMcpServer, type IxRunner } from "../../mcp/server.js";
+
+const clients: Client[] = [];
+afterEach(async () => {
+ await Promise.all(clients.splice(0).map((client) => client.close()));
+});
+
+async function connect(runIx: IxRunner): Promise<Client> {
+ const server = createIxMcpServer({ version: "test", runIx });
+ const client = new Client({ name: "ix-mcp-params-test", version: "1.0.0" });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ clients.push(client);
+ return client;
+}
+
+function recorder(stdout = "ok") {
+ const calls: string[][] = [];
+ const runIx: IxRunner = async (args) => {
+ calls.push(args);
+ return { ok: true, stdout, stderr: "" };
+ };
+ return { calls, runIx };
+}
+
+describe("resolving an ambiguous symbol over MCP", () => {
+ it("forwards --kind, --path, --pick and --limit on an edge tool", async () => {
+ // Without these there was no second call that could get past "Ambiguous
+ // symbol": the CLI's own disambiguation flags were unreachable over MCP,
+ // and the agent's only move was to shell out.
+ const { calls, runIx } = recorder();
+ const client = await connect(runIx);
+
+ await client.callTool({
+ name: "ix_callers",
+ arguments: { symbol: "config", kind: "function", path: "src/cli", pick: 2, limit: 20 },
+ });
+
+ expect(calls).toEqual([
+ ["callers", "--kind=function", "--path=src/cli", "--pick=2", "--limit=20", "--format=llm", "--", "config"],
+ ]);
+ });
+
+ it("sends nothing for the flags the caller left out", async () => {
+ const { calls, runIx } = recorder();
+ const client = await connect(runIx);
+ await client.callTool({ name: "ix_imports", arguments: { symbol: "config.ts" } });
+ expect(calls).toEqual([["imports", "--format=llm", "--", "config.ts"]]);
+ });
+
+ it("does not offer ix_explain a --limit it has no flag for", async () => {
+ const client = await connect(async () => ({ ok: true, stdout: "ok", stderr: "" }));
+ const explain = (await client.listTools()).tools.find((t) => t.name === "ix_explain")!;
+ const properties = (explain.inputSchema as { properties?: Record<string, unknown> }).properties ?? {};
+ expect(Object.keys(properties).sort()).toEqual(["kind", "path", "pick", "symbol"]);
+ });
+
+ it("gives ix_read the same flags, and no size bound of its own", async () => {
+ const { calls, runIx } = recorder();
+ const client = await connect(runIx);
+ await client.callTool({ name: "ix_read", arguments: { symbol: "config", pick: 1 } });
+ expect(calls).toEqual([["read", "--pick=1", "--format=llm", "--", "config"]]);
+ });
+});
+
+describe("ix_search", () => {
+ it("exists at all, which is the point", async () => {
+ const client = await connect(async () => ({ ok: true, stdout: "ok", stderr: "" }));
+ const names = (await client.listTools()).tools.map((t) => t.name);
+ expect(names).toContain("ix_search");
+ });
+
+ it("forwards its filters, and a bounded default limit", async () => {
+ const { calls, runIx } = recorder();
+ const client = await connect(runIx);
+ await client.callTool({ name: "ix_search", arguments: { term: "resolveWorkspace", kind: "function" } });
+ expect(calls).toEqual([["search", "--limit=10", "--kind=function", "--format=llm", "--", "resolveWorkspace"]]);
+ });
+});
+
+describe("bounds", () => {
+ it("gives ix_trace a depth it defaults to", async () => {
+ const { calls, runIx } = recorder();
+ const client = await connect(runIx);
+ await client.callTool({ name: "ix_trace", arguments: { symbol: "verify" } });
+ expect(calls).toEqual([["trace", "--depth=3", "--format=llm", "--", "verify"]]);
+ });
+
+ it("caps a record stream on a line boundary and says it did", async () => {
+ const line = "node name=a kind=function path=src/a.ts\n";
+ const big = line.repeat(2000);
+ const capped = capRecordStream(big, "ix_text");
+
+ expect(capped.length).toBeLessThan(big.length);
+ const lines = capped.split("\n");
+ // Every record before the marker is whole.
+ for (const l of lines.slice(0, -1)) {
+ if (l) expect(l).toBe(line.trimEnd());
+ }
+ expect(lines[lines.length - 1]).toMatch(
+ /^truncated tool=ix_text shown_bytes=\d+ total_bytes=\d+ hint="/,
+ );
+ });
+
+ it("leaves a result that fits exactly as it was", () => {
+ expect(capRecordStream("node name=a\n", "ix_text")).toBe("node name=a\n");
+ });
+
+ it("caps through the tool, not only in the helper", async () => {
+ const big = "node name=a kind=function path=src/a.ts\n".repeat(2000);
+ const client = await connect(async () => ({ ok: true, stdout: big, stderr: "" }));
+ const result = (await client.callTool({ name: "ix_text", arguments: { pattern: "a" } })) as CallToolResult;
+ const first = result.content?.[0];
+ expect(first?.type === "text" && first.text.includes("truncated tool=ix_text")).toBe(true);
+ expect(first?.type === "text" && first.text.length).toBeLessThan(big.length);
+ });
+});
diff --git a/ix-cli/src/mcp/server.ts b/ix-cli/src/mcp/server.ts
index a6c3664c..6027dad0 100644
--- a/ix-cli/src/mcp/server.ts
+++ b/ix-cli/src/mcp/server.ts
@@ -29,6 +29,10 @@ export type { IxRunner } from "./runner.js";
export const IX_MCP_OSS_TOOL_NAMES = [
"ix_health",
"ix_locate",
+ // `ix search` is the command every other one starts from, and it was the one
+ // command with no tool at all — an agent over MCP could follow an edge from
+ // a symbol it already knew, and had no way to find the first symbol.
+ "ix_search",
"ix_text",
"ix_impact",
"ix_map",
@@ -114,6 +118,7 @@ const UNVERIFIED = (title: string): ToolAnnotations => ({ title });
const TOOL_ANNOTATIONS: Record<(typeof IX_MCP_TOOL_NAMES)[number], ToolAnnotations> = {
ix_health: { ...READ_ONLY, title: "Check Ix backend and graph readiness" },
ix_locate: { ...READ_ONLY, title: "Resolve a symbol to its canonical target" },
+ ix_search: { ...READ_ONLY, title: "Search the graph by name" },
ix_text: { ...READ_ONLY, title: "Search text across the indexed repository" },
ix_impact: { ...READ_ONLY, title: "Analyze the blast radius of changing a symbol" },
ix_map: { ...WRITE, title: "Ingest or refresh the workspace architecture map" },
@@ -232,6 +237,25 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
{ symbol: z.string().min(1) },
async (input) => runFormatted(runIx, "ix_locate", ix("locate", [stringArg(input, "symbol")])),
);
+ registerTool(
+ server,
+ "ix_search",
+ "Search the graph by name, ranked, with each hit's path",
+ {
+ term: z.string().min(1),
+ kind: z.string().min(1).optional().describe("narrow to one entity kind"),
+ path: z.string().min(1).optional().describe("narrow to files whose path contains this"),
+ language: z.string().min(1).optional(),
+ limit: z.number().int().min(1).max(200).default(10),
+ },
+ async (input) => {
+ const options = [`--limit=${numberArg(input, "limit")}`];
+ pushOption(options, "--kind", input.kind);
+ pushOption(options, "--path", input.path);
+ pushOption(options, "--language", input.language);
+ return runFormatted(runIx, "ix_search", ix("search", [stringArg(input, "term")], options));
+ },
+ );
registerTool(
server,
"ix_text",
@@ -276,9 +300,18 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
registerTool(
server,
"ix_read",
- "Read graph-bounded source for a symbol or indexed file",
- { symbol: z.string().min(1) },
- async (input) => runFormatted(runIx, "ix_read", ix("read", [stringArg(input, "symbol")])),
+ "Read a symbol's source, or a line range of a file",
+ {
+ symbol: z.string().min(1).describe("a symbol, a path, or `path:start-end`"),
+ kind: z.string().min(1).optional(),
+ path: z.string().min(1).optional(),
+ pick: z.number().int().min(1).max(50).optional().describe("choose the Nth candidate, 1-based"),
+ },
+ // Nothing is forwarded as a size bound: `ix read` owns its own cap, and a
+ // second one here would be a number to keep in sync with it. A range goes
+ // in the target, where the CLI already takes one: `read src/a.ts:40-80`.
+ async (input) =>
+ runFormatted(runIx, "ix_read", ix("read", [stringArg(input, "symbol")], symbolOptions(input, { limit: false }))),
);
registerTool(
server,
@@ -323,9 +356,13 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
{
symbol: z.string().min(1),
to: z.string().min(1).optional(),
+ // The one tool whose traversal had no bound it could be told about:
+ // `ix_depends` has had a `depth` since it was written and this did not,
+ // so a trace through a hub ran as deep as the graph goes.
+ depth: z.number().int().min(1).max(10).default(3),
},
async (input) => {
- const options: string[] = [];
+ const options = [`--depth=${numberArg(input, "depth")}`];
pushOption(options, "--to", input.to);
return runFormatted(runIx, "ix_trace", ix("trace", [stringArg(input, "symbol")], options));
},
@@ -336,6 +373,9 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
"ix_explain",
"Explain a symbol using graph evidence",
"explain",
+ // No `--limit`: `ix explain` has none, and forwarding a flag the command
+ // rejects turns a resolvable call into a usage error.
+ { symbol: SYMBOL_TOOL_INPUT.symbol, kind: SYMBOL_TOOL_INPUT.kind, path: SYMBOL_TOOL_INPUT.path, pick: SYMBOL_TOOL_INPUT.pick },
);
registerTool(
server,
@@ -503,15 +543,45 @@ export async function startIxMcpServer(version = "0.0.0"): Promise<void> {
await server.connect(new StdioServerTransport(process.stdin, createProtocolStdout()));
}
+/**
+ * The flags that let a caller resolve an ambiguous symbol.
+ *
+ * Every one of these tools took a bare `symbol` and nothing else, so a name
+ * with three definitions answered "Ambiguous symbol" and there was no second
+ * call that could get past it — the CLI's own `--pick`, `--kind` and `--path`
+ * were unreachable over MCP. An agent's only move was to shell out, which is
+ * the thing this server exists to avoid.
+ */
+const SYMBOL_TOOL_INPUT = {
+ symbol: z.string().min(1),
+ kind: z.string().min(1).optional().describe("narrow to one entity kind"),
+ path: z.string().min(1).optional().describe("narrow to files whose path contains this"),
+ pick: z.number().int().min(1).max(50).optional().describe("choose the Nth candidate, 1-based"),
+ limit: z.number().int().min(1).max(500).optional().describe("max rows"),
+} as const;
+
+/** Turn the shared disambiguation input into CLI flags. */
+function symbolOptions(input: ToolInput, opts: { limit?: boolean } = {}): string[] {
+ const options: string[] = [];
+ pushOption(options, "--kind", input.kind);
+ pushOption(options, "--path", input.path);
+ if (typeof input.pick === "number") options.push(`--pick=${numberArg(input, "pick")}`);
+ if (opts.limit !== false && typeof input.limit === "number") {
+ options.push(`--limit=${numberArg(input, "limit")}`);
+ }
+ return options;
+}
+
function registerSymbolTool(
server: McpServer,
runIx: IxRunner,
name: string,
description: string,
command: string,
+ input: z.ZodRawShape = SYMBOL_TOOL_INPUT,
): void {
- registerTool(server, name, description, { symbol: z.string().min(1) }, async (input) =>
- runFormatted(runIx, name, ix(command, [stringArg(input, "symbol")])),
+ registerTool(server, name, description, input, async (args) =>
+ runFormatted(runIx, name, ix(command, [stringArg(args, "symbol")], symbolOptions(args))),
);
}
@@ -549,6 +619,32 @@ function toArgv(argv: IxArgv, format: string): string[] {
return args;
}
+/**
+ * How much of one tool result a client should have to hold.
+ *
+ * The only bound before this was the runner's 16 MiB heap guard, which exists
+ * to stop a long-lived server growing — not to stop a single `ix text` filling
+ * a model's context. Most hosts truncate a tool result themselves, from the
+ * end, with no marker: the caller then cannot tell a short answer from a
+ * chopped one.
+ */
+const MAX_TOOL_RESULT_BYTES = 24 * 1024;
+
+/**
+ * Cap a record stream, on a line boundary, and say so in a record.
+ *
+ * Record streams only. Cutting JSON produces something that does not parse,
+ * which is worse than something large — so `runJson`, `runJsonStructured` and
+ * `runSmells` are deliberately uncapped, and their size is bounded by the
+ * command's own budgets instead.
+ */
+export function capRecordStream(text: string, tool: string): string {
+ if (text.length <= MAX_TOOL_RESULT_BYTES) return text;
+ const boundary = text.lastIndexOf("\n", MAX_TOOL_RESULT_BYTES);
+ const head = text.slice(0, boundary > 0 ? boundary : MAX_TOOL_RESULT_BYTES);
+ return `${head}\ntruncated tool=${tool} shown_bytes=${head.length} total_bytes=${text.length} hint="Narrow the call — every one of these tools takes a limit, a path or a depth."`;
+}
+
async function runFormatted(
runIx: IxRunner,
tool: string,
@@ -562,7 +658,12 @@ async function runFormatted(
// Only the leading record governs status. `ix_read` may contain error-like
// source lines after its successful `content` record.
const semanticError = first?.type === "text" && first.text.startsWith("error code=");
- return semanticError ? { ...result, isError: true } : result;
+ if (semanticError) return { ...result, isError: true };
+ if (first?.type !== "text") return result;
+ const capped = capRecordStream(first.text, tool);
+ return capped === first.text
+ ? result
+ : { ...result, content: [{ type: "text", text: capped }, ...result.content.slice(1)] };
}
async function runJson(