import { Cause, Clock, Context, Effect, Exit, Layer, Match, Stream, Tracer, type Scope, } from "effect"; import { McpProtocol, McpServer } from "effect/ai"; import { HttpBody, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; import type { ElicitationMode } from "../contracts/elicitation.ts"; import { McpToolkit, NativeMcpToolkit, BrowserMcpToolkit, type McpOptions, } from "../contracts/tools.ts"; import type { BrowserExecutionResult } from "../contracts/browser-tools.ts"; import type { BrowserApprovals, BrowserDelivery } from "../contracts/browser.ts"; import type { McpExecutionResult } from "../contracts/execute.ts"; import { makeExecutions } from "./executions.ts"; import { executeNative } from "./native-elicitation.ts"; import { callTools, describeCatalog, executeProgram, searchCatalog } from "./execute.ts"; import { decodeSkillsInput, skills } from "./skills.ts"; import { skillCatalog } from "./skill-catalog.ts"; import { eventsHandler } from "./events.ts"; import { withOperationSpan } from "./telemetry.ts"; const observeExecution = (name: "mcp.execute" | "mcp.call" | "mcp.resume") => (work: Effect.Effect) => Effect.gen(function* () { const started = yield* Clock.currentTimeMillis; yield* Effect.annotateCurrentSpan("executor.attempt.id", crypto.randomUUID()); return yield* work.pipe( Effect.onExit((exit) => Effect.gen(function* () { yield* Effect.annotateCurrentSpan( "executor.duration_ms", Math.max(0, (yield* Clock.currentTimeMillis) - started), ); if (Exit.isFailure(exit)) { yield* Effect.annotateCurrentSpan( "executor.outcome", Cause.hasInterruptsOnly(exit.cause) ? "cancelled" : "failed", ); return; } const result: McpExecutionResult = exit.value; yield* Match.value(result).pipe( Match.when({ status: "completed" }, ({ execution }) => Effect.annotateCurrentSpan({ "executor.outcome": execution.ok ? "completed" : "failed", "executor.tool_call.count": execution.toolCalls.length, "executor.tool_call.succeeded": execution.toolCalls.filter( ({ outcome }) => outcome === "success", ).length, ...(execution.ok ? {} : { "error.type": execution.error.kind }), }), ), Match.when({ status: "approval-required" }, () => Effect.annotateCurrentSpan("executor.outcome", "pending"), ), Match.when({ status: "input-required" }, () => Effect.annotateCurrentSpan("executor.outcome", "pending"), ), Match.when({ status: "capacity-exceeded" }, () => Effect.annotateCurrentSpan({ "executor.outcome": "failed", "error.type": "CapacityExceeded", }), ), Match.when({ status: "unavailable" }, ({ reason }) => Effect.annotateCurrentSpan({ "executor.outcome": "failed", "error.type": "ContinuationUnavailable", "executor.resume.unavailable_reason": reason, }), ), Match.when({ status: "busy" }, () => Effect.annotateCurrentSpan("executor.outcome", "busy"), ), Match.exhaustive, ); }), ), ); }).pipe(withOperationSpan(name)); const protocols = [ McpProtocol.v2026_07_28, McpProtocol.v2025_11_25, McpProtocol.v2025_06_18, McpProtocol.v2025_03_26, ] as const; const nativeProtocols = [McpProtocol.v2025_11_25, McpProtocol.v2025_06_18] as const; const callerIdentity = (product: string, mode: Exclude) => JSON.stringify([product, mode]); const browserSessionSuffix = (session: string) => `,"browser",${JSON.stringify(session)}]`; const browserIdentity = (product: string, session: string) => JSON.stringify([product, "browser", session]); const withSseHeartbeat = (response: HttpServerResponse.HttpServerResponse) => { const body = response.body; const contentType = response.headers["content-type"]; if ( !(body instanceof HttpBody.Stream) || contentType?.split(";")[0]?.trim() !== "text/event-stream" ) return response; const comment = new TextEncoder().encode(": keep-alive\n\n"); const heartbeat = Stream.tick("5 seconds").pipe( Stream.drop(1), Stream.map(() => comment), ); return HttpServerResponse.setBody( response, HttpBody.stream(Stream.merge(body.stream, heartbeat, { haltStrategy: "left" }), contentType), ); }; const withLink = ( result: McpExecutionResult, sessionId: string, delivery: BrowserDelivery, ): Effect.Effect => result.status === "approval-required" || result.status === "input-required" ? delivery .url({ sessionId, requestId: result.requestId }) .pipe(Effect.map((approvalUrl) => ({ ...result, approvalUrl }))) : Effect.succeed(result); export const makeMcp = (options: McpOptions) => Effect.gen(function* () { const executions = yield* makeExecutions( options.limits, options.beforeExecute, options.interactions, ); const handler = (mode: ElicitationMode) => Effect.gen(function* () { const delivery = options.browser; if (mode === "browser" && delivery === undefined) return Effect.succeed( HttpServerResponse.jsonUnsafe( { error: "Browser approval is unavailable on this host." }, { status: 400 }, ), ); const served = mode === "native" ? nativeProtocols : protocols; const caller = Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; const product = yield* options.caller; const sessionId = request.headers["mcp-session-id"] ?? "stateless"; return { id: mode === "browser" ? browserIdentity(product, sessionId) : callerIdentity(product, mode), sessionId, }; }); const skill = (params: unknown) => decodeSkillsInput(params).pipe( Effect.flatMap((input) => skills(input, options.backend).pipe( Effect.tap((result) => "content" in result ? options.annotateSkillRead(result) : Effect.void, ), withOperationSpan("mcp.skills", { attributes: { "executor.skill.operation": input.name === undefined ? "list" : "read", }, }), ), ), ); const approval = mode === "automatic" ? "client" : "ask"; const search = (input: Parameters[1]) => searchCatalog(options.backend, input).pipe(withOperationSpan("mcp.search")); const describe = (input: Parameters[1]) => describeCatalog(options.backend, input).pipe(withOperationSpan("mcp.describe")); const toolkit = mode === "native" ? McpServer.toolkit(NativeMcpToolkit).pipe( Layer.provide( NativeMcpToolkit.toLayer({ execute: ({ code }) => caller.pipe( Effect.flatMap(({ id }) => executeNative(executions, id, options.backend, executeProgram(code)), ), observeExecution("mcp.execute"), ), call: (input) => caller.pipe( Effect.flatMap(({ id }) => executeNative( executions, id, options.backend, callTools(input), "client", ), ), observeExecution("mcp.call"), ), search, describe, skills: skill, }), ), ) : mode === "browser" && delivery !== undefined ? McpServer.toolkit(BrowserMcpToolkit).pipe( Layer.provide( BrowserMcpToolkit.toLayer({ execute: ({ code }) => caller.pipe( Effect.flatMap(({ id, sessionId }) => executions .execute(id, options.backend, executeProgram(code), "result") .pipe( Effect.flatMap((result) => withLink(result, sessionId, delivery)), ), ), observeExecution("mcp.execute"), ), call: (input) => caller.pipe( Effect.flatMap(({ id, sessionId }) => executions .execute(id, options.backend, callTools(input), "result") .pipe( Effect.flatMap((result) => withLink(result, sessionId, delivery)), ), ), observeExecution("mcp.call"), ), search, describe, resume: ({ requestId }) => caller.pipe( Effect.flatMap(({ id, sessionId }) => Effect.gen(function* () { const response = yield* executions.browserAnswer( id, requestId, delivery.pollMs ?? 25_000, ); if (response !== undefined) return yield* executions .resume(id, options.backend, { requestId, response }) .pipe( Effect.flatMap((result) => withLink(result, sessionId, delivery), ), ); const pending = yield* executions.pendingInteraction(id, requestId); return yield* pending === undefined ? executions.unavailable(id, requestId) : withLink(pending, sessionId, delivery); }), ), observeExecution("mcp.resume"), ), skills: skill, }), ), ) : McpServer.toolkit(McpToolkit).pipe( Layer.provide( McpToolkit.toLayer({ execute: ({ code }) => caller.pipe( Effect.flatMap(({ id }) => executions.execute( id, options.backend, executeProgram(code), "result", approval, ), ), observeExecution("mcp.execute"), ), call: (input) => caller.pipe( Effect.flatMap(({ id }) => executions.execute( id, options.backend, callTools(input), "result", approval, ), ), observeExecution("mcp.call"), ), search, describe, resume: (input) => caller.pipe( Effect.flatMap(({ id }) => executions.resume(id, options.backend, input)), observeExecution("mcp.resume"), ), skills: skill, }), ), ); return yield* Layer.mergeAll( toolkit, McpServer.events(eventsHandler(options.backend)), McpServer.skillCatalog(skillCatalog(options.backend)), ).pipe( Layer.provide( McpServer.layerHttp({ name: "Executor", version: "0.1.0", instructions: options.instructions, path: "/mcp", protocols: served, sessions: options.sessions?.(mode), maxSessions: options.maxSessions, ...(mode === "browser" && options.maxSessions !== undefined ? { heldSession: (session: string) => { const named = browserSessionSuffix(session); return executions.holds((caller) => caller.endsWith(named)); }, } : {}), }), ), HttpRouter.toHttpEffect, Effect.provideService(Layer.CurrentMemoMap, yield* Layer.makeMemoMap), Effect.orDie, ); }).pipe( Effect.updateContext((context: Context.Context) => Context.omit(Tracer.ParentSpan)(context), ), ); const context = yield* Effect.context>>(); const onFirstUse = (mode: ElicitationMode) => Effect.cached( handler(mode).pipe( Effect.updateContext>>(() => context), Effect.uninterruptible, ), ).pipe(Effect.map(Effect.flatten)); const model = yield* onFirstUse("model"), native = yield* onFirstUse("native"), browser = yield* onFirstUse("browser"), automatic = yield* onFirstUse("automatic"); const http = Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => { const url = new URL(request.url, "http://mcp.internal"); return options.mode.pipe( Effect.flatMap((mode) => Match.value(mode).pipe( Match.when("model", () => model), Match.when("native", () => native), Match.when("browser", () => browser), Match.when("automatic", () => automatic), Match.exhaustive, ), ), Effect.provideService( HttpServerRequest.HttpServerRequest, request.modify({ url: `/mcp${url.search}` }), ), ); }).pipe(Effect.map(withSseHeartbeat)); const approvals: BrowserApprovals = { get: (product, address) => executions.browserView(browserIdentity(product, address.sessionId), address.requestId), answer: (product, address, response) => executions.answerInBrowser( browserIdentity(product, address.sessionId), address.requestId, response, ), }; return { http, approvals, programs: executions.live }; }); export const mcp = (options: McpOptions) => Layer.unwrap(makeMcp(options).pipe(Effect.map(({ http }) => HttpRouter.add("*", "/mcp", http))));