diff --git a/packages/core/src/mcp/client.ts b/packages/core/src/mcp/client.ts index c72d685c068..d7d09aa03be 100644 --- a/packages/core/src/mcp/client.ts +++ b/packages/core/src/mcp/client.ts @@ -50,6 +50,7 @@ import type { Session } from "@opencode/schema/session" import { isRecord } from "@opencode/util/record" import { codecFor } from "../tool/runtime.js" import { McpStdio } from "./stdio.js" +import { McpTarget } from "./target.js" import { EventStreamRejectedError, EventStreamTerminatedError, reopen } from "./event-stream.js" import { ConnectError, NeedsAuthError, SessionExpiredError, SkillMismatchError } from "./errors.js" @@ -330,7 +331,7 @@ export interface Attached { export interface ConnectOptions { readonly server: string - readonly config: typeof ConfigMCP.Server.Type | Attached + readonly target: McpTarget.Target | Attached /** Resolves a relative stdio `cwd` and is the default one, and is the root `roots/list` answers with. */ readonly directory: string /** Remote only. A 401 the provider cannot recover from ends in UnauthorizedError → needs_auth. */ @@ -352,13 +353,13 @@ export interface ConnectOptions { */ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) { const server = options.server - const config = options.config + const target = options.target const elicitation = options.elicitation // The SDK takes list-changed handlers at construction, but consumers register after connect. On a // modern connection the SDK opens the subscriptions/listen stream behind these itself. const timeout: (typeof ConfigMCP.Server.Type)["timeout"] = - config.type === "attached" ? { execution: ATTACHED_EXECUTION_TIMEOUT } : config.timeout - const protocol = config.protocol ?? (config.type === "attached" ? "legacy" : "auto") + target.type === "attached" ? { execution: ATTACHED_EXECUTION_TIMEOUT } : target.config.timeout + const protocol = target.type === "attached" ? (target.protocol ?? "legacy") : (target.config.protocol ?? "auto") const changed = { tools: () => {}, prompts: () => {}, resources: () => {} } const listChanged = (key: keyof typeof changed) => ({ autoRefresh: false, @@ -537,18 +538,18 @@ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) { } const exit = yield* Effect.gen(function* () { - if (config.type === "attached") return yield* initialize(config.transport, protocol) - if (config.type === "local") { - const [command, ...args] = config.command + if (target.type === "attached") return yield* initialize(target.transport, protocol) + if (target.type === "local") { + const command = target.command const spawn = (protocol: ConfigMCP.Protocol) => McpStdio.make({ server, command, - args, - cwd: McpStdio.resolveCwd(options.directory, config.cwd), + args: target.args, + cwd: McpStdio.resolveCwd(options.directory, target.config.cwd), environment: { ...(command === "opencode" ? { BUN_BE_BUN: "1" } : {}), - ...config.environment, + ...target.config.environment, }, }).pipe(Effect.flatMap((transport) => initialize(transport, protocol))) // Some legacy servers exit on the auto probe's unknown request (Python SDK 1.3 does), so respawn for initialize. @@ -566,14 +567,10 @@ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) { } const { McpOAuth } = yield* Effect.promise(() => import("./oauth.js")) const fetch = yield* McpOAuth.loggedFetch({ server, directory: options.directory }) - // Servers that bundle their own Code Mode (Cloudflare and others) expose raw tools when asked - // with ?codemode=false, which is what our Code Mode wants. The configured URL stays the OAuth identity. - const url = new URL(config.url) - const addedCodemode = config.codemode !== false && !url.searchParams.has("codemode") && !rejectsUnknownQuery(url) - if (addedCodemode) url.searchParams.set("codemode", "false") + const dialed = McpTarget.dialUrl(target.url, target.config.codemode) const open = Effect.fnUntraced(function* (url: URL, protocol: ConfigMCP.Protocol, startup?: number) { session.transport = new StreamableHTTPClientTransport(url, { - requestInit: config.headers ? { headers: config.headers } : undefined, + requestInit: target.config.headers ? { headers: target.config.headers } : undefined, authProvider: options.authProvider, fetch, }) @@ -601,12 +598,12 @@ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) { return yield* retrying( "MCP connect", - negotiate(url).pipe( + negotiate(dialed ?? target.url).pipe( Effect.catch((error) => { - if (!addedCodemode || !(error instanceof SdkHttpError) || (error.status !== 400 && error.status !== 404)) + if (!dialed || !(error instanceof SdkHttpError) || (error.status !== 400 && error.status !== 404)) return Effect.fail(error) // Servers that reject unknown query params get one retry at the configured URL. - return negotiate(new URL(config.url)) + return negotiate(target.url) }), ), deadline, @@ -1071,17 +1068,6 @@ function repeats(error: unknown): boolean { ) } -// These servers reject any unknown query parameter and have no Code Mode of their own, so adding -// ?codemode=false only costs a failed request before the retry at the configured URL. -function rejectsUnknownQuery(url: URL) { - // Google Workspace MCP (gmailmcp, drivemcp, calendarmcp, ...) returns 404. - if (url.hostname.endsWith(".googleapis.com")) return true - // Zoho MCP gateways (zohomcp.com, zohomcp.eu, ...) return 400. - if (/(^|\.)zohomcp\.[a-z.]+$/.test(url.hostname)) return true - // Loopback servers run on this machine (Figma Desktop's Dev Mode MCP returns 404), so they are not hosted Code Mode servers. - return url.hostname === "localhost" || url.hostname === "[::1]" || /^127(\.\d+){3}$/.test(url.hostname) -} - // Legacy sends the plain initialize handshake with no discover probe. function negotiation(protocol: ConfigMCP.Protocol, startup: number): VersionNegotiationOptions | undefined { if (protocol === "legacy") return undefined diff --git a/packages/core/src/mcp/connection.ts b/packages/core/src/mcp/connection.ts index 44e8fac400c..efeeda3f5a3 100644 --- a/packages/core/src/mcp/connection.ts +++ b/packages/core/src/mcp/connection.ts @@ -8,6 +8,7 @@ import { Environment } from "../environment/index.js" import { KeyedMutex } from "../effect/keyed-mutex.js" import type { McpClient } from "./client.js" import { McpError } from "./errors.js" +import type { McpTarget } from "./target.js" export type Failure = Extract @@ -45,7 +46,7 @@ export interface Events { /** Everything about the server to connect to and what capabilities to negotiate with it. */ export interface Spec { readonly name: string - readonly config: Mcp.ServerConfig + readonly target: McpTarget.Target readonly directory: string readonly clientInfo?: { readonly name: string; readonly version: string } /** Lists the server's MCP Skills when it offers them. */ @@ -136,6 +137,21 @@ type Opened = | { readonly _tag: "Legacy"; readonly client: McpClient.Connection } | { readonly _tag: "Listed"; readonly client: McpClient.Connection; readonly tools: ReadonlyArray } +/** A server whose config could not be parsed: every attempt fails with the reason, and nothing ever connects. */ +export const invalid = (events: Events, error: McpError.InvalidConfigError): Connection => ({ + client: undefined, + tools: undefined, + prompts: undefined, + skills: undefined, + start: events.connecting.pipe( + Effect.andThen(events.failed({ status: "failed", error: error.message }, false)), + Effect.ensuring(events.settled), + ), + stop: Effect.void, + recovering: (client, run) => run(client), + catalog: readCatalog, +}) + export function make(input: Input): Connection { let state: State = { _tag: "Idle" } const current = (): Connected | undefined => { @@ -237,10 +253,7 @@ export function make(input: Input): Connection { const start: Effect.Effect = Effect.suspend(() => Effect.gen(function* () { yield* input.events.connecting - // Checked before the OAuth provider is built, which parses the URL too. - const config = input.spec.config - if (config.type === "remote" && !URL.canParse(config.url)) - return yield* input.events.failed({ status: "failed", error: `Invalid MCP server URL: ${config.url}` }, false) + const target = input.spec.target // The attempt owns its scope until a connection takes it over, and closes it on any other exit, interruption // included, before the outcome is reported. const result = yield* Effect.acquireUseRelease( @@ -270,7 +283,9 @@ export function make(input: Input): Connection { Effect.provideService(FetchHttpClient.Fetch, input.fetch), Scope.provide(scope), (effect) => - config.type === "remote" && !input.shared ? input.endpointLoads.withLock(config.url)(effect) : effect, + target.type === "remote" && !input.shared + ? input.endpointLoads.withLock(target.config.url)(effect) + : effect, ) switch (opened._tag) { case "Legacy": diff --git a/packages/core/src/mcp/errors.ts b/packages/core/src/mcp/errors.ts index 8f9230eece5..b20166027b2 100644 --- a/packages/core/src/mcp/errors.ts +++ b/packages/core/src/mcp/errors.ts @@ -9,6 +9,12 @@ export class NeedsAuthError extends Schema.TaggedError()("MCP.Ne message: Schema.String, }) {} +/** A server's config can't be used as written, so it is never connected or offered for sign-in. */ +export class InvalidConfigError extends Schema.TaggedError()("MCP.InvalidConfigError", { + server: Schema.String, + message: Schema.String, +}) {} + export class ConnectError extends Schema.TaggedError()("MCP.ConnectError", { server: Schema.String, message: Schema.String, diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index 8946379110b..eebf639b41b 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -18,6 +18,7 @@ import { Latch, Layer, Queue, + Result, Schedule, Schema, Scope, @@ -44,7 +45,9 @@ import type { McpClient } from "./client.js" import { EventStreamRejectedError, EventStreamTerminatedError, reopen } from "./event-stream.js" import { canonicalJson } from "../util/canonical-json.js" import { McpConnection } from "./connection.js" +import type { McpError } from "./errors.js" import { McpPool } from "./pool.js" +import { McpTarget } from "./target.js" export const ServerName = Schema.String.pipe(Schema.brand("MCP.ServerName")) export type ServerName = typeof ServerName.Type @@ -133,6 +136,7 @@ type Transition = type ServerEntry = { readonly config: Mcp.ServerConfig + readonly target: Result.Result phase: Phase readonly startup: Latch.Latch readonly connection: McpConnection.Connection @@ -143,6 +147,10 @@ type ServerEntry = { registration?: State.Registration } +// Only a remote server whose config parsed can sign in. +const remoteTarget = (entry: ServerEntry) => + Result.isSuccess(entry.target) && entry.target.success.type === "remote" ? entry.target.success : undefined + const next = (phase: Phase, transition: Transition): Phase => { switch (transition._tag) { case "Connecting": @@ -633,14 +641,14 @@ export const layer = (options?: Options) => // Register every remote server as an OAuth integration so credentials live in the global store // rather than in committed config. Servers that connect anonymously simply never use the method. const register = Effect.fnUntraced(function* (name: ServerName, entry: ServerEntry) { - if (entry.config.type !== "remote" || entry.config.oauth === false) return - const remote = entry.config + const target = remoteTarget(entry) + if (!target || target.config.oauth === false) return // Key identity on name + url, not url alone: two configs for the same url under different names are // distinct logical servers that may hold different accounts, so they must not share a credential row. const suffix = "mcp_" + createHash("sha1") - .update(name + "\u0000" + remote.url) + .update(name + "\u0000" + target.config.url) .digest("hex") .slice(0, 16) const integrationID = Integration.ID.make(suffix) @@ -663,7 +671,7 @@ export const layer = (options?: Options) => authorize: () => Effect.gen(function* () { const { McpOAuth } = yield* Effect.promise(() => import("./oauth.js")) - return yield* McpOAuth.authorize({ name, config: remote, integrationID, methodID }).pipe( + return yield* McpOAuth.authorize({ name, target, integrationID, methodID }).pipe( Effect.provideService(Credential.Service, credentials), Effect.provideService(FetchHttpClient.Fetch, fetch), ) @@ -695,9 +703,10 @@ export const layer = (options?: Options) => entry: ServerEntry, credential: Credential.Info | undefined, ) { - if (entry.config.type !== "remote" || !entry.integrationID) return undefined + const target = remoteTarget(entry) + if (!target || !entry.integrationID) return undefined const { McpOAuth } = yield* Effect.promise(() => import("./oauth.js")) - return yield* McpOAuth.connectProvider({ server: name, config: entry.config, credential }).pipe( + return yield* McpOAuth.connectProvider({ server: name, target, credential }).pipe( Effect.provideService(Credential.Service, credentials), Effect.provideService(FetchHttpClient.Fetch, fetch), ) @@ -785,14 +794,7 @@ export const layer = (options?: Options) => config.pool === true && config.protocol !== "legacy" && (config.type === "remote" || environment.local === true) - const base: Omit = { - spec: { - name, - config, - directory: location.directory, - clientInfo: options?.clientInfo, - skills, - }, + const base: Omit = { authProvider: Effect.suspend(() => selectCredential(entry).pipe(Effect.flatMap((credential) => connectProvider(name, entry, credential))), ), @@ -843,18 +845,16 @@ export const layer = (options?: Options) => changed: (kind) => bus.publish(changes[kind], { server: name }), }, } - const entry: ServerEntry = { - config, - phase: { _tag: "Starting", started, settled: Latch.makeUnsafe() }, - startup: Latch.makeUnsafe(), - connection: pooled + const connection = (spec: McpConnection.Spec) => + pooled ? pool.connection({ ...base, + spec, select: Effect.gen(function* () { - if (base.spec.config.type === "remote") { + if (spec.target.type === "remote") { const credential = yield* selectCredential(entry) return { - key: McpPool.key({ ...base.spec, config: base.spec.config, credential: credential?.id }), + key: McpPool.key({ ...spec, config: spec.target.config, credential: credential?.id }), authProvider: connectProvider(name, entry, credential), } } @@ -862,15 +862,30 @@ export const layer = (options?: Options) => const { McpStdio } = yield* Effect.promise(() => import("./stdio.js")) return { key: McpPool.key({ - ...base.spec, - config: base.spec.config, - cwd: McpStdio.resolveCwd(base.spec.directory, base.spec.config.cwd), + ...spec, + config: spec.target.config, + cwd: McpStdio.resolveCwd(spec.directory, spec.target.config.cwd), }), authProvider: base.authProvider, } }), }) - : McpConnection.make({ ...base, endpointLoads: pool.endpointLoads }), + : McpConnection.make({ ...base, spec, endpointLoads: pool.endpointLoads }) + const target = McpTarget.parse(name, config) + const entry: ServerEntry = { + config, + target, + phase: { _tag: "Starting", started, settled: Latch.makeUnsafe() }, + startup: Latch.makeUnsafe(), + connection: Result.isFailure(target) + ? McpConnection.invalid(base.events, target.failure) + : connection({ + name, + target: target.success, + directory: location.directory, + clientInfo: options?.clientInfo, + skills, + }), } return entry } @@ -997,7 +1012,7 @@ export const layer = (options?: Options) => let closed = false const result = yield* McpClient.connect({ server: name, - config: { type: "attached", transport }, + target: { type: "attached", transport }, directory: location.directory, elicitation, clientInfo: options?.clientInfo, diff --git a/packages/core/src/mcp/oauth.ts b/packages/core/src/mcp/oauth.ts index 3aab3d03da1..47530793746 100644 --- a/packages/core/src/mcp/oauth.ts +++ b/packages/core/src/mcp/oauth.ts @@ -26,12 +26,12 @@ import { Cause, Clock, Data, Deferred, Duration, Effect, Exit, Option, Schema } import { FetchHttpClient } from "effect/http" import type { ServerResponse } from "node:http" import type { AddressInfo } from "node:net" -import { ConfigMCP } from "@opencode/schema/config/mcp" import { Credential } from "../credential.js" import { OauthCallbackPage } from "../oauth/page.js" import { OauthRedirect } from "../oauth/redirect.js" import type { Integration } from "../integration.js" import { ErrorSummary } from "../util/error-summary.js" +import { McpTarget } from "./target.js" /** Client ID Metadata Document: servers that support CIMD accept this URL as the client_id without registration. */ export const CLIENT_METADATA_URL = "https://opencode.ai/oauth/opencode/client.json" @@ -109,19 +109,18 @@ export const loggedFetch = (fields: { readonly server: string; readonly director // A configured authorization server document stands in for RFC 9728 discovery: the SDK reuses this // state instead of probing the resource server, whose well-known path may not exist. const configuredDiscovery = async (input: { - readonly config: typeof ConfigMCP.Remote.Type + readonly target: McpTarget.Remote readonly fetchFn: FetchLike }): Promise => { - const url = input.config.oauth ? input.config.oauth.auth_server_metadata_url : undefined - if (!url) return undefined - const response = await input.fetchFn(url, { headers: { accept: "application/json" } }) + if (!input.target.metadata) return undefined + const response = await input.fetchFn(input.target.metadata, { headers: { accept: "application/json" } }) if (!response.ok) throw new Error(`HTTP ${response.status} trying to load OAuth authorization server metadata`) const body = await response.json() const metadata = OAuthMetadataSchema.safeParse(body).data ?? OpenIdProviderDiscoveryMetadataSchema.parse(body) return { authorizationServerUrl: metadata.issuer, authorizationServerMetadata: metadata, - resourceMetadata: { resource: resourceUrlFromServerUrl(input.config.url).toString() }, + resourceMetadata: { resource: resourceUrlFromServerUrl(input.target.url).toString() }, } } @@ -135,7 +134,7 @@ const slashOnly = (error: unknown): error is IssuerMismatchError => error.expected.replace(/\/$/, "") === error.received.replace(/\/$/, "") // Without validation any issuer passes, so the retry holds it to the one the failed check reported. -const discover = (serverUrl: string, options: { readonly resourceMetadataUrl?: URL; readonly fetchFn: FetchLike }) => +const discover = (serverUrl: URL, options: { readonly resourceMetadataUrl?: URL; readonly fetchFn: FetchLike }) => discoverOAuthServerInfo(serverUrl, options).catch(async (error: unknown) => { if (!slashOnly(error)) throw error const info = await discoverOAuthServerInfo(serverUrl, { ...options, skipIssuerMetadataValidation: true }) @@ -164,7 +163,7 @@ interface Store { } interface Options { - readonly config: typeof ConfigMCP.Remote.Type + readonly target: McpTarget.Remote readonly store: Store readonly redirect: { readonly url: () => string @@ -177,7 +176,7 @@ interface Options { } const provider = (options: Options): OAuthClientProvider => { - const oauth = options.config.oauth || undefined + const oauth = options.target.config.oauth || undefined const client = oauth?.client_id ? { client_id: oauth.client_id, client_secret: oauth.client_secret } : undefined const redirect = options.redirect let discovery = options.discovery @@ -189,7 +188,7 @@ const provider = (options: Options): OAuthClientProvider => { saveDiscoveryState: (state) => { discovery = state }, - validateResourceURL: async (_serverUrl, resource) => selectResource(options.config, resource), + validateResourceURL: async (_serverUrl, resource) => selectResource(options.target, resource), ...(options.clientMetadataUrl ? { clientMetadataUrl: options.clientMetadataUrl } : {}), state: () => redirect.state, clientMetadata: { @@ -209,7 +208,7 @@ const provider = (options: Options): OAuthClientProvider => { redirectToAuthorization: (url) => { if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error( - `MCP server "${options.config.url}" returned a ${url.protocol} authorization URL; only http and https are supported`, + `MCP server "${options.target.config.url}" returned a ${url.protocol} authorization URL; only http and https are supported`, ) // Google issues a refresh token only when asked with its own access_type, not the offline_access scope. if (url.hostname === "accounts.google.com" && !url.searchParams.has("access_type")) @@ -227,24 +226,13 @@ const provider = (options: Options): OAuthClientProvider => { // The SDK sends no RFC 8707 resource when the server publishes no resource metadata; some // authorization servers require one, so fall back to the configured URL. -const selectResource = (config: typeof ConfigMCP.Remote.Type, resource: string | undefined) => { - const identity = new URL(config.url) +const selectResource = (target: McpTarget.Remote, resource: string | undefined) => { + const identity = new URL(target.url) identity.hash = "" if (!resource) return identity if (!checkResourceAllowed({ requestedResource: identity, configuredResource: resource })) throw new Error(`Protected resource ${resource} does not cover ${identity}`) - const canonical = new URL(resource) - // The transport adds ?codemode=false when dialing and some servers echo that query back as - // the protected resource. Strip only that transport parameter so refresh names the same - // resource login did, without overwriting a queryless canonical resource with config.url. - if ( - canonical.origin === identity.origin && - canonical.pathname === identity.pathname && - canonical.searchParams.has("codemode") && - !identity.searchParams.has("codemode") - ) - canonical.searchParams.delete("codemode") - return canonical + return McpTarget.withoutDialParams(new URL(resource), identity) } const memoryStore = (): Store => { @@ -327,7 +315,7 @@ const toCredential = (input: { */ export const connectProvider = Effect.fnUntraced(function* (input: { readonly server: string - readonly config: typeof ConfigMCP.Remote.Type + readonly target: McpTarget.Remote readonly credential: Credential.Info | undefined }): Effect.fn.Return { const found = input.credential @@ -342,7 +330,7 @@ export const connectProvider = Effect.fnUntraced(function* (input: { credentials.refresh(id, { stale, refresh: (current) => - exchange({ config: input.config, fetchFn, current, resourceMetadataUrl }).pipe( + exchange({ target: input.target, fetchFn, current, resourceMetadataUrl }).pipe( Effect.tapError((error) => error instanceof RefreshRejected ? Effect.logWarning("mcp oauth credential invalidated", { credentialID: id, reason: error.message }).pipe( @@ -353,7 +341,7 @@ export const connectProvider = Effect.fnUntraced(function* (input: { ), }) const due = (current: Credential.OAuth, now: number) => Credential.expiring(current, now, REFRESH_AHEAD) - const refused = () => new UnauthorizedError(`MCP server "${input.config.url}" requires user authorization`) + const refused = () => new UnauthorizedError(`MCP server "${input.target.config.url}" requires user authorization`) // The token last sent. A 401 refreshes only while the row still holds it: another connection or process may // have refreshed it already. let presented: string | undefined @@ -407,7 +395,7 @@ export const connectProvider = Effect.fnUntraced(function* (input: { // Refreshes with the discovery the login saved, or discovers as the login did and saves the result. const exchange = (input: { - readonly config: typeof ConfigMCP.Remote.Type + readonly target: McpTarget.Remote readonly fetchFn: FetchLike readonly current: Credential.OAuth readonly resourceMetadataUrl: URL | undefined @@ -421,13 +409,13 @@ const exchange = (input: { throw new Error(`HTTP ${response.status}`) return response } - const oauth = input.config.oauth || undefined + const oauth = input.target.config.oauth || undefined const client = oauth?.client_id ? { client_id: oauth.client_id, client_secret: oauth.client_secret } : clientFromCredential(input.current) if (!client) throw new RefreshRejected({ message: "no OAuth client information" }) const saved = discoveryFromCredential(input.current) - const configured = await configuredDiscovery({ config: input.config, fetchFn }) + const configured = await configuredDiscovery({ target: input.target, fetchFn }) const server = configured ?? (saved @@ -436,12 +424,12 @@ const exchange = (input: { authorizationServerMetadata: await discoverMetadata(saved.authorizationServer, fetchFn), resourceMetadata: undefined, } - : await discover(input.config.url, { resourceMetadataUrl: input.resourceMetadataUrl, fetchFn })) + : await discover(input.target.url, { resourceMetadataUrl: input.resourceMetadataUrl, fetchFn })) const found = server.authorizationServerMetadata?.issuer ?? server.authorizationServerUrl const issuer = input.current.metadata?.issuer if (typeof issuer === "string" && found.replace(/\/$/, "") !== issuer.replace(/\/$/, "")) throw new IssuerChanged({ message: `issued by ${issuer}, but discovery names ${found}` }) - const resource = saved?.resource ?? selectResource(input.config, server.resourceMetadata?.resource).toString() + const resource = saved?.resource ?? selectResource(input.target, server.resourceMetadata?.resource).toString() // Some authorization servers (Microsoft Entra ID) refuse a refresh that names no scope. const scope = typeof input.current.metadata?.scope === "string" ? input.current.metadata.scope : oauth?.scope const tokens = await refreshAuthorization(server.authorizationServerUrl, { @@ -454,7 +442,7 @@ const exchange = (input: { }) return toCredential({ methodID: input.current.methodID, - serverUrl: input.config.url, + serverUrl: input.target.config.url, tokens: { refresh_token: input.current.refresh, ...tokens, @@ -476,7 +464,7 @@ const exchange = (input: { export const authorize = (input: { readonly name: string - readonly config: typeof ConfigMCP.Remote.Type + readonly target: McpTarget.Remote readonly integrationID: Integration.ID readonly methodID: Integration.MethodID }) => @@ -488,7 +476,7 @@ export const authorize = (input: { const credentials = yield* Credential.Service const fetchFn = yield* loggedFetch({ server: input.name }).pipe(Effect.annotateLogs(fields)) yield* Effect.logInfo("mcp oauth authorization started", fields) - const oauth = input.config.oauth || undefined + const oauth = input.target.config.oauth || undefined const store = memoryStore() const previous = (yield* credentials.list(input.integrationID)).at(-1)?.value const registeredClient = previous?.type === "oauth" ? clientFromCredential(previous) : undefined @@ -496,7 +484,7 @@ export const authorize = (input: { { code: string; iss: string | undefined; host?: string; response?: ServerResponse }, Error >() - const redirect = oauth?.redirect_uri ? new URL(oauth.redirect_uri) : undefined + const redirect = input.target.redirect const redirectPath = redirect?.pathname ?? "/callback" const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url") @@ -565,10 +553,10 @@ export const authorize = (input: { // The server's 401 names where its resource metadata lives and which scopes it wants; without it // discovery can only guess the well-known path, which not every server layout answers. const challenge = yield* Effect.tryPromise((signal) => - fetchFn(input.config.url, { + fetchFn(input.target.url, { method: "POST", headers: { - ...input.config.headers, + ...input.target.config.headers, "content-type": "application/json", accept: "application/json, text/event-stream", }, @@ -590,8 +578,8 @@ export const authorize = (input: { // lists the loopback redirect; a configured client_id always wins. const discovery = yield* Effect.tryPromise({ try: async () => - (await configuredDiscovery({ config: input.config, fetchFn })) ?? - discover(input.config.url, { resourceMetadataUrl, fetchFn }), + (await configuredDiscovery({ target: input.target, fetchFn })) ?? + discover(input.target.url, { resourceMetadataUrl, fetchFn }), catch: (error) => (error instanceof Error ? error : new Error(String(error))), }) const cimd = @@ -615,7 +603,7 @@ export const authorize = (input: { let reached = "127.0.0.1" let authorizationUrl: URL | undefined const oauthProvider = provider({ - config: input.config, + target: input.target, store, clientMetadataUrl: cimd ? CLIENT_METADATA_URL : undefined, discovery: { ...discovery, resourceMetadataUrl: resourceMetadataUrl?.toString() }, @@ -641,21 +629,21 @@ export const authorize = (input: { }) return toCredential({ methodID: input.methodID, - serverUrl: input.config.url, + serverUrl: input.target.config.url, tokens, client, scope: authorizationUrl?.searchParams.get("scope") ?? undefined, - discovery: oauth?.auth_server_metadata_url + discovery: input.target.metadata ? undefined : { authorizationServer: discovery.authorizationServerUrl, - resource: selectResource(input.config, discovery.resourceMetadata?.resource).toString(), + resource: selectResource(input.target, discovery.resourceMetadata?.resource).toString(), }, }) }) yield* Effect.tryPromise({ - try: () => auth(oauthProvider, { serverUrl: input.config.url, scope: oauth?.scope ?? challenge.scope, fetchFn }), + try: () => auth(oauthProvider, { serverUrl: input.target.url, scope: oauth?.scope ?? challenge.scope, fetchFn }), catch: (error) => (error instanceof Error ? error : new Error(String(error))), }) @@ -679,7 +667,7 @@ export const authorize = (input: { return Effect.tryPromise({ try: () => auth(oauthProvider, { - serverUrl: input.config.url, + serverUrl: input.target.url, authorizationCode: value.code, iss: value.iss, scope: oauth?.scope ?? challenge.scope, diff --git a/packages/core/src/mcp/pool.ts b/packages/core/src/mcp/pool.ts index 167b4784f69..2cbe0a68ce6 100644 --- a/packages/core/src/mcp/pool.ts +++ b/packages/core/src/mcp/pool.ts @@ -14,6 +14,7 @@ import { SharedCache } from "../shared-cache.js" import { canonicalJson } from "../util/canonical-json.js" import type { McpClient } from "./client.js" import { McpConnection } from "./connection.js" +import { McpTarget } from "./target.js" export interface Input extends Omit { /** @@ -51,7 +52,7 @@ export class Service extends Context.Service()("@opencode/Mc * keyed or left out on purpose with `null`. */ export const key = ( - input: Omit & + input: Omit & ( | { readonly config: Mcp.RemoteConfig @@ -68,7 +69,7 @@ export const key = ( const spec = { clientInfo: input.clientInfo ?? null, skills: input.skills ?? false, - } satisfies Record, Schema.Json> + } satisfies Record, Schema.Json> const timeout = { startup: input.config.timeout?.startup ?? null, catalog: input.config.timeout?.catalog ?? null, @@ -372,8 +373,8 @@ export const layer = Layer.effect( }, start: Effect.gen(function* () { if ( - input.spec.config.type === "local" && - input.spec.config.cwd === undefined && + input.spec.target.type === "local" && + input.spec.target.config.cwd === undefined && !unfixed.has(input.spec.name) ) { unfixed.add(input.spec.name) @@ -386,13 +387,13 @@ export const layer = Layer.effect( } const selected = yield* input.select if (!unpoolable.has(selected.key) && (yield* join(selected))) return - const config = + const target = unpoolable.get(selected.key) === "legacy" - ? { ...input.spec.config, protocol: "legacy" as const } - : input.spec.config + ? McpTarget.withProtocol(input.spec.target, "legacy") + : input.spec.target const own = McpConnection.make({ ...input, - spec: { ...input.spec, config }, + spec: { ...input.spec, target }, authProvider: selected.authProvider, endpointLoads, }) diff --git a/packages/core/src/mcp/target.ts b/packages/core/src/mcp/target.ts new file mode 100644 index 00000000000..f7c7f0629e3 --- /dev/null +++ b/packages/core/src/mcp/target.ts @@ -0,0 +1,94 @@ +export * as McpTarget from "./target.js" + +import type { Mcp } from "@opencode/schema/mcp" +import { Result } from "effect" +import { McpError } from "./errors.js" + +export interface Local { + readonly type: "local" + readonly config: Mcp.LocalConfig + readonly command: string + readonly args: ReadonlyArray +} + +export interface Remote { + readonly type: "remote" + readonly config: Mcp.RemoteConfig + readonly url: URL + readonly redirect: URL | undefined + readonly metadata: URL | undefined +} + +/** A server's config with the parts that must parse already parsed, so nothing past here meets a raw URL or command. */ +export type Target = Local | Remote + +export const parse = (server: string, config: Mcp.ServerConfig): Result.Result => + config.type === "local" ? local(server, config) : remote(server, config) + +export const local = (server: string, config: Mcp.LocalConfig): Result.Result => { + const [command, ...args] = config.command + if (command === undefined) return invalid(server, "MCP server command is empty") + return Result.succeed({ type: "local", config, command, args }) +} + +export const remote = ( + server: string, + config: Mcp.RemoteConfig, +): Result.Result => { + const url = URL.parse(config.url) + if (!url) return invalid(server, `Invalid MCP server URL: ${config.url}`) + const oauth = config.oauth || undefined + // An empty value counts as unset, as an unset `{env:VAR}` substitutes one. + const redirect = oauth?.redirect_uri ? URL.parse(oauth.redirect_uri) : undefined + if (redirect === null) return invalid(server, `Invalid MCP OAuth redirect_uri: ${oauth?.redirect_uri}`) + const metadata = oauth?.auth_server_metadata_url ? URL.parse(oauth.auth_server_metadata_url) : undefined + if (metadata === null) + return invalid(server, `Invalid MCP OAuth auth_server_metadata_url: ${oauth?.auth_server_metadata_url}`) + return Result.succeed({ type: "remote", config, url, redirect, metadata }) +} + +const invalid = (server: string, message: string) => Result.fail(new McpError.InvalidConfigError({ server, message })) + +/** Keeps each variant's config paired with its type. */ +export const withProtocol = (target: Target, protocol: Mcp.Protocol): Target => + target.type === "local" + ? { ...target, config: { ...target.config, protocol } } + : { ...target, config: { ...target.config, protocol } } + +/** + * Servers that bundle their own Code Mode (Cloudflare and others) expose raw tools when dialed with ?codemode=false, + * which is what ours wants. Returns the URL to dial with it, or undefined to dial the configured URL as is. The + * configured URL stays the OAuth identity. + */ +export const dialUrl = (url: URL, codemode: boolean | undefined) => { + if (codemode === false || url.searchParams.has("codemode") || rejectsUnknownQuery(url)) return undefined + const dialed = new URL(url) + dialed.searchParams.set("codemode", "false") + return dialed +} + +/** + * Some servers echo the ?codemode=false a connection dialed with back as their protected resource. Drops only that + * parameter, so a refresh names the same resource the login did. + */ +export const withoutDialParams = (resource: URL, configured: URL) => { + const result = new URL(resource) + if ( + result.origin === configured.origin && + result.pathname === configured.pathname && + !configured.searchParams.has("codemode") + ) + result.searchParams.delete("codemode") + return result +} + +// These servers reject any unknown query parameter and have no Code Mode of their own, so adding +// ?codemode=false only costs a failed request before the retry at the configured URL. +function rejectsUnknownQuery(url: URL) { + // Google Workspace MCP (gmailmcp, drivemcp, calendarmcp, ...) returns 404. + if (url.hostname.endsWith(".googleapis.com")) return true + // Zoho MCP gateways (zohomcp.com, zohomcp.eu, ...) return 400. + if (/(^|\.)zohomcp\.[a-z.]+$/.test(url.hostname)) return true + // Loopback servers run on this machine (Figma Desktop's Dev Mode MCP returns 404), so they are not hosted Code Mode servers. + return url.hostname === "localhost" || url.hostname === "[::1]" || /^127(\.\d+){3}$/.test(url.hostname) +} diff --git a/packages/core/test/automation-event.test.ts b/packages/core/test/automation-event.test.ts index 8d3508fb052..28cdf27045a 100644 --- a/packages/core/test/automation-event.test.ts +++ b/packages/core/test/automation-event.test.ts @@ -145,7 +145,7 @@ const connect = Effect.fnUntraced(function* (directory: string) { const producer = yield* eventProducer(types) const connection = yield* McpClient.connect({ server: "ci", - config: { type: "attached", transport: producer.client, protocol: "2026-07-28" }, + target: { type: "attached", transport: producer.client, protocol: "2026-07-28" }, directory, events: true, }).pipe(Effect.provide(hostEnvironmentLayer)) diff --git a/packages/core/test/mcp-events.test.ts b/packages/core/test/mcp-events.test.ts index 5d3363314a0..abed343b4f0 100644 --- a/packages/core/test/mcp-events.test.ts +++ b/packages/core/test/mcp-events.test.ts @@ -96,7 +96,7 @@ const eventServer = Effect.fnUntraced(function* ( ) const connection = yield* McpClient.connect({ server: "jobs", - config: { type: "attached", transport: client, protocol: input.protocol ?? "2026-07-28" }, + target: { type: "attached", transport: client, protocol: input.protocol ?? "2026-07-28" }, directory: import.meta.dir, events: input.declares ?? true, }) diff --git a/packages/core/test/mcp-oauth.test.ts b/packages/core/test/mcp-oauth.test.ts index 565520f0f91..b153b9d502c 100644 --- a/packages/core/test/mcp-oauth.test.ts +++ b/packages/core/test/mcp-oauth.test.ts @@ -8,7 +8,8 @@ import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { Integration } from "@opencode/core/integration" import { McpClient } from "@opencode/core/mcp/client" import { McpOAuth } from "@opencode/core/mcp/oauth" -import { Cause, Effect, Exit, ManagedRuntime } from "effect" +import { McpTarget } from "@opencode/core/mcp/target" +import { Cause, Effect, Exit, ManagedRuntime, Result } from "effect" import { TestClock } from "effect/testing" import { hostEnvironmentLayer } from "./fixture/environment" import { tmpdir } from "./fixture/tmpdir" @@ -20,6 +21,7 @@ const integrationID = Integration.ID.make("mcp_test") const methodID = Integration.MethodID.make("oauth") const remote = (url: string) => new ConfigMCP.Remote({ type: "remote", url, oauth: { client_id: "client" } }) +const target = (config: ConfigMCP.Remote) => Result.getOrThrow(McpTarget.remote("test", config)) const credential = (input: { access: string; refresh: string; expires?: number; url: string }) => new Credential.Info({ @@ -90,18 +92,20 @@ const authorizationServer = (metadata: Record) => { } const start = ( - target: string | ReturnType, + server: string | ReturnType, oauth?: ConfigMCP.OAuth, store: ReturnType = memoryCredentials([]), ) => Effect.gen(function* () { const authorization = yield* McpOAuth.authorize({ name: "test", - config: new ConfigMCP.Remote({ - type: "remote", - url: typeof target === "string" ? target : target.url.href, - ...(oauth ? { oauth } : {}), - }), + target: target( + new ConfigMCP.Remote({ + type: "remote", + url: typeof server === "string" ? server : server.url.href, + ...(oauth ? { oauth } : {}), + }), + ), integrationID, methodID, }) @@ -281,10 +285,6 @@ describe("MCP OAuth", () => { expect(await authorize(redirect)).toBe(redirect) }) - test("rejects an invalid redirect URL", async () => { - await expect(authorize("not a URL")).rejects.toThrow(TypeError) - }) - test("rejects an authorization endpoint that is not http or https", async () => { const { server } = authorizationServer({ authorization_endpoint: "file:///tmp/authorize" }) @@ -654,7 +654,11 @@ describe("MCP OAuth connections", () => { Credential.Service.use((credentials) => credentials .get(id) - .pipe(Effect.flatMap((credential) => McpOAuth.connectProvider({ server: "test", config, credential }))), + .pipe( + Effect.flatMap((credential) => + McpOAuth.connectProvider({ server: "test", target: target(config), credential }), + ), + ), ), ) return { @@ -679,7 +683,12 @@ describe("MCP OAuth connections", () => { const connect = (provider: AuthProvider, url: string, config = remote(url)) => Effect.runPromise( Effect.scoped( - McpClient.connect({ server: "test", config, directory: import.meta.dir, authProvider: provider }), + McpClient.connect({ + server: "test", + target: target(config), + directory: import.meta.dir, + authProvider: provider, + }), ).pipe(Effect.provide(hostEnvironmentLayer), Effect.exit), ) @@ -862,7 +871,7 @@ describe("MCP OAuth connections", () => { }) const url = `${server.url.origin}/mcp` const provider = await Effect.runPromise( - McpOAuth.connectProvider({ server: "test", config: remote(url), credential: undefined }).pipe( + McpOAuth.connectProvider({ server: "test", target: target(remote(url)), credential: undefined }).pipe( Effect.provideService(Credential.Service, memoryCredentials([]).service), ), ) @@ -1236,7 +1245,7 @@ describe("MCP OAuth connections", () => { const credentials = yield* Credential.Service const provider = yield* McpOAuth.connectProvider({ server: "test", - config: remote(url), + target: target(remote(url)), credential: yield* credentials.get(id), }) yield* Effect.promise(() => provider.token()) diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts index f2caa3ffde7..ee04a51ca56 100644 --- a/packages/core/test/mcp.test.ts +++ b/packages/core/test/mcp.test.ts @@ -31,6 +31,7 @@ import { Location } from "@opencode/core/location" import { Mcp } from "@opencode/core/mcp/index" import { McpClient } from "@opencode/core/mcp/client" import { McpPool } from "@opencode/core/mcp/pool" +import { McpTarget } from "@opencode/core/mcp/target" import { McpStdio } from "@opencode/core/mcp/stdio" import { Permission } from "@opencode/core/permission" import { AbsolutePath } from "@opencode/core/schema" @@ -56,6 +57,7 @@ import { PubSub, Queue, Ref, + Result, Schedule, Schema, Scope, @@ -472,8 +474,10 @@ function resourceMcpLayer( ) } +const target = (config: typeof ConfigMCP.Server.Type) => Result.getOrThrow(McpTarget.parse("test", config)) + const connect = (server: string, config: typeof ConfigMCP.Server.Type, directory: string) => - McpClient.connect({ server, config, directory }).pipe(Effect.provide(hostEnvironmentLayer)) + McpClient.connect({ server, target: target(config), directory }).pipe(Effect.provide(hostEnvironmentLayer)) // Reads no longer wait for startup, so tests that assert on a connected server settle it first. const settled = (service: Mcp.Interface, name = "resources") => @@ -746,7 +750,11 @@ test("spawns local MCP servers through the location environment", async () => { await Effect.runPromise( Effect.scoped( Effect.gen(function* () { - const connection = yield* McpClient.connect({ server: "environment", config, directory: import.meta.dir }) + const connection = yield* McpClient.connect({ + server: "environment", + target: target(config), + directory: import.meta.dir, + }) yield* connection.tools() }), ).pipe(Effect.provide(recordingEnvironmentLayer(spawns))), @@ -1942,7 +1950,7 @@ test("adds, disconnects, and reconnects MCP servers at runtime", async () => { ) }) -test("marks a remote MCP server with an invalid URL as failed", async () => { +test("marks an MCP server with an invalid config as failed", async () => { await Effect.runPromise( Effect.scoped( Effect.gen(function* () { @@ -1956,6 +1964,16 @@ test("marks a remote MCP server with an invalid URL as failed", async () => { yield* service.add("broken", new ConfigMCP.Remote({ type: "remote", url: "not a url" })) expect(yield* status("broken")).toEqual({ status: "failed", error: "Invalid MCP server URL: not a url" }) + expect((yield* service.servers()).find((server) => server.name === "broken")?.integrationID).toBeUndefined() + yield* service.add("empty", new ConfigMCP.Local({ type: "local", command: [] })) + expect(yield* status("empty")).toEqual({ status: "failed", error: "MCP server command is empty" }) + yield* service.add("redirect", new ConfigMCP.Remote({ ...config, oauth: { redirect_uri: "not a url" } })) + expect(yield* status("redirect")).toEqual({ + status: "failed", + error: "Invalid MCP OAuth redirect_uri: not a url", + }) + yield* service.add("unset", new ConfigMCP.Remote({ ...config, oauth: { redirect_uri: "" } })) + expect(yield* status("unset")).toEqual({ status: "connected" }) expect(yield* status("resources")).toEqual({ status: "connected" }) yield* service.add("broken", new ConfigMCP.Remote(config)) @@ -4005,7 +4023,7 @@ describe("MCP pool", () => { const scope = yield* Effect.scope const run = yield* FiberSet.makeRuntime() const connection = pool.connection({ - spec: { name, config, directory }, + spec: { name, target: target(config), directory }, authProvider: Effect.undefined, elicitation: { create: (request) => diff --git a/packages/core/test/tool-mcp-events.test.ts b/packages/core/test/tool-mcp-events.test.ts index 79a90f10df7..c832c1deb6b 100644 --- a/packages/core/test/tool-mcp-events.test.ts +++ b/packages/core/test/tool-mcp-events.test.ts @@ -29,7 +29,7 @@ const setup = Effect.fnUntraced(function* () { ]) const connection = yield* McpClient.connect({ server: "jobs", - config: { type: "attached", transport: producer.client, protocol: "2026-07-28" }, + target: { type: "attached", transport: producer.client, protocol: "2026-07-28" }, directory: import.meta.dir, events: true, }).pipe(Effect.provide(hostEnvironmentLayer))