mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 03:24:54 +00:00
fix(core): keep the MCP SDK out of startup and type MCP errors (#66915)
This commit is contained in:
parent
59af60fbf4
commit
86de9febb9
5 changed files with 86 additions and 47 deletions
|
|
@ -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<string, unknown>
|
||||
}
|
||||
|
||||
export class NeedsAuthError extends Schema.TaggedError<NeedsAuthError>()("MCP.NeedsAuthError", {
|
||||
server: Schema.String,
|
||||
message: Schema.String,
|
||||
}) {}
|
||||
|
||||
export class ConnectError extends Schema.TaggedError<ConnectError>()("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<SessionExpiredError>()("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<EventMessage, Error>
|
||||
}
|
||||
|
||||
/** 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<SkillMismatchError>()("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. */
|
||||
|
|
|
|||
|
|
@ -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<Mcp.Status, { readonly status: "failed" | "needs_auth" }>
|
||||
|
||||
|
|
@ -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 = <A, E extends Error>(
|
||||
client: McpClient.Connection,
|
||||
run: (client: McpClient.Connection) => Effect.Effect<A, E>,
|
||||
|
|
@ -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),
|
||||
|
|
|
|||
33
packages/core/src/mcp/errors.ts
Normal file
33
packages/core/src/mcp/errors.ts
Normal file
|
|
@ -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<NeedsAuthError>()("MCP.NeedsAuthError", {
|
||||
server: Schema.String,
|
||||
message: Schema.String,
|
||||
}) {}
|
||||
|
||||
export class ConnectError extends Schema.TaggedError<ConnectError>()("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<SessionExpiredError>()("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<SkillMismatchError>()("McpClient.SkillMismatchError", {
|
||||
uri: Schema.String,
|
||||
check: Schema.Literals(["unlisted", "size", "digest", "frontmatter"]),
|
||||
message: Schema.String,
|
||||
}) {}
|
||||
|
|
@ -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 },
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -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<string, { imports: ReadonlyArray<{ path: string; kind: string; original?: string }> }>
|
||||
}
|
||||
|
||||
// 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<string, string | undefined>([[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
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue