Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
feat(mcp): tell agents when Ix beats grep, and make hints callable
KageBinary4840ad5dec33
diff --git a/ix-cli/src/cli/__tests__/mcp-hints.test.ts b/ix-cli/src/cli/__tests__/mcp-hints.test.tsnew file mode 100644index 00000000..62dedf44--- /dev/null+++ b/ix-cli/src/cli/__tests__/mcp-hints.test.ts@@ -0,0 +1,309 @@+// Copyright 2026 Ix Infrastructure Inc.++import { existsSync, readFileSync } from "node:fs";++import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";+import { Command } from "commander";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { createInProcessRunner } from "../../mcp/runner.js";+import {+ createIxMcpServer,+ IX_MCP_CORE_TOOL_NAMES,+ IX_MCP_INSTRUCTIONS,+ IX_MCP_TOOL_NAMES,+ type IxRunner,+} from "../../mcp/server.js";+import { NEXT_READ_MAX_LINES, nextReads, nextToolCalls, truncationAdvice } from "../commands/context.js";+import { inferRiskSemantics, type ImpactFacts } from "../impact/risk-semantics.js";+import { disambiguationHint, forMcp, IX_CALLER_ENV, toolCall } from "../next-step.js";+import { roleHint } from "../role-filter.js";+import { reportAmbiguousTarget } from "../ui.js";++const CORE = new Set<string>(IX_MCP_CORE_TOOL_NAMES);++/**+ * What an MCP hint must never contain: a CLI flag, a CLI command, or a tool a+ * core session does not have.+ */+function expectRunnableOverMcp(text: string): void {+ expect(text, text).not.toMatch(/(^|\s)--[a-z]/);+ expect(text, text).not.toMatch(/`?\bix (read|callers|callees|imports|imported-by|impact|context|contains|depends|conflicts|explain|map|text|search)\b/);+ for (const tool of text.match(/\bix_[a-z_]+/g) ?? []) {+ expect(CORE.has(tool), `${tool} is not a core tool, in: ${text}`).toBe(true);+ }+}++function withCaller(value: string | undefined): void {+ if (value === undefined) delete process.env[IX_CALLER_ENV];+ else process.env[IX_CALLER_ENV] = value;+}++const clients: Client[] = [];+afterEach(async () => {+ await Promise.all(clients.splice(0).map((client) => client.close()));+});++async function connect(runIx: IxRunner = async () => ({ ok: true, stdout: "ok", stderr: "" })): Promise<Client> {+ const server = createIxMcpServer({ version: "test", runIx });+ const client = new Client({ name: "ix-mcp-hints-test", version: "1.0.0" });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ await server.connect(st);+ await client.connect(ct);+ clients.push(client);+ return client;+}++describe("server instructions", () => {+ it("reach the client in the initialize result", async () => {+ // The one channel a host that defers tool schemas still puts in front of+ // the model.+ const client = await connect();+ expect(client.getInstructions()).toBe(IX_MCP_INSTRUCTIONS);+ });++ it("are a few lines, name the tools to reach for first, and say when not to", () => {+ const lines = IX_MCP_INSTRUCTIONS.split("\n");+ expect(lines.length).toBeGreaterThanOrEqual(5);+ expect(lines.length).toBeLessThanOrEqual(8);+ for (const tool of ["ix_context", "ix_neighbors", "ix_impact"]) expect(IX_MCP_INSTRUCTIONS).toContain(tool);+ expect(IX_MCP_INSTRUCTIONS).toMatch(/Not for a literal string/);+ expect(IX_MCP_INSTRUCTIONS).toMatch(/Grep/);+ });++ it("name only tools every session has", () => {+ const named = IX_MCP_INSTRUCTIONS.match(/\bix_[a-z_]+/g) ?? [];+ expect(named.length).toBeGreaterThan(0);+ for (const tool of named) expect(CORE.has(tool), tool).toBe(true);+ // And every core tool is a real one.+ for (const tool of CORE) expect(IX_MCP_TOOL_NAMES as readonly string[]).toContain(tool);+ });+});++describe("hints produced for an MCP caller", () => {+ beforeEach(() => withCaller("mcp"));+ afterEach(() => withCaller(undefined));++ function bundle(+ target: { name: string; kind: string; path?: string },+ cut: Array<{ what: string; count: number }> = [],+ evidence: Array<Record<string, unknown>> = [],+ ): never {+ return {+ target: { id: "t", resolutionMode: "exact", ...target },+ evidence,+ truncation: {+ entitiesTruncated: 0,+ relationshipsTruncated: 0,+ evidenceTruncated: cut.reduce((n, c) => n + c.count, 0),+ charactersTruncated: 0,+ cut,+ },+ } as never;+ }++ it("send every truncated category to a core tool or to max_tokens", () => {+ const cuts = ["member", "caller", "dependent", "import", "call", "relationship", "claim", "conflict", "decision"];+ for (const kind of ["function", "file", "class"]) {+ for (const what of cuts) {+ const advice = truncationAdvice(bundle({ name: "verify", kind, path: "src/auth.ts" }, [{ what, count: 3 }]))!;+ expectRunnableOverMcp(advice);+ expect(advice, advice).toContain("max_tokens");+ }+ }+ });++ it("name the core tool that answers the same question", () => {+ const advice = truncationAdvice(bundle({ name: "verify", kind: "function", path: "src/auth.ts" }, [{ what: "caller", count: 4 }]));+ expect(advice).toContain("ix_neighbors symbol=verify relation=callers path=src/auth.ts");+ });++ it("close a symbol's bundle with callers and impact before any read", () => {+ const steps = nextToolCalls(bundle(+ { name: "verify", kind: "function", path: "src/auth.ts" },+ [],+ [{ location: { path: "src/auth.ts", lineStart: 10, lineEnd: 40 } }],+ ));+ expect(steps.map((s) => s.cmd)).toEqual([+ "ix_neighbors symbol=verify relation=callers path=src/auth.ts",+ "ix_impact target=verify path=src/auth.ts",+ "ix_read symbol=src/auth.ts:10-40",+ ]);+ for (const step of steps) {+ expectRunnableOverMcp(step.cmd);+ expect(step.why.length, step.cmd).toBeGreaterThan(0);+ }+ });++ it("close a file's bundle with its importers, by path", () => {+ const steps = nextToolCalls(bundle({ name: "auth.ts", kind: "file", path: "src/auth.ts" }));+ expect(steps[0].cmd).toBe("ix_neighbors symbol=src/auth.ts relation=imported_by");+ expect(steps[1].cmd).toBe("ix_impact target=src/auth.ts");+ });++ it("cap a suggested read, rather than hand over a 558-line range", () => {+ const steps = nextToolCalls(bundle(+ { name: "Big", kind: "class", path: "src/big.ts" },+ [],+ [{ location: { path: "src/big.ts", lineStart: 21, lineEnd: 578 } }],+ ));+ const read = steps.find((s) => s.cmd.startsWith("ix_read"))!;+ expect(read.cmd).toBe(`ix_read symbol=src/big.ts:21-${21 + NEXT_READ_MAX_LINES - 1}`);+ expect(read.why).toContain("of 558 lines");+ });++ it("offer include_tests, which ix_search takes, not --include-tests", () => {+ const hint = roleHint(3)!;+ expectRunnableOverMcp(hint);+ expect(hint).toContain("include_tests=true");+ });++ it("disambiguate with tool arguments", () => {+ const hint = disambiguationHint("Use --pick <n> or --path to disambiguate.");+ expectRunnableOverMcp(hint);+ expect(hint).toContain("pick=");++ const log = vi.spyOn(console, "log").mockImplementation(() => {});+ try {+ reportAmbiguousTarget(+ "verify",+ {+ resolutionMode: "ambiguous",+ candidates: [+ { id: "a", name: "verify", kind: "function", path: "src/a.ts" },+ { id: "b", name: "verify", kind: "function", path: "src/b.ts" },+ ],+ },+ "llm",+ );+ const printed = log.mock.calls.map((call) => String(call[0])).join("\n");+ const hintLine = printed.split("\n").find((line) => line.startsWith("hint "))!;+ expectRunnableOverMcp(hintLine);+ expect(hintLine).toContain("pick=<n>");+ } finally {+ log.mockRestore();+ }+ });++ it("send ix_impact's next step to a core tool", () => {+ const base: ImpactFacts = {+ name: "X",+ kind: "function",+ targetPath: "src/x.ts",+ members: 0,+ callers: 2,+ callees: 1,+ directImporters: 0,+ directDependents: 0,+ memberLevelCallers: 0,+ propagationBuckets: [],+ };+ const cases: ImpactFacts[] = [+ { ...base, name: "NodeKind", kind: "enum", members: 24, directImporters: 8, directDependents: 12 },+ { ...base, name: "pickBest", path: "ix-cli/src/cli/resolve.ts", callers: 1, callees: 4 },+ { ...base, name: "IxClient", kind: "class", members: 15, callers: 0, directImporters: 8, directDependents: 20, memberLevelCallers: 66 },+ ];+ let seen = 0;+ for (const facts of cases) {+ const next = inferRiskSemantics(facts).nextStep;+ if (next === undefined) continue;+ seen += 1;+ expectRunnableOverMcp(next);+ expect(next).toMatch(/ix_neighbors symbol=\S+ relation=(callers|imported_by)/);+ }+ expect(seen).toBeGreaterThanOrEqual(2);+ });+});++describe("hints produced for the CLI", () => {+ beforeEach(() => withCaller(undefined));++ it("are unchanged", () => {+ expect(forMcp()).toBe(false);+ expect(roleHint(1)).toBe("1 test/fixture candidate hidden. Use --include-tests to include.");+ expect(disambiguationHint("Use --pick <n> or --path to disambiguate.")).toBe("Use --pick <n> or --path to disambiguate.");+ expect(nextReads({ evidence: [{ location: { path: "src/a.ts", lineStart: 1, lineEnd: 900 } }] } as never)).toEqual([+ "ix read src/a.ts:1-900",+ ]);+ });+});++describe("toolCall", () => {+ it("drops empty arguments and quotes values with spaces", () => {+ expect(toolCall("ix_search", { term: "parse config", kind: undefined, limit: 5 })).toBe(+ 'ix_search term="parse config" limit=5',+ );+ });+});++describe("the MCP runner", () => {+ afterEach(() => withCaller(undefined));++ it("marks every command it runs as serving MCP, and only while it runs", async () => {+ withCaller(undefined);+ const runIx = createInProcessRunner({+ createProgram: () => {+ const program = new Command();+ program.command("probe").action(() => console.log(`caller=${process.env[IX_CALLER_ENV] ?? "cli"}`));+ return program;+ },+ });+ const result = await runIx(["probe"]);+ expect(result.stdout.trim()).toBe("caller=mcp");+ expect(process.env[IX_CALLER_ENV]).toBeUndefined();+ });+});++describe("ix_context over MCP", () => {+ it("takes issue text, through a file that is gone after the call", async () => {+ const seen: Array<{ args: string[]; text?: string }> = [];+ const client = await connect(async (args) => {+ const flag = args.find((arg) => arg.startsWith("--from-issue="));+ const file = flag?.slice("--from-issue=".length);+ seen.push({ args, text: file ? readFileSync(file, "utf8") : undefined });+ return { ok: true, stdout: "context target=x", stderr: "" };+ });++ const result = await client.callTool({ name: "ix_context", arguments: { issue: "Login fails in verify()", max_tokens: 1500 } });++ expect(result.isError).toBeFalsy();+ expect(seen).toHaveLength(1);+ expect(seen[0].text).toBe("Login fails in verify()");+ expect(seen[0].args).toContain("--max-tokens=1500");+ expect(seen[0].args).not.toContain("--");+ const file = seen[0].args.find((arg) => arg.startsWith("--from-issue="))!.slice("--from-issue=".length);+ expect(existsSync(file)).toBe(false);+ });++ it("forwards the disambiguation a target needs", async () => {+ const calls: string[][] = [];+ const client = await connect(async (args) => {+ calls.push(args);+ return { ok: true, stdout: "ok", stderr: "" };+ });+ await client.callTool({ name: "ix_context", arguments: { target: "verify", path: "src/auth.ts", pick: 2 } });+ await client.callTool({ name: "ix_impact", arguments: { target: "verify", kind: "function", pick: 1 } });+ await client.callTool({ name: "ix_search", arguments: { term: "verify", include_tests: true } });+ expect(calls).toEqual([+ ["context", "--path=src/auth.ts", "--pick=2", "--format=llm", "--", "verify"],+ ["impact", "--kind=function", "--pick=1", "--format=llm", "--", "verify"],+ ["search", "--limit=10", "--include-tests", "--format=llm", "--", "verify"],+ ]);+ });++ it("refuses combinations in its own terms, not the CLI's flags", async () => {+ const client = await connect();+ for (const args of [+ {},+ { target: "a", issue: "b" },+ { issue: "b", path: "src" },+ { target: "a", max_tokens: 1000, max_chars: 4000 },+ ]) {+ const result = await client.callTool({ name: "ix_context", arguments: args });+ expect(result.isError, JSON.stringify(args)).toBe(true);+ const text = (result.content as Array<{ type: string; text: string }>)[0].text;+ expect(text, text).not.toMatch(/--[a-z]/);+ }+ });+});diff --git a/ix-cli/src/cli/__tests__/mcp-structured-output.test.ts b/ix-cli/src/cli/__tests__/mcp-structured-output.test.tsindex 6555c06a..a87aae3e 100644--- a/ix-cli/src/cli/__tests__/mcp-structured-output.test.ts+++ b/ix-cli/src/cli/__tests__/mcp-structured-output.test.ts@@ -172,7 +172,9 @@ describe("ix mcp structured output", () => {// Against the full catalog, which is what `connect` builds here. What a// session actually pays is the core set, and `mcp-toolset.test.ts` holds// that number.- expect(total).toBeLessThan(16_000);+ // The full catalog's descriptions now say when to use each tool and when+ // not to, which is what a caller of `--tools=all` is choosing between.+ expect(total).toBeLessThan(17_000);});it("attaches structuredContent only where an outputSchema was declared", async () => {diff --git a/ix-cli/src/cli/__tests__/mcp-toolset.test.ts b/ix-cli/src/cli/__tests__/mcp-toolset.test.tsindex f74cebe0..5f853e7a 100644--- a/ix-cli/src/cli/__tests__/mcp-toolset.test.ts+++ b/ix-cli/src/cli/__tests__/mcp-toolset.test.ts@@ -36,30 +36,46 @@ async function names(opts: Parameters<typeof connect>[0] = {}): Promise<string[]}describe("the core toolset", () => {- it("is what a session gets without asking", async () => {- expect(await names()).toEqual([...IX_MCP_CORE_TOOL_NAMES]);+ it("is what a session gets without asking, ix_context first", async () => {+ const listed = await names();+ expect([...listed].sort()).toEqual([...IX_MCP_CORE_TOOL_NAMES].sort());+ expect(listed[0]).toBe("ix_context");});- it("is ten tools, not twenty-six", async () => {- // `tools/list` is paid on every session before a single call is made, and a- // model choosing between 26 near-identical names picks worse than one- // choosing between ten.- expect(IX_MCP_CORE_TOOL_NAMES.length).toBe(10);+ it("is five task-shaped tools, one per question", async () => {+ // Ten was still too many: four of them answered "tell me about X" and two+ // were name lookups, and recorded agents never reached for the graph's own+ // answers (callers, importers, impact).+ expect([...IX_MCP_CORE_TOOL_NAMES]).toEqual([+ "ix_context",+ "ix_search",+ "ix_neighbors",+ "ix_impact",+ "ix_read",+ ]);expect((await names({ tools: "all" })).length).toBeGreaterThan(20);});+ it("leaves ix_health and the overlapping lookups to --tools=all", async () => {+ const core = await names();+ const all = await names({ tools: "all" });+ for (const name of ["ix_health", "ix_text", "ix_locate", "ix_overview", "ix_explain"]) {+ expect(core, name).not.toContain(name);+ expect(all, name).toContain(name);+ }+ });+it("costs a fraction of what the full catalog costs", async () => {const client = await connect();const core = JSON.stringify((await client.listTools()).tools).length;const full = JSON.stringify((await (await connect({ tools: "all" })).listTools()).tools).length;- // Measured: 6,437 bytes for ten tools against 15,365 for today's catalog,- // a 58% cut. The spec asked for 5 KB, which is not reachable: a tool with- // no parameters at all is 412 bytes of name, description and annotations,- // so ten of them are 4.1 KB before a single input is declared. Getting to- // 5 KB would mean giving back the disambiguation parameters that make an- // ambiguous symbol resolvable at all.- expect(core).toBeLessThan(6_600);+ // Measured: 6,437 bytes for the old ten-tool core. Five tools with+ // when-to-use descriptions, and disambiguation on every symbol tool, come+ // to about 5 KB, and the server instructions (~850 bytes) are sent once in+ // `initialize` on top of that, so the total still comes in under the old+ // tools/list alone.+ expect(core).toBeLessThan(5_300);expect(core).toBeLessThan(full / 2);});@@ -141,11 +157,29 @@ describe("ix_neighbors", () => {});describe("tool descriptions", () => {- it("stay inside a line, so a catalog is skimmable", async () => {+ it("stay within three short sentences, so a catalog is skimmable", async () => {const tools = (await (await connect({ tools: "all", proAvailable: true })).listTools()).tools;for (const tool of tools) {expect(tool.description, tool.name).toBeDefined();- expect(tool.description!.length, `${tool.name}: ${tool.description}`).toBeLessThanOrEqual(120);+ expect(tool.description!.length, `${tool.name}: ${tool.description}`).toBeLessThanOrEqual(300);+ }+ });++ it("say when to use each core tool and when not to", async () => {+ // "Use instead of grep" gave no reason to. Each core description now says+ // when to reach for it, what it returns, and what to use instead.+ const tools = (await (await connect()).listTools()).tools;+ for (const tool of tools) {+ expect(tool.description, tool.name).toMatch(/^Use (when|first|before)/);+ expect(tool.description, tool.name).toMatch(/Returns /);+ expect(tool.description, tool.name).toMatch(/Not (for|needed)|For (a|transitive)/);+ }+ });++ it("keep titles as labels, with the guidance in the description", async () => {+ const tools = (await (await connect({ tools: "all" })).listTools()).tools;+ for (const tool of tools) {+ expect(tool.annotations?.title?.length ?? 0, tool.name).toBeLessThanOrEqual(40);}});diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex 8eac3d7b..7746844f 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -42,6 +42,7 @@ import { activeReadScope, ensureReadScope, resolveFileOrReport } from "../resolvimport { createStaleProbe, hasCompletedSourceGraphBaseline } from "../stale.js";import { renderNote, renderSection, renderWarning, renderWarningErr, reportFailure } from "../ui.js";import { printJson, relativePath } from "../format.js";+import { forMcp, suggest, toolCall } from "../next-step.js";/** The `--max-*` knobs that bound a bundle. */interface BudgetSnapshot {@@ -2367,7 +2368,9 @@ export function renderBundle(bundle: ContextBundle, format: string): void {// `--format json` carries the rest for a caller that wants it....bundle.evidence.map(evidenceRecord(undefined)),// Last, so it reads as the closing instruction it is.- ...nextReads(bundle).map((cmd) => llmLine("next", { cmd })),+ ...(forMcp()+ ? nextToolCalls(bundle).map((step) => llmLine("next", { cmd: step.cmd, why: step.why }))+ : nextReads(bundle).map((cmd) => llmLine("next", { cmd }))),]);return;}@@ -2475,9 +2478,9 @@ function summariseCut(dropped: EvidenceItem[]): Array<{ what: string; count: num* for anything and pays for everything.*/function cutLever(bundle: ContextBundle, top: { what: string }): string {+ if (forMcp()) return mcpCutLever(bundle, top);const name = bundle.target.name;- const container = ["file", "module", "class", "object", "trait", "interface"]- .includes(bundle.target.kind.toLowerCase());+ const container = CONTAINER_TARGET_KINDS.includes(bundle.target.kind.toLowerCase());switch (top.what) {case "member":return container@@ -2501,6 +2504,36 @@ function cutLever(bundle: ContextBundle, top: { what: string }): string {}}+const CONTAINER_TARGET_KINDS: readonly string[] = ["file", "module", "class", "object", "trait", "interface"];++/**+ * {@link cutLever} for an MCP caller: only core tools, and `max_tokens` for+ * the budget, since `ix_context` takes no flags. `ix contains`, `ix depends`+ * and `ix conflicts` have no core tool, so those cuts fall back to the nearest+ * one that does exist, or to the budget alone.+ */+function mcpCutLever(bundle: ContextBundle, top: { what: string }): string {+ const { name, path } = bundle.target;+ const container = CONTAINER_TARGET_KINDS.includes(bundle.target.kind.toLowerCase());+ const pin = container ? {} : { path };+ const budget = "raise max_tokens (default 3000)";+ switch (top.what) {+ case "member":+ return container ? `call ix_context on one of them, or ${budget}` : budget;+ case "caller":+ return `${suggest.neighbors(name, "callers", pin)}, or ${budget}`;+ case "dependent":+ case "relationship":+ return `${suggest.impact(name, pin)}, or ${budget}`;+ case "import":+ return `${suggest.neighbors(name, "imports", pin)}, or ${budget}`;+ case "call":+ return `${suggest.neighbors(name, "callees", pin)}, or ${budget}`;+ default:+ return budget;+ }+}+/** One sentence naming what was cut and the cheapest way to get it back. */export function truncationAdvice(bundle: ContextBundle): string | undefined {const cut = bundle.truncation.cut ?? [];@@ -2571,6 +2604,53 @@ export function nextReads(bundle: ContextBundle, limit = 3): string[] {return reads;}+/** Longest range a suggested read may span; past it the read covers its head only. */+export const NEXT_READ_MAX_LINES = 120;++/**+ * The next calls worth making, for an MCP caller.+ *+ * {@link nextReads} closes a CLI bundle with `ix read path:a-b`, which over MCP+ * is the one suggestion an agent's own Read tool already covers — and the+ * recorded agents that did follow the bundle never once asked the graph the+ * questions only it answers. So the MCP close leads with those: who calls (or+ * imports) the target across files, and what a change to it reaches. A read of+ * the target's own range comes last, capped so a 558-line class does not turn+ * into a 558-line suggestion.+ *+ * Every call names core tools only, and pins the target's file with `path=` so+ * an ambiguous name resolves to the entity this bundle was built for.+ */+export function nextToolCalls(bundle: ContextBundle): Array<{ cmd: string; why: string }> {+ const { name, kind, path } = bundle.target;+ const steps: Array<{ cmd: string; why: string }> = [];+ const isFile = kind.toLowerCase() === "file";+ // A file resolves by its path; a symbol by name, pinned to its file.+ const symbol = isFile ? (path ?? name) : name;+ const pin = isFile ? {} : { path };++ steps.push(+ isFile+ ? { cmd: suggest.neighbors(symbol, "imported_by", pin), why: "every file that imports this one" }+ : { cmd: suggest.neighbors(symbol, "callers", pin), why: "every call site across files, from the graph rather than a name match" },+ );+ steps.push({ cmd: suggest.impact(symbol, pin), why: "what a change here reaches, before you edit it" });++ const read = bundle.evidence.find(+ (item) => item.location?.path && item.location.lineStart !== undefined && item.location.lineEnd !== undefined,+ )?.location;+ if (read?.lineStart !== undefined && read.lineEnd !== undefined) {+ const end = Math.min(read.lineEnd, read.lineStart + NEXT_READ_MAX_LINES - 1);+ steps.push({+ cmd: toolCall("ix_read", { symbol: `${read.path}:${read.lineStart}-${end}` }),+ why: end < read.lineEnd+ ? `first ${NEXT_READ_MAX_LINES} of ${read.lineEnd - read.lineStart + 1} lines of the top-ranked evidence`+ : "the top-ranked evidence",+ });+ }+ return steps;+}+function locationField(ref: Located | undefined): { location?: EvidenceLocation } {if (!ref?.path) return {};return { location: { ...locationFields(ref), path: ref.path } };diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.tsindex 521eed96..1d0d34d2 100644--- a/ix-cli/src/cli/commands/explain.ts+++ b/ix-cli/src/cli/commands/explain.ts@@ -14,6 +14,7 @@ import { renderExplainLlm, renderExplainRawLlm } from "../explain/llm.js";import { printLlmLines } from "../llm.js";import { parsePickOption } from "../options.js";import { renderSection, renderWarning, renderNote } from "../ui.js";+import { forMcp, toolCall } from "../next-step.js";export function registerExplainCommand(program: Command): void {program@@ -145,7 +146,7 @@ async function rawExplain(name: name || e.dst,kind: calleeNode.kind,resolved: false,- suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,+ suggestedCommand: forMcp() ? toolCall("ix_text", { pattern: e.dst.slice(0, 8) }) : `ix text "${e.dst.slice(0, 8)}"`,};}return {@@ -154,14 +155,14 @@ async function rawExplain(id: e.dst,resolved: true,path: relativePath(calleeNode.provenance?.source_uri ?? calleeNode.provenance?.sourceUri),- suggestedCommand: `ix explain "${name}"`,+ suggestedCommand: forMcp() ? toolCall("ix_explain", { symbol: name }) : `ix explain "${name}"`,};} catch {return {name: e.dst,resolved: false,diagnostic: "unresolved_call_target",- suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,+ suggestedCommand: forMcp() ? toolCall("ix_text", { pattern: e.dst.slice(0, 8) }) : `ix text "${e.dst.slice(0, 8)}"`,} as EntityRef;}})@@ -171,7 +172,7 @@ async function rawExplain(if (unresolvedCount > 0) {diagnostics.push({code: "unresolved_call_target",- message: `${unresolvedCount} callee(s) could not be resolved to named entities. Use ix text to locate them.`,+ message: `${unresolvedCount} callee(s) could not be resolved to named entities. Use ${forMcp() ? "ix_text" : "ix text"} to locate them.`,});}}diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.tsindex a4a23285..4c3f5b16 100644--- a/ix-cli/src/cli/commands/impact.ts+++ b/ix-cli/src/cli/commands/impact.ts@@ -8,7 +8,7 @@ import { getEndpoint } from "../config.js";import { resolveFileOrReport, printResolved } from "../resolve.js";import { bucketByHierarchy, getSystemPath, formatSystemPath, hasMapData, type SystemPath } from "../hierarchy.js";import { inferRiskSemantics, humanizeLabel, type ImpactFacts, type RiskSemantics } from "../impact/risk-semantics.js";-import { lineSpan, printJson, rowLocation, stripNulls } from "../format.js";+import { lineSpan, printJson, relativePath, rowLocation, stripNulls } from "../format.js";import { llmLine } from "../llm.js";import { parsePickOption } from "../options.js";@@ -262,7 +262,7 @@ export function impactTailLlm(async function containerImpact(client: IxClient,- target: { id: string; kind: string; name: string; resolutionMode: string },+ target: { id: string; kind: string; name: string; resolutionMode: string; path?: string },limit: number,depth: number,format: string@@ -352,6 +352,7 @@ async function containerImpact(const riskFacts: ImpactFacts = {name: target.name,kind: target.kind,+ targetPath: target.path ? (relativePath(target.path) ?? target.path) : undefined,container: undefined,systemPath: systemPathMapped,members: members.length,@@ -452,7 +453,7 @@ async function containerImpact(async function leafImpact(client: IxClient,- target: { id: string; kind: string; name: string; resolutionMode: string },+ target: { id: string; kind: string; name: string; resolutionMode: string; path?: string },depth: number,format: string): Promise<void> {@@ -492,6 +493,7 @@ async function leafImpact(const riskFacts: ImpactFacts = {name: target.name,kind: target.kind,+ targetPath: target.path ? (relativePath(target.path) ?? target.path) : undefined,container: undefined,systemPath: systemPathMapped,members: 0,diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.tsindex 436dae0b..49cf19be 100644--- a/ix-cli/src/cli/commands/locate.ts+++ b/ix-cli/src/cli/commands/locate.ts@@ -15,6 +15,7 @@ import { parsePickOption } from "../options.js";import { getEffectiveSystemPath, hasMapData } from "../hierarchy.js";import { humanizeLabel } from "../impact/risk-semantics.js";import { renderSection, renderKeyValue, renderNote, renderWarning, renderBreadcrumb, reportAmbiguousTarget } from "../ui.js";+import { forMcp } from "../next-step.js";const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);const FILE_KINDS = new Set(["file"]);@@ -148,7 +149,7 @@ export function registerLocateCommand(program: Command): void {// Diagnostic for missing map dataconst hasMap = hasMapData(systemPath);if (!hasMap) {- diagnostics.push("No system map. Run `ix map` to see hierarchy.");+ diagnostics.push(`No system map. Run ${forMcp() ? "ix_map" : "`ix map`"} to see hierarchy.`);}// Build system path: append resolved symbol for non-file targetsdiff --git a/ix-cli/src/cli/commands/mcp.ts b/ix-cli/src/cli/commands/mcp.tsindex c26d7605..61966324 100644--- a/ix-cli/src/cli/commands/mcp.ts+++ b/ix-cli/src/cli/commands/mcp.ts@@ -104,7 +104,7 @@ export function registerMcpCommand(program: Command): void {.description("Serve Ix tools over the Model Context Protocol (stdio)").option("--tools <set>",- "Which catalog to advertise (core|all). core is ten tools; all is every one",+ "Which catalog to advertise (core|all). core is five task-shaped tools; all is every one","core",).action(async (opts: { tools: string }) => {diff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.tsindex eabb54db..fe027eee 100644--- a/ix-cli/src/cli/commands/overview.ts+++ b/ix-cli/src/cli/commands/overview.ts@@ -10,6 +10,7 @@ import { relativePath, printJson } from "../format.js";import { llmLine, type LlmValue } from "../llm.js";import { parsePickOption } from "../options.js";import { renderSection, renderKeyValue, renderNote, renderBreadcrumb } from "../ui.js";+import { forMcp } from "../next-step.js";const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);const STRUCTURAL_CONTAINER_KINDS = new Set(["class", "object", "trait", "interface"]);@@ -166,7 +167,7 @@ async function overviewContainer(const hasMap = hasMapData(systemPath);if (!hasMap) {- diagnostics.push("No system map. Run `ix map` to see hierarchy.");+ diagnostics.push(`No system map. Run ${forMcp() ? "ix_map" : "`ix map`"} to see hierarchy.`);}// Append container symbol to system path for non-file, non-region containers@@ -246,7 +247,7 @@ async function overviewLeaf(const hasMap = hasMapData(systemPath);if (!hasMap) {- diagnostics.push("No system map. Run `ix map` to see hierarchy.");+ diagnostics.push(`No system map. Run ${forMcp() ? "ix_map" : "`ix map`"} to see hierarchy.`);}// Append target to system path if not already therediff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.tsindex c28ab92a..37ec59c0 100644--- a/ix-cli/src/cli/commands/read.ts+++ b/ix-cli/src/cli/commands/read.ts@@ -12,6 +12,7 @@ import { isFileStale } from "../stale.js";import { relativePath, printJson } from "../format.js";import { llmError, llmLine, llmShortId, printLlmLines } from "../llm.js";import { parsePickOption } from "../options.js";+import { disambiguationHint } from "../next-step.js";import { reportUnresolvedTarget } from "../ui.js";export interface ReadResult {@@ -221,7 +222,7 @@ export function renderReadAmbiguityLlm(result: AmbiguityResult, target: string):"text",isFile? "Provide a more specific path to disambiguate."- : "Use --pick <n>, --kind, or --path to disambiguate.",+ : disambiguationHint("Use --pick <n>, --kind, or --path to disambiguate."),]]));for (const d of result.diagnostics ?? []) {lines.push(llmLine("diagnostic", [["code", d.code], ["message", d.message]]));@@ -447,7 +448,7 @@ Examples:outputAmbiguity({targetType: "ambiguous-symbol",candidates: symbolResult.candidates.map((c, i) => ({ ...c, rank: i + 1 })),- diagnostics: [{ code: "ambiguous_resolution", message: "Use --pick <n> or --path to disambiguate." }],+ diagnostics: [{ code: "ambiguous_resolution", message: disambiguationHint("Use --pick <n> or --path to disambiguate.") }],}, target, opts.format);return;}diff --git a/ix-cli/src/cli/explain/facts.ts b/ix-cli/src/cli/explain/facts.tsindex 178717f8..308041ac 100644--- a/ix-cli/src/cli/explain/facts.ts+++ b/ix-cli/src/cli/explain/facts.ts@@ -9,6 +9,7 @@ import { buildDependencyTree } from "../commands/depends.js";import { getSystemPath } from "../hierarchy.js";import type { CommitRef } from "./history.js";import type { RelatedRef } from "./related-files.js";+import { forMcp, toolCall } from "../next-step.js";/** A related entity and where it is defined. */export interface EntityLocation {@@ -439,7 +440,7 @@ export async function collectFacts(name: name || e.dst,kind: calleeNode.kind,resolved: false,- suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,+ suggestedCommand: forMcp() ? toolCall("ix_text", { pattern: e.dst.slice(0, 8) }) : `ix text "${e.dst.slice(0, 8)}"`,};}return {@@ -448,14 +449,14 @@ export async function collectFacts(id: e.dst,resolved: true,path: relativePath(calleeNode.provenance?.source_uri ?? calleeNode.provenance?.sourceUri),- suggestedCommand: `ix explain "${name}"`,+ suggestedCommand: forMcp() ? toolCall("ix_explain", { symbol: name }) : `ix explain "${name}"`,};} catch {return {name: e.dst,resolved: false,diagnostic: "unresolved_call_target",- suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,+ suggestedCommand: forMcp() ? toolCall("ix_text", { pattern: e.dst.slice(0, 8) }) : `ix text "${e.dst.slice(0, 8)}"`,} as EntityRef;}}),diff --git a/ix-cli/src/cli/explain/render.ts b/ix-cli/src/cli/explain/render.tsindex 8dab6814..359397fc 100644--- a/ix-cli/src/cli/explain/render.ts+++ b/ix-cli/src/cli/explain/render.ts@@ -11,6 +11,7 @@ import {} from "./hierarchy-semantics.js";import { inferSystemMeaning } from "./system-meaning.js";import { type FlowSemantics, inferFlowSemantics } from "./flow-semantics.js";+import { forMcp, suggest } from "../next-step.js";export interface ExplanationOutput {explanation: string;@@ -202,7 +203,7 @@ function renderFlowWhyItMatters(`Although it has ${callerPhrase}, this ${role} sits in the ${flowName} ` +`and feeds ${downstream}, ` +`making it a critical decision point in that flow. ` +- `Consider running \`ix impact ${facts.name}\` before modifying.`+ `Consider running \`${suggest.impact(facts.name)}\` before modifying.`);}@@ -210,7 +211,7 @@ function renderFlowWhyItMatters(return (`Because this ${role} ${behaviorVerb}, changes here ${verb} affect how ` +`${actionNoun} behaves across the system. ` +- `Run \`ix impact ${facts.name}\` before modifying.`+ `Run \`${suggest.impact(facts.name)}\` before modifying.`);}@@ -401,7 +402,7 @@ function renderWhyItMatters(`Although it has ${callerPhrase}, it sits inside the ${location} ` +`and feeds ${facts.downstreamDependents} downstream dependents, ` +`making it a critical decision point in that flow. ` +- `Consider running \`ix impact ${facts.name}\` before modifying.`+ `Consider running \`${suggest.impact(facts.name)}\` before modifying.`);}@@ -409,7 +410,7 @@ function renderWhyItMatters(`Although it has ${callerPhrase}, it sits in a path with ` +`${facts.downstreamDependents} downstream dependents, making it a ` +`structurally important decision point in the pipeline. ` +- `Consider running \`ix impact ${facts.name}\` before modifying.`+ `Consider running \`${suggest.impact(facts.name)}\` before modifying.`);}@@ -419,7 +420,7 @@ function renderWhyItMatters(if (hierPhrase) {return (`Because ${hierPhrase}. ` +- `Run \`ix impact ${facts.name}\` before modifying.`+ `Run \`${suggest.impact(facts.name)}\` before modifying.`);}@@ -428,7 +429,7 @@ function renderWhyItMatters(if (roleContext) {return (`${roleContext}, changes here ${verb} propagate across the codebase. ` +- `Run \`ix impact ${facts.name}\` before modifying.`+ `Run \`${suggest.impact(facts.name)}\` before modifying.`);}@@ -437,7 +438,7 @@ function renderWhyItMatters(: "High connectivity";return (`${reasonStr}. This is a central shared dependency — changes ${verb} propagate broadly. ` +- `Run \`ix impact ${facts.name}\` before modifying.`+ `Run \`${suggest.impact(facts.name)}\` before modifying.`);}@@ -461,7 +462,7 @@ function renderWhyItMatters(if (hierPhrase) {return (`Because ${hierPhrase}. ` +- `Run \`ix impact ${facts.name}\` before modifying.`+ `Run \`${suggest.impact(facts.name)}\` before modifying.`);}@@ -469,7 +470,7 @@ function renderWhyItMatters(if (roleContext) {return (`${roleContext}, changes here ${verb} have wide impact. ` +- `Run \`ix impact ${facts.name}\` before modifying.`+ `Run \`${suggest.impact(facts.name)}\` before modifying.`);}@@ -478,7 +479,7 @@ function renderWhyItMatters(: "This entity has high connectivity";return (`${reasonStr}. Changes here ${verb} have wide impact — run ` +- `\`ix impact ${facts.name}\` before modifying.`+ `\`${suggest.impact(facts.name)}\` before modifying.`);}@@ -535,7 +536,7 @@ function renderNotes(facts: EntityFacts): string[] {for (const d of facts.diagnostics) {switch (d.code) {case "unresolved_call_target":- notes.push("Some downstream calls could not be resolved to named entities. Run `ix map` to improve coverage.");+ notes.push(`Some downstream calls could not be resolved to named entities. Run ${forMcp() ? "ix_map" : "`ix map`"} to improve coverage.`);break;case "stale_source":notes.push("Source file has changed since last ingest — results may be incomplete.");diff --git a/ix-cli/src/cli/explain/system-meaning.ts b/ix-cli/src/cli/explain/system-meaning.tsindex 1be5d126..8989af35 100644--- a/ix-cli/src/cli/explain/system-meaning.ts+++ b/ix-cli/src/cli/explain/system-meaning.ts@@ -4,6 +4,7 @@ import type { EntityFacts } from "./facts.js";import type { RoleLabel } from "./role-inference.js";import type { HierarchySemantics } from "./hierarchy-semantics.js";import type { ImportanceInference } from "./importance.js";+import { suggest } from "../next-step.js";export interface SystemMeaning {archetype: "foundation" | "boundary" | "flow" | "general";@@ -82,7 +83,7 @@ function buildFoundationMeaning(facts: EntityFacts, sem: HierarchySemantics, implet importanceNarrative: string | undefined;if (importance.level === "high") {const context = location ? `in the ${location}` : "across the system";- importanceNarrative = `This is a shared foundational type ${context}. Changes propagate to all importers — run \`ix impact ${facts.name}\` before modifying.`;+ importanceNarrative = `This is a shared foundational type ${context}. Changes propagate to all importers — run \`${suggest.impact(facts.name)}\` before modifying.`;}return { archetype: "foundation", identitySummary, responsibility, usageSummary, importanceNarrative };diff --git a/ix-cli/src/cli/impact/risk-semantics.ts b/ix-cli/src/cli/impact/risk-semantics.tsindex 568b5e94..1308c63a 100644--- a/ix-cli/src/cli/impact/risk-semantics.ts+++ b/ix-cli/src/cli/impact/risk-semantics.ts@@ -1,5 +1,7 @@// Copyright 2026 Ix Infrastructure Inc.+import { forMcp, suggest } from "../next-step.js";+/*** Risk-semantics inference for ix impact.*@@ -42,6 +44,12 @@ export interface ImpactFacts {name: string;kind: string;path?: string;+ /**+ * The target's workspace-relative file, used only to pin the suggested next+ * call to this entity. Kept apart from `path`, which feeds categorisation:+ * setting that would move the risk category the CLI has always printed.+ */+ targetPath?: string;// Container (class/module name wrapping this entity)container?: { kind: string; name: string };@@ -506,6 +514,7 @@ function buildMostAffectedHint(facts: ImpactFacts, category: RiskCategory): stri// ── Next step ────────────────────────────────────────────────────────────────function buildNextStep(facts: ImpactFacts, category: RiskCategory): string | undefined {+ if (forMcp()) return mcpNextStep(facts, category);if ((category === "foundation" || category === "shared") && facts.directImporters >= 3) {return `Understand its system role: ix explain ${facts.name}`;}@@ -518,6 +527,29 @@ function buildNextStep(facts: ImpactFacts, category: RiskCategory): string | undreturn undefined;}+/**+ * {@link buildNextStep} for an MCP caller, who has neither `ix explain` nor+ * `ix depends` in the core toolset. The same three situations, each sent to+ * the one-hop list that names the files involved: importers for a foundation+ * type, callers for a boundary or a flow stage.+ */+function mcpNextStep(facts: ImpactFacts, category: RiskCategory): string | undefined {+ const isFile = facts.kind.toLowerCase() === "file";+ // A file resolves by its path; a symbol by name, pinned to its file.+ const symbol = isFile ? (facts.targetPath ?? facts.name) : facts.name;+ const pin = isFile ? {} : { path: facts.targetPath };+ if ((category === "foundation" || category === "shared") && facts.directImporters >= 3) {+ return `List every importer, with path:lines: ${suggest.neighbors(symbol, "imported_by", pin)}`;+ }+ if (category === "boundary" && facts.memberLevelCallers >= 10) {+ return `List every caller, with path:lines: ${suggest.neighbors(symbol, "callers", pin)}`;+ }+ if (category === "flow" && facts.callers >= 1) {+ return `List every caller, with path:lines: ${suggest.neighbors(symbol, "callers", pin)}`;+ }+ return undefined;+}+// ── Flow propagation ─────────────────────────────────────────────────────────function buildFlowPropagation(diff --git a/ix-cli/src/cli/next-step.ts b/ix-cli/src/cli/next-step.tsnew file mode 100644index 00000000..5a4bcd61--- /dev/null+++ b/ix-cli/src/cli/next-step.ts@@ -0,0 +1,93 @@+// Copyright 2026 Ix Infrastructure Inc.++/**+ * Hints and next steps, phrased for whoever will act on them.+ *+ * A command's closing advice used to be CLI text everywhere: `ix callers X`,+ * `raise --max-tokens`, `Use --include-tests`. Over MCP the same output reaches+ * an agent that has tools, not a shell: `ix_context` has no `--max-tokens`,+ * `ix_search` had no `--include-tests`, and `ix conflicts` is not a tool at+ * all. Advice the reader cannot run is worse than none, because it reads as+ * the one move left.+ *+ * The MCP runner sets {@link IX_CALLER_ENV} for the duration of every command+ * it runs (in-process and in the child-process runner alike), and every hint+ * generator asks {@link forMcp} which phrasing to produce. CLI output is+ * unchanged: the CLI branch of every helper here returns the exact string the+ * command printed before.+ *+ * Over MCP, a hint from a command in the core toolset may name only core+ * tools (see `IX_MCP_CORE_TOOL_NAMES`), because a core session has nothing+ * else. A command outside the core set is only reachable with `--tools=all`,+ * so its hints may name any tool in that catalog.+ */++/** Set to `mcp` by the MCP runner; unset (or anything else) means a person at a shell. */+export const IX_CALLER_ENV = "IX_CALLER";++/** True while a command's output is being produced for an MCP client. */+export function forMcp(): boolean {+ return process.env[IX_CALLER_ENV] === "mcp";+}++type ArgValue = string | number | boolean | undefined | null;++/**+ * One MCP tool call as a caller would write it: `ix_neighbors symbol=X relation=callers`.+ *+ * Empty arguments are dropped, and a value with whitespace or a quote is+ * JSON-quoted so the call still reads as one token per argument.+ */+export function toolCall(tool: string, args: Record<string, ArgValue> = {}): string {+ const parts = [tool];+ for (const [key, value] of Object.entries(args)) {+ if (value === undefined || value === null || value === "") continue;+ const text = String(value);+ parts.push(`${key}=${/[\s"'=]/.test(text) ? JSON.stringify(text) : text}`);+ }+ return parts.join(" ");+}++/** The four edge directions `ix_neighbors` takes, and the CLI command for each. */+export type Relation = "callers" | "callees" | "imports" | "imported_by";++const RELATION_COMMAND: Record<Relation, string> = {+ callers: "callers",+ callees: "callees",+ imports: "imports",+ imported_by: "imported-by",+};++/**+ * Suggestions for the core tools, each in the reader's phrasing.+ *+ * The CLI forms are the strings the commands printed before this module+ * existed; keep them byte-identical so CLI output does not move.+ */+export const suggest = {+ neighbors(symbol: string, relation: Relation, opts: { path?: string } = {}): string {+ return forMcp()+ ? toolCall("ix_neighbors", { symbol, relation, path: opts.path })+ : `ix ${RELATION_COMMAND[relation]} ${symbol}`;+ },+ impact(target: string, opts: { path?: string } = {}): string {+ return forMcp() ? toolCall("ix_impact", { target, path: opts.path }) : `ix impact ${target}`;+ },+ context(target: string, opts: { path?: string } = {}): string {+ return forMcp() ? toolCall("ix_context", { target, path: opts.path }) : `ix context ${target}`;+ },+ read(target: string): string {+ return forMcp() ? toolCall("ix_read", { symbol: target }) : `ix read ${target}`;+ },+};++/**+ * How a caller disambiguates a name that resolved to more than one entity.+ *+ * Every core tool that takes a symbol also takes `pick`, `kind` and `path`+ * (`ix_neighbors`, `ix_read`, `ix_impact`, `ix_context`), so the MCP form can+ * name them without knowing which tool it is inside.+ */+export function disambiguationHint(cli: string): string {+ return forMcp() ? "Pass pick=<n> (1-based), kind=<kind> or path=<file substring> to disambiguate." : cli;+}diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.tsindex b6e982db..27a08009 100644--- a/ix-cli/src/cli/resolve.ts+++ b/ix-cli/src/cli/resolve.ts@@ -11,6 +11,7 @@ import { readStitchScope, writeStitchScope } from "./config.js";import { reportAmbiguousTarget, reportResolutionFailure } from "./ui.js";import { relativePath } from "./format.js";import { isQuiet } from "./output-shape.js";+import { disambiguationHint } from "./next-step.js";import {candidateOrigin, isFileStemMatch, looksLikeCodeIdentifier, requestsNonCode,} from "./candidate-origin.js";@@ -662,7 +663,7 @@ function buildAmbiguous(nodes: any[], scores?: number[]): AmbiguousResult {return {resolutionMode: "ambiguous",candidates,- diagnostics: [{ code: "ambiguous_resolution", message: "Use --pick <n> or --path to disambiguate." }],+ diagnostics: [{ code: "ambiguous_resolution", message: disambiguationHint("Use --pick <n> or --path to disambiguate.") }],};}diff --git a/ix-cli/src/cli/role-filter.ts b/ix-cli/src/cli/role-filter.tsindex a9a6e62d..4fef860b 100644--- a/ix-cli/src/cli/role-filter.ts+++ b/ix-cli/src/cli/role-filter.ts@@ -1,5 +1,7 @@// Copyright 2026 Ix Infrastructure Inc.+import { forMcp } from "./next-step.js";+export type EntityRole = 'production' | 'test' | 'fixture' | 'generated' | 'external' | 'tooling';export const TEST_ROLES = new Set<string>(['test', 'fixture']);@@ -46,5 +48,7 @@ export function applyRoleFilter<T>(export function roleHint(hiddenTestCount: number): string | null {if (hiddenTestCount === 0) return null;const s = hiddenTestCount === 1 ? 'candidate' : 'candidates';- return `${hiddenTestCount} test/fixture ${s} hidden. Use --include-tests to include.`;+ return forMcp()+ ? `${hiddenTestCount} test/fixture ${s} hidden. Pass include_tests=true to include.`+ : `${hiddenTestCount} test/fixture ${s} hidden. Use --include-tests to include.`;}diff --git a/ix-cli/src/cli/ui.ts b/ix-cli/src/cli/ui.tsindex 95eef269..f44b6286 100644--- a/ix-cli/src/cli/ui.ts+++ b/ix-cli/src/cli/ui.ts@@ -13,6 +13,7 @@ import { llmError, llmLine } from "./llm.js";import { printJson, relativePath } from "./format.js";import { isQuiet } from "./output-shape.js";import type { AmbiguousResult, ResolveResult, Suggestion } from "./resolve.js";+import { forMcp } from "./next-step.js";// ── Brand palette ─────────────────────────────────────────────────────────────//@@ -240,13 +241,15 @@ export function reportAmbiguousTarget(return;}if (format === "llm") {- const hints = ["--pick <n>"];- if (!opts?.kind) hints.push("--kind");- if (!opts?.path) hints.push("--path");+ // Over MCP the same three levers are tool arguments, not flags.+ const mcp = forMcp();+ const hints = [mcp ? "pick=<n>" : "--pick <n>"];+ if (!opts?.kind) hints.push(mcp ? "kind=<kind>" : "--kind");+ if (!opts?.path) hints.push(mcp ? "path=<file substring>" : "--path");const lines = [llmError("ambiguous_target", message, [["count", String(result.candidates.length)]]),...candidateLines(result.candidates, "candidate"),- llmLine("hint", [["text", `Use ${hints.join(" or ")} to disambiguate.`]]),+ llmLine("hint", [["text", `${mcp ? "Pass" : "Use"} ${hints.join(" or ")} to disambiguate.`]]),...(result.diagnostics ?? []).map((d) => llmLine("diagnostic", [["code", d.code], ["message", d.message]])),];console.log(lines.join("\n"));diff --git a/ix-cli/src/mcp/runner.ts b/ix-cli/src/mcp/runner.tsindex 3340b4fa..e029ac60 100644--- a/ix-cli/src/mcp/runner.ts+++ b/ix-cli/src/mcp/runner.ts@@ -14,6 +14,7 @@ import { registerOssCommands, registerProStubs } from "../cli/register/oss.js";import { tryLoadProCommands } from "../cli/register/pro-loader.js";import { resetReadScope } from "../cli/resolve.js";import { releaseLocksOwnedBy, setLockOwnerResolver } from "../cli/single-flight.js";+import { IX_CALLER_ENV } from "../cli/next-step.js";const execFileAsync = promisify(execFile);const CLI_ENTRYPOINT = fileURLToPath(new URL("../cli/main.js", import.meta.url));@@ -390,6 +391,12 @@ async function executeInProcess(const callerExitCode = process.exitCode;process.exitCode = undefined;activeRun = run;+ // Tell the command who is reading, so its hints name tools and arguments+ // rather than CLI flags (see cli/next-step.ts). Scoped to the run: a command+ // that outlives its timeout and prints afterwards writes into a closed run,+ // whose output is dropped, so the restore cannot mislabel anything shown.+ const callerSurface = process.env[IX_CALLER_ENV];+ process.env[IX_CALLER_ENV] = "mcp";// Decided before the command starts: an orphan already in flight can write// process.exitCode at any point during this run, and there is no way to tell@@ -427,6 +434,8 @@ async function executeInProcess(} finally {commandExitCode = commandExitCode ?? (exitCodeIsOurs ? process.exitCode : undefined);process.exitCode = callerExitCode;+ if (callerSurface === undefined) delete process.env[IX_CALLER_ENV];+ else process.env[IX_CALLER_ENV] = callerSurface;if (failure !== null) {if (run.truncated) {// appendChunk is a no-op once the cap has fired, but *why* the command@@ -561,7 +570,7 @@ export async function runCurrentIx(try {const { stdout, stderr } = await execFileAsync(process.execPath, [CLI_ENTRYPOINT, ...args], {cwd: process.cwd(),- env: { ...process.env, IX_MCP_CHILD: "1" },+ env: { ...process.env, IX_MCP_CHILD: "1", [IX_CALLER_ENV]: "mcp" },encoding: "utf8",maxBuffer: MAX_OUTPUT_BYTES,timeout: timeoutMs,diff --git a/ix-cli/src/mcp/server.ts b/ix-cli/src/mcp/server.tsindex 00af17a7..87f0dad7 100644--- a/ix-cli/src/mcp/server.ts+++ b/ix-cli/src/mcp/server.ts@@ -3,6 +3,10 @@import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";import type { CallToolResult, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { z } from "zod";import {@@ -26,6 +30,8 @@ export type { IxRunner } from "./runner.js";* `ix_overview`, all of which are here individually.*/export const IX_MCP_OSS_TOOL_NAMES = [+ // First, as it is registered first: tools/list leads with where to start.+ "ix_context","ix_health","ix_locate",// `ix search` is the command every other one starts from, and it was the one@@ -54,7 +60,6 @@ export const IX_MCP_OSS_TOOL_NAMES = ["ix_stats","ix_subsystems","ix_history",- "ix_context","ix_ingest",] as const;@@ -117,36 +122,39 @@ const WRITE_OPEN_WORLD: ToolAnnotations = {*/const UNVERIFIED = (title: string): ToolAnnotations => ({ title });+// Titles are display labels, a few words each. What a tool is FOR — when to+// reach for it, what it returns that Grep and Read cannot, and when not to use+// it — is in its description, which is the text a model actually weighs.const TOOL_ANNOTATIONS: Record<(typeof IX_MCP_TOOL_NAMES)[number], ToolAnnotations> = {- ix_health: { ...READ_ONLY, title: "Is the graph up to date. Call once at most; every other tool reports its own failure" },- 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: "What a change to this would reach. Members and dependents carry path:lines" },- ix_map: { ...WRITE, title: "Re-ingest the workspace. Slow; run after editing code, not before reading it" },- ix_overview: { ...READ_ONLY, title: "One call: what a file or symbol is, what it holds, and what it touches" },+ ix_health: { ...READ_ONLY, title: "Graph health" },+ ix_locate: { ...READ_ONLY, title: "Locate a definition" },+ ix_search: { ...READ_ONLY, title: "Find definitions by name" },+ ix_text: { ...READ_ONLY, title: "Ranked text search" },+ ix_impact: { ...READ_ONLY, title: "Change impact" },+ ix_map: { ...WRITE, title: "Re-map the workspace" },+ ix_overview: { ...READ_ONLY, title: "Structural overview" },// Not "graph-bounded": `ix read` resolves an exact file path before it// consults the graph at all, so the title has to describe the whole command.- ix_read: { ...READ_ONLY, title: "Read source from the workspace" },- ix_diff: { ...READ_ONLY, title: "What changed between two graph revisions, by entity rather than by line" },- ix_neighbors: { ...READ_ONLY, title: "List a symbol's callers, callees, imports or importers" },- ix_callers: { ...READ_ONLY, title: "Who calls this. Rows carry path:lines. Prefer ix_neighbors" },- ix_callees: { ...READ_ONLY, title: "What this calls. Rows carry path:lines. Prefer ix_neighbors" },- ix_imported_by: { ...READ_ONLY, title: "What imports this. Rows carry path:lines. Prefer ix_neighbors" },- ix_imports: { ...READ_ONLY, title: "What this imports. Rows carry path:lines. Prefer ix_neighbors" },- ix_depends: { ...READ_ONLY, title: "Show downstream dependencies" },- ix_trace: { ...READ_ONLY, title: "Follow edges through a symbol, or find a path to another one. Bounded by depth" },- ix_explain: { ...READ_ONLY, title: "What a symbol is for, from its edges: role, importance, and who uses it with path:lines" },- ix_rank: { ...READ_ONLY, title: "Rank graph entities by importance" },- ix_inventory: { ...READ_ONLY, title: "List graph entities by kind" },- ix_smells: { ...WRITE, title: "Orphans, god modules and cycles the graph can see. Not a linter" },- ix_stats: { ...READ_ONLY, title: "Node and edge counts by kind. Use to tell an empty graph from a missing symbol" },- ix_subsystems: { ...READ_ONLY, title: "The regions the map grouped this repo into, with health and confidence" },- ix_history: { ...READ_ONLY, title: "Show provenance and patch history" },- ix_ingest: { ...WRITE_OPEN_WORLD, title: "Ingest a path or GitHub repository into the graph" },+ ix_read: { ...READ_ONLY, title: "Read source by symbol or range" },+ ix_diff: { ...READ_ONLY, title: "Graph diff between revisions" },+ ix_neighbors: { ...READ_ONLY, title: "Callers, callees, imports, importers" },+ ix_callers: { ...READ_ONLY, title: "Callers" },+ ix_callees: { ...READ_ONLY, title: "Callees" },+ ix_imported_by: { ...READ_ONLY, title: "Importers" },+ ix_imports: { ...READ_ONLY, title: "Imports" },+ ix_depends: { ...READ_ONLY, title: "Dependent tree" },+ ix_trace: { ...READ_ONLY, title: "Trace paths" },+ ix_explain: { ...READ_ONLY, title: "Explain a symbol" },+ ix_rank: { ...READ_ONLY, title: "Rank by connectivity" },+ ix_inventory: { ...READ_ONLY, title: "Inventory by kind" },+ ix_smells: { ...WRITE, title: "Architecture smells" },+ ix_stats: { ...READ_ONLY, title: "Graph statistics" },+ ix_subsystems: { ...READ_ONLY, title: "Subsystems" },+ ix_history: { ...READ_ONLY, title: "Patch history" },+ ix_ingest: { ...WRITE_OPEN_WORLD, title: "Ingest a path or GitHub repo" },// Reads the graph and composes a bundle; the CLI's --save and --out, which are// the only parts of `ix context` that write anything, are not exposed here.- ix_context: { ...READ_ONLY, title: "Build a bounded context bundle for a target" },+ ix_context: { ...READ_ONLY, title: "Context bundle" },// Implemented in @ix/pro, so nothing here can check these are true.ix_briefing: UNVERIFIED("Load the Ix Pro session briefing"),ix_decisions: UNVERIFIED("List Ix Pro architecture decisions"),@@ -192,27 +200,59 @@ export type ToolsetName = "core" | "all";** `tools/list` is paid on every session before a single call is made, and the* full catalog is 26 tools of which a recorded run used four. The cost is not- * only bytes: a model choosing between 26 near-identical names picks worse than- * one choosing between ten, and `ix_callers` / `ix_callees` / `ix_imports` /- * `ix_imported_by` had byte-identical schemas differing only in a word.+ * only bytes: a model choosing between near-identical names picks worse than+ * one choosing between a few that each answer a different question.*- * Those four are one `ix_neighbors{relation}` here. Everything that is gone is- * still reachable with `--tools=all`, which advertises the whole catalog —- * including the four singles, so nothing that works today stops working.+ * Ten was still too many. With Ix connected and told to use it, recorded+ * agents called `ix_context`, `ix_read` and `ix_search` and never `ix_explain`,+ * `ix_impact`, `ix_overview` or `ix_locate` — four of the ten answered "tell me+ * about X" and two were name lookups, so the graph's own answers (who calls+ * this, what does a change reach) went unasked. The five kept are one per+ * question, each something Grep/Glob/Read cannot answer in one step:+ *+ * - `ix_context`: where to start on a target or an issue, ranked.+ * - `ix_search`: which definition a name means, definitions first.+ * - `ix_neighbors`: who calls / is called by / imports / is imported by X.+ * - `ix_impact`: what a change to X reaches.+ * - `ix_read`: a definition's source by name, without knowing its file.+ *+ * Left for `--tools=all`: `ix_health` (every tool reports backend and graph+ * failures itself), `ix_text` (ripgrep with a ranking — the caller already has+ * Grep), and `ix_locate` / `ix_overview` / `ix_explain`, which `ix_search` and+ * `ix_context` cover. Nothing is removed: `--tools=all` advertises the whole+ * catalog, including the four `ix_neighbors` singles.*/export const IX_MCP_CORE_TOOL_NAMES = [- "ix_health",- "ix_locate",+ "ix_context","ix_search",- "ix_text",+ "ix_neighbors","ix_impact",- "ix_overview","ix_read",- "ix_neighbors",- "ix_explain",- "ix_context",] as const;+/**+ * Server instructions, sent in the `initialize` result.+ *+ * The one channel that reaches the model when a host defers tool schemas.+ * Claude Code shows a deferred server's tools as bare names until the model+ * searches for them, and in 32 recorded runs no agent ever did, so not one+ * tool description was read and Ix went uncalled. Instructions go into the+ * system prompt either way.+ *+ * Written for an agent that already has Grep, Glob and Read: when the graph+ * answers something they cannot, which tool, and when not to bother. Every+ * tool it names is in the core set, so it is true for every session.+ */+export const IX_MCP_INSTRUCTIONS = [+ "Ix is a code graph of this repository: definitions, calls and imports parsed from the source, not matched as text. Use it next to Grep/Glob/Read for what they cannot answer in one step:",+ "- Where to start on an issue or task, or what a file or symbol touches: ix_context (target=<name or path>, or issue=<issue text>). Ranked evidence, each row path:lines.",+ "- Who calls or imports X across files, or what X calls or imports: ix_neighbors (relation=callers|callees|imports|imported_by).",+ "- What a change to X would reach, before you edit it: ix_impact.",+ "- Which definition a name means when several share it: ix_search (definitions first); ix_read returns a definition's source by name.",+ "Not for a literal string, a regex, or a line in a file you already have open: use Grep/Read.",+ "No health check is needed first; a tool that cannot answer says why.",+].join("\n");+interface CreateServerOptions {version?: string;runIx?: IxRunner;@@ -261,10 +301,14 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer((args, timeoutMs) =>(fallback ??= resolveDefaultRunner({ version, redirectIdleStdout: true }))(args, timeoutMs));- const server = new McpServer({- name: "ix-memory",- version,- });+ const server = new McpServer(+ {+ // Not renamed: every existing registration is keyed by this name.+ name: "ix-memory",+ version,+ },+ { instructions: IX_MCP_INSTRUCTIONS },+ );// `core` unless asked otherwise. A tool left out here is not removed from the// CLI, only from what this session is told about.@@ -281,39 +325,110 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer|| (IX_MCP_PRO_TOOL_NAMES as readonly string[]).includes(name),};- registerTool(ctx, "ix_health", "Check Ix backend and graph readiness", {}, async () =>+ // First, so it heads tools/list: it is where a session should start.+ registerTool(+ ctx,+ "ix_context",+ "Use first on an issue, a task, or an unfamiliar symbol or file (target=<name or path>, or issue=<text>). Returns ranked evidence (definition, members, callers, importers, related files, recent commits), each row path:lines, then next calls. Not for a literal string: use Grep.",+ {+ target: z.string().min(1).optional(),+ issue: z.string().min(1).max(200_000).optional().describe("issue or task text, instead of target"),+ kind: SYMBOL_TOOL_INPUT.kind,+ path: SYMBOL_TOOL_INPUT.path,+ pick: SYMBOL_TOOL_INPUT.pick,+ as_of_rev: z.number().int().nonnegative().optional(),+ max_entities: z.number().int().min(1).max(500).optional(),+ max_relationships: z.number().int().min(1).max(1000).optional(),+ max_evidence: z.number().int().min(1).max(200).optional(),+ max_tokens: z.number().int().min(500).max(200_000).optional().describe("default 3000"),+ max_chars: z+ .number()+ .int()+ .min(1000)+ .max(1_000_000)+ .optional()+ .describe("exact character budget, instead of max_tokens"),+ structured: z+ .boolean()+ .optional()+ .describe("JSON bundle as structuredContent, not records"),+ },+ async (input) => {+ const hasTarget = typeof input.target === "string";+ const hasIssue = typeof input.issue === "string";+ // Checked here rather than left to the CLI, whose refusals name flags an+ // MCP caller does not have.+ const refusal =+ hasTarget === hasIssue+ ? "pass exactly one of target or issue"+ : hasIssue && ["kind", "path", "pick"].some((key) => input[key] !== undefined)+ ? "kind, path and pick narrow a named target; they do not combine with issue"+ : input.max_tokens !== undefined && input.max_chars !== undefined+ ? "pass max_tokens or max_chars, not both; they bound the same evidence in different units"+ : undefined;+ if (refusal) return textResult(JSON.stringify({ error: refusal, tool: "ix_context" }), true);+ const options: string[] = symbolOptions(input, { limit: false });+ if (typeof input.as_of_rev === "number") options.push(`--as-of-rev=${numberArg(input, "as_of_rev")}`);+ if (typeof input.max_entities === "number") options.push(`--max-entities=${numberArg(input, "max_entities")}`);+ if (typeof input.max_relationships === "number")+ options.push(`--max-relationships=${numberArg(input, "max_relationships")}`);+ if (typeof input.max_evidence === "number") options.push(`--max-evidence=${numberArg(input, "max_evidence")}`);+ if (typeof input.max_tokens === "number") options.push(`--max-tokens=${numberArg(input, "max_tokens")}`);+ if (typeof input.max_chars === "number") options.push(`--max-chars=${numberArg(input, "max_chars")}`);+ const run = (argv: IxArgv) =>+ // Once, in the format the reader is: an agent. The bundle used to go out+ // twice on every call — the JSON text AND the same object again as+ // structuredContent — so a 20 KB bundle cost 40 KB, and the copy a model+ // actually reads is the smaller `llm` one that was not being sent at all.+ input.structured === true+ ? runJsonStructured(runIx, "ix_context", argv)+ : runFormatted(runIx, "ix_context", argv);+ if (hasTarget) return run(ix("context", [stringArg(input, "target")], options));+ // `--from-issue` reads a file. The in-process runner has no stdin to give+ // it, so the text goes through a private temp file that lives only for+ // this call.+ return withIssueFile(stringArg(input, "issue"), (file) =>+ run(ix("context", [], [...options, `--from-issue=${file}`])),+ );+ },+ );+ registerTool(ctx, "ix_health", "Use only when a result suggests the graph is missing or stale. Returns backend reachability, workspace mapping and freshness. Not needed before other calls: each reports its own failure.", {}, async () =>runFormatted(runIx, "ix_health", ix("status")),);registerTool(ctx,"ix_locate",- "One name to one definition, with its path:lines. Use before reading when a name is ambiguous",+ "Use when a name has several definitions and you want the canonical one. Returns one definition with path:lines, or the candidates when it cannot choose. For a ranked list use ix_search.",{ symbol: z.string().min(1) },async (input) => runFormatted(runIx, "ix_locate", ix("locate", [stringArg(input, "symbol")])),);registerTool(ctx,"ix_search",- "Find a symbol by name. Ranked, each row carries path:lines. Use instead of grep for a definition",+ "Use when you know a name, or part of one, and need its definition, or which of several same-named definitions you mean. Returns entities ranked definitions-first, each with kind and path:lines, not every text occurrence. Not for strings, comments or regex: use Grep.",{term: z.string().min(1),kind: z.string().min(1).optional(),path: z.string().min(1).optional(),language: z.string().min(1).optional(),limit: z.number().int().min(1).max(200).default(10),+ // Search hides test and fixture entities, and says how many it hid; this+ // is the argument that hint names.+ include_tests: z.boolean().optional(),},async (input) => {const options = [`--limit=${numberArg(input, "limit")}`];pushOption(options, "--kind", input.kind);pushOption(options, "--path", input.path);pushOption(options, "--language", input.language);+ if (input.include_tests === true) options.push("--include-tests");return runFormatted(runIx, "ix_search", ix("search", [stringArg(input, "term")], options));},);registerTool(ctx,"ix_text",- "Literal or regex search, code ranked above tests above prose. Use instead of grep for a string",+ "Use for a literal or regex match when you want code ranked above tests above docs. Returns matching lines with path:line. The same matches Grep finds; prefer Grep when you have it.",{pattern: z.string().min(1),limit: z.number().int().min(1).max(100).default(20),@@ -330,14 +445,22 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServerregisterTool(ctx,"ix_impact",- "Analyze the blast radius and risk of changing a symbol or file",- { target: z.string().min(1) },- async (input) => runFormatted(runIx, "ix_impact", ix("impact", [stringArg(input, "target")])),+ "Use before changing a symbol or file, to see what the change reaches. Returns a risk level, dependents grouped by subsystem and the most affected members with path:lines, which grep cannot compute. For a flat list of direct callers use ix_neighbors.",+ {+ target: z.string().min(1),+ // The disambiguation the CLI already has. Without them an ambiguous name+ // had no second call that could get past it.+ kind: SYMBOL_TOOL_INPUT.kind,+ path: SYMBOL_TOOL_INPUT.path,+ pick: SYMBOL_TOOL_INPUT.pick,+ },+ async (input) =>+ runFormatted(runIx, "ix_impact", ix("impact", [stringArg(input, "target")], symbolOptions(input, { limit: false }))),);registerTool(ctx,"ix_map",- "Ingest one path or refresh the full workspace architecture map",+ "Use after editing code, when later answers must see the change. Re-ingests one path, or the whole workspace. Slow; not needed before reading.",{ file: z.string().min(1).optional() },async (input) => {const positionals = typeof input.file === "string" ? [input.file] : [];@@ -347,14 +470,14 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServerregisterTool(ctx,"ix_overview",- "Return the structural overview of a symbol, file, or subsystem",+ "Use for a one-call summary of a file, symbol or subsystem: what it is, what it holds, and what it touches. For ranked evidence around a task use ix_context.",{ target: z.string().min(1) },async (input) => runFormatted(runIx, "ix_overview", ix("overview", [stringArg(input, "target")])),);registerTool(ctx,"ix_read",- "Source for a symbol, or path:start-end for a range. Prefer a range over a whole file",+ "Use when you have a symbol name but not its file or lines. Returns exactly that definition's source; also takes a path or path:start-end. Not needed when you already know path and range: Read does that.",{symbol: z.string().min(1).describe("a symbol, a path, or `path:start-end`"),kind: z.string().min(1).optional(),@@ -370,7 +493,7 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServerregisterTool(ctx,"ix_diff",- "Show the structural diff between two graph revisions",+ "Use to see what changed between two graph revisions. Returns added, removed and modified entities rather than changed lines.",{from_rev: z.number().int().nonnegative(),to_rev: z.number().int().nonnegative(),@@ -389,7 +512,7 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServerregisterTool(ctx,"ix_neighbors",- "Who calls, is called by, imports or is imported by a symbol. Rows carry path:lines",+ "Use when you need who calls X, what X calls, what X imports, or which files import X, across the repo. Returns one row per resolved edge with path:lines, where grep finds every same-named symbol too. For transitive reach use ix_impact.",{...SYMBOL_TOOL_INPUT,relation: z@@ -407,10 +530,10 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer);},);- registerSymbolTool(ctx, runIx, "ix_callers", "List incoming call edges", "callers");- registerSymbolTool(ctx, runIx, "ix_callees", "List outgoing call edges", "callees");- registerSymbolTool(ctx, runIx, "ix_imported_by", "List incoming import edges", "imported-by");- registerSymbolTool(ctx, runIx, "ix_imports", "List outgoing import edges", "imports");+ registerSymbolTool(ctx, runIx, "ix_callers", "Who calls this. Rows carry path:lines. Prefer ix_neighbors relation=callers.", "callers");+ registerSymbolTool(ctx, runIx, "ix_callees", "What this calls. Rows carry path:lines. Prefer ix_neighbors relation=callees.", "callees");+ registerSymbolTool(ctx, runIx, "ix_imported_by", "What imports this. Rows carry path:lines. Prefer ix_neighbors relation=imported_by.", "imported-by");+ registerSymbolTool(ctx, runIx, "ix_imports", "What this imports. Rows carry path:lines. Prefer ix_neighbors relation=imports.", "imports");registerTool(ctx,"ix_depends",@@ -427,7 +550,7 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServerregisterTool(ctx,"ix_trace",- "Trace execution paths through a symbol",+ "Use to follow edges through a symbol, or find a path from it to another (to=). Returns the chain, bounded by depth.",{symbol: z.string().min(1),to: z.string().min(1).optional(),@@ -446,7 +569,7 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServerctx,runIx,"ix_explain",- "Explain a symbol using graph evidence",+ "Use to learn what a symbol is for from how it is used. Returns its role, importance and main users with path:lines, inferred from graph edges. For ranked evidence around a task use ix_context.","explain",// No `--limit`: `ix explain` has none, and forwarding a flag the command// rejects turns a resolvable call into a usage error.@@ -495,7 +618,7 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServerregisterTool(ctx,"ix_smells",- "Detect graph-backed architecture smells",+ "Orphans, god modules and cycles the graph can see. Not a linter.",{path: z.string().min(1).optional(),limit: z.number().int().min(1).max(500).default(50),@@ -506,10 +629,10 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer},async (input) => runSmells(runIx, input),);- registerTool(ctx, "ix_stats", "Return graph-wide statistics", {}, async () =>+ registerTool(ctx, "ix_stats", "Node and edge counts by kind. Use to tell an empty graph from a missing symbol.", {}, async () =>runFormatted(runIx, "ix_stats", ix("stats")),);- registerTool(ctx, "ix_subsystems", "List graph-derived subsystems", {}, async () =>+ registerTool(ctx, "ix_subsystems", "The regions the map grouped this repo into, with health and confidence.", {}, async () =>runFormatted(runIx, "ix_subsystems", ix("subsystems")),);registerTool(@@ -519,46 +642,6 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer{ target: z.string().min(1) },async (input) => runFormatted(runIx, "ix_history", ix("history", [stringArg(input, "target")])),);- registerTool(- ctx,- "ix_context",- "Start here. Ranked evidence around a target, every row a path:lines, ending in reads to run",- {- target: z.string().min(1),- as_of_rev: z.number().int().nonnegative().optional().describe("graph revision for historical context"),- max_entities: z.number().int().min(1).max(500).optional(),- max_relationships: z.number().int().min(1).max(1000).optional(),- max_evidence: z.number().int().min(1).max(200).optional(),- max_chars: z- .number()- .int()- .min(1000)- .max(1_000_000)- .optional()- .describe("exact serialized-character budget for the evidence list"),- structured: z- .boolean()- .optional()- .describe("return the JSON bundle as structuredContent instead of llm records"),- },- async (input) => {- const options: string[] = [];- if (typeof input.as_of_rev === "number") options.push(`--as-of-rev=${numberArg(input, "as_of_rev")}`);- if (typeof input.max_entities === "number") options.push(`--max-entities=${numberArg(input, "max_entities")}`);- if (typeof input.max_relationships === "number")- options.push(`--max-relationships=${numberArg(input, "max_relationships")}`);- if (typeof input.max_evidence === "number") options.push(`--max-evidence=${numberArg(input, "max_evidence")}`);- if (typeof input.max_chars === "number") options.push(`--max-chars=${numberArg(input, "max_chars")}`);- const argv = ix("context", [stringArg(input, "target")], options);- // Once, in the format the reader is: an agent. The bundle used to go out- // twice on every call — the JSON text AND the same object again as- // structuredContent — so a 20 KB bundle cost 40 KB, and the copy a model- // actually reads is the smaller `llm` one that was not being sent at all.- return input.structured === true- ? runJsonStructured(runIx, "ix_context", argv)- : runFormatted(runIx, "ix_context", argv);- },- );registerTool(ctx,"ix_ingest",@@ -892,6 +975,18 @@ async function runSmells(runIx: IxRunner, input: ToolInput): Promise<CallToolResreturn structured ? { ...text, structuredContent: payload } : text;}+/** Hand `work` a private file holding `text`, and remove it afterwards whatever happens. */+async function withIssueFile<T>(text: string, work: (file: string) => Promise<T>): Promise<T> {+ const dir = await mkdtemp(join(tmpdir(), "ix-mcp-issue-"));+ try {+ const file = join(dir, "issue.md");+ await writeFile(file, text, { encoding: "utf8", mode: 0o600 });+ return await work(file);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+}+function textResult(text: string, isError = false): CallToolResult {return {content: [{ type: "text", text }],