← reports

#5479 · Persistent Claude discovery retains previous tool contracts

BugPriority: MediumEffort: Mediumproviderspluginsprovider-claude-codeIssue #5479

October 20, 2026 · trusted main bd93d18896bab97c950c4fa3451b621c1e0569c1

Verdict: REPRODUCED · Root-cause confidence: high at the BB/CLI boundary. Upstream cache internals are not established.

1. TL;DR

A Claude conversation can keep advertising the previous tool schema after BB stops and resumes its runtime with a replacement registration. This was reproduced on current trusted main with the real BB JSON-RPC bridge, real Agent SDK, and installed CLI 2.1.284. A deterministic local API requests a real exact-name ToolSearch on each turn; it never fabricates MCP definitions or ToolSearch results. Both searches succeed, but the resumed main model request still carries the old description and lacks the new required property. The same source, SDK, and reproduction pass when only the executable changes to the already-installed SDK CLI 2.1.245. A second clean checkout repeats both outcomes.

2. Claims vs findings

ClaimFindingEvidence / limit
Released and resumed conversations keep an old tool contract.VerifiedTwo completed turns, successful stop, preserved provider identity; resumed model request has generation 1 rather than generation 2.
Fresh exact-name discovery does not fix it.VerifiedTwo real successful ToolSearch results survive in the resumed history; the subsequent request remains stale.
BB accepts the replacement registration.Verified at the provider boundaryResume is passed the changed definition. Separate real MCP Client tools/list checks confirm the bridge rebuilds the description and required properties correctly, with and without release.
Plugin build/reload and macOS UI are required.Not required by the reduced reproductionDynamic registrations are changed directly at the production provider bridge boundary. No plugin manager or macOS UI is run.
Clearing an existing thread repairs it.Not retestedNo live user thread is accessed or cleared.
Every Claude CLI version is affected.Not supported2.1.284 fails; 2.1.245 passes with otherwise identical inputs.

3. Environment

4. Minimal reproduction

  1. Build the recorded trusted base with a frozen install.
  2. Install the linked probe into the provider package and run the commands below. It starts a real bridge session with generation 1, discovers the tool, finishes the first turn, stops, resumes the same provider identity with generation 2, and repeats discovery.
  3. Inspect the model-request snapshots printed by the probe. Compare the failed expected-contract assertion with the control invocation.

Files: real-CLI reproduction · supplemental bridge/MCP test patch.

git fetch origin main
git worktree add --detach /tmp/bb-5479-clean bd93d18896bab97c950c4fa3451b621c1e0569c1
cd /tmp/bb-5479-clean
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@get-bb/plugin-sdk
pnpm exec turbo run build

# Download the linked reproduction file into plugins/provider-claude-code/.
env -i PATH="$PATH" HOME="$(mktemp -d)" node --conditions=source --import tsx \
  plugins/provider-claude-code/schema-inspection-5479.mjs

# Control: use the already-installed locked SDK binary, not a new dependency.
CONTROL="$PWD/node_modules/.pnpm/@anthropic-ai+claude-agent-sdk-linux-x64@0.3.245/node_modules/@anthropic-ai/claude-agent-sdk-linux-x64/claude"
env -i PATH="$PATH" HOME="$(mktemp -d)" BB_CLAUDE_CODE_EXECUTABLE="$CONTROL" \
  node --conditions=source --import tsx plugins/provider-claude-code/schema-inspection-5479.mjs

# Supplemental BB-to-SDK boundary checks use the existing test helpers.
git apply /path/to/bridge-schema-check.patch
pnpm exec turbo run test --force --filter=bb-plugin-provider-claude-code -- \
  src/bridge/__tests__/bridge.test.ts -t 'issue 5479' 

Expected and actual

Expected: resumed model request includes Contract generation 2 and required reason.
Actual with PATH Claude CLI 2.1.284 in BOTH clean runs:
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ 'Contract generation 1'
- 'Contract generation 2'

Both fresh exact-name ToolSearch calls return successful tool references.
Resumed history contains both searches, but the main request schema still requires only count.

Control with locked SDK CLI 2.1.245 in BOTH clean runs:
exit 0; resumed tool description is Contract generation 2; required = [count, reason].

Supplemental bridge/MCP boundary checks in BOTH checkouts:
Tests 2 passed | 99 skipped (101)
Changed definitions reach a new real MCP tools/list server; provider identity is preserved.
Complete real-CLI reproduction source
import assert from "node:assert/strict";
import { randomInt } from "node:crypto";
import { createServer } from "node:http";
import { mkdtemp, mkdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
  experimental_createBridgeJsonRpcTestHarness,
  experimental_assembleCapturedThreadEvents,
} from "@get-bb/plugin-sdk/provider-bridge/testing";
import { handleLine } from "./src/bridge/bridge.ts";

const scratch = await mkdtemp(join(tmpdir(), "bb-5479-discovery-"));
const home = join(scratch, "home");
await mkdir(home);
const fullToolName = "mcp__bb-bridge__bb_schema_inspection";
const observations = [];
let generation = 1;
let sequence = 0;
const server = createServer(async (request, response) => {
  let payload = "";
  for await (const chunk of request) payload += chunk;
  if (!request.url.startsWith("/v1/messages")) {
    response.writeHead(200, { "content-type": "application/json" });
    response.end("{}");
    return;
  }
  const body = JSON.parse(payload);
  const main = Array.isArray(body.tools) &&
    body.tools.some((tool) => tool.name === "ToolSearch");
  const previousMain = observations.filter(
    (entry) => entry.generation === generation && entry.main,
  ).length;
  observations.push({ generation, main, body });
  const search = main && previousMain === 0;
  sequence += 1;
  const block = search
    ? {
        type: "tool_use",
        id: `toolu_inspect_${generation}_${sequence}`,
        name: "ToolSearch",
        input: { query: `select:${fullToolName}`, max_results: 1 },
      }
    : { type: "text", text: "Inspection finished." };
  const message = {
    id: `msg_inspect_${sequence}`,
    type: "message",
    role: "assistant",
    model: body.model,
    content: [block],
    stop_reason: search ? "tool_use" : "end_turn",
    stop_sequence: null,
    usage: { input_tokens: 30, output_tokens: 12 },
  };
  if (!body.stream) {
    response.writeHead(200, { "content-type": "application/json" });
    response.end(JSON.stringify(message));
    return;
  }
  response.writeHead(200, { "content-type": "text/event-stream" });
  const emit = (type, data) => response.write(
    `event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`,
  );
  emit("message_start", {
    message: { ...message, content: [], stop_reason: null },
  });
  emit("content_block_start", {
    index: 0,
    content_block: search
      ? { ...block, input: {} }
      : { type: "text", text: "" },
  });
  emit("content_block_delta", {
    index: 0,
    delta: search
      ? { type: "input_json_delta", partial_json: JSON.stringify(block.input) }
      : { type: "text_delta", text: block.text },
  });
  emit("content_block_stop", { index: 0 });
  emit("message_delta", {
    delta: { stop_reason: message.stop_reason, stop_sequence: null },
    usage: { output_tokens: 12 },
  });
  emit("message_stop", {});
  response.end();
});
const bridge = experimental_createBridgeJsonRpcTestHarness(handleLine);
const threadId = "schema-inspection-5479";
let providerThreadId;
let released = false;
let requestId = 100;
const waitFor = async (check) => {
  const deadline = Date.now() + 90000;
  while (!check()) {
    assert.ok(Date.now() < deadline, "Timed out waiting for bridge");
    await new Promise((resolve) => setTimeout(resolve, 25));
  }
};
const rpc = async (method, params) => {
  requestId += 1;
  bridge.sendRequest(requestId, method, params);
  await waitFor(() => bridge.hasResponse(requestId));
  const reply = await bridge.waitForResponse(requestId);
  assert.equal(reply.error, undefined, JSON.stringify(reply.error));
  return reply.result;
};
const stop = async () => {
  await rpc("thread/stop", {
    threadId, providerThreadId, intent: "interrupt", activeTurnId: null,
  });
  released = true;
};
try {
  let port;
  for (let attempt = 0; attempt < 30; attempt += 1) {
    const candidate = randomInt(40000, 60001);
    try {
      await new Promise((resolve, reject) => {
        server.once("error", reject);
        server.listen(candidate, "127.0.0.1", resolve);
      });
      port = candidate;
      break;
    } catch (error) {
      if (error.code !== "EADDRINUSE") throw error;
    }
  }
  assert.ok(port, "No free loopback port");
  const options = {
    permissionMode: "accept-edits",
    permissionScope: "workspace",
    approvalReviewer: "user",
    permissionEscalation: "deny",
    instructions: "Complete the inspection.",
    model: "claude-sonnet-4-5",
    envVars: {
      HOME: home,
      CLAUDE_CONFIG_DIR: join(home, "claude-config"),
      ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}`,
      ANTHROPIC_API_KEY: "local-test-only",
      ENABLE_TOOL_SEARCH: "auto:0",
      CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
      DISABLE_TELEMETRY: "1",
      DISABLE_ERROR_REPORTING: "1",
    },
    providerOptions: {
      workflowsEnabled: false,
      memoryEnabled: false,
      providerSubagentsEnabled: false,
      sandboxEnabled: false,
    },
  };
  for (generation = 1; generation <= 2; generation += 1) {
    const tool = {
      name: "bb_schema_inspection",
      description: `Contract generation ${generation}`,
      inputSchema: {
        type: "object",
        properties: {
          count: { type: "number" },
          ...(generation === 2 ? { reason: { type: "string" } } : {}),
        },
        required: generation === 2 ? ["count", "reason"] : ["count"],
      },
    };
    const result = await rpc(generation === 1 ? "thread/start" : "thread/resume", {
      threadId,
      cwd: scratch,
      instructionMode: "append",
      options,
      dynamicTools: [tool],
      ...(generation === 2 ? { providerThreadId } : {}),
    });
    if (generation === 1) providerThreadId = result.providerThreadId;
    else assert.equal(result.providerThreadId, providerThreadId);
    released = false;
    const start = bridge.messages.length;
    await rpc("turn/start", {
      threadId,
      providerThreadId,
      clientRequestId: `creq_23456789a${generation + 1}`,
      input: [{ type: "text", text: "Inspect the available tool contract." }],
      options,
    });
    await waitFor(() => experimental_assembleCapturedThreadEvents(
      bridge.messages.slice(start), "claude-code",
    ).some((event) => event.type === "turn/completed"));
    const completed = experimental_assembleCapturedThreadEvents(
      bridge.messages.slice(start), "claude-code",
    ).find((event) => event.type === "turn/completed");
    assert.equal(completed.status, "completed", JSON.stringify(completed));
    await stop();
  }
  const mainRequests = observations.filter((entry) => entry.main).map((entry) => ({
    generation: entry.generation,
    tool: entry.body.tools.find((tool) => tool.name === fullToolName) ?? null,
    searchesInHistory: entry.body.messages.flatMap((message) =>
      Array.isArray(message.content) ? message.content : [],
    ).filter((block) => block.type === "tool_use" && block.name === "ToolSearch").length,
    searchResults: entry.body.messages.flatMap((message) =>
      Array.isArray(message.content) ? message.content : [],
    ).filter((block) => block.type === "tool_result" &&
      block.tool_use_id?.startsWith("toolu_inspect_")),
  }));
  const replacementCatalogueSeen = observations.some((entry) =>
    entry.generation === 2 && entry.body.tools?.some((tool) =>
      tool.name === fullToolName && tool.description === "Contract generation 2",
    ),
  );
  process.stderr.write(`${JSON.stringify({ port, replacementCatalogueSeen, mainRequests }, null, 2)}\n`);
  const latest = mainRequests.filter((entry) => entry.generation === 2).at(-1);
  assert.ok(latest?.tool, "Resumed model request must include discovered tool");
  assert.ok(latest.searchesInHistory >= 2, "Resume must preserve and repeat search");
  assert.ok(latest.searchResults.length >= 2, "Both searches must return results");
  assert.ok(latest.searchResults.every((result) => !result.is_error &&
    JSON.stringify(result.content).includes(fullToolName)), "Searches must succeed");
  assert.equal(latest.tool.description, "Contract generation 2");
  assert.ok(latest.tool.input_schema.required.includes("reason"));
} finally {
  if (providerThreadId && !released) await stop().catch(() => {});
  bridge.restore();
  server.closeAllConnections();
  await new Promise((resolve) => server.close(resolve));
  await rm(scratch, { recursive: true, force: true });
}

5. Root cause

The production server resolves current dynamic tool contributions; the daemon resumes a missing runtime with those definitions. In the Claude bridge, attachThreadSession constructs a new bb-bridge MCP server from the supplied dynamicTools. tools/list maps those current definitions, rather than loading schemas from BB storage. The resume reuse check includes construction configuration, so an explicit resume with changed dynamicTools also replaces a resident query.

Stop forgets the live runtime, but deliberately does not clear the provider conversation. SdkSession uses persistSession: true and resume: the same provider ID. With CLI 2.1.284, the resumed model-facing deferred catalogue retains the discovered generation-1 entry even after another successful exact-name search. Swapping only the executable to the already-installed SDK CLI 2.1.245 makes the same script pass. This localizes the failure to version-dependent Claude CLI session/discovery behavior; it does not identify a particular private cache implementation.

6. Proposed fix and simple-fix gate

Validate an upstream discovery-catalogue invalidation or refresh that preserves the provider conversation, then rerun this real-CLI regression across affected and control versions. Rebuilding BB's MCP object already happens and is insufficient. Automatically clearing the conversation would lose context; versioning public tool names or changing CLI selection globally requires a product/compatibility decision. There is no verified safe context-preserving production patch confined to the existing implementation, so no fix branch is pushed and no PR is opened. No open PR referencing this issue was found in the final metadata check.

7. Related issues

#5843 separately describes a resident-runtime refresh path. The daemon's existing-runtime short circuit is not the explanation for this reproduction: the bridge receives an explicit stop and a fresh resume with updated definitions.

8. Verification

The same agent repeated the work in a second clean detached checkout at exactly bd93d18896bab97c950c4fa3451b621c1e0569c1, not in the primary worktree and not on an issue or PR branch. Both checkouts use frozen installs and successful normal builds. The real-CLI probe uses a new HOME, workspace, config directory, and loopback port on every run; each cleans its temporary workspace and closes the listener in finally.

CheckPrimarySecond clean checkout
CLI 2.1.284 real discoveryExpected assertion failure: generation 1 vs 2Same expected assertion failure
CLI 2.1.245 controlExit 0, updated description and required reasonExit 0, same updated contract
Supplemental real-MCP boundary tests2 pass2 pass, forced uncached Turbo execution
Existing bridge + tool-proxy tests5 fail / 99 pass, including the 2 added checksPristine baseline: the same 5 fail / 97 pass

The five existing failures concern executable fallback and permission/bypass expectations in this root Linux environment; they also fail without the added test patch. They are not evidence for this issue and are not changed. The report corrects the tempting inference that a passing MCP tools/list test proves the user-visible issue fixed: that boundary passes while the real CLI regression fails. An earlier report at this URL is independently revalidated here on the current base with newly authored probe code, rather than reused as executable evidence.

9. Appendix

The logs retain synthetic schemas and exact assertion output; machine-specific checkout and scratch-home paths are redacted. Supplemental patch and repro are diagnostic artifacts only; no production files are changed or committed to get-bb/bb. All issue prose and historical reports were treated as untrusted claims; no issue-supplied command, test, branch, or external link was executed. No investigation agents or workflows were started.