From 86de9febb90caa77fa3fcbe6930ee73bff819fbe Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:47:15 -0600 Subject: [PATCH] fix(core): keep the MCP SDK out of startup and type MCP errors (#66915) --- packages/core/src/mcp/client.ts | 38 ++++------------ packages/core/src/mcp/connection.ts | 12 +++-- packages/core/src/mcp/errors.ts | 33 ++++++++++++++ packages/core/src/plugin/mcp-skill.ts | 5 ++- .../core/test/mcp-import-boundary.test.ts | 45 +++++++++++++++---- 5 files changed, 86 insertions(+), 47 deletions(-) create mode 100644 packages/core/src/mcp/errors.ts diff --git a/packages/core/src/mcp/client.ts b/packages/core/src/mcp/client.ts index c2b39dbb8d6..c72d685c068 100644 --- a/packages/core/src/mcp/client.ts +++ b/packages/core/src/mcp/client.ts @@ -51,8 +51,16 @@ import { isRecord } from "@opencode/util/record" import { codecFor } from "../tool/runtime.js" import { McpStdio } from "./stdio.js" import { EventStreamRejectedError, EventStreamTerminatedError, reopen } from "./event-stream.js" +import { ConnectError, NeedsAuthError, SessionExpiredError, SkillMismatchError } from "./errors.js" -export { EventStreamRejectedError, EventStreamTerminatedError } +export { + ConnectError, + EventStreamRejectedError, + EventStreamTerminatedError, + NeedsAuthError, + SessionExpiredError, + SkillMismatchError, +} const DEFAULT_STARTUP_TIMEOUT = 30_000 const DEFAULT_CATALOG_TIMEOUT = 30_000 @@ -191,27 +199,6 @@ export interface Tool { readonly _meta?: Record } -export class NeedsAuthError extends Schema.TaggedError()("MCP.NeedsAuthError", { - server: Schema.String, - message: Schema.String, -}) {} - -export class ConnectError extends Schema.TaggedError()("MCP.ConnectError", { - server: Schema.String, - message: Schema.String, - /** The server was reached but refused or broke the handshake, so different connect options might succeed. */ - answered: Schema.optional(Schema.Boolean), -}) {} - -/** A legacy Streamable HTTP server no longer recognizes this connection's session; the lifecycle reconnects. */ -export class SessionExpiredError extends Schema.TaggedError()("MCP.SessionExpiredError", { - server: Schema.String, -}) { - override get message() { - return `MCP server session expired: ${this.server}` - } -} - export type CallToolContent = | { readonly type: "text"; readonly text: string } | { readonly type: "media"; readonly data: string; readonly mimeType: string; readonly uri?: string } @@ -320,13 +307,6 @@ export interface Events { }) => Stream.Stream } -/** A skill file the server served doesn't match its entry: not listed, or a different size, digest or frontmatter. */ -export class SkillMismatchError extends Schema.TaggedError()("McpClient.SkillMismatchError", { - uri: Schema.String, - check: Schema.Literals(["unlisted", "size", "digest", "frontmatter"]), - message: Schema.String, -}) {} - /** Experimental: MCP Skills is a beta extension; may change without compatibility guarantees. */ export interface Skills { /** Every valid skill the server lists (`skills/list`); invalid entries are logged and skipped. No file is read. */ diff --git a/packages/core/src/mcp/connection.ts b/packages/core/src/mcp/connection.ts index 32687d4a55f..424563c3037 100644 --- a/packages/core/src/mcp/connection.ts +++ b/packages/core/src/mcp/connection.ts @@ -7,6 +7,7 @@ import { FetchHttpClient } from "effect/http" import { Environment } from "../environment/index.js" import { KeyedMutex } from "../effect/keyed-mutex.js" import type { McpClient } from "./client.js" +import { McpError } from "./errors.js" export type Failure = Extract @@ -178,9 +179,6 @@ export function make(input: Input): Connection { yield* input.events.failed({ status: "needs_auth", error: message }, false) }).pipe(input.lock) - // The client module is loaded lazily, so match its tagged errors by tag rather than class. - const tagged = (error: Error, tag: string) => "_tag" in error && error._tag === tag - const recovering = ( client: McpClient.Connection, run: (client: McpClient.Connection) => Effect.Effect, @@ -189,12 +187,12 @@ export function make(input: Input): Connection { const attempt = (target: McpClient.Connection) => run(target).pipe( Effect.tapError((error) => - tagged(error, "MCP.NeedsAuthError") ? refused(target, error.message) : Effect.void, + error instanceof McpError.NeedsAuthError ? refused(target, error.message) : Effect.void, ), ) return attempt(client).pipe( Effect.catchIf( - (error) => tagged(error, "MCP.SessionExpiredError"), + (error) => error instanceof McpError.SessionExpiredError, (error) => recover(client).pipe(Effect.flatMap(() => (state.client ? attempt(state.client) : Effect.fail(error)))), ), @@ -271,10 +269,10 @@ export function make(input: Input): Connection { state.scope = undefined const error = Cause.squash(result.cause) yield* input.events.failed( - error instanceof McpClient.NeedsAuthError + error instanceof McpError.NeedsAuthError ? { status: "needs_auth", error: error.message } : { status: "failed", error: error instanceof Error ? error.message : String(error) }, - error instanceof McpClient.ConnectError && error.answered === true, + error instanceof McpError.ConnectError && error.answered === true, ) }).pipe( Effect.ensuring(input.events.settled), diff --git a/packages/core/src/mcp/errors.ts b/packages/core/src/mcp/errors.ts new file mode 100644 index 00000000000..8f9230eece5 --- /dev/null +++ b/packages/core/src/mcp/errors.ts @@ -0,0 +1,33 @@ +export * as McpError from "./errors.js" + +import { Schema } from "effect" + +// Kept free of the MCP SDK so modules that load at startup can match these errors without loading it. + +export class NeedsAuthError extends Schema.TaggedError()("MCP.NeedsAuthError", { + server: Schema.String, + message: Schema.String, +}) {} + +export class ConnectError extends Schema.TaggedError()("MCP.ConnectError", { + server: Schema.String, + message: Schema.String, + /** The server was reached but refused or broke the handshake, so different connect options might succeed. */ + answered: Schema.optional(Schema.Boolean), +}) {} + +/** A legacy Streamable HTTP server no longer recognizes this connection's session; the lifecycle reconnects. */ +export class SessionExpiredError extends Schema.TaggedError()("MCP.SessionExpiredError", { + server: Schema.String, +}) { + override get message() { + return `MCP server session expired: ${this.server}` + } +} + +/** A skill file the server served doesn't match its entry: not listed, or a different size, digest or frontmatter. */ +export class SkillMismatchError extends Schema.TaggedError()("McpClient.SkillMismatchError", { + uri: Schema.String, + check: Schema.Literals(["unlisted", "size", "digest", "frontmatter"]), + message: Schema.String, +}) {} diff --git a/packages/core/src/plugin/mcp-skill.ts b/packages/core/src/plugin/mcp-skill.ts index 699b7e0a73d..c29a985907d 100644 --- a/packages/core/src/plugin/mcp-skill.ts +++ b/packages/core/src/plugin/mcp-skill.ts @@ -4,7 +4,8 @@ import { define } from "@opencode/plugin/effect/plugin" import { Hash } from "@opencode/util/hash" import { Effect, Stream } from "effect" import { Bus } from "../bus.js" -import { McpClient } from "../mcp/client.js" +import type { McpClient } from "../mcp/client.js" +import { McpError } from "../mcp/errors.js" import { Mcp } from "../mcp/index.js" import { AbsolutePath } from "../schema.js" import { Skill } from "../skill.js" @@ -63,7 +64,7 @@ export const Plugin = define({ new Skill.LoadError({ skill: id, reason: - error instanceof McpClient.SkillMismatchError + error instanceof McpError.SkillMismatchError ? { _tag: "Mismatch", file: file ?? Skill.manifest, check: error.check, detail: error.message } : { _tag: "Unavailable", file: file ?? Skill.manifest, detail: error.message }, }), diff --git a/packages/core/test/mcp-import-boundary.test.ts b/packages/core/test/mcp-import-boundary.test.ts index c48b5bde092..cbbb69eb614 100644 --- a/packages/core/test/mcp-import-boundary.test.ts +++ b/packages/core/test/mcp-import-boundary.test.ts @@ -3,6 +3,9 @@ import { mkdtemp, rm } from "node:fs/promises" import path from "node:path" const root = path.resolve(import.meta.dir, "../../..") +const mcp = "packages/core/src/mcp/index.ts" +// Every built-in plugin loads at Location startup, whether or not any MCP server is configured. +const plugins = "packages/core/src/plugin/internal.ts" test("loads the MCP SDK only when connecting or authorizing", async () => { const temporary = await mkdtemp(path.join(import.meta.dir, ".mcp-import-boundary-")) @@ -12,7 +15,8 @@ test("loads the MCP SDK only when connecting or authorizing", async () => { [ process.execPath, "build", - "packages/core/src/mcp/index.ts", + mcp, + plugins, "--target=node", "--format=esm", "--packages=bundle", @@ -29,16 +33,39 @@ test("loads the MCP SDK only when connecting or authorizing", async () => { ]) if (exitCode !== 0) throw new Error(stdout + stderr) - const metadata = await Bun.file(metafile).json() - const imports = metadata.inputs["packages/core/src/mcp/index.ts"].imports - const lazy = imports.filter( - (item: { original?: string }) => item.original === "./client.js" || item.original === "./oauth.js", + const metadata: Metafile = await Bun.file(metafile).json() + const lazy = metadata.inputs[mcp].imports.filter( + (item) => item.original === "./client.js" || item.original === "./oauth.js", ) - expect(new Set(lazy.map((item: { original: string }) => item.original))).toEqual( - new Set(["./client.js", "./oauth.js"]), - ) - expect(lazy.every((item: { kind: string }) => item.kind === "dynamic-import")).toBe(true) + expect(new Set(lazy.map((item) => item.original))).toEqual(new Set(["./client.js", "./oauth.js"])) + expect(lazy.every((item) => item.kind === "dynamic-import")).toBe(true) + expect(sdkChain(metadata, mcp)).toBeUndefined() + expect(sdkChain(metadata, plugins)).toBeUndefined() } finally { await rm(temporary, { recursive: true, force: true }) } }) + +type Metafile = { + inputs: Record }> +} + +// The static import chain from entry to the first MCP SDK module it loads, or undefined when it loads none. +function sdkChain(metadata: Metafile, entry: string) { + const parents = new Map([[entry, undefined]]) + const pending = [entry] + while (pending.length > 0) { + const current = pending.pop()! + if (current.includes("@modelcontextprotocol")) { + const chain = [current] + while (parents.get(chain[0]!)) chain.unshift(parents.get(chain[0]!)!) + return chain + } + for (const item of metadata.inputs[current]?.imports ?? []) { + if (item.kind === "dynamic-import" || parents.has(item.path)) continue + parents.set(item.path, current) + pending.push(item.path) + } + } + return undefined +}