diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index 4e66ee54275..475a1275f9a 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -19,13 +19,13 @@ import type { Skill } from "@opencode/schema/skill" import type { FileDiff } from "@opencode/schema/file-diff" import type { InstructionEntry } from "@opencode/schema/instruction-entry" import type { Schema } from "effect" +import type { Mcp } from "@opencode/schema/mcp" import type { Event } from "@opencode/schema/event" import type { EventLog } from "@opencode/schema/event-log" import type { Shell } from "@opencode/schema/shell" import type { Provider } from "@opencode/schema/provider" import type { Form } from "@opencode/schema/form" import type { Integration } from "@opencode/schema/integration" -import type { Mcp } from "@opencode/schema/mcp" import type { Credential } from "@opencode/schema/credential" import type { PermissionSaved } from "@opencode/schema/permission-saved" import type { FileSystem } from "@opencode/schema/filesystem" @@ -411,6 +411,20 @@ export type SessionInstructionsEntryRemoveOperation = ( input: SessionInstructionsEntryRemoveInput, ) => Effect.Effect +export type SessionMcpAddInput = { + readonly sessionID: Session.ID + readonly server: string + readonly config: Mcp.LocalConfig | Mcp.RemoteConfig +} +export type SessionMcpAddOutput = void +export type SessionMcpAddOperation = (input: SessionMcpAddInput) => Effect.Effect + +export type SessionMcpRemoveInput = { readonly sessionID: Session.ID; readonly server: string } +export type SessionMcpRemoveOutput = void +export type SessionMcpRemoveOperation = ( + input: SessionMcpRemoveInput, +) => Effect.Effect + export type SessionGenerateInput = { readonly sessionID: Session.ID; readonly prompt: string } export type SessionGenerateOutput = { readonly text: string } export type SessionGenerateOperation = ( @@ -1477,6 +1491,7 @@ export interface SessionApi { readonly remove: SessionInstructionsEntryRemoveOperation } } + readonly mcp: { readonly add: SessionMcpAddOperation; readonly remove: SessionMcpRemoveOperation } readonly generate: SessionGenerateOperation readonly log: SessionLogOperation readonly interrupt: SessionInterruptOperation diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index a8c4a68a6cc..fbb274f500d 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -83,6 +83,10 @@ import type { SessionInstructionsEntryPutOutput, SessionInstructionsEntryRemoveInput, SessionInstructionsEntryRemoveOutput, + SessionMcpAddInput, + SessionMcpAddOutput, + SessionMcpRemoveInput, + SessionMcpRemoveOutput, SessionGenerateInput, SessionGenerateOutput, SessionLogInput, @@ -657,6 +661,21 @@ const EndpointSessionInstructionsEntryRemove = ), ) +const EndpointSessionMcpAdd = (raw: RawClient["server.session"]) => (input: SessionMcpAddInput) => + preserveEffect()( + raw["session.mcp.add"]({ + params: { sessionID: input["sessionID"], server: input["server"] }, + payload: { config: input["config"] }, + }).pipe(Effect.mapError(mapClientError)), + ) + +const EndpointSessionMcpRemove = (raw: RawClient["server.session"]) => (input: SessionMcpRemoveInput) => + preserveEffect()( + raw["session.mcp.remove"]({ params: { sessionID: input["sessionID"], server: input["server"] } }).pipe( + Effect.mapError(mapClientError), + ), + ) + const EndpointSessionGenerate = (raw: RawClient["server.session"]) => (input: SessionGenerateInput) => preserveEffect()( raw["session.generate"]({ params: { sessionID: input["sessionID"] }, payload: { prompt: input["prompt"] } }).pipe( @@ -796,6 +815,7 @@ const adaptGroupSession = (raw: RawClient["server.session"]) => ({ remove: EndpointSessionInstructionsEntryRemove(raw), }, }, + mcp: { add: EndpointSessionMcpAdd(raw), remove: EndpointSessionMcpRemove(raw) }, generate: EndpointSessionGenerate(raw), log: EndpointSessionLog(raw), interrupt: EndpointSessionInterrupt(raw), diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 27826bac171..4fb7bf3ae0e 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -77,6 +77,10 @@ import type { SessionInstructionsEntryPutOutput, SessionInstructionsEntryRemoveInput, SessionInstructionsEntryRemoveOutput, + SessionMcpAddInput, + SessionMcpAddOutput, + SessionMcpRemoveInput, + SessionMcpRemoveOutput, SessionGenerateInput, SessionGenerateOutput, SessionLogInput, @@ -946,6 +950,31 @@ export function make(options: ClientOptions) { ), }, }, + mcp: { + add: (input: SessionMcpAddInput, requestOptions?: RequestOptions) => + request( + { + method: "PUT", + path: `/api/experimental/session/${encodeURIComponent(input.sessionID)}/mcp/${encodeURIComponent(input.server)}`, + body: { config: input["config"] }, + successStatus: 204, + declaredStatuses: [400, 401, 404], + empty: true, + }, + requestOptions, + ), + remove: (input: SessionMcpRemoveInput, requestOptions?: RequestOptions) => + request( + { + method: "DELETE", + path: `/api/experimental/session/${encodeURIComponent(input.sessionID)}/mcp/${encodeURIComponent(input.server)}`, + successStatus: 204, + declaredStatuses: [400, 401, 404], + empty: true, + }, + requestOptions, + ), + }, generate: (input: SessionGenerateInput, requestOptions?: RequestOptions) => request<{ readonly data: SessionGenerateOutput }>( { diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 5cf39951bb4..e6e505d0263 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2618,6 +2618,14 @@ export const isInstructionEntryValueTooLargeError = (value: unknown): value is I "_tag" in value && value["_tag"] === "InstructionEntryValueTooLargeError" +export type McpServerNotFoundError = { + readonly _tag: "McpServerNotFoundError" + readonly server: string + readonly message: string +} +export const isMcpServerNotFoundError = (value: unknown): value is McpServerNotFoundError => + typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "McpServerNotFoundError" + export type FormNotFoundError = { readonly _tag: "FormNotFoundError"; readonly id: string; readonly message: string } export const isFormNotFoundError = (value: unknown): value is FormNotFoundError => typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "FormNotFoundError" @@ -2672,14 +2680,6 @@ export type IntegrationMethodNotFoundError = { export const isIntegrationMethodNotFoundError = (value: unknown): value is IntegrationMethodNotFoundError => typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "IntegrationMethodNotFoundError" -export type McpServerNotFoundError = { - readonly _tag: "McpServerNotFoundError" - readonly server: string - readonly message: string -} -export const isMcpServerNotFoundError = (value: unknown): value is McpServerNotFoundError => - typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "McpServerNotFoundError" - export type ProjectNotFoundError = { readonly _tag: "ProjectNotFoundError" readonly projectID: string @@ -4556,6 +4556,52 @@ export type SessionInstructionsEntryRemoveInput = { export type SessionInstructionsEntryRemoveOutput = void +export type SessionMcpAddInput = { + readonly sessionID: { readonly sessionID: string; readonly server: string }["sessionID"] + readonly server: { readonly sessionID: string; readonly server: string }["server"] + readonly config: { + readonly config: + | { + readonly type: "local" + readonly command: ReadonlyArray + readonly cwd?: string + readonly environment?: { readonly [x: string]: string } + readonly disabled?: boolean + readonly codemode?: boolean + readonly timeout?: { readonly startup?: number; readonly catalog?: number; readonly execution?: number } + readonly protocol?: "legacy" | "auto" | "2026-07-28" + } + | { + readonly type: "remote" + readonly url: string + readonly headers?: { readonly [x: string]: string } + readonly oauth?: + | { + readonly client_id?: string + readonly client_secret?: string + readonly scope?: string + readonly callback_port?: number + readonly redirect_uri?: string + readonly auth_server_metadata_url?: string + } + | false + readonly disabled?: boolean + readonly codemode?: boolean + readonly timeout?: { readonly startup?: number; readonly catalog?: number; readonly execution?: number } + readonly protocol?: "legacy" | "auto" | "2026-07-28" + } + }["config"] +} + +export type SessionMcpAddOutput = void + +export type SessionMcpRemoveInput = { + readonly sessionID: { readonly sessionID: string; readonly server: string }["sessionID"] + readonly server: { readonly sessionID: string; readonly server: string }["server"] +} + +export type SessionMcpRemoveOutput = void + export type SessionGenerateInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] readonly prompt: { readonly prompt: string }["prompt"] diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index f7e69bc0054..a383cfb3ab4 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -4,6 +4,7 @@ import { Mcp } from "@opencode/schema/mcp" import { McpEvent } from "@opencode/schema/mcp-event" import { ephemeral } from "@opencode/schema/event" import type { Session } from "@opencode/schema/session" +import { SessionEvent } from "@opencode/schema/session-event" import { createHash } from "node:crypto" import { isDeepStrictEqual } from "node:util" import { Cause, Context, Effect, Exit, FiberSet, Latch, Layer, Schema, Scope, Semaphore, Stream, Types } from "effect" @@ -15,6 +16,7 @@ import { Form } from "../form.js" import { Integration } from "../integration.js" import { KeyedMutex } from "../effect/keyed-mutex.js" import { Location } from "../location.js" +import { SessionStore } from "../session/store.js" import { waitForAbort } from "@opencode/util/process" import { State } from "../state.js" import type { McpClient } from "./client.js" @@ -33,7 +35,12 @@ export interface ServerInstructions { } /** SDK tool definition tagged with the server that owns it. */ -export type Tool = McpClient.Tool & { readonly server: ServerName; readonly codemode?: boolean } +export type Tool = McpClient.Tool & { + readonly server: ServerName + readonly codemode?: boolean + /** Owner of the Session-scoped server that provides this tool; absent for Location servers. */ + readonly sessionID?: Session.ID +} export type ToolResultContent = McpClient.CallToolContent export type ToolResult = McpClient.CallToolResult & { readonly server: ServerName; readonly tool: string } export type Prompt = McpClient.Prompt & { readonly server: ServerName } @@ -64,6 +71,7 @@ export class ToolCallError extends Schema.TaggedError()("MCP.Tool type ServerEntry = { readonly config: Mcp.ServerConfig + readonly sessionID?: Session.ID status: Status readonly startup: Latch.Latch scope?: Scope.Closeable @@ -97,31 +105,41 @@ export type Editor = { const cloneConfig = (config: Mcp.ServerConfig) => structuredClone(config) as Types.DeepMutable +/** + * Methods taking a `sessionID` resolve the servers visible to that Session: servers registered for the + * Session or one of its ancestors, nearest owner first, shadowing Location servers of the same name. + * Without a `sessionID` they address Location servers only. + */ export interface Interface extends State.Transformable { - readonly servers: () => Effect.Effect - readonly add: (server: ServerName | string, config: Mcp.ServerConfig) => Effect.Effect + readonly servers: (sessionID?: Session.ID) => Effect.Effect + /** Session-scoped servers are process-local and released when removed or when their Session is deleted or moved. */ + readonly add: (server: ServerName | string, config: Mcp.ServerConfig, sessionID?: Session.ID) => Effect.Effect readonly connect: (server: ServerName | string) => Effect.Effect readonly disconnect: (server: ServerName | string) => Effect.Effect - readonly remove: (server: ServerName | string) => Effect.Effect - readonly tools: () => Effect.Effect + readonly remove: (server: ServerName | string, sessionID?: Session.ID) => Effect.Effect + readonly tools: (sessionID?: Session.ID) => Effect.Effect readonly callTool: (input: { readonly server: ServerName | string readonly name: string readonly args?: Record readonly sessionID?: Session.ID }) => Effect.Effect - readonly instructions: () => Effect.Effect + readonly instructions: (sessionID?: Session.ID) => Effect.Effect readonly prompts: () => Effect.Effect readonly prompt: (input: { readonly server: ServerName | string readonly name: string readonly args?: Record }) => Effect.Effect - readonly resourceCatalog: () => Effect.Effect - readonly resources: (input: { readonly server: ServerName | string }) => Effect.Effect + readonly resourceCatalog: (sessionID?: Session.ID) => Effect.Effect + readonly resources: (input: { + readonly server: ServerName | string + readonly sessionID?: Session.ID + }) => Effect.Effect readonly readResource: (input: { readonly server: ServerName | string readonly uri: string + readonly sessionID?: Session.ID }) => Effect.Effect } @@ -147,13 +165,17 @@ export const layer = (options?: Options) => const forms = yield* Form.Service const integration = yield* Integration.Service const credentials = yield* Credential.Service + const store = yield* SessionStore.Service const root = yield* Effect.scope const fork = yield* FiberSet.makeRuntime() const entries = new Map() + const sessionEntries = new Map>() // Serializes lifecycle operations per server. Anything taking this lock from a connection // callback must stay forked: lifecycle operations close scopes while holding it, firing onClose. - const locks = KeyedMutex.makeUnsafe() + const locks = KeyedMutex.makeUnsafe() + const slot = (name: ServerName, sessionID: Session.ID | undefined) => + sessionID === undefined ? name : sessionID + "\u0000" + name // Legacy era only: pending URL-mode elicitation forms, settled by notifications/elicitation/complete. const urlElicitations = new Map() @@ -200,9 +222,25 @@ export const layer = (options?: Options) => }) .pipe(Scope.provide(scope)) }) - const requireServer = Effect.fnUntraced(function* (server: ServerName | string) { + const sessionServers = Effect.fnUntraced(function* (sessionID: Session.ID | undefined) { + const scoped = new Map() + if (sessionID === undefined || sessionEntries.size === 0) return scoped + let current: Session.ID | undefined = sessionID + while (current) { + for (const [name, entry] of sessionEntries.get(current) ?? []) if (!scoped.has(name)) scoped.set(name, entry) + current = (yield* store.get(current))?.parentID + } + return scoped + }) + + const visibleServers = Effect.fnUntraced(function* (sessionID: Session.ID | undefined) { + const scoped = yield* sessionServers(sessionID) + return [...Array.from(entries).filter(([name]) => !scoped.has(name)), ...scoped] + }) + + const requireServer = Effect.fnUntraced(function* (server: ServerName | string, sessionID?: Session.ID) { const name = ServerName.make(server) - const entry = entries.get(name) + const entry = (yield* sessionServers(sessionID)).get(name) ?? entries.get(name) if (!entry) return yield* new NotFoundError({ server: name }) return { name, entry } }) @@ -292,6 +330,7 @@ export const layer = (options?: Options) => ...tool, server, ...(entry.config.codemode === undefined ? {} : { codemode: entry.config.codemode }), + ...(entry.sessionID === undefined ? {} : { sessionID: entry.sessionID }), }) const refreshTools = (name: ServerName, entry: ServerEntry, connection: McpClient.Connection) => @@ -317,7 +356,7 @@ export const layer = (options?: Options) => (effect: Effect.Effect) => fork( Effect.suspend(() => (entry.client === connection ? effect : Effect.void)).pipe( - locks.withLock(name), + locks.withLock(slot(name, entry.sessionID)), Effect.ignore, ), ) @@ -330,7 +369,7 @@ export const layer = (options?: Options) => yield* Effect.logInfo("mcp session expired, reconnecting", { server: name }) yield* stopServer(name, entry) yield* startServer(name, entry) - }).pipe(locks.withLock(name)) + }).pipe(locks.withLock(slot(name, entry.sessionID))) // Runs a request against the live connection and, if that request observed a session expiry, // reconnects and runs it once more against the replacement. Any other failure passes through. @@ -518,6 +557,48 @@ export const layer = (options?: Options) => yield* bus.publish(McpEvent.StatusChanged, { server: name }) }) + // Session-scoped servers skip OAuth integration registration: integrations are keyed by name and + // URL, so a Session registration would share and then dispose another owner's credential wiring. + const addSessionServer = (sessionID: Session.ID, name: ServerName, serverConfig: Mcp.ServerConfig) => + Effect.gen(function* () { + const config = cloneConfig(serverConfig) + const servers = sessionEntries.get(sessionID) ?? new Map() + const previous = servers.get(name) + if (previous && isDeepStrictEqual(previous.config, config)) return + if (previous) yield* stopServer(name, previous) + const entry: ServerEntry = { config, sessionID, status: { status: "pending" }, startup: Latch.makeUnsafe() } + sessionEntries.set(sessionID, servers.set(name, entry)) + yield* ( + config.disabled + ? Effect.sync(() => { + entry.status = { status: "disabled" } + }) + : startServer(name, entry) + ).pipe(Effect.ensuring(entry.startup.open)) + }).pipe(locks.withLock(slot(name, sessionID))) + + const removeSessionServer = (sessionID: Session.ID, name: ServerName) => + Effect.gen(function* () { + const servers = sessionEntries.get(sessionID) + const entry = servers?.get(name) + if (!servers || !entry) return yield* new NotFoundError({ server: name }) + yield* stopServer(name, entry) + servers.delete(name) + if (servers.size === 0) sessionEntries.delete(sessionID) + }).pipe(locks.withLock(slot(name, sessionID))) + + fork( + bus.subscribe([SessionEvent.Deleted, SessionEvent.Moved]).pipe( + Stream.runForEach((event) => + Effect.forEach( + Array.from(sessionEntries.get(event.data.sessionID)?.keys() ?? []), + (name) => removeSessionServer(event.data.sessionID, name).pipe(Effect.ignore), + { discard: true }, + ), + ), + ), + ) + let applied: Map | undefined const overrides = new Map() const reconcileLock = Semaphore.makeUnsafe(1) @@ -614,13 +695,14 @@ export const layer = (options?: Options) => return Service.of({ transform: state.transform, reload: state.reload, - servers: Effect.fn("MCP.servers")(function* () { - return Array.from(entries) + servers: Effect.fn("MCP.servers")(function* (sessionID) { + return (yield* visibleServers(sessionID)) .toSorted(([a], [b]) => a.localeCompare(b)) .map(([name, entry]): ServerInfo => ({ name, status: entry.status, integrationID: entry.integrationID })) }), - add: Effect.fn("MCP.add")(function* (server, config) { + add: Effect.fn("MCP.add")(function* (server, config, sessionID) { const name = ServerName.make(server) + if (sessionID !== undefined) return yield* addSessionServer(sessionID, name, config) overrides.set(name, config) yield* state.reload() }), @@ -641,20 +723,21 @@ export const layer = (options?: Options) => yield* bus.publish(McpEvent.StatusChanged, { server: name }) }).pipe(locks.withLock(name)) }), - remove: Effect.fn("MCP.remove")(function* (server) { + remove: Effect.fn("MCP.remove")(function* (server, sessionID) { const name = ServerName.make(server) + if (sessionID !== undefined) return yield* removeSessionServer(sessionID, name) yield* requireServer(name) overrides.set(name, false) yield* state.reload() }), // Reads report what is connected now; servers still starting contribute once they publish a change. - tools: Effect.fn("MCP.tools")(function* () { - return Array.from(entries.values()) - .flatMap((entry) => entry.tools ?? []) + tools: Effect.fn("MCP.tools")(function* (sessionID) { + return (yield* visibleServers(sessionID)) + .flatMap(([, entry]) => entry.tools ?? []) .toSorted((a, b) => a.server.localeCompare(b.server) || a.name.localeCompare(b.name)) }), callTool: Effect.fn("MCP.callTool")(function* (input) { - const target = yield* requireServer(input.server) + const target = yield* requireServer(input.server, input.sessionID) yield* target.entry.startup.await if (!target.entry.client) return yield* new ToolCallError({ @@ -671,8 +754,8 @@ export const layer = (options?: Options) => ) return { ...result, server: target.name, tool: input.name } }), - instructions: Effect.fn("MCP.instructions")(function* () { - return Array.from(entries) + instructions: Effect.fn("MCP.instructions")(function* (sessionID) { + return (yield* visibleServers(sessionID)) .flatMap(([server, entry]) => { const instructions = entry.client?.instructions if (!instructions) return [] @@ -695,10 +778,10 @@ export const layer = (options?: Options) => if (!result) return undefined return { ...result, server: target.name, name: input.name } }), - resourceCatalog: Effect.fn("MCP.resourceCatalog")(function* () { + resourceCatalog: Effect.fn("MCP.resourceCatalog")(function* (sessionID) { const empty = ResourceCatalog.make({ resources: [], templates: [] }) const catalogs = yield* Effect.forEach( - Array.from(entries), + yield* visibleServers(sessionID), ([name, entry]) => entry.client ? loadCatalog(name, entry, entry.client).pipe(Effect.orElseSucceed(() => empty)) @@ -708,13 +791,13 @@ export const layer = (options?: Options) => return mergeCatalogs(catalogs) }), resources: Effect.fn("MCP.resources")(function* (input) { - const target = yield* requireServer(input.server) + const target = yield* requireServer(input.server, input.sessionID) yield* target.entry.startup.await if (!target.entry.client) return ResourceCatalog.make({ resources: [], templates: [] }) return mergeCatalogs([yield* loadCatalog(target.name, target.entry, target.entry.client)]) }), readResource: Effect.fn("MCP.readResource")(function* (input) { - const target = yield* requireServer(input.server) + const target = yield* requireServer(input.server, input.sessionID) yield* target.entry.startup.await if (!target.entry.client) return undefined const result = yield* recovering(target.name, target.entry, target.entry.client, (connection) => @@ -757,7 +840,7 @@ export function configured(options?: Options) { return makeLocationNode({ service: Service, layer: layer(options), - deps: [Location.node, Environment.node, Bus.node, Form.node, Integration.node, Credential.node], + deps: [Location.node, Environment.node, Bus.node, Form.node, Integration.node, Credential.node, SessionStore.node], }) } diff --git a/packages/core/src/mcp/instructions.ts b/packages/core/src/mcp/instructions.ts index 3517b74ce9d..0c89ba88d5a 100644 --- a/packages/core/src/mcp/instructions.ts +++ b/packages/core/src/mcp/instructions.ts @@ -1,5 +1,6 @@ export * as McpInstructions from "./instructions.js" +import type { Session } from "@opencode/schema/session" import { makeLocationNode } from "@opencode/util/effect/app-node" import { Context, Effect, Layer, Schema } from "effect" import { Permission } from "../permission.js" @@ -55,7 +56,7 @@ const update = (previous: ReadonlyArray, current: ReadonlyArray Effect.Effect + readonly load: (permissions: Permission.Ruleset, sessionID?: Session.ID) => Effect.Effect } export class Service extends Context.Service()("@opencode/McpInstructions") {} @@ -66,7 +67,7 @@ export const layer = Layer.effect( const mcp = yield* Mcp.Service return Service.of({ - load: Effect.fn("McpInstructions.load")(function* (permissions) { + load: Effect.fn("McpInstructions.load")(function* (permissions, sessionID) { const source = (value: ReadonlyArray | Instructions.Removed) => Instructions.make>({ key: Instructions.Key.make("core/mcp-guidance"), @@ -78,7 +79,7 @@ export const layer = Layer.effect( removed: () => "MCP server instructions are no longer available.", }, }) - const [instructions, tools] = yield* Effect.all([mcp.instructions(), mcp.tools()], { + const [instructions, tools] = yield* Effect.all([mcp.instructions(sessionID), mcp.tools(sessionID)], { concurrency: "unbounded", }) const canExecute = Permission.evaluate("execute", "*", permissions).effect !== "deny" diff --git a/packages/core/src/session/context.ts b/packages/core/src/session/context.ts index e8cf2455bfa..9ebd84f9359 100644 --- a/packages/core/src/session/context.ts +++ b/packages/core/src/session/context.ts @@ -131,12 +131,12 @@ const layer = Layer.effect( const permissions = Permission.merge(agent.info.permissions, session.permissions ?? []) const loaded = yield* Effect.all( { - tools: registry.snapshot(permissions), + tools: mcpTools.overlay(sessionID).pipe(Effect.flatMap((overlay) => registry.snapshot(permissions, overlay))), builtins: builtins.load(), discovery: discovery.load(), skills: skillInstructions.load(permissions), references: referenceInstructions.load(), - mcp: mcpInstructions.load(permissions), + mcp: mcpInstructions.load(permissions, sessionID), entries: entries.load(sessionID), }, { concurrency: "unbounded" }, diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index 5e2ca8401aa..97b6fac47ce 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -1,6 +1,6 @@ export * as Tool from "./tool.js" export { CallID, Content, Error, FileContent, TextContent } from "@opencode/schema/tool" -export type { Context, Metadata, Namespace, Options, Result } from "@opencode/schema/tool" +export type { Context, Info, Metadata, Namespace, Options, Result } from "@opencode/schema/tool" import { ToolDefinition, type ToolCall } from "@opencode/ai" import { Tool } from "@opencode/schema/tool" @@ -38,9 +38,16 @@ type Data = { errors: { kind: "tool" | "namespace"; name: string; namespace?: string; error: RegistrationError }[] } +/** Session-specific tools layered over the Location registry for one snapshot. */ +export interface Overlay { + readonly tools: ReadonlyArray + /** Effective names of registered tools the overlay hides. */ + readonly hidden: ReadonlySet +} + export interface Interface extends State.Transformable { readonly list: () => Effect.Effect> - readonly snapshot: (permissions?: Permission.Ruleset) => Effect.Effect + readonly snapshot: (permissions?: Permission.Ruleset, overlay?: Overlay) => Effect.Effect } /** A local execution result after hooks and content normalization. */ @@ -155,7 +162,9 @@ const layer = Layer.effect( } }) - let catalog: { data: Data; names: string; value: CodeModeCatalog.Inventory } | undefined + let catalog: + | { data: Data; names: string; overlay: ReadonlyArray; value: CodeModeCatalog.Inventory } + | undefined const state = State.create({ name: "tool", initial: () => ({ @@ -222,12 +231,19 @@ const layer = Layer.effect( transform: state.transform, reload: state.reload, list: () => Effect.sync(() => Array.from(state.get().tools.values())), - snapshot: Effect.fn("Tool.snapshot")((permissions) => + snapshot: Effect.fn("Tool.snapshot")((permissions, overlay) => Effect.sync(() => { const data = state.get() const active = new Map() const rules = permissions ?? [] - for (const [name, tool] of data.tools) { + const overlaid = overlay?.tools.filter((tool) => !registrationError(tool)) ?? [] + const registered = overlay + ? [ + ...Array.from(data.tools).filter(([name]) => !overlay.hidden.has(name)), + ...overlaid.map((tool) => [effectiveName(tool), tool] as const), + ] + : data.tools + for (const [name, tool] of registered) { if (whollyDisabled(tool.options?.permission ?? name, rules)) continue active.set(name, tool) } @@ -248,10 +264,13 @@ const layer = Layer.effect( // definitions/executors fresh, but share the much larger rendered catalog across steps. const codeModeCatalog = !codeModeEnabled ? undefined - : catalog?.data === data && catalog.names === names + : catalog?.data === data && + catalog.names === names && + catalog.overlay.length === overlaid.length && + catalog.overlay.every((tool, index) => tool === overlaid[index]) ? catalog.value : CodeModeTool.catalog(codeModeInventory) - if (codeModeCatalog) catalog = { data, names, value: codeModeCatalog } + if (codeModeCatalog) catalog = { data, names, overlay: overlaid, value: codeModeCatalog } return { ...(codeModeCatalog === undefined ? {} : { codeModeCatalog }), definitions: [ diff --git a/packages/core/src/tool/AGENTS.md b/packages/core/src/tool/AGENTS.md index 4af998f8cb6..ff5f9512dfe 100644 --- a/packages/core/src/tool/AGENTS.md +++ b/packages/core/src/tool/AGENTS.md @@ -43,6 +43,8 @@ The service uses shared `State` to replay synchronous transforms in registration MCP owns one stable tool transform that reads its latest discovered tools. Tool-list changes update that source and reload the tool state instead of re-registering at the end of the transform order. MCP refresh therefore preserves the precedence of later plugin overrides. +Session-scoped MCP servers never enter the registry. `McpTool.overlay(sessionID)` returns their tools plus the effective names of the Location MCP tools they shadow, and `Tool.Service.snapshot(permissions, overlay)` layers them over the registry for that snapshot only. Registry transforms, including plugin overrides, do not apply to overlay tools. + Type safety ends at registration. The registry validates model input and declared output at runtime and should not carry producer schema generics through storage or execution. `Tool.Service` is Location-scoped. Do not make the registry process-global or construct a separate application-tool service for each Location. @@ -61,4 +63,4 @@ Producer capture remains local to producers. Shell stores combined process outpu ## Current Gaps -- Future Session-scoped registrations still need an explicit canonical registration design. +- Session-scoped registrations beyond MCP servers still need an explicit canonical registration design. diff --git a/packages/core/src/tool/mcp.ts b/packages/core/src/tool/mcp.ts index 5274e5509cf..1168bac6937 100644 --- a/packages/core/src/tool/mcp.ts +++ b/packages/core/src/tool/mcp.ts @@ -2,6 +2,7 @@ export * as McpTool from "./mcp.js" import { ToolFailure } from "@opencode/ai" import { McpEvent } from "@opencode/schema/mcp-event" +import type { Session } from "@opencode/schema/session" import { Context, Effect, Fiber, type JsonSchema, Layer, PubSub, Semaphore, Stream } from "effect" import { makeLocationNode } from "@opencode/util/effect/app-node" import { Bus } from "../bus.js" @@ -19,6 +20,8 @@ export const name = (server: string, tool: string) => `${namespace(server)}_${to export interface Interface { /** Wait for the initial MCP tool registration to settle. */ readonly flush: Effect.Effect + /** Session-scoped server tools visible to the Session, hiding the Location server tools they shadow. */ + readonly overlay: (sessionID: Session.ID) => Effect.Effect } export class Service extends Context.Service()("@opencode/McpTool") {} @@ -33,90 +36,98 @@ export const layer = Layer.effect( const lock = Semaphore.makeUnsafe(1) let discovered: Mcp.Tool[] = [] + // Keyed by the MCP tool object so unchanged tools keep their identity across snapshots. + const infos = new WeakMap() + const info = (tool: Mcp.Tool) => { + const cached = infos.get(tool) + if (cached) return cached + const created: Tool.Info = { + name: tool.name, + options: { namespace: namespace(tool.server), codemode: tool.codemode !== false }, + description: tool.description ?? "", + input: (tool.inputSchema ?? { type: "object", properties: {} }) as JsonSchema.JsonSchema, + output: (tool.outputSchema ?? {}) as JsonSchema.JsonSchema, + execute: (input, context) => + Effect.gen(function* () { + yield* permission.assert({ + action: name(tool.server, tool.name), + resources: ["*"], + save: ["*"], + metadata: {}, + sessionID: context.sessionID, + agent: context.agent, + source: { + type: "tool", + messageID: context.messageID, + id: context.id, + }, + }) + const result = yield* mcp + .callTool({ + server: tool.server, + name: tool.name, + args: (input ?? {}) as Record, + sessionID: context.sessionID, + }) + .pipe( + Effect.catchTags({ + "MCP.NotFoundError": (error) => + new ToolFailure({ message: `MCP server "${error.server}" is not available` }), + "MCP.ToolCallError": (error) => new ToolFailure({ message: error.message }), + }), + ) + if (result.isError) + return yield* new ToolFailure({ + message: + result.content + .flatMap((part) => (part.type === "text" ? [part.text] : [])) + .join("\n") + .trim() || "MCP tool returned an error", + }) + const content = result.content.map((part) => + part.type === "text" + ? { type: "text" as const, text: part.text } + : { + type: "file" as const, + uri: `data:${part.mimeType};base64,${part.data}`, + mime: part.mimeType, + }, + ) + const text = content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n") + const output = () => { + if (result.structured !== undefined) return result.structured + if (text === "") return null + // Agents assume JSON returned as text is already an object, so parse it when the server declares no schema. + if (tool.outputSchema === undefined && (text.startsWith("{") || text.startsWith("["))) { + try { + return JSON.parse(text) + } catch {} + } + return text + } + return { + output: output(), + ...(content.length === 0 ? {} : { content }), + } + }).pipe( + Effect.mapError((error) => + error instanceof ToolFailure + ? error + : new ToolFailure({ message: `Unable to execute ${name(tool.server, tool.name)}` }), + ), + ), + } + infos.set(tool, created) + return created + } + // Register once after initial discovery; only subsequent updates need a debounced reload. const initial = yield* lock .withPermit( Effect.gen(function* () { discovered = yield* mcp.tools() yield* tools.transform((editor) => { - for (const tool of discovered) { - editor.add({ - name: tool.name, - options: { namespace: namespace(tool.server), codemode: tool.codemode !== false }, - description: tool.description ?? "", - input: (tool.inputSchema ?? { type: "object", properties: {} }) as JsonSchema.JsonSchema, - output: (tool.outputSchema ?? {}) as JsonSchema.JsonSchema, - execute: (input, context) => - Effect.gen(function* () { - yield* permission.assert({ - action: name(tool.server, tool.name), - resources: ["*"], - save: ["*"], - metadata: {}, - sessionID: context.sessionID, - agent: context.agent, - source: { - type: "tool", - messageID: context.messageID, - id: context.id, - }, - }) - const result = yield* mcp - .callTool({ - server: tool.server, - name: tool.name, - args: (input ?? {}) as Record, - sessionID: context.sessionID, - }) - .pipe( - Effect.catchTags({ - "MCP.NotFoundError": (error) => - new ToolFailure({ message: `MCP server "${error.server}" is not available` }), - "MCP.ToolCallError": (error) => new ToolFailure({ message: error.message }), - }), - ) - if (result.isError) - return yield* new ToolFailure({ - message: - result.content - .flatMap((part) => (part.type === "text" ? [part.text] : [])) - .join("\n") - .trim() || "MCP tool returned an error", - }) - const content = result.content.map((part) => - part.type === "text" - ? { type: "text" as const, text: part.text } - : { - type: "file" as const, - uri: `data:${part.mimeType};base64,${part.data}`, - mime: part.mimeType, - }, - ) - const text = content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n") - const output = () => { - if (result.structured !== undefined) return result.structured - if (text === "") return null - // Agents assume JSON returned as text is already an object, so parse it when the server declares no schema. - if (tool.outputSchema === undefined && (text.startsWith("{") || text.startsWith("["))) { - try { - return JSON.parse(text) - } catch {} - } - return text - } - return { - output: output(), - ...(content.length === 0 ? {} : { content }), - } - }).pipe( - Effect.mapError((error) => - error instanceof ToolFailure - ? error - : new ToolFailure({ message: `Unable to execute ${name(tool.server, tool.name)}` }), - ), - ), - }) - } + for (const tool of discovered) editor.add(info(tool)) }) }), ) @@ -141,7 +152,19 @@ export const layer = Layer.effect( Stream.runForEach(() => reconcile), Effect.forkScoped({ startImmediately: true }), ) - return Service.of({ flush: Effect.asVoid(Fiber.await(initial)) }) + return Service.of({ + flush: Effect.asVoid(Fiber.await(initial)), + overlay: Effect.fn("McpTool.overlay")(function* (sessionID) { + const visible = yield* mcp.tools(sessionID) + const owned = visible.filter((tool) => tool.sessionID !== undefined) + const shown = new Set( + visible.filter((tool) => tool.sessionID === undefined).map((tool) => name(tool.server, tool.name)), + ) + const hidden = new Set(discovered.map((tool) => name(tool.server, tool.name)).filter((id) => !shown.has(id))) + if (owned.length === 0 && hidden.size === 0) return undefined + return { tools: owned.map(info), hidden } + }), + }) }), ) diff --git a/packages/core/src/tool/plugin/mcp-resource.ts b/packages/core/src/tool/plugin/mcp-resource.ts index f7bf6e3db9d..29bd7271f7d 100644 --- a/packages/core/src/tool/plugin/mcp-resource.ts +++ b/packages/core/src/tool/plugin/mcp-resource.ts @@ -32,7 +32,9 @@ export const Plugin = { Effect.gen(function* () { // Listing every server checks each server name so per-server rules still apply. const servers = - input.server === undefined ? (yield* mcp.servers()).map((server) => server.name) : [input.server] + input.server === undefined + ? (yield* mcp.servers(context.sessionID)).map((server) => server.name) + : [input.server] yield* permission.assert({ action: "opencode_list_mcp_resources", resources: servers, @@ -42,8 +44,8 @@ export const Plugin = { agent: context.agent, source: { type: "tool", messageID: context.messageID, id: context.id }, }) - if (input.server === undefined) return { output: yield* mcp.resourceCatalog() } - return { output: yield* mcp.resources({ server: input.server }) } + if (input.server === undefined) return { output: yield* mcp.resourceCatalog(context.sessionID) } + return { output: yield* mcp.resources({ server: input.server, sessionID: context.sessionID }) } }).pipe(Effect.mapError((error) => new ToolFailure({ message: error.message, error }))), }) editor.add({ @@ -71,7 +73,7 @@ export const Plugin = { agent: context.agent, source: { type: "tool", messageID: context.messageID, id: context.id }, }) - const resource = yield* mcp.readResource(input) + const resource = yield* mcp.readResource({ ...input, sessionID: context.sessionID }) if (!resource) return yield* new ToolFailure({ message: `MCP server "${input.server}" is not connected or does not expose resources`, diff --git a/packages/core/test/fixture/mcp-identity.ts b/packages/core/test/fixture/mcp-identity.ts new file mode 100644 index 00000000000..1129ed7b6a5 --- /dev/null +++ b/packages/core/test/fixture/mcp-identity.ts @@ -0,0 +1,20 @@ +import { Server } from "@modelcontextprotocol/server" +import { StdioServerTransport } from "@modelcontextprotocol/server/stdio" + +const [identity = "unknown", pidFile] = process.argv.slice(2) +if (pidFile) await Bun.write(pidFile, String(process.pid)) + +const server = new Server({ name: `identity-${identity}`, version: "1.0.0" }, { capabilities: { tools: {} } }) + +server.setRequestHandler("tools/list", () => + Promise.resolve({ + tools: [ + { name: "whoami", inputSchema: { type: "object" } }, + { name: `only_${identity}`, inputSchema: { type: "object" } }, + ], + }), +) + +server.setRequestHandler("tools/call", () => Promise.resolve({ content: [{ type: "text", text: identity }] })) + +await server.connect(new StdioServerTransport()) diff --git a/packages/core/test/mcp-session.test.ts b/packages/core/test/mcp-session.test.ts new file mode 100644 index 00000000000..d011229dad0 --- /dev/null +++ b/packages/core/test/mcp-session.test.ts @@ -0,0 +1,190 @@ +import path from "node:path" +import { describe, expect } from "bun:test" +import { Context, Effect, Layer, Schedule } from "effect" +import { ConfigMCP } from "@opencode/schema/config/mcp" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { Database } from "@opencode/core/database/database" +import { Bus } from "@opencode/core/bus" +import { Instance } from "@opencode/core/instance/service" +import { Location } from "@opencode/core/location" +import { LocationServiceMap } from "@opencode/core/location-services" +import { Mcp } from "@opencode/core/mcp/index" +import { Project } from "@opencode/core/project" +import { AbsolutePath } from "@opencode/core/schema" +import { Session } from "@opencode/core/session" +import { SessionEnvironment } from "@opencode/core/session/environment" +import { SessionExecution } from "@opencode/core/session/execution" +import { SessionModelTransport } from "@opencode/core/session/model-transport" +import { SessionProjector } from "@opencode/core/session/projector" +import { SessionStore } from "@opencode/core/session/store" +import { Tool } from "@opencode/core/tool" +import { McpTool } from "@opencode/core/tool/mcp" +import { testEffect } from "./lib/effect" +import { globalProjectNode } from "./lib/project" +import { codeModeListings, waitForCodeModeTool } from "./lib/tool" +import { offlineModels } from "./fixture/models" +import { tmpdirScoped } from "./fixture/tmpdir" + +const transport = Layer.succeed( + SessionModelTransport.Service, + SessionModelTransport.Service.of({ + bind: () => ({ execute: () => Effect.die("Unexpected WebSocket execution") }), + close: () => Effect.void, + closeAll: Effect.void, + }), +) + +const it = testEffect( + AppNodeBuilder.build( + LayerNode.group([ + Database.node, + Bus.node, + SessionProjector.node, + SessionStore.node, + SessionEnvironment.node, + Session.node, + Instance.node, + LocationServiceMap.node, + ]), + [ + Project.node.replace(globalProjectNode), + SessionExecution.node.replace(SessionExecution.noopLayer), + SessionModelTransport.node.replace(transport), + offlineModels, + ], + ), +) + +const fixture = Effect.gen(function* () { + const temporary = yield* tmpdirScoped() + const location = Location.Ref.make({ directory: AbsolutePath.make(temporary.path) }) + const locations = yield* LocationServiceMap.Service + const context = yield* Effect.acquireRelease(locations.contextEffect(location), () => locations.invalidate(location)) + const server = (identity: string) => + new ConfigMCP.Local({ + type: "local", + command: [ + process.execPath, + path.join(import.meta.dir, "fixture/mcp-identity.ts"), + identity, + path.join(temporary.path, `${identity}.pid`), + ], + }) + const pid = (identity: string) => + Effect.promise(() => Bun.file(path.join(temporary.path, `${identity}.pid`)).text()).pipe(Effect.map(Number)) + return { + location, + server, + pid, + mcp: Context.get(context, Mcp.Service), + mcpTools: Context.get(context, McpTool.Service), + registry: Context.get(context, Tool.Service), + } +}) + +const whoami = (mcp: Mcp.Interface, sessionID?: Session.ID) => + mcp + .callTool({ server: "ctx", name: "whoami", sessionID }) + .pipe(Effect.map((result) => result.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join(""))) + +// The harness still reads the user's global config, so assertions only look at the fixture's server. +const toolNames = (tools: ReadonlyArray) => + tools.filter((tool) => tool.server === "ctx").map((tool) => `${tool.server}.${tool.name}`) +const serverNames = (servers: ReadonlyArray) => + servers.map((server) => server.name).filter((name) => name === "ctx") + +const running = (pid: number) => { + try { + process.kill(pid, 0) + return true + } catch { + return false + } +} + +const exited = (pid: number) => + Effect.suspend(() => (running(pid) ? Effect.fail(`process ${pid} is still running`) : Effect.void)).pipe( + Effect.retry({ times: 300, schedule: Schedule.spaced("10 millis") }), + ) + +describe("Session-scoped MCP servers", () => { + it.live("are visible only to their Session tree and shadow Location servers there", () => + Effect.gen(function* () { + const test = yield* fixture + const sessions = yield* Session.Service + const root = yield* sessions.create({ location: test.location }) + const child = yield* sessions.create({ parentID: root.id }) + const other = yield* sessions.create({ location: test.location }) + const bystander = yield* sessions.create({ location: test.location }) + + yield* test.mcp.add("ctx", test.server("root"), root.id) + + expect(toolNames(yield* test.mcp.tools(root.id))).toEqual(["ctx.only_root", "ctx.whoami"]) + expect(toolNames(yield* test.mcp.tools(child.id))).toEqual(["ctx.only_root", "ctx.whoami"]) + expect(toolNames(yield* test.mcp.tools(other.id))).toEqual([]) + expect(toolNames(yield* test.mcp.tools())).toEqual([]) + expect(serverNames(yield* test.mcp.servers())).toEqual([]) + expect(serverNames(yield* test.mcp.servers(child.id))).toEqual(["ctx"]) + expect(yield* whoami(test.mcp, child.id)).toBe("root") + expect(yield* whoami(test.mcp, other.id).pipe(Effect.flip)).toBeInstanceOf(Mcp.NotFoundError) + + yield* test.mcp.add("ctx", test.server("other"), other.id) + yield* test.mcp.add("ctx", test.server("location")) + + expect(yield* whoami(test.mcp, root.id)).toBe("root") + expect(yield* whoami(test.mcp, other.id)).toBe("other") + expect(yield* whoami(test.mcp, bystander.id)).toBe("location") + expect(yield* whoami(test.mcp)).toBe("location") + expect(toolNames(yield* test.mcp.tools(root.id))).toEqual(["ctx.only_root", "ctx.whoami"]) + expect(toolNames(yield* test.mcp.tools())).toEqual(["ctx.only_location", "ctx.whoami"]) + + yield* waitForCodeModeTool(test.registry, "ctx.only_location") + const listed = (sessionID: Session.ID) => + test.mcpTools.overlay(sessionID).pipe( + Effect.flatMap((overlay) => test.registry.snapshot(undefined, overlay)), + Effect.map((snapshot) => + (snapshot.codeModeCatalog ? codeModeListings(snapshot.codeModeCatalog) : []) + .map((tool) => tool.path) + .filter((path) => path.startsWith("ctx.")), + ), + ) + expect(yield* listed(child.id)).toEqual(["ctx.only_root", "ctx.whoami"]) + expect(yield* listed(bystander.id)).toEqual(["ctx.only_location", "ctx.whoami"]) + }), + ) + + it.live("releases servers on replacement, removal, and Session deletion", () => + Effect.gen(function* () { + const test = yield* fixture + const sessions = yield* Session.Service + const first = yield* sessions.create({ location: test.location }) + const second = yield* sessions.create({ location: test.location }) + + yield* test.mcp.add("ctx", test.server("first"), first.id) + yield* test.mcp.add("ctx", test.server("second"), second.id) + const firstPid = yield* test.pid("first") + const secondPid = yield* test.pid("second") + + yield* test.mcp.add("ctx", test.server("first"), first.id) + expect(yield* test.pid("first")).toBe(firstPid) + expect(running(firstPid)).toBe(true) + + yield* test.mcp.add("ctx", test.server("replaced"), first.id) + yield* exited(firstPid) + expect(yield* whoami(test.mcp, first.id)).toBe("replaced") + expect(yield* whoami(test.mcp, second.id)).toBe("second") + expect(running(secondPid)).toBe(true) + + const replacedPid = yield* test.pid("replaced") + yield* test.mcp.remove("ctx", first.id) + yield* exited(replacedPid) + expect(toolNames(yield* test.mcp.tools(first.id))).toEqual([]) + expect(yield* test.mcp.remove("ctx", first.id).pipe(Effect.flip)).toBeInstanceOf(Mcp.NotFoundError) + + yield* sessions.remove(second.id) + yield* exited(secondPid) + expect(toolNames(yield* test.mcp.tools(second.id))).toEqual([]) + }), + ) +}) diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts index 81785d1d369..18419b02415 100644 --- a/packages/core/test/mcp.test.ts +++ b/packages/core/test/mcp.test.ts @@ -30,6 +30,7 @@ import { McpStdio } from "@opencode/core/mcp/stdio" import { Permission } from "@opencode/core/permission" import { AbsolutePath } from "@opencode/core/schema" import { Session } from "@opencode/core/session" +import { SessionStore } from "@opencode/core/session/store" import { State } from "@opencode/core/state" import { McpTool } from "@opencode/core/tool/mcp" import { McpResourceTools } from "@opencode/core/tool/plugin/mcp-resource" @@ -348,6 +349,7 @@ function resourceMcpLayer( }, }), Layer.mock(Credential.Service, {}), + Layer.mock(SessionStore.Service, {}), overrides?.environment ?? hostEnvironmentLayer, ), ), @@ -1989,8 +1991,17 @@ testEffect(Layer.empty).live("keeps MCP config snapshots stable during an in-fli const shutdownIt = testEffect( AppNodeBuilder.build( - LayerNode.group([Bus.node, Integration.node, Credential.node, Form.node, Environment.node, Location.node]), + LayerNode.group([ + Bus.node, + Integration.node, + Credential.node, + Form.node, + Environment.node, + Location.node, + SessionStore.node, + ]), [ + SessionStore.node.replace(Layer.mock(SessionStore.Service, {})), Location.node.replace( Layer.succeed( Location.Service, diff --git a/packages/protocol/src/groups/session.ts b/packages/protocol/src/groups/session.ts index d6cc9358bcf..2e072cc6a84 100644 --- a/packages/protocol/src/groups/session.ts +++ b/packages/protocol/src/groups/session.ts @@ -4,6 +4,7 @@ import { PromptInput } from "@opencode/schema/prompt-input" import { Session } from "@opencode/schema/session" import { SessionStats } from "@opencode/schema/session-stats" import { InstructionEntry } from "@opencode/schema/instruction-entry" +import { Mcp } from "@opencode/schema/mcp" import { Project } from "@opencode/schema/project" import { AbsolutePath, @@ -25,6 +26,7 @@ import { FormNotFoundError, InvalidCursorError, InvalidRequestError, + McpServerNotFoundError, MessageNotFoundError, ServiceUnavailableError, SessionBusyError, @@ -702,6 +704,38 @@ export const makeSessionGroup = < }), ), ) + .add( + HttpApiEndpoint.put("session.mcp.add", "/api/experimental/session/:sessionID/mcp/:server", { + params: { sessionID: Session.ID, server: Schema.String }, + payload: Schema.Struct({ config: Mcp.ServerConfig }), + success: HttpApiSchema.NoContent, + error: SessionNotFoundError, + }) + .middleware(sessionLocationMiddleware) + .annotateMerge( + OpenApi.annotations({ + identifier: "experimental.session.mcp.add", + summary: "Add session MCP server", + description: + "Add or replace an MCP server visible only to this session and its child sessions, connecting it immediately. It shadows a Location server of the same name for those sessions, is not persisted, and is released when removed or when the session is deleted or moved. Re-adding an identical config is a no-op.", + }), + ), + ) + .add( + HttpApiEndpoint.delete("session.mcp.remove", "/api/experimental/session/:sessionID/mcp/:server", { + params: { sessionID: Session.ID, server: Schema.String }, + success: HttpApiSchema.NoContent, + error: [SessionNotFoundError, McpServerNotFoundError], + }) + .middleware(sessionLocationMiddleware) + .annotateMerge( + OpenApi.annotations({ + identifier: "experimental.session.mcp.remove", + summary: "Remove session MCP server", + description: "Stop an MCP server registered for this session and remove it.", + }), + ), + ) .add( HttpApiEndpoint.post("session.generate", "/api/session/:sessionID/generate", { params: { sessionID: Session.ID }, diff --git a/packages/server/src/handlers/session.ts b/packages/server/src/handlers/session.ts index cefdef08efd..f5f355450c1 100644 --- a/packages/server/src/handlers/session.ts +++ b/packages/server/src/handlers/session.ts @@ -4,6 +4,7 @@ import { SessionTitle } from "@opencode/core/session/title" import { SessionTransfer } from "@opencode/core/session/transfer" import { InstructionEntry } from "@opencode/core/session/instruction-entry" import { Form } from "@opencode/core/form" +import { Mcp } from "@opencode/core/mcp/index" import { DateTime, Effect, Stream } from "effect" import { HttpApiBuilder, HttpApiSchema } from "effect/unstable/httpapi" import { Api } from "../api" @@ -17,6 +18,7 @@ import { FormNotFoundError, InvalidRequestError, InvalidCursorError, + McpServerNotFoundError, MessageNotFoundError, ServiceUnavailableError, SessionBusyError, @@ -583,6 +585,28 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl return HttpApiSchema.NoContent.make() }), ) + .handle( + "session.mcp.add", + Effect.fn(function* (ctx) { + const mcp = yield* Mcp.Service + yield* mcp.add(ctx.params.server, ctx.payload.config, ctx.params.sessionID) + return HttpApiSchema.NoContent.make() + }), + ) + .handle( + "session.mcp.remove", + Effect.fn(function* (ctx) { + const mcp = yield* Mcp.Service + yield* mcp + .remove(ctx.params.server, ctx.params.sessionID) + .pipe( + Effect.mapError( + (error) => new McpServerNotFoundError({ server: error.server, message: error.message }), + ), + ) + return HttpApiSchema.NoContent.make() + }), + ) .handle( "session.generate", Effect.fn(function* (ctx) { diff --git a/packages/server/test/session-mcp.test.ts b/packages/server/test/session-mcp.test.ts new file mode 100644 index 00000000000..e1534326a75 --- /dev/null +++ b/packages/server/test/session-mcp.test.ts @@ -0,0 +1,44 @@ +import { expect } from "bun:test" +import { Session } from "@opencode/schema/session" +import { Effect, Schema } from "effect" +import { it } from "../../core/test/lib/effect" +import { ServerFetch } from "../src/fetch" + +const SessionResponse = Schema.Struct({ data: Schema.toEncoded(Session.Info) }) + +it.live("adds and removes session-scoped MCP servers", () => + Effect.gen(function* () { + const handler = yield* ServerFetch.make({ + app: { version: "test" }, + database: { path: ":memory:" }, + fs: { filewatcher: false }, + models: { fetch: false }, + }) + const request = (path: string, method: string, body?: unknown) => + Effect.promise(async () => { + const response = await handler( + new Request(`http://opencode.local${path}`, { + method, + headers: { "content-type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + }), + ) + return { status: response.status, body: response.status === 204 ? undefined : await response.json() } + }) + const config = { config: { type: "local", command: ["unused"], disabled: true } } + + const created = Schema.decodeUnknownSync(SessionResponse)((yield* request("/api/session", "POST", {})).body) + const path = `/api/experimental/session/${created.data.id}/mcp/ctx` + + expect((yield* request(path, "PUT", config)).status).toBe(204) + expect((yield* request(path, "DELETE")).status).toBe(204) + expect(yield* request(path, "DELETE")).toMatchObject({ + status: 404, + body: { _tag: "McpServerNotFoundError", server: "ctx" }, + }) + expect(yield* request("/api/experimental/session/ses_missing/mcp/ctx", "PUT", config)).toMatchObject({ + status: 404, + body: { _tag: "SessionNotFoundError" }, + }) + }).pipe(Effect.scoped), +)