Skip to content

mcp: hold the standalone SSE GET until the first tools/list settles (saves one TLS handshake) #239

Open

Description

@byapparov

Summary

For a remote (Streamable HTTP) MCP server, tools/list currently opens a second TCP+TLS connection on every run. Holding the standalone SSE GET until the first tools/list settles removes that handshake from the path to the first request: about −108 ms when a new connection costs 100 ms.

Why it happens

In MCP SDK 1.32.1, the client sends initialize → notifications/initialized → standalone SSE GET (fire-and-forget) → tools/list. Bun 1.4.3 fetch speaks HTTP/1.1 only, so:

  1. The GET is sent first and takes the idle keep-alive socket.
  2. tools/list has to open a new connection.

In a local stub, tools/list went out on a fresh socket in 20 of 20 runs on main, and 0 of 20 with the patch.

Change (mcp/index.ts)

  • Give the StreamableHTTP transport a fetch wrapper that delays only GET requests with Accept: text/event-stream, until the first listTools attempt succeeds or fails.
  • OAuth metadata GETs and all POSTs pass through unchanged.
  • If the transport closes in the meantime, the held GET is aborted and never sent.
  • Servers that support the stream still get exactly one GET, one round trip later.

This is within the spec, because the standalone GET is a MAY. Out of scope:

  • Skipping the GET: servers use it for list_changed.
  • Pipelining initialized with tools/list: stateful servers may reject a request that arrives before initialized.

Measurements

Measured on main @ e88ed7f432 with Bun 1.4.3. Each run was a fresh container, in-process time from process start to the first model request, median of 20 runs.

Setup main
(a) bare: no MCP, no skills 287 ms
(b) with a remote MCP server, skills and a git repo 482 ms
(b′) as (b), plus 100 ms per new TCP+TLS connection to the MCP host 678 ms

Local stub, 50 ms per MCP request:

Build 0 ms per new connection 100 ms per new connection
main 625.5 831.7
main + this change 630.7 (noise) 724.1 (−108)

The saving equals one connection setup to the MCP host. On loopback a new connection costs nothing, so there's no change there.

Risks

  • A server-to-client message on the standalone stream arrives about one round trip later. This is no more racy than today.
  • SDK coupling: the change matches the GET by method and Accept header. A test pins the request order, so an SDK change fails CI.
  • If Bun's fetch ever negotiates HTTP/2, this becomes a harmless no-op.

Tests

test/mcp/early-connect.test.ts checks the order initialize, initialized, tools/list, GET, that tools/list goes on the same socket as initialized, and that exactly one GET is sent. It fails on main.

A prototype covering this issue and its follow-up (early connect) is below. This issue is the "hold" part only: the holdStandaloneStream wrapper and its gate.

Prototype patch (S8: hold GET + early connect)
diff --git a/packages/cli/src/cli/cmd/run.ts b/packages/cli/src/cli/cmd/run.ts
index 0d23ac9dac..58af5bdc57 100644
--- a/packages/cli/src/cli/cmd/run.ts
+++ b/packages/cli/src/cli/cmd/run.ts
@@ -25,6 +25,7 @@ import { Session } from "../../session"
 import type { MessageV2 } from "../../session/message-v2"
 import { SessionPrompt } from "../../session/prompt"
 import { Command } from "../../command"
+import { MCP } from "../../mcp"
 import { GlobalBus } from "../../bus/global"
 import { Instance } from "../../project/instance"
 import { Tool } from "../../tool/tool"
@@ -1181,6 +1182,10 @@ export const RunCommand = cmd({
     HeadlessRun.enable()
     Skill.setScope({ allow: allowlist })
     const execution = bootstrap(process.cwd(), async () => {
+      // The first model request needs MCP tools. Connect now, after plugins
+      // have applied their config hooks, so the handshake overlaps session
+      // creation and prompt preparation.
+      MCP.warm()
       const sdk = {
         session: {
           async list() {
diff --git a/packages/cli/src/mcp/index.ts b/packages/cli/src/mcp/index.ts
index 9a2b04e3ed..de28e6b224 100644
--- a/packages/cli/src/mcp/index.ts
+++ b/packages/cli/src/mcp/index.ts
@@ -4,6 +4,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/
 import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
 import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
 import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
+import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"
 import {
   CallToolResultSchema,
   type Tool as MCPToolDef,
@@ -200,6 +201,47 @@ export namespace MCP {
     })
   }
 
+  /**
+   * Holds the optional standalone SSE stream (a GET to the MCP endpoint) until
+   * `released` settles. The SDK opens that stream as soon as the server accepts
+   * `notifications/initialized`, in parallel with `tools/list`. Bun's fetch uses
+   * HTTP/1.1, so the GET takes the idle keep-alive socket and `tools/list` has
+   * to open a new TCP and TLS connection. Holding the GET until the initial
+   * discovery settles keeps `tools/list` on the warm socket. Servers that offer
+   * the stream still get it, one round trip later.
+   */
+  function holdStandaloneStream(released: Promise<void>): FetchLike {
+    return async (url, init) => {
+      if (opensStandaloneStream(init)) await released
+      return fetch(url, init)
+    }
+  }
+
+  function opensStandaloneStream(init?: RequestInit) {
+    return init?.method === "GET" && new Headers(init.headers).get("accept") === "text/event-stream"
+  }
+
+  // Aborted when the instance is disposed. Connection attempts still in flight
+  // (for example from warm() on a run that exits early) then close their
+  // transport instead of holding disposal until the connect timeout.
+  const cancellation = Instance.state(
+    () => new AbortController(),
+    async (controller) => controller.abort(),
+  )
+
+  /** Runs one connection step, calling `close` if the instance is disposed before the step settles. */
+  async function untilDisposed<T>(close: () => Promise<void>, step: () => Promise<T>): Promise<T> {
+    const signal = cancellation().signal
+    signal.throwIfAborted()
+    const onAbort = () => void close().catch(() => {})
+    signal.addEventListener("abort", onAbort, { once: true })
+    try {
+      return await step()
+    } finally {
+      signal.removeEventListener("abort", onAbort)
+    }
+  }
+
   // Store transports for OAuth servers to allow finishing auth
   type TransportWithAuth = StreamableHTTPClientTransport | SSEClientTransport
   const pendingOAuthTransports = new Map<string, TransportWithAuth>()
@@ -345,6 +387,15 @@ export namespace MCP {
     return commands
   }
 
+  /**
+   * Starts connecting every configured server and discovering its tools
+   * without waiting. Later callers await the same memoized state, so nothing
+   * connects twice, and instance disposal closes or cancels what this opened.
+   */
+  export function warm() {
+    state().catch((error) => log.error("MCP warm-up failed", { error }))
+  }
+
   export async function add(name: string, mcp: Config.Mcp) {
     const s = await state()
     await disconnect(name)
@@ -385,6 +436,8 @@ export namespace MCP {
     log.info("found", { key, type: mcp.type })
     let mcpClient: MCPClient | undefined
     let status: Status | undefined = undefined
+    // Settles when the first tools/list does; see holdStandaloneStream.
+    const initialDiscovery = Promise.withResolvers<void>()
 
     if (mcp.type === "remote") {
       // OAuth is enabled by default for remote servers unless explicitly disabled with oauth: false
@@ -416,6 +469,7 @@ export namespace MCP {
           transport: new StreamableHTTPClientTransport(new URL(mcp.url), {
             authProvider,
             requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
+            fetch: holdStandaloneStream(initialDiscovery.promise),
           }),
         },
         {
@@ -435,7 +489,10 @@ export namespace MCP {
             name: "aictrl",
             version: Installation.VERSION,
           })
-          await withTimeout(client.connect(transport), connectTimeout)
+          await untilDisposed(
+            () => transport.close(),
+            () => withTimeout(client.connect(transport), connectTimeout),
+          )
           mcpClient = client
           log.info("connected", { key, transport: name })
           status = { status: "connected" }
@@ -503,7 +560,10 @@ export namespace MCP {
           name: "aictrl",
           version: Installation.VERSION,
         })
-        await withTimeout(client.connect(transport), connectTimeout)
+        await untilDisposed(
+          () => transport.close(),
+          () => withTimeout(client.connect(transport), connectTimeout),
+        )
         mcpClient = client
         status = {
           status: "connected",
@@ -548,10 +608,15 @@ export namespace MCP {
     }
 
     const cfg = await Config.get()
-    const result = await withTimeout(mcpClient.listTools(), mcp.timeout ?? DEFAULT_TIMEOUT).catch((err) => {
+    const connected = mcpClient
+    const result = await untilDisposed(
+      () => connected.close(),
+      () => withTimeout(connected.listTools(), mcp.timeout ?? DEFAULT_TIMEOUT),
+    ).catch((err) => {
       log.error("failed to get tools from client", { key, error: err })
       return undefined
     })
+    initialDiscovery.resolve()
     if (!result) {
       await mcpClient.close().catch((error) => {
         log.error("Failed to close MCP client", {
diff --git a/packages/cli/test/cli/run-mcp-discovery.test.ts b/packages/cli/test/cli/run-mcp-discovery.test.ts
index 48b863c310..8863d87da5 100644
--- a/packages/cli/test/cli/run-mcp-discovery.test.ts
+++ b/packages/cli/test/cli/run-mcp-discovery.test.ts
@@ -55,6 +55,7 @@ describe("headless MCP discovery", () => {
     async ({ notify, failure, hang, turns, code }) => {
       await using tmp = await tmpdir()
       let lists = 0
+      let initializes = 0
       let records = 0
       const requests: string[][] = []
       const descriptions: string[] = []
@@ -68,6 +69,7 @@ describe("headless MCP discovery", () => {
             const body = (await req.json()) as { id?: number; method: string; params: { protocolVersion: string } }
             if (body.method === "notifications/initialized") return new Response(null, { status: 202 })
             if (body.method === "initialize") {
+              initializes++
               return Response.json({
                 jsonrpc: "2.0",
                 id: body.id,
@@ -214,6 +216,7 @@ describe("headless MCP discovery", () => {
         expect(events.find((event) => event.type === "tool_catalog")?.tools).toContainEqual(
           expect.objectContaining({ name: "aictrl_record_finding", source: "mcp" }),
         )
+        expect(initializes, "bootstrap warm-up and tool readers share one connection").toBe(1)
         expect(lists).toBe(notify ? 2 : 1)
         expect(records).toBe(1)
         expect(descriptions).toEqual(
diff --git a/packages/cli/test/cli/run-mcp-early-connect.test.ts b/packages/cli/test/cli/run-mcp-early-connect.test.ts
new file mode 100644
index 0000000000..9282fac5a1
--- /dev/null
+++ b/packages/cli/test/cli/run-mcp-early-connect.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, test } from "bun:test"
+import path from "path"
+import { tmpdir } from "../fixture/fixture"
+
+const entry = path.resolve(import.meta.dir, "../../src/index.ts")
+const command = process.env.AICTRL_TEST_BINARY
+  ? [process.env.AICTRL_TEST_BINARY]
+  : ["bun", "run", "--conditions=browser", entry]
+
+// An MCP server whose initialize never answers, so any connection the run
+// opens stays pending until the run closes it.
+async function runAgainstHungMcp(args: readonly string[]) {
+  await using tmp = await tmpdir()
+  const requests: string[] = []
+  let aborted = 0
+  const server = Bun.serve({
+    hostname: "127.0.0.1",
+    port: 0,
+    idleTimeout: 0,
+    async fetch(req): Promise<Response> {
+      requests.push(req.method)
+      req.signal.addEventListener("abort", () => aborted++)
+      return new Promise<Response>(() => {})
+    },
+  })
+  const config = {
+    provider: {
+      fixture: {
+        npm: "@ai-sdk/openai-compatible",
+        options: { apiKey: "fixture", baseURL: "http://127.0.0.1:9/v1" },
+        models: { fixture: { name: "fixture", tool_call: true, limit: { context: 100000, output: 1000 } } },
+      },
+    },
+    mcp: { hung: { type: "remote", url: `http://127.0.0.1:${server.port}/mcp`, oauth: false, timeout: 10_000 } },
+    permission: { "*": "allow" },
+  }
+  const proc = Bun.spawn([...command, "run", ...args], {
+    cwd: tmp.path,
+    env: {
+      ...process.env,
+      AICTRL_CONFIG_CONTENT: JSON.stringify(config),
+      AICTRL_DISABLE_PROJECT_CONFIG: "true",
+      AICTRL_TEST_HOME: tmp.path,
+      AICTRL_TEST_MANAGED_CONFIG_DIR: path.join(tmp.path, "managed"),
+      XDG_DATA_HOME: path.join(tmp.path, "data"),
+      XDG_CONFIG_HOME: path.join(tmp.path, "config"),
+      XDG_STATE_HOME: path.join(tmp.path, "state"),
+      XDG_CACHE_HOME: path.join(tmp.path, "cache"),
+    },
+    stdin: "ignore",
+    stdout: "pipe",
+    stderr: "pipe",
+  })
+  const kill = setTimeout(() => proc.kill("SIGKILL"), 15000)
+  const started = performance.now()
+  try {
+    const [stdout, stderr, exit] = await Promise.all([
+      new Response(proc.stdout).text(),
+      new Response(proc.stderr).text(),
+      proc.exited,
+    ])
+    const elapsed = performance.now() - started
+    // Let the server observe the closed sockets.
+    await Bun.sleep(100)
+    return { exit, elapsed, output: stderr + stdout, requests, aborted }
+  } finally {
+    clearTimeout(kill)
+    proc.kill("SIGKILL")
+    server.stop(true)
+  }
+}
+
+describe("headless MCP early connect", () => {
+  test.each([
+    { name: "--help", args: ["--help"] },
+    { name: "an argument error", args: ["--share", "hello"] },
+  ])(
+    "$name exits without contacting MCP",
+    async ({ args }) => {
+      const result = await runAgainstHungMcp(args)
+      expect(result.requests, result.output).toEqual([])
+    },
+    20000,
+  )
+
+  test("a run that fails before its first model request closes the warm connection promptly", async () => {
+    const result = await runAgainstHungMcp(["--model", "fixture/missing", "Review this input."])
+    expect(result.exit, result.output).toBe(1)
+    expect(result.requests, "MCP connects at bootstrap, before the model is resolved").toEqual(["POST"])
+    expect(result.aborted, "the pending initialize must be closed").toBe(1)
+    expect(result.elapsed, "exit must not wait out the 10s MCP timeout").toBeLessThan(8000)
+  }, 20000)
+})
diff --git a/packages/cli/test/mcp/early-connect.test.ts b/packages/cli/test/mcp/early-connect.test.ts
new file mode 100644
index 0000000000..22b5221c6f
--- /dev/null
+++ b/packages/cli/test/mcp/early-connect.test.ts
@@ -0,0 +1,167 @@
+import { expect, test } from "bun:test"
+import path from "path"
+import { tmpdir } from "../fixture/fixture"
+
+type Mode = "healthy" | "hang-initialize" | "hang-list"
+type Seen = { method: string; rpc?: string; port: number; done?: number }
+
+// Real SDK clients run in children so unrelated transport mocks cannot leak in.
+async function run(mode: Mode, source: string, timeout = 10_000) {
+  await using tmp = await tmpdir()
+  const seen: Seen[] = []
+  let aborted = 0
+  const server = Bun.serve({
+    hostname: "127.0.0.1",
+    port: 0,
+    idleTimeout: 0,
+    async fetch(req, srv): Promise<Response> {
+      if (new URL(req.url).pathname === "/inspect") return Response.json({ seen, aborted })
+      const entry: Seen = { method: req.method, port: srv.requestIP(req)?.port ?? -1 }
+      seen.push(entry)
+      req.signal.addEventListener("abort", () => aborted++)
+      const hang = () => new Promise<Response>(() => {})
+      if (req.method !== "POST") return new Response(null, { status: 405 })
+      const body = (await req.json()) as { id?: number; method: string; params: { protocolVersion: string } }
+      entry.rpc = body.method
+      if (body.method === "notifications/initialized") return new Response(null, { status: 202 })
+      if (body.method === "initialize") {
+        if (mode === "hang-initialize") return hang()
+        return Response.json({
+          jsonrpc: "2.0",
+          id: body.id,
+          result: {
+            protocolVersion: body.params.protocolVersion,
+            capabilities: { tools: {} },
+            serverInfo: { name: "fixture", version: "1" },
+          },
+        })
+      }
+      if (body.method === "tools/list") {
+        if (mode === "hang-list") return hang()
+        await Bun.sleep(50)
+        entry.done = performance.now()
+        return Response.json({
+          jsonrpc: "2.0",
+          id: body.id,
+          result: { tools: [{ name: "record", description: "fixture", inputSchema: { type: "object" } }] },
+        })
+      }
+      return new Response(null, { status: 400 })
+    },
+  })
+  const base = `http://127.0.0.1:${server.port}`
+  await Bun.write(
+    path.join(tmp.path, "aictrl.json"),
+    JSON.stringify({ mcp: { fixture: { type: "remote", url: `${base}/mcp`, oauth: false, timeout } } }),
+  )
+  const probe = path.join(tmp.path, "probe.ts")
+  await Bun.write(
+    probe,
+    `
+    import assert from "node:assert/strict"
+    import { MCP } from ${JSON.stringify(path.resolve(import.meta.dir, "../../src/mcp/index.ts"))}
+    import { Instance } from ${JSON.stringify(path.resolve(import.meta.dir, "../../src/project/instance.ts"))}
+    const inspect = async () => (await fetch(${JSON.stringify(base)} + "/inspect")).json()
+    const wait = async (condition) => {
+      for (let i = 0; i < 300; i++) {
+        if (await condition()) return
+        await Bun.sleep(10)
+      }
+      throw new Error("Fixture condition did not become true")
+    }
+    await Instance.provide({ directory: process.cwd(), fn: async () => { ${source} } })
+  `,
+  )
+  const proc = Bun.spawn(["bun", "run", probe], {
+    cwd: tmp.path,
+    env: {
+      ...process.env,
+      AICTRL_CONFIG_CONTENT: "{}",
+      AICTRL_DISABLE_PROJECT_CONFIG: "false",
+      AICTRL_TEST_HOME: tmp.path,
+      AICTRL_TEST_MANAGED_CONFIG_DIR: path.join(tmp.path, "managed"),
+      XDG_DATA_HOME: path.join(tmp.path, "data"),
+      XDG_CONFIG_HOME: path.join(tmp.path, "config"),
+      XDG_STATE_HOME: path.join(tmp.path, "state"),
+      XDG_CACHE_HOME: path.join(tmp.path, "cache"),
+    },
+    stdout: "pipe",
+    stderr: "pipe",
+  })
+  const kill = setTimeout(() => proc.kill("SIGKILL"), 15000)
+  try {
+    const [stderr, exit] = await Promise.all([new Response(proc.stderr).text(), proc.exited])
+    expect(exit, stderr).toBe(0)
+  } finally {
+    clearTimeout(kill)
+    proc.kill("SIGKILL")
+    server.stop(true)
+  }
+}
+
+test("warm() connects once and later readers reuse that connection", async () => {
+  await run(
+    "healthy",
+    `
+    MCP.warm()
+    const [tools, entries] = await Promise.all([MCP.tools(), MCP.toolEntries()])
+    assert.deepEqual(Object.keys(tools), ["fixture_record"])
+    assert.deepEqual(entries, [{ toolKey: "fixture_record", serverName: "fixture" }])
+    const rpc = (await inspect()).seen.map((r) => r.rpc ?? r.method)
+    assert.deepEqual(rpc.filter((m) => m === "initialize" || m === "tools/list"), ["initialize", "tools/list"])
+    await Instance.dispose()
+  `,
+  )
+}, 20000)
+
+test("tools/list reuses the warm socket and the standalone SSE GET waits for it", async () => {
+  await run(
+    "healthy",
+    `
+    await MCP.tools()
+    await wait(async () => (await inspect()).seen.some((r) => r.method === "GET"))
+    const { seen } = await inspect()
+    const initialized = seen.find((r) => r.rpc === "notifications/initialized")
+    const list = seen.find((r) => r.rpc === "tools/list")
+    const get = seen.find((r) => r.method === "GET")
+    assert.deepEqual(seen.map((r) => r.rpc ?? r.method), ["initialize", "notifications/initialized", "tools/list", "GET"])
+    assert.equal(list.port, initialized.port, "tools/list must not open a new connection")
+    assert.equal(seen.filter((r) => r.method === "GET").length, 1, "the stream is still opened once")
+    assert.ok(seen.indexOf(get) > seen.indexOf(list))
+    await Instance.dispose()
+  `,
+  )
+}, 20000)
+
+for (const mode of ["hang-initialize", "hang-list"] as const) {
+  test(`disposal closes a warm connection stuck in ${mode.slice(5)} without waiting for the timeout`, async () => {
+    await run(
+      mode,
+      `
+      MCP.warm()
+      await wait(async () => (await inspect()).seen.some((r) => r.rpc === ${JSON.stringify(mode === "hang-list" ? "tools/list" : "initialize")}))
+      const started = performance.now()
+      await Instance.dispose()
+      assert.ok(performance.now() - started < 2000, "disposal must not wait out the 10s MCP timeout")
+      await wait(async () => (await inspect()).aborted >= 1)
+      const { seen } = await inspect()
+      assert.ok(!seen.some((r) => r.method === "GET"), "no fallback transport may start after disposal")
+    `,
+    )
+  }, 20000)
+}
+
+test("a hung server still times out into a failed status with no tools", async () => {
+  await run(
+    "hang-initialize",
+    `
+    assert.deepEqual(await MCP.tools(), {})
+    const status = (await MCP.status()).fixture
+    assert.equal(status.status, "failed")
+    const { seen } = await inspect()
+    assert.deepEqual(seen.map((r) => r.rpc ?? r.method), ["initialize", "GET"], "SSE fallback still runs after a timeout")
+    await Instance.dispose()
+  `,
+    300,
+  )
+}, 20000)

Activity

  1. added
    enhancement
    P3
    performance
    on Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3enhancementperformance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions