← reports

#6655 · Diagnostic Claude processes reconnect to configured MCP servers

Bug Priority: Medium Effort: Medium providers · provider-claude-code · perf GitHub issue October 30, 2026 · base a1bf55b6a04c7948ae5ae0dcfcbdec27d2b507a2

Verdict: REPRODUCED · Root-cause confidence: high · reproduction label: confirmed-repro

1. TL;DR

Reading Claude model metadata or context usage starts another Claude process, even when an existing conversation process remains active. Each diagnostic process loads the configured user MCP servers. In two clean runs, two metadata probes each opened a fresh MCP connection; the context probe also connected and then abandoned all three outstanding discovery requests. The result is unnecessary connection churn and canceled server work, without requiring a user tool call or a failed conversation. The repeatable evidence uses the real provider functions, real SDK, and its pinned native Claude executable against a synthetic local MCP server; it does not use an account or the reporter’s configuration.

2. Claims vs findings

ClaimFindingEvidence / limit
Initialization probes inherit user MCP configuration.VerifiedEach of two probes generated an MCP initialize request in both clean runs, while still returning five model records.
The isolated context probe reconnects and cuts off discovery.VerifiedA valid synthetic saved session was resumed; context usage returned successfully, and tools/list, prompts/list, and resources/list responses were canceled before the fixture completed them.
Initialization may terminate MCP listing requests.Verified, timing-dependentAn initial exploratory run observed three aborted listing responses from a metadata probe. The final repeated runs closed earlier, after the initialize handshake, and recorded zero metadata listing aborts. Reconnection is deterministic here; the exact stage reached before closure varies.
The extra context process runs at the start of every turn.RefinedThe trusted source schedules capture on SDK result, system init, and compact-boundary messages. This is recurring diagnostic work, but not a universal unconditional start-of-turn hook.
Every configured server, headers helpers, macOS Keychain access, daily counts, and error quota impact.Not independently measuredOnly one synthetic user-configured HTTP MCP server was tested. No helper command, Keychain, account logs, production server, or macOS environment was used. Reported fleet-wide volume and billing impact remain unverified.
The long-lived conversation remains usable.Limited verificationThe existing owner-boundary test for blocked reporting and continued prompt delivery passes. No real authenticated long-lived conversation was run for this report.

3. Environment

4. Minimal reproduction

The fixture receives real HTTP MCP requests. It answers initialization immediately, holds listing responses for 1.5 seconds, and records response closure before completion. A synthetic transcript makes the context resume valid. A loopback token-count response allows context collection without an external service or credentials. There is no mock of the production probes or SDK.

  1. On Linux x64, clone the trusted repository and install the frozen dependencies:
    git clone https://github.com/get-bb/bb.git bb-6655
    cd bb-6655
    git checkout --detach a1bf55b6a04c7948ae5ae0dcfcbdec27d2b507a2
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build:types build --filter=@get-bb/plugin-sdk
  2. Save the complete authored program below as repro-6655.ts in the checkout root. Run:
    pnpm exec tsx repro-6655.ts
  3. Expected: metadata probes make no configured MCP connection; context reporting does not abandon pending discovery. The final assertion expects no violating observations and should exit 0 after a complete fix.
  4. Actual: the unchanged trusted code exits 1 with ERR_ASSERTION. The successful metadata/context results and observation summary in the first checkout are verbatim:
    {"probe":"initialization-1","initialized":true,"models":5}
    {"probe":"initialization-2","initialized":true,"models":5}
    {"probe":"context","returnedUsage":true}
    {"observations":[{"probe":"initialization-1","connections":1,"abandonedRequests":0},{"probe":"initialization-2","connections":1,"abandonedRequests":0},{"probe":"context","connections":1,"abandonedRequests":3}]}
  5. The context probe’s three abandoned responses are tools/list, prompts/list, and resources/list. The error is a behavioral assertion failure, not missing authentication, an invalid resume, or an SDK import error.

Complete reproduction source

The reports repository publishes self-contained HTML only. The complete source and evidence are embedded here rather than linked as separate scripts or logs.

import { createServer } from "node:http";
import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { randomUUID } from "node:crypto";
import assert from "node:assert/strict";
import { setTimeout as delay } from "node:timers/promises";
import { probeClaudeInitialization } from "./plugins/provider-claude-code/src/bridge/initialization-probe.js";
import { readIsolatedClaudeContextUsage } from "./plugins/provider-claude-code/src/bridge/context-usage-probe.js";

const directory = await mkdtemp(join(tmpdir(), "bb-6655-fixture-"));
const home = join(directory, "home");
const config = join(home, ".claude");
const cwd = join(directory, "workspace");
await mkdir(config, { recursive: true });
await mkdir(cwd);
const events: { probe: string; event: string; method?: string }[] = [];
let probe = "setup";
const server = createServer(async (request, response) => {
  const chunks: Buffer[] = [];
  for await (const chunk of request) chunks.push(chunk);
  if (request.method !== "POST") {
    response.writeHead(405).end();
    return;
  }
  const message = JSON.parse(Buffer.concat(chunks).toString());
  if (request.url?.startsWith("/v1/messages/count_tokens")) {
    response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ input_tokens: 123 }));
    return;
  }
  const currentProbe = probe;
  events.push({ probe: currentProbe, event: "received", method: message.method });
  response.on("close", () => {
    if (!response.writableEnded) {
      events.push({ probe: currentProbe, event: "aborted", method: message.method });
    }
  });
  if (message.id === undefined) {
    response.writeHead(202).end();
    return;
  }
  if (message.method === "initialize") {
    response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({
      jsonrpc: "2.0", id: message.id,
      result: { protocolVersion: message.params.protocolVersion, capabilities: { tools: {}, prompts: {}, resources: {} }, serverInfo: { name: "local-fixture", version: "1" } },
    }));
    return;
  }
  await delay(1500);
  if (!response.destroyed) {
    const result = message.method === "tools/list" ? { tools: [] } : message.method === "prompts/list" ? { prompts: [] } : { resources: [] };
    response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));
  }
});
server.listen(0, "127.0.0.1");
await new Promise<void>((resolve) => server.once("listening", resolve));
const address = server.address();
if (address === null || typeof address === "string") throw new Error("Missing fixture port");
await writeFile(join(config, ".claude.json"), JSON.stringify({
  hasCompletedOnboarding: true,
  mcpServers: { "local-fixture": { type: "http", url: `http://127.0.0.1:${address.port}/mcp` } },
}));
const executable = resolve("node_modules/.pnpm/@anthropic-ai+claude-agent-sdk-linux-x64@0.3.245/node_modules/@anthropic-ai/claude-agent-sdk-linux-x64/claude");
const env = {
  PATH: "/usr/local/bin:/usr/bin:/bin",
  HOME: home,
  CLAUDE_CONFIG_DIR: config,
  BB_CLAUDE_CODE_EXECUTABLE: executable,
  CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
  DISABLE_AUTOUPDATER: "1",
  ANTHROPIC_API_KEY: "local-fixture-only",
  ANTHROPIC_BASE_URL: `http://127.0.0.1:${address.port}`,
};
const sessionId = randomUUID();
const transcriptDirectory = join(config, "projects", cwd.replace(/[^a-zA-Z0-9]/g, "-"));
await mkdir(transcriptDirectory, { recursive: true });
const messageId = randomUUID();
await writeFile(join(transcriptDirectory, `${sessionId}.jsonl`), [
  { type: "user", uuid: messageId, parentUuid: null, sessionId, cwd, isSidechain: false, timestamp: "2026-10-30T00:00:00.000Z", message: { role: "user", content: "Synthetic fixture question" } },
  { type: "assistant", uuid: randomUUID(), parentUuid: messageId, sessionId, cwd, isSidechain: false, timestamp: "2026-10-30T00:00:01.000Z", message: { id: "local-message", type: "message", role: "assistant", model: "claude-sonnet-4-6", content: [{ type: "text", text: "Synthetic fixture answer" }], stop_reason: "end_turn", usage: { input_tokens: 10, output_tokens: 5 } } },
].map((record) => JSON.stringify(record)).join("\n") + "\n");
try {
  for (const name of ["initialization-1", "initialization-2", "context"]) {
    probe = name;
    try {
      if (name === "context") {
        const usage = await readIsolatedClaudeContextUsage({
          sessionOptions: { cwd, env, systemPrompt: "Synthetic diagnostic fixture", allowBypassPermissions: false, pathToClaudeCodeExecutable: executable },
          providerSessionId: sessionId, dynamicTools: [], signal: AbortSignal.timeout(5000),
        });
        console.log(JSON.stringify({ probe: name, returnedUsage: usage !== null }));
      } else {
        const result = await probeClaudeInitialization({ cwd, env });
        console.log(JSON.stringify({ probe: name, initialized: true, models: result.models?.length }));
      }
    } catch (error) {
      console.log(JSON.stringify({ probe: name, error: error instanceof Error ? error.message : String(error) }));
    }
    await delay(2000);
  }
  console.log(JSON.stringify({ events }, null, 2));
  const observations = ["initialization-1", "initialization-2", "context"].map((name) => ({
    probe: name,
    connections: events.filter((event) => event.probe === name && event.method === "initialize").length,
    abandonedRequests: events.filter((event) => event.probe === name && event.event === "aborted").length,
  }));
  console.log(JSON.stringify({ observations }));
  assert.deepEqual(observations.filter((entry) => entry.abandonedRequests > 0 || (entry.probe.startsWith("initialization") && entry.connections > 0)), [], "Diagnostic probes must not cause unnecessary MCP connections or abandon discovery requests");
} finally {
  server.closeAllConnections();
  await new Promise<void>((resolve) => server.close(() => resolve()));
  await rm(directory, { recursive: true, force: true });
}

5. Root cause

Short-lived SDK queries inherit user MCP configuration and close after metadata or context collection, without waiting for configured MCP discovery to finish. The metadata query does not need tool discovery, but passes all setting sources and no strict MCP configuration:

Metadata query and unconditional close

    session = query({
      prompt: promptWithoutMessages(promptEnd.signal),
      options: {
        cwd: args.cwd,
        env: args.env,
        persistSession: false,
        settingSources: ["user", "project", "local"],
        ...(pathToClaudeCodeExecutable ? { pathToClaudeCodeExecutable } : {}),
      },

The context query likewise loads user/project/local settings. Its tool denial callback prevents tool execution, not MCP startup or discovery. Setting disableAllHooks is not MCP isolation. Its only MCP readiness loop is conditional on BB dynamic tools and checks only the BB bridge, not every user-configured server:

Inherited MCP configuration and readiness/close behavior

  try {
    args.signal.throwIfAborted();
    await session.initializationResult();
    while (args.dynamicTools.length > 0) {
      const server = (await session.mcpServerStatus()).find(
        (server) => server.name === BB_BRIDGE_MCP_SERVER_NAME,
      );
      if (server?.status === "connected") break;
      if (server && server.status !== "pending") return null;
      await delay(25, undefined, { signal: args.signal });
    }
    return await session.getContextUsage();
  } finally {
    args.signal.removeEventListener("abort", close);
    close();
  }

Capture trigger schedules another isolated reader on result, initialization, and compaction events. Model and command discovery also call the metadata helper: model caller and command caller.

The native SDK’s MCP discovery is asynchronous relative to initialization and context collection. Therefore an initialize response or context result does not mean every configured MCP listing has completed; unconditional closure can terminate that work. This also explains why initialization sometimes closes before listing even begins.

6. Proposed fix and simple-fix assessment

Metadata discovery can be isolated from configured MCP servers using the SDK’s strict MCP option and an empty explicit server configuration. A dependency-backed regression should prove metadata still works and the configured fixture receives no connection. That addresses only one half of this issue.

The context path needs a design choice before a complete repair is safe: retain accurate MCP/tool accounting while avoiding repeated discovery and preserving the existing isolation from the live conversation. Silently dropping MCP changes the meaning of the report. Moving the request to the live process reverses the protection introduced in the reporting-isolation change, which was needed because a stalled token-count request could block subsequent prompts. Caching or reusing diagnostic state also needs explicit invalidation and lifecycle ownership.

No pull request was opened: the complete fix requires an architecture/product decision about context reporting, so it does not pass the requested simple-fix gate. No candidate production patch, branch, commit, dependency, or wire change was made. No linked open pull request was present in issue timeline metadata or the issue-number PR search.

7. Verification

The same investigator repeated the program in a second clean checkout at the exact recorded trusted commit. Before copying in the authored reproduction, git status --short was empty. That checkout received its own frozen dependency install and successful Turbo SDK builds. The reproduction allocated new temporary directories and a new loopback port, and all fixture data and listeners were removed on exit.

git checkout --detach a1bf55b6a04c7948ae5ae0dcfcbdec27d2b507a2
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build:types build --filter=@get-bb/plugin-sdk
pnpm exec tsx repro-6655.ts
Exit status: 1 (expected regression failure)

Second-run results, verbatim:

{"probe":"initialization-1","initialized":true,"models":5}
{"probe":"initialization-2","initialized":true,"models":5}
{"probe":"context","returnedUsage":true}
{"observations":[{"probe":"initialization-1","connections":1,"abandonedRequests":0},{"probe":"initialization-2","connections":1,"abandonedRequests":0},{"probe":"context","connections":1,"abandonedRequests":3}]}

The two final runs agree. No report correction was needed after the second run. This is a repeated clean-checkout verification by the same investigator, not an independent investigation. Root-cause permalinks were checked against the recorded commit; there are no visual assets.

Relevant existing tests on unchanged main also passed:

pnpm exec turbo run test --filter=bb-plugin-provider-claude-code -- src/bridge/__tests__/context-usage.test.ts
Tests: 8 passed

pnpm exec turbo run test --filter=bb-plugin-provider-claude-code -- src/bridge/__tests__/bridge.test.ts -t 'keeps prompts on the live session while automatic context reporting is blocked'
Tests: 1 passed | 105 skipped

8. Related work

Reporting isolation history documents why sending these requests to the live conversation is not an interchangeable implementation. The existing initialization filesystem-lifecycle report concerns another effect of short-lived probes; it is not evidence for the network behavior tested here.

9. Appendix

Untrusted-data handling: the issue and comments were used only as claims. Issue suggestions were not executed. The reproduction and fix assessment were derived from trusted origin/main source, SDK type declarations, observed local HTTP requests, and repository history. No linked branch, external issue-supplied URL, account data, or secrets were used.

The investigation used GitHub reads for classification definitions, labels, similar issue classifications, comments, repository visibility, and linked-PR metadata; trusted repository clones/fetches; frozen pnpm installs; Turbo builds/tests; and the authored diagnostic program. Publication includes only this report, its summary metadata, and the generated report index. Raw logs and fixture scratch remain outside the reports repository.

Impact-based classification: Medium priority because conversations remain usable but recurring probes create unwanted external work; Medium effort because preserving accurate, nonblocking context collection needs more than a contained metadata option change.

> AGENT GENERATED