Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(mcp): register no session tools in a server inside an MCP session
Jack Rudenko1b73e51c02a6
diff --git a/docs/usage/mcp-server.md b/docs/usage/mcp-server.mdindex f63a2764..044bef61 100644--- a/docs/usage/mcp-server.md+++ b/docs/usage/mcp-server.md@@ -230,6 +230,8 @@ Each session is an interactive Claude Code running your model in its own headles`CLAUDISH_MCP_TOOLS` accepts: `all` (default), `channel`, `agentic`, or `low-level`. Channel tools are included in `all` by default.+Inside a session that claudish itself started (a `create_session` or `team` pane), the server runs in nested mode. Whatever `CLAUDISH_MCP_TOOLS` says, it offers at most the four one-shot tools (`run_prompt`, `compare_models`, `list_models`, `search_models`) and no session tools. A model-running `claudish` launched from that session's shell (`-p`, interactive, `team run`) exits 64 with `nested session refused`. One level of nesting is the limit.+### Channel eventsWhen a session runs, Claude Code receives `<channel source="claudish">` notifications with these event types:diff --git a/packages/cli/src/mcp-blackbox/tool-surface.blackbox.test.ts b/packages/cli/src/mcp-blackbox/tool-surface.blackbox.test.tsindex 4d16a203..bbb6f04d 100644--- a/packages/cli/src/mcp-blackbox/tool-surface.blackbox.test.ts+++ b/packages/cli/src/mcp-blackbox/tool-surface.blackbox.test.ts@@ -7,9 +7,12 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { existsSync } from "node:fs";import { join } from "node:path";+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";import { useBlackboxEnv } from "../test-helpers/blackbox-env.js";import {McpServer,+ SERVER_ENTRY,type ToolResult,paneOrphans,serverEnv,@@ -25,17 +28,19 @@ const CAPABILITIES = ["list", "status", "cancel", "capture", "capture_since_seq"let layout: TempLayout;let server: McpServer;-beforeEach(async () => {- layout = makeTempLayout("bbsurface");- server = await McpServer.start({ env: serverEnv(layout), cwd: layout.cwd });-});+function useStandardServer(): void {+ beforeEach(async () => {+ layout = makeTempLayout("bbsurface");+ server = await McpServer.start({ env: serverEnv(layout), cwd: layout.cwd });+ });-afterEach(async () => {- await server.close();- const report = await paneOrphans(layout);- layout.cleanup();- expect(report).toEqual({ processes: [], files: [] });-});+ afterEach(async () => {+ await server.close();+ const report = await paneOrphans(layout);+ layout.cleanup();+ expect(report).toEqual({ processes: [], files: [] });+ });+}function contractError(r: ToolResult, code: string): void {expect(r.isError).toBe(true);@@ -47,6 +52,7 @@ function contractError(r: ToolResult, code: string): void {}describe("tool list (FR11, §4)", () => {+ useStandardServer();test("14 tools, capture_session among them, team modes are exactly the seven", async () => {const tools = await server.listTools();const names = tools.map((t) => t.name);@@ -92,6 +98,7 @@ describe("tool list (FR11, §4)", () => {});describe("team: mode and argument errors", () => {+ useStandardServer();test("an unknown team mode answers the text `Error: Unknown mode: <mode>`", async () => {const r = await server.callTool("team", { mode: "bogus-mode", path: join(layout.cwd, "x") });expect(r.isError).toBe(true);@@ -175,6 +182,7 @@ describe("team: mode and argument errors", () => {});describe("channel: argument errors that need no pane", () => {+ useStandardServer();test("create_session refuses a print-mode flag with text `Error: invalid_args:`", async () => {const r = await server.callTool("create_session", {model: "contract-fake-model",@@ -186,3 +194,130 @@ describe("channel: argument errors that need no pane", () => {expect((list.json as Json).sessions).toEqual([]);});});++describe("nested MCP server over stdio", () => {+ let layout: TempLayout;+ let client: Client | undefined;+ let transport: StdioClientTransport | undefined;+ let stderr: string;++ beforeEach(() => {+ layout = makeTempLayout("nested-surface");+ client = undefined;+ transport = undefined;+ stderr = "";+ });++ afterEach(async () => {+ try {+ if (client) await client.close();+ } finally {+ try {+ await transport?.close();+ } finally {+ const report = await paneOrphans(layout);+ layout.cleanup();+ expect(report).toEqual({ processes: [], files: [] });+ }+ }+ }, 30_000);++ async function connect(mode: string | undefined, nested = true): Promise<Client> {+ transport = new StdioClientTransport({+ command: process.execPath,+ args: ["run", SERVER_ENTRY, "--mcp"],+ cwd: layout.cwd,+ env: serverEnv(layout, {+ CLAUDISH_PANE_CHILD: nested ? "1" : undefined,+ CLAUDISH_MCP_TOOLS: mode,+ }),+ stderr: "pipe",+ });+ transport.stderr?.on("data", (chunk: Buffer) => {+ stderr += chunk.toString();+ });+ client = new Client({ name: "nested-surface-tests", version: "1.0.0" }, { capabilities: {} });+ await client.connect(transport);+ return client;+ }++ const fourTools = ["compare_models", "list_models", "run_prompt", "search_models"];+ const removedTools = [+ "team",+ "create_session",+ "send_input",+ "get_output",+ "cancel_session",+ "list_sessions",+ "get_diagnostics",+ "capture_session",+ "preflight",+ "report_error",+ ];++ test("T-MCP-1: all exposes exactly four nested tools and logs the nested startup line", async () => {+ const c = await connect("all");+ const names = (await c.listTools()).tools.map((tool) => tool.name).sort();+ expect(names).toEqual(fourTools);+ for (const name of removedTools) expect(names).not.toContain(name);+ // stderr and stdout are separate pipes: wait briefly for the startup line to be drained.+ const deadline = Date.now() + 2000;+ while (!stderr.includes("MCP server started") && Date.now() < deadline) await Bun.sleep(10);+ expect(stderr.split(/\r?\n/)).toContain(+ "[claudish] MCP server started (tools: nested, 4 tools)"+ );+ }, 30_000);++ for (const [mode, expected] of [+ ["channel", []],+ ["low-level", fourTools],+ ["agentic", []],+ [undefined, fourTools],+ ] as const) {+ test(`T-MCP-2: ${mode ?? "unset"} intersects its tool group with nested tools`, async () => {+ const c = await connect(mode);+ expect((await c.listTools()).tools.map((tool) => tool.name).sort()).toEqual([...expected]);+ expect(c.getServerCapabilities()).toHaveProperty("tools");+ expect(c.getServerCapabilities()).not.toHaveProperty("experimental");+ expect(c.getInstructions()).toContain("## Nested mode — no sessions");+ expect(c.getInstructions()).not.toContain("Channel Mode");+ }, 30_000);+ }++ test("T-MCP-3: initialize advertises tools without channels and gives nested instructions", async () => {+ const c = await connect("all");+ expect(c.getServerCapabilities()).toHaveProperty("tools");+ expect(c.getServerCapabilities()).not.toHaveProperty("experimental");+ const instructions = c.getInstructions();+ const { NESTED_INSTRUCTIONS } = await import("../mcp/nested-mode.js");+ expect(instructions).toBe(NESTED_INSTRUCTIONS);+ expect(+ instructions?.startsWith(+ "Claudish MCP server provides access to external AI models for one-shot calls."+ )+ ).toBe(true);+ expect(instructions).toContain("## Nested mode — no sessions");+ expect(instructions).toContain("nested session refused");+ expect(instructions).not.toContain("Channel Mode");+ expect(instructions).not.toMatch(/^- (?:preflight|report_error):/m);+ }, 30_000);++ test("T-MCP-4: removed session tools answer Unknown tool and leave no panes", async () => {+ const c = await connect("all");+ for (const name of ["create_session", "team"]) {+ const result = await c.callTool({ name, arguments: { model: "x", prompt: "y" } });+ expect(result.isError).toBe(true);+ expect(result.content).toEqual([{ type: "text", text: `Error: Unknown tool "${name}"` }]);+ }+ expect(await paneOrphans(layout)).toEqual({ processes: [], files: [] });+ }, 30_000);++ test("T-MCP-5: without the flag all still exposes 14 tools and the channel capability", async () => {+ const c = await connect("all", false);+ const tools = (await c.listTools()).tools;+ expect(tools).toHaveLength(14);+ expect(new Set(tools.map((tool) => tool.name)).size).toBe(14);+ expect(c.getServerCapabilities()?.experimental?.["claude/channel"]).toBeDefined();+ expect(c.getInstructions()).not.toContain("## Nested mode — no sessions");+ }, 30_000);+});diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.tsindex 81e73de7..356a9e33 100644--- a/packages/cli/src/mcp-server.ts+++ b/packages/cli/src/mcp-server.ts@@ -26,6 +26,7 @@ import { SessionManager } from "./channel/index.js";import { parentSessionForCall } from "./channel/parent-session.js";import type { ChannelEventType } from "./channel/types.js";import { isSubscriptionProvider } from "./handlers/shared/remote-provider-types.js";+import { NESTED_INSTRUCTIONS, NESTED_MCP_TOOL_NAMES } from "./mcp/nested-mode.js";import {type HeartbeatHandle,NOOP_HEARTBEAT,@@ -33,6 +34,9 @@ import {startHeartbeat,} from "./mcp/progress-heartbeat.js";import { type RecommendedModelsDoc, getRecommendedModels } from "./model-loader.js";+// Imported for the predicate only. child-env's import-time bootstrap is a no-op here:+// a claudish MCP server is never the pane child (it carries no CLAUDISH_PANE_CWD).+import { inMcpSession } from "./pane/child-env.js";import {ContractErrorException,type FailureReason,@@ -817,10 +821,15 @@ type ChannelNotifier = (params: {function defineTools(sessionManager: SessionManager,- notifyChannel: ChannelNotifier+ notifyChannel: ChannelNotifier,+ nested: boolean): ToolDefinition[] {const tools: ToolDefinition[] = [];+ // A nested server does not register `report_error` (mcp/nested-mode.ts), so an+ // error text must not point at it.+ const reportHint = (text: string): string => (nested ? "" : text);+// ── Low-Level Tools ──────────────────────────────────────────────────/**@@ -883,7 +892,7 @@ function defineTools({type: "text" as const,text: withOpFailureContext(- `Error: ${errMsg}\n\n---\n**To report this error**, use the \`report_error\` tool with \`error_type: "provider_failure"\` and \`model: "${args.model}"\`.`,+ `Error: ${errMsg}${reportHint(`\n\n---\n**To report this error**, use the \`report_error\` tool with \`error_type: "provider_failure"\` and \`model: "${args.model}"\`.`)}`,`while routing ${args.model}`),},@@ -1118,8 +1127,9 @@ function defineTools(}const failed = results.filter((r) => r.error);if (failed.length > 0) {- output +=- '---\n**To report failed model(s)**, use the `report_error` tool with `error_type: "provider_failure"` and the model ID(s) above.\n';+ output += reportHint(+ '---\n**To report failed model(s)**, use the `report_error` tool with `error_type: "provider_failure"` and the model ID(s) above.\n'+ );}return { content: [{ type: "text" as const, text: output }] };},@@ -2267,17 +2277,23 @@ export function mapEventToTaskStatus(event: string): TaskStatus {async function main() {const toolMode = (process.env.CLAUDISH_MCP_TOOLS || "all").toLowerCase();+ // Inside a session a claudish owner started, one level of nesting is the limit:+ // only the one-shot tools of NESTED_MCP_TOOL_NAMES, intersected with the groups+ // CLAUDISH_MCP_TOOLS enables (never widened), no channel capability, and the+ // nested instructions. See pane-session.md § One level of nesting.+ const nested = inMcpSession();const enabledGroups = resolveToolGroups(toolMode);+ const channelEnabled = !nested && enabledGroups.has("channel");// Create server with channel capabilityconst server = new Server({ name: "claudish", version: "9.0.0" },{capabilities: {- ...(enabledGroups.has("channel") ? { experimental: { "claude/channel": {} } } : {}),+ ...(channelEnabled ? { experimental: { "claude/channel": {} } } : {}),tools: {},},- instructions: INSTRUCTIONS,+ instructions: nested ? NESTED_INSTRUCTIONS : INSTRUCTIONS,});@@ -2331,7 +2347,6 @@ async function main() {// actually being declared — emitting a channel frame the client never// registered for is silently dropped, and `team` still writes status.txt// regardless, so there is always a visible path.- const channelEnabled = enabledGroups.has("channel");const notifyChannel: ChannelNotifier = (p) => {if (!channelEnabled) return;try {@@ -2364,11 +2379,16 @@ async function main() {const progressIntervalMs = resolveProgressIntervalMs();// Build tool registry- const allTools = defineTools(sessionManager, notifyChannel);- const enabledTools = allTools.filter((t) => enabledGroups.has(t.group));+ const allTools = defineTools(sessionManager, notifyChannel, nested);+ const nestedNames: readonly string[] = NESTED_MCP_TOOL_NAMES;+ const enabledTools = allTools.filter(+ (t) => enabledGroups.has(t.group) && (!nested || nestedNames.includes(t.name))+ );const toolMap = new Map(enabledTools.map((t) => [t.name, t]));- console.error(`[claudish] MCP server started (tools: ${toolMode}, ${enabledTools.length} tools)`);+ console.error(+ `[claudish] MCP server started (tools: ${nested ? "nested" : toolMode}, ${enabledTools.length} tools)`+ );// Register ListTools handlerserver.setRequestHandler(ListToolsRequestSchema, async () => ({diff --git a/packages/cli/src/mcp/nested-mode.test.ts b/packages/cli/src/mcp/nested-mode.test.tsnew file mode 100644index 00000000..0491f730--- /dev/null+++ b/packages/cli/src/mcp/nested-mode.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from "bun:test";+import { NESTED_INSTRUCTIONS, NESTED_MCP_TOOL_NAMES } from "./nested-mode.js";++describe("nested MCP mode", () => {+ test("T-U-10: the nested surface has exactly four one-shot and discovery tools", () => {+ expect([...NESTED_MCP_TOOL_NAMES].sort()).toEqual([+ "compare_models",+ "list_models",+ "run_prompt",+ "search_models",+ ]);+ });++ test("T-U-11: instructions describe one-shot calls and the nesting refusal", () => {+ expect(+ NESTED_INSTRUCTIONS.startsWith(+ "Claudish MCP server provides access to external AI models for one-shot calls."+ )+ ).toBe(true);+ expect(NESTED_INSTRUCTIONS).toContain(+ "create_session, team, send_input, get_output, cancel_session, list_sessions, get_diagnostics, capture_session, preflight, report_error"+ );+ expect(NESTED_INSTRUCTIONS).toContain(+ "- run_prompt or compare_models: a one-shot answer from another model."+ );+ expect(NESTED_INSTRUCTIONS).toContain("- list_models, search_models: find a model.");+ expect(NESTED_INSTRUCTIONS).toContain("## Nested mode — no sessions");+ expect(NESTED_INSTRUCTIONS).toContain("nested session refused");+ expect(NESTED_INSTRUCTIONS).not.toContain("Channel Mode");+ expect(NESTED_INSTRUCTIONS).not.toMatch(/^- (?:preflight|report_error):/m);+ });+});diff --git a/packages/cli/src/mcp/nested-mode.ts b/packages/cli/src/mcp/nested-mode.tsnew file mode 100644index 00000000..0cbd5280--- /dev/null+++ b/packages/cli/src/mcp/nested-mode.ts@@ -0,0 +1,38 @@+/**+ * The claudish MCP server's surface inside a session that a claudish owner started+ * (`CLAUDISH_PANE_CHILD=1`, read by `inMcpSession()`), where one level of nesting is+ * the limit. See `ai-docs/architecture/mcp-channel.md` § Nested mode and+ * `pane-session.md` § One level of nesting.+ *+ * A leaf module that imports nothing, so a test can read the list without importing+ * `mcp-server.ts`, which loads `.env` at import time.+ */++/**+ * The tools a nested server registers, by NAME. The rule: keep a tool only if it is a+ * one-shot call that starts no session, no pane and no claudish child. `run_prompt` and+ * `compare_models` answer through an in-process proxy; the two catalog reads start+ * nothing. The list fails closed: a tool added later is absent in nested mode until+ * someone lists it here, which a group filter would not guarantee.+ *+ * Nested mode INTERSECTS this list with the groups `CLAUDISH_MCP_TOOLS` enables; it+ * never widens them.+ */+export const NESTED_MCP_TOOL_NAMES = [+ "run_prompt",+ "list_models",+ "search_models",+ "compare_models",+] as const;++/** The server instructions in nested mode, in place of the channel-mode text. */+export const NESTED_INSTRUCTIONS = `Claudish MCP server provides access to external AI models for one-shot calls.++## Nested mode — no sessions++This server runs inside a session that a claudish MCP server started (CLAUDISH_PANE_CHILD=1). One level of nesting is the limit, so these tools are not registered: create_session, team, send_input, get_output, cancel_session, list_sessions, get_diagnostics, capture_session, preflight, report_error. No channel notifications are sent.++- run_prompt or compare_models: a one-shot answer from another model.+- list_models, search_models: find a model.++Do not start a claudish session another way: \`claudish -p\`, an interactive claudish or \`claudish team\` run from this session's shell exits 64 with "nested session refused".`;