ai icon indicating copy to clipboard operation
ai copied to clipboard

harness-pi: deferred MCP tools loaded with tool_search are declared removed after a session resumes from sessionStorage

Open samialdury opened this issue 1 month ago • 5 comments

Description

With @ai-sdk/harness-pi, a deferred MCP tool that the model loaded with tool_search in an earlier turn is declared removed on the first turn after the session is resumed from sessionStorage. The model then reports that the tool is no longer available and does not call it.

Steps:

  1. Create a Pi harness with one MCP server that uses exposure: "deferred", and a sessionStorage.
  2. Turn 1: the model loads the tool with tool_search and calls it. The transcript records a system entry with toolsAdded: ["mcp__demo__echo"].
  3. Detach the session, then create a new HarnessAgent with the same configuration and storage, and resume it with createSession({ sessionId, resumeFrom }). This is what happens when another process takes over the conversation.
  4. Turn 2: ask the model to call the same tool again.

Expected: the tool is still active in turn 2, because the transcript declares it.

Actual: the first request of turn 2 records a system entry with toolsRemoved: ["mcp__demo__echo"], and the model answers without calling the tool:

turn 1: { tools: [ 'tool_search', 'mcp__demo__echo' ], text: "The demo server's echo tool returned `echo: one`." }
turn 2: { tools: [], text: "I can't call the echo tool this time. The harness says `mcp__demo__echo` is no longer available, so it has been unloaded. ..." }
loadout entries: [{"added":["read","write","edit","bash","grep","find","ls","tool_search"],"removed":[]},{"added":["mcp__demo__echo"],"removed":[]},{"added":[],"removed":["mcp__demo__echo"]}]

What I see: when the session is rebuilt from its entries, Pi restores the MCP tools of the recorded loadout as pending, because the MCP servers are still connecting. They are not active when the first request is prepared, so the agent loop declares them removed, and a removed tool stays inactive. In a before_agent_start handler on the resumed session, all MCP tools are registered about 300 ms later, but none of the restored ones is active. The 1.0.170 changelog mentions the limitation ("Deferred MCP tools that tool_search loaded in an earlier turn are not re-activated when the session is rebuilt from entries, as before"). This report adds that the tools are then recorded as removed, which the model reads as the tool having been taken away.

Workaround that fixes the repro (turn 2 then calls mcp__demo__echo and returns echo: two): an extension that waits for the restored MCP tools to register and activates them again before the first request.

const restoreLoadedMcpTools = (pi) => {
  pi.on("before_agent_start", async (_event, ctx) => {
    const declared = new Set<string>();
    for (const entry of ctx.sessionManager.getBranch()) {
      if (entry.type !== "message" || entry.message?.role !== "system") continue;
      for (const tool of entry.message.toolsRemoved ?? []) declared.delete(tool.name);
      for (const tool of entry.message.toolsAdded ?? []) declared.add(tool.name);
    }
    const mcp = [...declared].filter((name) => name.startsWith("mcp__"));
    const registered = () => mcp.every((name) => pi.getAllTools().some((tool) => tool.name === name));
    for (let i = 0; i < 200 && !registered(); i++) await new Promise((resolve) => setTimeout(resolve, 50));
    const active = pi.getActiveTools();
    pi.setActiveTools([...active, ...mcp.filter((name) => !active.includes(name))]);
  });
};
// createPi({ ..., extensionFactories: [restoreLoadedMcpTools] })

A fix in the harness could wait for the MCP servers whose tools the restored loadout names before the first request of a resumed session, or keep those tools pending until they register instead of declaring them removed.

Reproduction

Runnable with tsx. It needs an Anthropic API key (ANTHROPIC_API_KEY, optionally ANTHROPIC_BASE_URL) and an E2B key (E2B_API_KEY) for the sandbox. Any sandbox session should do; the bug is in session restore, not in the sandbox.

import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { createE2BSandbox } from "@e2b/ai-sdk-sandbox";
import { createPi, type PiSessionStorage } from "@ai-sdk/harness-pi";
import { HarnessAgent } from "@ai-sdk/harness/agent";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { Sandbox } from "e2b";
import { z } from "zod";

// A local MCP server with one tool.
const http = createServer(async (req, res) => {
  const mcp = new McpServer({ name: "demo", version: "1.0.0" });
  mcp.registerTool(
    "echo",
    { description: "Echo the text back", inputSchema: { text: z.string() } },
    async ({ text }) => ({ content: [{ type: "text", text: `echo: ${text}` }] })
  );
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
  await mcp.connect(transport);
  await transport.handleRequest(req, res);
});
await new Promise<void>((resolve) => http.listen(0, "127.0.0.1", resolve));
const mcpUrl = `http://127.0.0.1:${(http.address() as AddressInfo).port}/mcp`;

// In-memory session storage.
type Entry = Parameters<PiSessionStorage["append"]>[0]["entry"];
const entries = new Map<string, Entry>();
let last: string | undefined;
const sessionStorage: PiSessionStorage = {
  append: async ({ entry }) => {
    entries.set(entry.entryId, entry);
    last = entry.entryId;
  },
  appendMany: async ({ entries: many }) => {
    for (const entry of many) {
      entries.set(entry.entryId, entry);
      last = entry.entryId;
    }
  },
  read: async ({ leafId }) => {
    const path: Entry[] = [];
    for (let id = leafId ?? last; id; id = entries.get(id)?.parentEntryId) path.unshift(entries.get(id)!);
    return path;
  },
};

const agent = () =>
  new HarnessAgent({
    harness: createPi({
      auth: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY!, ANTHROPIC_BASE_URL: process.env.ANTHROPIC_BASE_URL },
      mcpServers: { demo: { url: mcpUrl, exposure: "deferred" } },
      reattachInProcess: false,
      sessionStorage,
    }),
    model: "claude-sonnet-5-5",
    instructions: "You are a test agent.",
  });

const run = async (result: { stream: ReadableStream<any> }) => {
  const tools: string[] = [];
  let text = "";
  for await (const part of result.stream) {
    if (part.type === "tool-call") tools.push(part.toolName);
    if (part.type === "text-delta") text += part.delta ?? part.text ?? "";
  }
  return { tools, text };
};

const loadouts = () =>
  [...entries.values()].flatMap(({ data }: any) =>
    data.type === "message" && data.message?.role === "system"
      ? [{
          added: (data.message.toolsAdded ?? []).map((t: any) => t.name),
          removed: (data.message.toolsRemoved ?? []).map((t: any) => t.name),
        }]
      : []
  );

const e2b = await Sandbox.create({ timeoutMs: 300_000 });
try {
  const sandboxSession = await createE2BSandbox({ sandbox: e2b }).createSession();
  const sessionId = "repro";

  // Turn 1 loads the deferred tool and calls it.
  const first = agent();
  const session1 = await first.createSession({ sessionId, sandboxSession });
  console.log("turn 1:", await run(await first.stream({
    session: session1,
    prompt: "Use tool_search to load the echo tool of the demo MCP server, then call it with the text one.",
  })));

  // Resume the same session in a new agent, as another process would.
  const resumeFrom = await session1.detach();
  const second = agent();
  const session2 = await second.createSession({ sessionId, resumeFrom, sandboxSession });

  // Turn 2 should be able to call the tool it loaded in turn 1.
  console.log("turn 2:", await run(await second.stream({
    session: session2,
    prompt: "Call the echo tool again with the text two. It is already loaded; do not search.",
  })));
  await session2.detach();
  console.log("loadout entries:", JSON.stringify(loadouts()));
} finally {
  await e2b.kill();
  http.close();
  process.exit(0);
}

AI SDK Version

  • @ai-sdk/harness: 1.0.167
  • @ai-sdk/harness-pi: 1.0.170 (the changelog up to 1.0.173 has no change for this)
  • @earendil-works/pi-coding-agent: 1.4.0
  • @e2b/ai-sdk-sandbox: 0.3.0
  • @modelcontextprotocol/sdk: 1.32.2
  • Node.js 24

Code of Conduct

  • [x] I agree to follow this project's Code of Conduct

samialdury avatar Nov 01 '26 11:11 samialdury

Identify issue type

Identified as Bug
Confidence: High

Rationale

The report identifies a concrete session-restoration failure that incorrectly removes previously loaded tools, supported by runnable reproduction code and observed output.

Evidence

  • After resuming a session from sessionStorage, a previously loaded deferred MCP tool is recorded as removed and cannot be called.
  • The reproduction shows the tool working in turn 1 but missing in turn 2, with an unexpected toolsRemoved entry.
  • Waiting for restored MCP tools to register and reactivating them fixes the reproduction.

ai-sdk-factory[bot] avatar Nov 01 '26 11:11 ai-sdk-factory[bot]

Bug discovery clarification

@samialdury, how did you discover this bug? Did you encounter it while using the AI SDK in production, find it while auditing or reviewing AI SDK source code, or discover it another way? Please describe the original discovery context.

The report demonstrates the bug but does not establish whether it was originally discovered in production, during source-code auditing, or through local experimentation. Ask the original author how they first discovered it.

ai-sdk-factory[bot] avatar Nov 01 '26 11:11 ai-sdk-factory[bot]

Found it while building an app on @ai-sdk/harness-pi with sessionStorage, during local development and testing, not from a source audit. A conversation that resumed in a new process after a restart could no longer call an MCP tool it had loaded with tool_search in an earlier turn. Inspecting the session events showed the toolsRemoved entry for that tool. The reproduction in the issue is reduced from that case. The changelogs for 1.0.171 to 1.0.173 do not mention a change to this path.

samialdury avatar Nov 02 '26 07:11 samialdury

Identify bug discovery

Discovery source: discovery:other (high confidence).

The original author explicitly clarified that the bug was discovered during local app development and testing, not production use or a source-code audit.

  • The author stated: "Found it while building an app ... during local development and testing, not from a source audit."
  • The initial failure occurred when a conversation resumed in a new process after a restart and could no longer call a previously loaded MCP tool.
  • The author inspected session events after encountering the failure and reduced that case into the reported reproduction.

ai-sdk-factory[bot] avatar Nov 02 '26 07:11 ai-sdk-factory[bot]

Thanks @samialdury, the repro made this easy to pin down.

What's happening: before the first prompt, Pi's MCP extension only waits for servers with direct tools (waitForDirectServers). When a session resumes, the tools of a deferred server that tool_search loaded earlier are restored as pending, but nothing waits for that server. They haven't registered by the time the first request is prepared, so Pi drops them as removed. The logic is the same in Pi 1.0.3 through 1.5.0.

I have a fix with tests on a branch: https://github.com/vercel/ai/compare/main...jadibdev:ai:jadibdev/harness-pi/restore-deferred-mcp-tools

  • A regression test resumes a session from a sessionStorage with the MCP server's tools/list delayed. It fails on main and passes with the fix.
  • A small harness extension waits, before the first agent loop of a resumed session, up to 10 seconds (Pi's own startup default) for the restored MCP tools to register, then re-activates them. It only covers configured servers, keeps tools that were removed earlier removed, and stops if the turn is aborted.

@gdaybrice since this is in the session-storage restore path: happy to open it as a PR. Or, if you'd rather fix it in Pi's MCP extension by also waiting for servers whose tools are pending after a restore, I can help with that instead.

jadibdev avatar Nov 04 '26 23:11 jadibdev