diff --git a/apps/cli/package.json b/apps/cli/package.json index 760b7c6a41..8daeeb7e5f 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -30,7 +30,6 @@ "@executor-js/runtime-quickjs": "workspace:*", "@executor-js/sdk": "workspace:*", "@jitl/quickjs-wasmfile-release-sync": "catalog:", - "@modelcontextprotocol/client": "2.0.0", "@modelcontextprotocol/sdk": "^1.29.0", "@sentry/bun": "^10.57.0", "effect": "catalog:", diff --git a/apps/cli/src/main.ts b/apps/cli/src/main.ts index 03df64876c..6fa8a26fa8 100644 --- a/apps/cli/src/main.ts +++ b/apps/cli/src/main.ts @@ -75,7 +75,7 @@ import type { PlatformError } from "effect/PlatformError"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Cause from "effect/Cause"; -import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js"; diff --git a/apps/cloud/src/auth/handlers.ts b/apps/cloud/src/auth/handlers.ts index 6445393b61..03b44f5a05 100644 --- a/apps/cloud/src/auth/handlers.ts +++ b/apps/cloud/src/auth/handlers.ts @@ -631,9 +631,6 @@ export const CloudSessionAuthHandlers = HttpApiBuilder.group( Effect.gen(function* () { const owner = yield* requireSelectedOrganization; const stub = getMcpSessionStub(params.mcpSessionId); - if (!stub) { - return yield* new McpExecutionNotFoundError({ executionId: params.executionId }); - } const result = yield* Effect.promise(() => stub.getPausedExecutionForApproval(params.executionId, { accountId: owner.accountId, @@ -655,9 +652,6 @@ export const CloudSessionAuthHandlers = HttpApiBuilder.group( Effect.gen(function* () { const owner = yield* requireSelectedOrganization; const stub = getMcpSessionStub(params.mcpSessionId); - if (!stub) { - return yield* new McpExecutionNotFoundError({ executionId: params.executionId }); - } const result = yield* Effect.promise(() => stub.resumeExecutionForApproval( params.executionId, diff --git a/apps/cloud/src/env-augment.d.ts b/apps/cloud/src/env-augment.d.ts index cb8070ae63..ef0b54da4a 100644 --- a/apps/cloud/src/env-augment.d.ts +++ b/apps/cloud/src/env-augment.d.ts @@ -91,10 +91,6 @@ declare global { MCP_RESOURCE_ORIGIN?: string; MCP_SESSION_TIMEOUT_MS?: string; MCP_PAUSED_SESSION_IDLE_TIMEOUT_MS?: string; - /** HMAC key for MCP 2026-07-28 continuation state (32+ byte secret). */ - MCP_REQUEST_STATE_KEY?: string; - /** Emergency rollback for inbound MCP 2026-07-28 traffic only. */ - MCP_2026_07_28_ENABLED?: string; NODE_ENV?: string; // Shared with frontend diff --git a/apps/cloud/src/mcp-session.e2e.node.test.ts b/apps/cloud/src/mcp-session.e2e.node.test.ts index 078200c237..37d140ab01 100644 --- a/apps/cloud/src/mcp-session.e2e.node.test.ts +++ b/apps/cloud/src/mcp-session.e2e.node.test.ts @@ -6,7 +6,7 @@ // FumaDB/Drizzle handle (the 2026-04-16 prod outage was a schema spread bug // here; see db/db.schema.test.ts) // - `createExecutionEngine` with an in-process code executor -// - `buildMcpServer` for the MCP request surface +// - `createExecutorMcpServer` for the MCP request surface // - Real `@modelcontextprotocol/sdk` Client → server round-trips // // This test replicates the DO's init path (minus the WorkerTransport and @@ -22,7 +22,7 @@ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { ElicitRequestSchema } from "@modelcontextprotocol/sdk/types.js"; import type { ClientCapabilities } from "@modelcontextprotocol/sdk/types.js"; -import { buildMcpServer } from "@executor-js/host-mcp/tool-server"; +import { createExecutorMcpServer } from "@executor-js/host-mcp/tool-server"; import { createExecutionEngine } from "@executor-js/execution"; import { makeQuickJsExecutor } from "@executor-js/runtime-quickjs"; import { collectTables } from "@executor-js/api/server"; @@ -138,12 +138,8 @@ const openSession = ( Effect.gen(function* () { const executor = yield* buildScopedExecutor(organizationId, `Org ${organizationId}`, options); const engine = createExecutionEngine({ executor, codeExecutor: makeQuickJsExecutor() }); - const mcpServer = yield* buildMcpServer({ + const mcpServer = yield* createExecutorMcpServer({ engine, - appsEnabled: false, - requestStateSigningKey: new Uint8Array(32).fill(23), - requestStatePrincipal: `cloud-mcp-test:${organizationId}`, - sessionful: true, elicitationMode: options.elicitationMode ? { mode: options.elicitationMode } : undefined, }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/apps/cloud/src/mcp/agent-handler.test.ts b/apps/cloud/src/mcp/agent-handler.test.ts deleted file mode 100644 index 0f6e539a53..0000000000 --- a/apps/cloud/src/mcp/agent-handler.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "@effect/vitest"; -import { Effect, Layer } from "effect"; - -import { - authenticated, - McpAuthProvider, - unauthorized, - type Principal, -} from "@executor-js/host-mcp"; - -import { cloudDeadSessionCacheForTest, makeCloudMcpAgentHandler } from "./agent-handler"; - -const principal: Principal = { - accountId: "acct_test", - organizationId: "org_test", - organizationName: "Test Org", - email: "test@example.com", - name: "Test", - avatarUrl: null, - roles: ["member"], -}; - -const AuthProviderLive = Layer.succeed(McpAuthProvider)({ - discoveryRoutes: [], - resourceMetadataUrl: (request) => new URL("/.well-known/mcp", request.url).toString(), - authenticate: (request) => - Effect.succeed( - request.headers.has("authorization") ? authenticated(principal) : unauthorized(), - ), -}); - -const requestFor = (method: "GET" | "POST", sessionId: string, authenticated = true): Request => - new Request("https://executor.test/mcp", { - method, - headers: { - ...(authenticated ? { authorization: "Bearer test" } : {}), - "mcp-session-id": sessionId, - ...(method === "POST" ? { "content-type": "application/json" } : {}), - }, - ...(method === "POST" - ? { - body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }), - } - : {}), - }); - -const makeHarness = (owner: "not_found" | "terminated" = "not_found") => { - const ownerChecks = { count: 0 }; - const traces = { count: 0 }; - const stub = { - validateMcpSessionOwner: async () => { - ownerChecks.count += 1; - return owner; - }, - }; - const namespace = { - idFromString: (sessionId: string) => sessionId, - get: () => stub, - }; - // oxlint-disable-next-line executor/no-double-cast -- test boundary: the handler only reads the MCP_SESSION namespace in these legacy dead-session cases - const env = { MCP_SESSION: namespace } as unknown as Env; - // oxlint-disable-next-line executor/no-double-cast -- test boundary: no ExecutionContext capability is used before the dead-session response - const ctx = {} as unknown as ExecutionContext; - const handler = makeCloudMcpAgentHandler({ - authProvider: AuthProviderLive, - makeModernServerBuilder: () => ({ build: () => Effect.die("unused modern builder") }), - traceRequest: async (request, _env, _ctx, handle) => { - traces.count += 1; - return handle(request); - }, - }); - return { ctx, env, handler, ownerChecks, traces }; -}; - -describe("cloud MCP dead-session negative cache", () => { - beforeEach(() => { - vi.useRealTimers(); - cloudDeadSessionCacheForTest.clear(); - }); - - it.each([ - { method: "GET" as const, status: 405 }, - { method: "POST" as const, status: 404 }, - ])("serves a repeated $method without another DO lookup", async ({ method, status }) => { - const { ctx, env, handler, ownerChecks, traces } = makeHarness(); - const sessionId = `dead-${method.toLowerCase()}`; - - const first = await handler(requestFor(method, sessionId), env, ctx); - const second = await handler(requestFor(method, sessionId), env, ctx); - - expect(first.status).toBe(status); - expect(second.status).toBe(status); - expect(ownerChecks.count).toBe(1); - expect(traces.count).toBe(1); - }); - - it("keeps authentication ahead of cached session existence", async () => { - const { ctx, env, handler, ownerChecks, traces } = makeHarness(); - const sessionId = "dead-auth"; - - expect((await handler(requestFor("GET", sessionId), env, ctx)).status).toBe(405); - const unauthenticated = await handler(requestFor("GET", sessionId, false), env, ctx); - - expect(unauthenticated.status).toBe(401); - expect(ownerChecks.count).toBe(1); - expect(traces.count).toBe(1); - }); - - it("preserves the terminated-session response on a cached hit", async () => { - const { ctx, env, handler, ownerChecks, traces } = makeHarness("terminated"); - const sessionId = "dead-terminated"; - - const first = await handler(requestFor("POST", sessionId), env, ctx); - const second = await handler(requestFor("POST", sessionId), env, ctx); - - expect(first.status).toBe(404); - expect(second.status).toBe(404); - expect(await second.text()).toBe(await first.text()); - expect(ownerChecks.count).toBe(1); - expect(traces.count).toBe(1); - }); - - it("consults the DO again after five minutes", async () => { - vi.useFakeTimers(); - vi.setSystemTime(0); - const { ctx, env, handler, ownerChecks } = makeHarness(); - const sessionId = "dead-expiry"; - - expect((await handler(requestFor("GET", sessionId), env, ctx)).status).toBe(405); - vi.advanceTimersByTime(5 * 60 * 1_000 + 1); - expect((await handler(requestFor("GET", sessionId), env, ctx)).status).toBe(405); - - expect(ownerChecks.count).toBe(2); - }); - - it("evicts the oldest entry without exceeding 4,096 sessions", () => { - for (let index = 0; index <= 4_096; index += 1) { - cloudDeadSessionCacheForTest.remember(`dead-${index}`, 0); - } - - expect(cloudDeadSessionCacheForTest.size()).toBe(4_096); - expect(cloudDeadSessionCacheForTest.has("dead-0", 1)).toBe(false); - expect(cloudDeadSessionCacheForTest.has("dead-1", 1)).toBe(true); - expect(cloudDeadSessionCacheForTest.has("dead-4096", 1)).toBe(true); - }); -}); diff --git a/apps/cloud/src/mcp/agent-handler.ts b/apps/cloud/src/mcp/agent-handler.ts index 0a8980bfe9..7738e79c6a 100644 --- a/apps/cloud/src/mcp/agent-handler.ts +++ b/apps/cloud/src/mcp/agent-handler.ts @@ -1,84 +1,40 @@ import * as OtelTracer from "@effect/opentelemetry/Tracer"; -import { Effect, Layer, Predicate } from "effect"; +import { Effect, Predicate } from "effect"; import { McpAuthProvider, jsonRpcErrorBody, - mcpModernDisabledResponse, defaultMcpResource, UNAVAILABLE_RETRY_AFTER_SECONDS, type AuthOutcome, - type McpModernServerBuilder, type McpResource, } from "@executor-js/host-mcp"; -import { requestBodyFromRequest } from "@executor-js/host-mcp/tool-server"; import { currentPropagationHeaders, readArtifactsEnabled, readElicitationMode, - withMcpResponseHeaders, - withPropagationHeaders, withVerifiedIdentityHeaders, } from "@executor-js/cloudflare/mcp/do-headers"; import type { McpSessionProps } from "@executor-js/cloudflare/mcp/agent-durable-object"; -import { - classifyMcpProtocolEra, - makeMcpModernRequestRouter, - mcpCorsPreflightResponse, - requireMcpRequestStateKey, -} from "@executor-js/cloudflare/mcp/modern-request-router"; -import { mcpExecutionOwnerDirectoryFromNamespace } from "@executor-js/cloudflare/mcp/execution-owner-directory"; -import { createMcpSessionStub, mcpSessionStub } from "@executor-js/cloudflare/mcp/session-stub"; +import { mcpSessionStub } from "@executor-js/cloudflare/mcp/session-stub"; import { wrapMcpSseResponse } from "../observability/memory-metrics"; import { WorkerTelemetryLive } from "../observability/telemetry"; import { cloudMcpAuth } from "./auth-provider"; +import { McpSessionDOSqlite } from "./session-durable-object"; import { parseTraceparent } from "./traceparent"; -const DEAD_SESSION_CACHE_TTL_MS = 5 * 60 * 1_000; -const DEAD_SESSION_CACHE_MAX_ENTRIES = 4_096; -const deadSessionExpiries = new Map(); -const timedOutSessionIds = new Set(); - -type DeadSessionReason = "not_found" | "timed_out"; - -const isDeadSessionCached = (sessionId: string, now = Date.now()): boolean => { - const expiry = deadSessionExpiries.get(sessionId); - if (expiry === undefined) return false; - if (expiry > now) return true; - deadSessionExpiries.delete(sessionId); - timedOutSessionIds.delete(sessionId); - return false; -}; - -const cacheDeadSession = (sessionId: string, reason: DeadSessionReason, now = Date.now()): void => { - deadSessionExpiries.delete(sessionId); - if (deadSessionExpiries.size >= DEAD_SESSION_CACHE_MAX_ENTRIES) { - const oldestSessionId = deadSessionExpiries.keys().next().value; - if (oldestSessionId !== undefined) { - deadSessionExpiries.delete(oldestSessionId); - timedOutSessionIds.delete(oldestSessionId); - } - } - deadSessionExpiries.set(sessionId, now + DEAD_SESSION_CACHE_TTL_MS); - if (reason === "timed_out") timedOutSessionIds.add(sessionId); - else timedOutSessionIds.delete(sessionId); -}; - -const cachedDeadSessionMessage = (sessionId: string): string => - timedOutSessionIds.has(sessionId) ? "Session timed out, please reconnect" : "Session not found"; - -/** Test-only access to reset and verify the isolate-local dead-session cache. */ -export const cloudDeadSessionCacheForTest = { - clear: (): void => { - deadSessionExpiries.clear(); - timedOutSessionIds.clear(); - }, - remember: (sessionId: string, now?: number): void => - cacheDeadSession(sessionId, "not_found", now), - has: isDeadSessionCached, - size: (): number => deadSessionExpiries.size, -}; +const corsPreflightResponse = (): Response => + new Response(null, { + status: 204, + headers: { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, DELETE, OPTIONS", + "access-control-allow-headers": + "content-type, authorization, mcp-session-id, accept, mcp-protocol-version", + "access-control-expose-headers": "mcp-session-id, WWW-Authenticate", + }, + }); const jsonRpcResponse = ( status: number, @@ -90,25 +46,6 @@ const jsonRpcResponse = ( ? jsonRpcErrorBody(status, code, message) : jsonRpcErrorBody(status, code, message, { challenge }); -/** - * A dead session id answers by request method. POST/DELETE keep the 404 that - * tells a compliant client to re-initialize. A standalone GET gets 405: the - * v1 SDK treats that as "no SSE stream offered" and stops retrying quietly, - * which breaks the reconnect loops of pre-cutover always-on deployments — - * their GET-404 path never re-initialized, it just retried forever. - */ -const deadSessionResponse = (method: string, message: string): Response => - method === "GET" - ? new Response(JSON.stringify({ jsonrpc: "2.0", error: { code: -32001, message }, id: null }), { - status: 405, - headers: { - "content-type": "application/json", - allow: "POST, DELETE", - "access-control-allow-origin": "*", - }, - }) - : jsonRpcResponse(404, -32001, message); - const renderAuthError = ( auth: McpAuthProvider["Service"], request: Request, @@ -142,14 +79,14 @@ const renderAuthError = ( }); }; -const authenticate = (request: Request, authProvider: Layer.Layer) => +const authenticate = (request: Request) => Effect.gen(function* () { const auth = yield* McpAuthProvider; const outcome = yield* auth.authenticate(request); return { auth, outcome }; - }).pipe(Effect.provide(authProvider)); + }).pipe(Effect.provide(cloudMcpAuth)); -// The earlier shared envelope ran the MCP auth path inside the Effect app, whose +// The pre-Agents envelope ran the MCP auth path inside the Effect app, whose // HttpMiddleware provided the OTEL tracer — that is where the `mcp.request` // span (client fingerprint, rpc method, auth outcome) exported from. This // handler dispatches from the raw worker entry instead, so a bare @@ -171,21 +108,6 @@ const runTraced = (request: Request, program: Effect.Effect): Promise = ); }; -type TraceCloudMcpRequest = ( - request: Request, - env: Env, - ctx: ExecutionContext, - handle: (tracedRequest: Request) => Promise, -) => Promise; - -interface CloudMcpAgentHandlerOptions { - readonly makeModernServerBuilder: ( - session: McpSessionProps["session"], - ) => McpModernServerBuilder["Service"]; - readonly authProvider?: Layer.Layer; - readonly traceRequest?: TraceCloudMcpRequest; -} - // The MCP resource the request targets. `server.ts` routes both the bare `/mcp` // and `/mcp/toolkits/` to this handler (`prepareMcpOrgScope` strips the org // selector but keeps the toolkit segment), so a session minted on a toolkit path @@ -218,25 +140,36 @@ const propsForPrincipal = ( }; }); -/** Build the cloud worker's authenticated legacy/modern MCP request handler. */ -export const makeCloudMcpAgentHandler = (options: CloudMcpAgentHandlerOptions) => { - const authProvider = options.authProvider ?? cloudMcpAuth; - const traceRequest = options.traceRequest ?? ((request, _env, _ctx, handle) => handle(request)); - const modern = makeMcpModernRequestRouter(); +export const makeCloudMcpAgentHandler = () => { + const serveOptions = { + binding: "MCP_SESSION", + transport: "streamable-http", + } as const; + // The agents SDK builds an exact-match `URLPattern` from the path handed to + // `serve` (see `createStreamingHttpHandler` in `agents/dist/mcp/index.js`) — + // a single `/mcp` handler never matches `/mcp/toolkits/` and falls + // through to its own internal 404. A second `serve` mounted on the + // parameterized path picks it up (`URLPattern` supports `:slug` segments); + // the auth/ownership/props logic above is unchanged and shared, only the + // final dispatch target differs. + const serve = McpSessionDOSqlite.serve("/mcp", serveOptions); + const serveToolkit = McpSessionDOSqlite.serve("/mcp/toolkits/:slug", serveOptions); + const ALLOWED_METHODS = new Set(["GET", "POST", "DELETE", "OPTIONS"]); - const handle = async (request: Request, env: Env, ctx: ExecutionContext): Promise => { - if (request.method === "OPTIONS") { - return mcpCorsPreflightResponse(request.headers.get("access-control-request-headers")); - } - // Preserve the old envelope's JSON-RPC 405 before authenticating, so - // unsupported methods never reach the session engine. + return async (request: Request, env: Env, ctx: ExecutionContext): Promise => { + if (request.method === "OPTIONS") return corsPreflightResponse(); + // The old envelope (packages/hosts/mcp/src/envelope.ts) answered anything + // outside GET/POST/DELETE/OPTIONS with a JSON-RPC 405; the agents SDK + // handler only understands its own transport verbs and falls through to + // a bare 404. Reject before authenticating so PUT/PATCH/etc never reach + // the session engine. if (!ALLOWED_METHODS.has(request.method)) { return jsonRpcResponse(405, -32001, "Method not allowed"); } const sessionId = request.headers.get("mcp-session-id"); - const { auth, outcome } = await runTraced(request, authenticate(request, authProvider)); + const { auth, outcome } = await runTraced(request, authenticate(request)); if (!Predicate.isTagged(outcome, "Authenticated")) { // Destroying a live session on auth grounds requires a POSITIVE // determination that access is genuinely gone — only `Forbidden` carries @@ -244,49 +177,17 @@ export const makeCloudMcpAgentHandler = (options: CloudMcpAgentHandlerOptions) = // / JWKS failure) and `Unauthorized` (retry with a fresh token) must leave // the session intact, so the condemn path is gated on `Forbidden` alone. if (Predicate.isTagged(outcome, "Forbidden") && sessionId) { - const session = mcpSessionStub(env.MCP_SESSION, sessionId); await Effect.runPromise( Effect.ignore( - session ? Effect.tryPromise(() => session._cf_scheduleDestroy()) : Effect.void, + Effect.tryPromise(() => + mcpSessionStub(env.MCP_SESSION, sessionId)._cf_scheduleDestroy(), + ), ), ); } return renderAuthError(auth, request, outcome); } - const parsedBody = await Effect.runPromise(requestBodyFromRequest(request)); - const era = await classifyMcpProtocolEra(request, parsedBody); - if (era === "modern") { - if (env.MCP_2026_07_28_ENABLED === "false") { - return mcpModernDisabledResponse(); - } - const resource = resourceFromPath(request); - const props = await runTraced( - request, - propsForPrincipal(request, outcome.principal, resource), - ); - (ctx as ExecutionContext & { props?: McpSessionProps }).props = props; - const forwarded = withVerifiedIdentityHeaders( - request, - { - accountId: outcome.principal.accountId, - organizationId: outcome.principal.organizationId, - }, - resource, - ); - return modern.fetch({ - request: forwarded, - parsedBody, - principal: outcome.principal, - resource, - props, - requestStateSigningKey: requireMcpRequestStateKey(env.MCP_REQUEST_STATE_KEY), - builder: options.makeModernServerBuilder(props.session), - sessions: env.MCP_SESSION, - executionOwners: mcpExecutionOwnerDirectoryFromNamespace(env.MCP_EXECUTION_OWNER), - }); - } - if (!sessionId && request.method === "DELETE") { // Matches the old envelope's contract (@modelcontextprotocol/sdk's // `WebStandardStreamableHTTPServerTransport.handleDeleteRequest`): 200, @@ -297,25 +198,19 @@ export const makeCloudMcpAgentHandler = (options: CloudMcpAgentHandlerOptions) = }); } - const existingSession = sessionId ? mcpSessionStub(env.MCP_SESSION, sessionId) : null; - if (sessionId && !existingSession) { - return deadSessionResponse(request.method, "Session not found"); - } - if (existingSession && sessionId) { - const owner = await existingSession.validateMcpSessionOwner({ + if (sessionId) { + const owner = await mcpSessionStub(env.MCP_SESSION, sessionId).validateMcpSessionOwner({ accountId: outcome.principal.accountId, organizationId: outcome.principal.organizationId, }); if (owner === "not_found") { - cacheDeadSession(sessionId, "not_found"); - return deadSessionResponse(request.method, "Session not found"); + return jsonRpcResponse(404, -32001, "Session not found"); } if (owner === "terminated") { // DELETE-condemned but the deferred destroy alarm hasn't wiped storage // yet. Same envelope as the post-destroy race below: the client must // treat the id as dead and reconnect. - cacheDeadSession(sessionId, "timed_out"); - return deadSessionResponse(request.method, "Session timed out, please reconnect"); + return jsonRpcResponse(404, -32001, "Session timed out, please reconnect"); } if (owner === "forbidden") { return jsonRpcResponse(403, -32003, "MCP session does not belong to the current bearer"); @@ -323,56 +218,42 @@ export const makeCloudMcpAgentHandler = (options: CloudMcpAgentHandlerOptions) = } const resource = resourceFromPath(request); - const propagation = await runTraced(request, currentPropagationHeaders(request)); - const forwarded = withPropagationHeaders( - withVerifiedIdentityHeaders( - request, - { - accountId: outcome.principal.accountId, - organizationId: outcome.principal.organizationId, - }, - resource, - ), - propagation, + const props = await runTraced(request, propsForPrincipal(request, outcome.principal, resource)); + (ctx as ExecutionContext & { props?: McpSessionProps }).props = props; + const forwarded = withVerifiedIdentityHeaders( + request, + { + accountId: outcome.principal.accountId, + organizationId: outcome.principal.organizationId, + }, + resource, ); - const target = existingSession ?? createMcpSessionStub(env.MCP_SESSION).stub; + const target = resource.kind === "toolkit" ? serveToolkit : serve; let response: Response; - // oxlint-disable-next-line executor/no-try-catch-or-throw -- adapter boundary: a condemned DO abort can reject its direct fetch + // oxlint-disable-next-line executor/no-try-catch-or-throw -- adapter boundary: the agents SDK aborts the isolate (throws) instead of returning a response for a condemned session try { - response = await target.fetch(forwarded); + response = await target.fetch(forwarded, env, ctx); } catch (error) { // `_cf_scheduleDestroy` (called above via DELETE) marks the DO - // condemned and schedules its alarm; the alarm's storage wipe then + // condemned and schedules its alarm; the alarm's `destroy()` then // `ctx.abort("destroyed")`s the isolate. A request that lands after the // alarm has already fired — same DO, same tick budget as the DELETE in - // tests — throws that abort reason out of `stub.fetch` instead of the + // tests — throws that abort reason out of `serve.fetch` instead of the // DO ever getting to answer. Map it to the old envelope's reconnect // error for a dead session (e2e/cloud/mcp-protocol.test.ts expects the // client to be told to reconnect, matching a timed-out session). // oxlint-disable-next-line executor/no-unknown-error-message -- adapter boundary: the abort reason is a plain runtime Error whose message IS the signal if (Predicate.isError(error) && error.message === "destroyed") { - if (sessionId) cacheDeadSession(sessionId, "timed_out"); - return deadSessionResponse(request.method, "Session timed out, please reconnect"); + return jsonRpcResponse(404, -32001, "Session timed out, please reconnect"); } // oxlint-disable-next-line executor/no-try-catch-or-throw -- adapter boundary: rethrow anything that isn't the condemned-DO abort to the Workers runtime unchanged throw error; } - return withMcpResponseHeaders(wrapMcpSseResponse(request, env, response)); - }; - - return async (request: Request, env: Env, ctx: ExecutionContext): Promise => { - const sessionId = request.headers.get("mcp-session-id"); - const cacheEligible = request.method !== "OPTIONS" && ALLOWED_METHODS.has(request.method); - if (cacheEligible && sessionId && isDeadSessionCached(sessionId)) { - return Effect.runPromise( - Effect.gen(function* () { - const { auth, outcome } = yield* authenticate(request, authProvider); - return Predicate.isTagged(outcome, "Authenticated") - ? deadSessionResponse(request.method, cachedDeadSessionMessage(sessionId)) - : renderAuthError(auth, request, outcome); - }).pipe(Effect.withTracerEnabled(false)), - ); + // The agents SDK answers a bare DELETE with 204; the old envelope's + // contract (see above) was 200 — rewrite for consistency. + if (request.method === "DELETE" && response.status === 204) { + return new Response(null, { status: 200, headers: response.headers }); } - return traceRequest(request, env, ctx, (tracedRequest) => handle(tracedRequest, env, ctx)); + return wrapMcpSseResponse(request, env, response); }; }; diff --git a/apps/cloud/src/mcp/index.ts b/apps/cloud/src/mcp/index.ts index fdc69035e1..a7ec769364 100644 --- a/apps/cloud/src/mcp/index.ts +++ b/apps/cloud/src/mcp/index.ts @@ -5,13 +5,12 @@ // - auth -> cloudMcpAuth (WorkOS JWT + API-key + org-liveness + the two OAuth // discovery docs) // -// `server.ts` intercepts `/mcp` transport for direct session Durable Object -// dispatch, so the app envelope mounts only cloud's OAuth discovery docs (no -// `sessions` or `reporter` seam). The MCP-path predicate lives in `./mount` -// (`classifyMcpPath` / `prepareMcpOrgScope`), imported directly there. The MCP -// session Durable Object class itself stays a platform-side export (server.ts) -// and imports its siblings directly, NOT this barrel, to keep the DO bundle -// react-start-free. +// `server.ts` intercepts `/mcp` transport for the hibernatable Agent bridge, so +// the app envelope mounts only cloud's OAuth discovery docs (no `sessions` or +// `reporter` seam). The MCP-path predicate lives in `./mount` (`classifyMcpPath` +// / `prepareMcpOrgScope`), imported directly there. The MCP session Durable +// Object class itself stays a platform-side export (server.ts) and imports its +// siblings directly, NOT this barrel, to keep the DO bundle react-start-free. // --------------------------------------------------------------------------- // `cloudMcpAuth` is the packaged seam (the WorkOS JWT/api-key auth provider with diff --git a/apps/cloud/src/mcp/mount.ts b/apps/cloud/src/mcp/mount.ts index 9e72d7fa14..96bb435305 100644 --- a/apps/cloud/src/mcp/mount.ts +++ b/apps/cloud/src/mcp/mount.ts @@ -3,7 +3,7 @@ // `server.ts`'s request dispatch. // --------------------------------------------------------------------------- // -// PRODUCTION serves /mcp through `server.ts`'s direct session DO dispatch. +// PRODUCTION serves /mcp through `server.ts`'s hibernatable Agent bridge. // Discovery docs flow through `app.ts`'s unified `ExecutorApp.make` handler // (the `auth` seam's discovery routes). This module exposes: // - `classifyMcpPath` — the "is this an MCP path?" predicate (`/mcp` + the @@ -129,8 +129,8 @@ export const prepareMcpOrgScope = (request: Request): Request => { return rewritten; }; -// Production no longer mounts the /mcp transport here. `server.ts` authenticates -// and forwards transport requests directly to their session Durable Objects, -// while `ExecutorApp.make` serves the OAuth discovery docs through the `auth` -// seam's discovery routes. `classifyMcpPath` + `prepareMcpOrgScope` remain because -// `server.ts`'s request dispatch uses them to recognize and normalize MCP paths. +// Production no longer mounts the /mcp transport here. `server.ts` intercepts MCP +// transport requests for the hibernatable Agent bridge, while `ExecutorApp.make` +// serves the OAuth discovery docs through the `auth` seam's discovery routes. +// `classifyMcpPath` + `prepareMcpOrgScope` remain because `server.ts`'s request +// dispatch uses them to recognize and normalize MCP paths. diff --git a/apps/cloud/src/mcp/session-durable-object.ts b/apps/cloud/src/mcp/session-durable-object.ts index b2bdbe11d2..31d6d4bf6b 100644 --- a/apps/cloud/src/mcp/session-durable-object.ts +++ b/apps/cloud/src/mcp/session-durable-object.ts @@ -1,6 +1,6 @@ // --------------------------------------------------------------------------- // Cloud MCP Session Durable Object — the cloud binding of the shared -// `McpAgentSessionDOBase` (@executor-js/cloudflare). Direct HTTP transport +// `McpAgentSessionDOBase` (@executor-js/cloudflare). Hibernatable transport // serving, cold restore, the inactivity alarm, owner validation, browser // approval storage, and the per-request span bridge live in the base. Cloud // supplies ONLY its injected dependencies: @@ -16,19 +16,14 @@ import { env } from "cloudflare:workers"; import { Data, Effect, Layer } from "effect"; import type { Cause } from "effect"; -import type * as Tracer from "effect/Tracer"; import * as OtelTracer from "@effect/opentelemetry/Tracer"; import { drizzle } from "drizzle-orm/postgres-js"; import postgres, { type Sql } from "postgres"; import { PAUSED_APPROVAL_TIMEOUT_MS, - buildMcpServer, - mcpRequestStatePrincipal, - type PausedExecutionHooks, - type ResumeFallbackOutcome, + createExecutorMcpServer, } from "@executor-js/host-mcp/tool-server"; -import type { McpModernServerBuilder, Principal } from "@executor-js/host-mcp"; import { buildResumeApprovalUrl } from "@executor-js/host-mcp/browser-approval"; import { artifactUrlFor } from "@executor-js/host-mcp/create-artifact"; import { makeAssetsShellHtmlLoader } from "@executor-js/mcp-apps-shell/worker"; @@ -36,20 +31,18 @@ import { smokeRenderArtifact } from "@executor-js/mcp-apps-shell/smoke-render"; import { McpAgentSessionDOBase, type BuiltMcpServer, - type BuiltModernMcpRuntime, type IncomingTraceHeaders, type McpApprovalOwner, type McpSessionModelResumeResult, type McpSessionInit, type SessionMeta, } from "@executor-js/cloudflare/mcp/agent-durable-object"; -import { requireMcpRequestStateKey } from "@executor-js/cloudflare/mcp/modern-request-router"; import { mcpExecutionOwnerDirectoryFromNamespace, type McpExecutionOwnerDirectory, type McpExecutionOwnerRoute, } from "@executor-js/cloudflare/mcp/execution-owner-directory"; -import { mcpSessionStubForOwner } from "@executor-js/cloudflare/mcp/session-stub"; +import { mcpSessionStub } from "@executor-js/cloudflare/mcp/session-stub"; import { buildExecuteDescription, type ResumeResponse } from "@executor-js/execution"; // The DO meters executions just like the HTTP `/api/*` plane: it builds its @@ -124,10 +117,6 @@ class McpModelResumeForwardError extends Data.TaggedError("McpModelResumeForward readonly cause: unknown; }> {} -class CloudModernMcpBuildError extends Data.TaggedError("CloudModernMcpBuildError")<{ - readonly cause: unknown; -}> {} - /** * The DO keeps one postgres.js client for the MCP session runtime. postgres.js * closes idle sockets quickly, while the runtime object stays alive so the MCP @@ -179,127 +168,6 @@ const loadAppShellHtml = makeAssetsShellHtmlLoader({ import("virtual:executor-mcp-apps-shell-dev-html").then((mod) => mod.devShellHtml), }); -const resolveCloudSessionMeta = (token: McpSessionInit, dbHandle: CloudSessionDbHandle) => - Effect.gen(function* () { - const org = yield* resolveOrganization(token.organizationId); - if (!org) { - return yield* new OrganizationNotFoundError({ organizationId: token.organizationId }); - } - return { - organizationId: org.id, - organizationName: org.name, - organizationSlug: org.slug, - userId: token.userId, - resource: token.resource, - elicitationMode: token.elicitationMode, - artifactsEnabled: token.artifactsEnabled, - webOrigin: token.webOrigin, - } satisfies SessionMeta; - }).pipe(Effect.provide(makeSessionServices(dbHandle))); - -const makeCloudExecutionRuntime = (sessionMeta: SessionMeta, dbHandle: CloudSessionDbHandle) => - Effect.gen(function* () { - yield* Effect.promise(() => preloadQuickJs()); - const { executor, engine } = yield* makeExecutionStack( - sessionMeta.userId, - sessionMeta.organizationId, - sessionMeta.organizationName, - { mcpResource: sessionMeta.resource }, - ).pipe( - Effect.provide(CloudMeteredExecutionStackLayer.pipe(Layer.provide(AutumnService.Default))), - Effect.withSpan("McpSessionDOSqlite.makeExecutionStack"), - ); - const description = yield* buildExecuteDescription(executor).pipe( - Effect.withSpan("mcp.execute.description.build"), - ); - return { executor, engine, description }; - }).pipe(Effect.provide(makeSessionServices(dbHandle))); - -type CloudExecutionRuntime = Effect.Success>; - -type CloudModernLifecycle = { - readonly pausedExecutionHooks?: PausedExecutionHooks; - readonly resumeFallback?: ( - executionId: string, - response: ResumeResponse, - ) => Effect.Effect; - readonly parentSpan?: () => Tracer.AnySpan | undefined; -}; - -const makeCloudModernRuntime = ( - sessionMeta: SessionMeta, - runtime: CloudExecutionRuntime, - lifecycle: CloudModernLifecycle = {}, -): BuiltModernMcpRuntime => ({ - engine: runtime.engine, - buildServer: (options) => - buildMcpServer({ - engine: runtime.engine, - description: runtime.description, - artifacts: runtime.executor.artifacts, - connections: runtime.executor.connections, - artifactsEnabled: sessionMeta.artifactsEnabled ?? true, - loadAppShellHtml, - smokeRenderArtifact, - artifactUrl: artifactUrlFor( - env.VITE_PUBLIC_SITE_URL ?? "https://executor.sh", - sessionMeta.organizationSlug, - ), - debug: env.EXECUTOR_MCP_DEBUG === "true", - elicitationMode: { mode: "native" }, - ...(lifecycle.parentSpan ? { parentSpan: lifecycle.parentSpan } : {}), - ...(lifecycle.pausedExecutionHooks - ? { - pausedExecutionHooks: lifecycle.pausedExecutionHooks, - pausedExecutionLeaseMs: PAUSED_APPROVAL_TIMEOUT_MS, - } - : {}), - ...(lifecycle.resumeFallback ? { resumeFallback: lifecycle.resumeFallback } : {}), - ...options, - }), -}); - -const closeModernServerWithDb = Promise }>( - server: Server, - dbHandle: CloudSessionDbHandle, -): Server => { - const closeServer = server.close.bind(server); - server.close = () => - Effect.runPromise( - Effect.promise(closeServer).pipe(Effect.ensuring(Effect.promise(() => dbHandle.end()))), - ); - return server; -}; - -/** Build one worker-side stateless MCP server over a fresh cloud runtime. */ -export const makeCloudModernMcpServerBuilder = ( - session: McpSessionInit, -): McpModernServerBuilder["Service"] => ({ - build: (principal: Principal, options) => { - const dbHandle = makeEphemeralDb(); - const { resource, ...requestOptions } = options; - const token: McpSessionInit = { - ...session, - userId: principal.accountId, - organizationId: principal.organizationId, - resource, - }; - return resolveCloudSessionMeta(token, dbHandle).pipe( - Effect.flatMap((sessionMeta) => - makeCloudExecutionRuntime(sessionMeta, dbHandle).pipe( - Effect.map((runtime) => ({ runtime, sessionMeta })), - ), - ), - Effect.flatMap(({ runtime, sessionMeta }) => - makeCloudModernRuntime(sessionMeta, runtime).buildServer(requestOptions), - ), - Effect.map((server) => closeModernServerWithDb(server, dbHandle)), - Effect.tapCause(() => Effect.promise(() => dbHandle.end())), - Effect.mapError((cause) => new CloudModernMcpBuildError({ cause })), - ); - }, -}); - // --------------------------------------------------------------------------- // Durable Object // --------------------------------------------------------------------------- @@ -325,12 +193,13 @@ export class McpSessionDOSqlite extends McpAgentSessionDOBase { - const ownerSession = mcpSessionStubForOwner(env.MCP_SESSION, owner); - if (!ownerSession) { - return Effect.succeed({ status: "execution_expired", ttlMs: PAUSED_APPROVAL_TIMEOUT_MS }); - } return Effect.tryPromise({ - try: () => ownerSession.resumeExecutionForModel(executionId, identity, response), + try: () => + mcpSessionStub(env.MCP_SESSION, owner.sessionId).resumeExecutionForModel( + executionId, + identity, + response, + ), catch: (cause) => new McpModelResumeForwardError({ cause }), }); } @@ -344,8 +213,23 @@ export class McpSessionDOSqlite extends McpAgentSessionDOBase { const dbHandle = makeEphemeralDb(); - return resolveCloudSessionMeta(token, dbHandle).pipe( + return Effect.gen(function* () { + const org = yield* resolveOrganization(token.organizationId); + if (!org) { + return yield* new OrganizationNotFoundError({ organizationId: token.organizationId }); + } + return { + organizationId: org.id, + organizationName: org.name, + organizationSlug: org.slug, + userId: token.userId, + resource: token.resource, + elicitationMode: token.elicitationMode, + artifactsEnabled: token.artifactsEnabled, + } satisfies SessionMeta; + }).pipe( Effect.withSpan("McpSessionDOSqlite.resolveSessionMeta"), + Effect.provide(makeSessionServices(dbHandle)), Effect.ensuring(Effect.promise(() => dbHandle.end())), // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: a vanished org is a defect; the worker already verified the bearer Effect.orDie, @@ -358,15 +242,36 @@ export class McpSessionDOSqlite extends McpAgentSessionDOBase { const self = this; return Effect.gen(function* () { - const runtime = yield* makeCloudExecutionRuntime(sessionMeta, dbHandle); - const { executor, engine, description } = runtime; - const modernRuntime = makeCloudModernRuntime(sessionMeta, runtime, { - pausedExecutionHooks: self.modernPausedExecutionHooks, - resumeFallback: self.modernModelResumeFallback, - parentSpan: () => self.currentParentSpan(), - }); + // QuickJS-WASM must be loaded before anything asks for a sandbox: the + // default variant cannot fetch its own `.wasm` on Workers. Cloud runs + // user `execute` code on the dynamic-worker runtime, but the artifact + // smoke render is a QuickJS sandbox on every host — without this it fails + // open on each create and the check silently does nothing. + // Idempotent per isolate. + yield* Effect.promise(() => preloadQuickJs()); + const { executor, engine } = yield* makeExecutionStack( + sessionMeta.userId, + sessionMeta.organizationId, + sessionMeta.organizationName, + { mcpResource: sessionMeta.resource }, + ).pipe( + // The metered stack tracks each execution to Autumn. It requires + // `AutumnService | DbService`; `AutumnService.Default` is provided here + // (it only reads `env`, no further deps), and `DbService` flows from the + // outer `makeSessionServices`. When `AUTUMN_SECRET_KEY` is unset the + // billing service degrades to a no-op tracker, so this stays inert in + // cloud dev/preview environments that run without a billing backend. + Effect.provide(CloudMeteredExecutionStackLayer.pipe(Layer.provide(AutumnService.Default))), + Effect.withSpan("McpSessionDOSqlite.makeExecutionStack"), + ); + // Build the description here so `executor.connections.list()` stays under + // the DO startup span and the MCP SDK receives a concrete string instead + // of invoking `engine.getDescription` across its async boundary. + const description = yield* buildExecuteDescription(executor).pipe( + Effect.withSpan("mcp.execute.description.build"), + ); const sessionElicitationMode = sessionMeta.elicitationMode ?? "model"; - const mcpServer = yield* buildMcpServer({ + const mcpServer = yield* createExecutorMcpServer({ engine, description, artifacts: executor.artifacts, @@ -379,17 +284,6 @@ export class McpSessionDOSqlite extends McpAgentSessionDOBase self.persistAppsEnabled(appsEnabled), - // Same restore contract for the client identity that keys the - // `mcp.client.*` span attribution on execution spans. - ...(sessionMeta.clientInfo ? { restoredClientInfo: sessionMeta.clientInfo } : {}), - onClientInfoChange: (clientInfo) => self.persistClientInfo(clientInfo), - appsEnabled: false, - sessionful: true, - requestStateSigningKey: self.modernRequestStateSigningKey(), - requestStatePrincipal: mcpRequestStatePrincipal({ - accountId: sessionMeta.userId, - organizationId: sessionMeta.organizationId, - }), loadAppShellHtml, smokeRenderArtifact, artifactUrl: artifactUrlFor( @@ -415,38 +309,16 @@ export class McpSessionDOSqlite extends McpAgentSessionDOBase { - const self = this; - return makeCloudExecutionRuntime(sessionMeta, dbHandle).pipe( - Effect.map((runtime) => - makeCloudModernRuntime(sessionMeta, runtime, { - pausedExecutionHooks: self.modernPausedExecutionHooks, - resumeFallback: self.modernModelResumeFallback, - parentSpan: () => self.currentParentSpan(), - }), - ), - Effect.withSpan("McpSessionDOSqlite.buildModernMcpRuntime"), - // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: runtime-build failures surface through the base RPC cleanup path - Effect.orDie, - ); - } - - protected override modernRequestStateSigningKey(): string { - return requireMcpRequestStateKey(env.MCP_REQUEST_STATE_KEY); - } - protected override withTelemetry( effect: Effect.Effect, incoming?: IncomingTraceHeaders, diff --git a/apps/cloud/src/mcp/telemetry-modern.test.ts b/apps/cloud/src/mcp/telemetry-modern.test.ts deleted file mode 100644 index 66db34036f..0000000000 --- a/apps/cloud/src/mcp/telemetry-modern.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it } from "@effect/vitest"; -import { Effect } from "effect"; -import type * as Tracer from "effect/Tracer"; - -import { annotateMcpRequest } from "./telemetry"; - -const makeRecordingTracer = (): { - readonly tracer: Tracer.Tracer; - readonly requestAttributes: () => ReadonlyMap | undefined; -} => { - const recorded: Array<{ - readonly name: string; - readonly attributes: Map; - }> = []; - const tracer: Tracer.Tracer = { - span: (options) => { - const attributes = new Map(); - recorded.push({ name: options.name, attributes }); - let status: Tracer.SpanStatus = { _tag: "Started", startTime: options.startTime }; - return { - _tag: "Span", - name: options.name, - spanId: `span-${recorded.length}`, - traceId: "trace-modern", - parent: options.parent, - annotations: options.annotations, - get status() { - return status; - }, - attributes, - links: options.links, - sampled: options.sampled, - kind: options.kind, - end: (endTime, exit) => { - status = { _tag: "Ended", startTime: options.startTime, endTime, exit }; - }, - attribute: (key, value) => { - attributes.set(key, value); - }, - event: () => undefined, - addLinks: () => undefined, - }; - }, - }; - return { - tracer, - requestAttributes: () => recorded.find(({ name }) => name === "mcp.request")?.attributes, - }; -}; - -describe("annotateMcpRequest modern envelope", () => { - it.effect("records the 2026 protocol version outside initialize", () => { - const { tracer, requestAttributes } = makeRecordingTracer(); - const request = new Request("https://executor.sh/mcp", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ - jsonrpc: "2.0", - id: 1, - method: "tools/list", - params: { - _meta: { - "io.modelcontextprotocol/protocolVersion": "2026-07-28", - "io.modelcontextprotocol/clientCapabilities": {}, - }, - }, - }), - }); - - return Effect.gen(function* () { - yield* annotateMcpRequest(request, { token: null, parseBody: true }); - const attributes = requestAttributes(); - expect(attributes?.get("mcp.rpc.method")).toBe("tools/list"); - expect(attributes?.get("mcp.client.protocol_version")).toBe("2026-07-28"); - }).pipe(Effect.withSpan("mcp.request"), Effect.withTracer(tracer)); - }); -}); diff --git a/apps/cloud/src/mcp/telemetry.ts b/apps/cloud/src/mcp/telemetry.ts index de53c3a49c..ec81548884 100644 --- a/apps/cloud/src/mcp/telemetry.ts +++ b/apps/cloud/src/mcp/telemetry.ts @@ -102,14 +102,6 @@ const InitializeParams = Schema.Struct({ capabilities: Schema.optional(UnknownRecord), }); -const ModernEnvelopeParams = Schema.Struct({ - _meta: Schema.optional( - Schema.Struct({ - "io.modelcontextprotocol/protocolVersion": Schema.optional(Schema.String), - }), - ), -}); - const NamedParams = Schema.Struct({ name: Schema.optional(Schema.String) }); const UriParams = Schema.Struct({ uri: Schema.optional(Schema.String) }); @@ -127,7 +119,6 @@ const decodeJsonRpcEnvelopeString = Schema.decodeUnknownOption( Schema.fromJsonString(JsonRpcEnvelope), ); const decodeInitializeParams = Schema.decodeUnknownOption(InitializeParams); -const decodeModernEnvelopeParams = Schema.decodeUnknownOption(ModernEnvelopeParams); const decodeNamedParams = Schema.decodeUnknownOption(NamedParams); const decodeUriParams = Schema.decodeUnknownOption(UriParams); const decodeCancelledParams = Schema.decodeUnknownOption(CancelledParams); @@ -145,14 +136,7 @@ const readJsonRpcEnvelope = (request: Request): Effect.Effect => { const params = envelope.params ?? {}; - const protocolAttrs = Option.match(decodeModernEnvelopeParams(params), { - onNone: () => ({}), - onSome: (modern) => { - const protocolVersion = modern._meta?.["io.modelcontextprotocol/protocolVersion"]; - return protocolVersion ? { "mcp.client.protocol_version": protocolVersion } : {}; - }, - }); - const methodSpecific = Match.value(envelope.method).pipe( + return Match.value(envelope.method).pipe( Match.when("initialize", () => Option.match(decodeInitializeParams(params), { onNone: () => ({}) as Record, @@ -197,7 +181,6 @@ const methodAttrs = (envelope: JsonRpcEnvelope): Record => { Match.option, Option.getOrElse(() => ({}) as Record), ); - return { ...protocolAttrs, ...methodSpecific }; }; const replyAttrs = (envelope: JsonRpcEnvelope): Record => { diff --git a/apps/cloud/src/server.ts b/apps/cloud/src/server.ts index 3d5a191ee4..d7bc00702a 100644 --- a/apps/cloud/src/server.ts +++ b/apps/cloud/src/server.ts @@ -17,10 +17,7 @@ import { passthroughResponse } from "./edge/passthrough"; import { makeCloudMcpAgentHandler } from "./mcp/agent-handler"; import { classifyMcpPath, prepareMcpOrgScope } from "./mcp/mount"; import { parseTraceparent } from "./mcp/traceparent"; -import { - makeCloudModernMcpServerBuilder, - McpSessionDOSqlite as McpSessionDOBase, -} from "./mcp/session-durable-object"; +import { McpSessionDOSqlite as McpSessionDOBase } from "./mcp/session-durable-object"; import { beforeSendWithOtelCorrelation, captureCause, @@ -187,10 +184,7 @@ const traceCloudMcpRequest = async ( ); }; -const mcpAgentHandler = makeCloudMcpAgentHandler({ - makeModernServerBuilder: makeCloudModernMcpServerBuilder, - traceRequest: traceCloudMcpRequest, -}); +const mcpAgentHandler = makeCloudMcpAgentHandler(); // --------------------------------------------------------------------------- // Isolate lifecycle signals @@ -264,7 +258,14 @@ const cloudflareHandler: ExportedHandler = { // to pass authenticated session props into the hibernatable DO. // Discovery docs still flow through the app-level MCP envelope. const forwarded = prepareMcpOrgScope(request); - return mcpAgentHandler(forwarded, env, ctx); + // /mcp leaves the Effect app for the Agents bridge, so no downstream + // HttpMiddleware.tracer opens the request envelope — this worker span is + // THE `http.server` span for MCP traffic, and its context is stamped onto + // the forwarded traceparent so the agent handler and session DO parent + // under it instead of exporting orphaned roots. + return traceCloudMcpRequest(forwarded, env, ctx, (tracedRequest) => + Promise.resolve(mcpAgentHandler(tracedRequest, env, ctx)), + ); } const tracingInstalled = installTracerProvider(); // Join the caller's W3C trace when the request carries one — the web UI diff --git a/apps/cloud/wrangler.jsonc b/apps/cloud/wrangler.jsonc index e701b0a470..3fa69306e0 100644 --- a/apps/cloud/wrangler.jsonc +++ b/apps/cloud/wrangler.jsonc @@ -46,12 +46,12 @@ }, ], }, - // The MCP session DO previously moved to a SQLite-backed class. The original - // `McpSessionDO` was created on the + // The MCP session DO moved to the Cloudflare Agents (`McpAgent`) base, which + // stores state in SQLite. The original `McpSessionDO` was created on the // key-value backend (`new_classes`) and cannot be converted in place. Cloudflare // also refuses to delete a class in the same deploy that moves its binding (it // validates the delete against the live binding), so v2 only CREATES the new - // SQLite class `McpSessionDOSqlite` and the `MCP_SESSION` binding moved to it. + // SQLite class `McpSessionDOSqlite` and the `MCP_SESSION` binding moves to it. // The old KV `McpSessionDO` is left orphaned (unbound, kept as a stub export in // server.ts so the migration stays valid); it can be deleted in a later deploy // now that nothing binds it. Session state is ephemeral, so nothing is lost. @@ -106,14 +106,7 @@ "version_metadata": { "binding": "CF_VERSION_METADATA", }, - // DEPLOYMENT PREREQUISITE: MCP 2026-07-28 requestState is shared between - // stateless Worker isolates and session DOs. Configure the same 32+ byte - // secret for both with `wrangler secret put MCP_REQUEST_STATE_KEY`. - // It must never be placed in `vars` or generated independently per isolate. "vars": { - // MCP_2026_07_28_ENABLED is intentionally absent: unset enables modern - // inbound serving. Set the Worker var to "false" for emergency rollback; - // legacy serving remains available. "VITE_PUBLIC_SITE_URL": "https://executor.sh", // Keeps the /__sentry-otel-verify probe live in production: Sentry // delivery failed silently for weeks (zero events after ~Jul 30 with an diff --git a/apps/host-cloudflare/src/app.ts b/apps/host-cloudflare/src/app.ts index 7a2b1bbfa5..8c3eebf789 100644 --- a/apps/host-cloudflare/src/app.ts +++ b/apps/host-cloudflare/src/app.ts @@ -16,7 +16,6 @@ import { ErrorCaptureLive } from "./observability"; import { cloudflareAccountMiddleware } from "./account/account-provider"; import { makeCloudflareApprovalHandler } from "./mcp"; import { makeCloudflareMcpAgentHandler } from "./mcp/agent-handler"; -import { makeCloudflareModernMcpServerBuilder } from "./mcp/session-durable-object"; import { preloadQuickJs } from "./quickjs"; // =========================================================================== @@ -46,9 +45,7 @@ export const makeCloudflareApp = async (env: CloudflareEnv) => { // handle the per-request scoped executor reads through the DbProvider seam. const dbHandle = await createD1ExecutorDb(env.DB, env.BLOBS); const identityLayer = cloudflareAccessIdentityLayer(config); - const mcpAgentHandler = makeCloudflareMcpAgentHandler(config, { - makeModernServerBuilder: makeCloudflareModernMcpServerBuilder, - }); + const mcpAgentHandler = makeCloudflareMcpAgentHandler(config); const approvalHandler = makeCloudflareApprovalHandler(config, env); const { appLayer, toWebHandler } = ExecutorApp.make({ diff --git a/apps/host-cloudflare/src/config.ts b/apps/host-cloudflare/src/config.ts index f6a3d3c09e..c397c4ef87 100644 --- a/apps/host-cloudflare/src/config.ts +++ b/apps/host-cloudflare/src/config.ts @@ -47,10 +47,6 @@ export interface CloudflareEnv { readonly SELF_HOSTED_ORG_SLUG?: string; /** At-rest secret-encryption key (a `wrangler secret`, NOT a var). */ readonly EXECUTOR_SECRET_KEY?: string; - /** HMAC key for MCP 2026-07-28 continuation state (32+ byte secret). */ - readonly MCP_REQUEST_STATE_KEY?: string; - /** Emergency rollback for inbound MCP 2026-07-28 traffic only. */ - readonly MCP_2026_07_28_ENABLED?: string; readonly ALLOW_LOCAL_NETWORK?: string; readonly VITE_PUBLIC_SITE_URL?: string; /** diff --git a/apps/host-cloudflare/src/mcp/agent-handler.test.ts b/apps/host-cloudflare/src/mcp/agent-handler.test.ts deleted file mode 100644 index 0d21240c53..0000000000 --- a/apps/host-cloudflare/src/mcp/agent-handler.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "@effect/vitest"; -import { Effect, Layer } from "effect"; - -import { - authenticated, - McpAuthProvider, - unauthorized, - type Principal, -} from "@executor-js/host-mcp"; - -import type { CloudflareConfig, CloudflareEnv } from "../config"; -import { cloudflareDeadSessionCacheForTest, makeCloudflareMcpAgentHandler } from "./agent-handler"; - -const principal: Principal = { - accountId: "acct_test", - organizationId: "org_test", - organizationName: "Test Org", - email: "test@example.com", - name: "Test", - avatarUrl: null, - roles: ["member"], -}; - -const config = { - accessTeamDomain: "test.cloudflareaccess.com", - accessAud: "aud_test", - accessNameClaim: "name", - accessGroupsClaim: "groups", - adminEmails: [], - organizationId: "org_test", - organizationName: "Test Org", - organizationSlug: "test-org", - secretKey: "test-secret-key-0123456789", - allowLocalNetwork: false, - enableDevAuth: false, -} satisfies CloudflareConfig; - -const AuthProviderLive = Layer.succeed(McpAuthProvider)({ - discoveryRoutes: [], - resourceMetadataUrl: (request) => new URL("/.well-known/mcp", request.url).toString(), - authenticate: (request) => - Effect.succeed( - request.headers.has("authorization") ? authenticated(principal) : unauthorized(), - ), -}); - -const requestFor = (method: "GET" | "POST", sessionId: string, authenticated = true): Request => - new Request("https://executor.test/mcp", { - method, - headers: { - ...(authenticated ? { authorization: "Bearer test" } : {}), - "mcp-session-id": sessionId, - ...(method === "POST" ? { "content-type": "application/json" } : {}), - }, - ...(method === "POST" - ? { - body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }), - } - : {}), - }); - -const makeHarness = (owner: "not_found" | "terminated" = "not_found") => { - const ownerChecks = { count: 0 }; - const stub = { - validateMcpSessionOwner: async () => { - ownerChecks.count += 1; - return owner; - }, - }; - const namespace = { - idFromString: (sessionId: string) => sessionId, - get: () => stub, - }; - // oxlint-disable-next-line executor/no-double-cast -- test boundary: the handler only reads the MCP_SESSION namespace in these legacy dead-session cases - const env = { MCP_SESSION: namespace } as unknown as CloudflareEnv; - // oxlint-disable-next-line executor/no-double-cast -- test boundary: no ExecutionContext capability is used before the dead-session response - const ctx = {} as unknown as ExecutionContext; - const handler = makeCloudflareMcpAgentHandler(config, { - authProvider: AuthProviderLive, - makeModernServerBuilder: () => ({ build: () => Effect.die("unused modern builder") }), - }); - return { ctx, env, handler, ownerChecks }; -}; - -describe("standalone Cloudflare MCP dead-session negative cache", () => { - beforeEach(() => { - vi.useRealTimers(); - cloudflareDeadSessionCacheForTest.clear(); - }); - - it.each([ - { method: "GET" as const, status: 405 }, - { method: "POST" as const, status: 404 }, - ])("serves a repeated $method without another DO lookup", async ({ method, status }) => { - const { ctx, env, handler, ownerChecks } = makeHarness(); - const sessionId = `dead-${method.toLowerCase()}`; - - const first = await handler(requestFor(method, sessionId), env, ctx); - const second = await handler(requestFor(method, sessionId), env, ctx); - - expect(first.status).toBe(status); - expect(second.status).toBe(status); - expect(ownerChecks.count).toBe(1); - }); - - it("keeps authentication ahead of cached session existence", async () => { - const { ctx, env, handler, ownerChecks } = makeHarness(); - const sessionId = "dead-auth"; - - expect((await handler(requestFor("GET", sessionId), env, ctx)).status).toBe(405); - const unauthenticated = await handler(requestFor("GET", sessionId, false), env, ctx); - - expect(unauthenticated.status).toBe(401); - expect(ownerChecks.count).toBe(1); - }); - - it("preserves the terminated-session response on a cached hit", async () => { - const { ctx, env, handler, ownerChecks } = makeHarness("terminated"); - const sessionId = "dead-terminated"; - - const first = await handler(requestFor("POST", sessionId), env, ctx); - const second = await handler(requestFor("POST", sessionId), env, ctx); - - expect(first.status).toBe(404); - expect(second.status).toBe(404); - expect(await second.text()).toBe(await first.text()); - expect(ownerChecks.count).toBe(1); - }); - - it("consults the DO again after five minutes", async () => { - vi.useFakeTimers(); - vi.setSystemTime(0); - const { ctx, env, handler, ownerChecks } = makeHarness(); - const sessionId = "dead-expiry"; - - expect((await handler(requestFor("GET", sessionId), env, ctx)).status).toBe(405); - vi.advanceTimersByTime(5 * 60 * 1_000 + 1); - expect((await handler(requestFor("GET", sessionId), env, ctx)).status).toBe(405); - - expect(ownerChecks.count).toBe(2); - }); - - it("evicts the oldest entry without exceeding 4,096 sessions", () => { - for (let index = 0; index <= 4_096; index += 1) { - cloudflareDeadSessionCacheForTest.remember(`dead-${index}`, 0); - } - - expect(cloudflareDeadSessionCacheForTest.size()).toBe(4_096); - expect(cloudflareDeadSessionCacheForTest.has("dead-0", 1)).toBe(false); - expect(cloudflareDeadSessionCacheForTest.has("dead-1", 1)).toBe(true); - expect(cloudflareDeadSessionCacheForTest.has("dead-4096", 1)).toBe(true); - }); -}); diff --git a/apps/host-cloudflare/src/mcp/agent-handler.ts b/apps/host-cloudflare/src/mcp/agent-handler.ts index 9fcdbd47cf..5ec09fc1b3 100644 --- a/apps/host-cloudflare/src/mcp/agent-handler.ts +++ b/apps/host-cloudflare/src/mcp/agent-handler.ts @@ -1,80 +1,36 @@ -import { Effect, Layer, Predicate } from "effect"; +import { Effect, Predicate } from "effect"; import { McpAuthProvider, jsonRpcErrorBody, - mcpModernDisabledResponse, defaultMcpResource, type AuthOutcome, - type McpModernServerBuilder, type Principal, } from "@executor-js/host-mcp"; -import { requestBodyFromRequest } from "@executor-js/host-mcp/tool-server"; import { currentPropagationHeaders, readArtifactsEnabled, readElicitationMode, - withMcpResponseHeaders, - withPropagationHeaders, withVerifiedIdentityHeaders, } from "@executor-js/cloudflare/mcp/do-headers"; import type { McpSessionProps } from "@executor-js/cloudflare/mcp/agent-durable-object"; -import { - classifyMcpProtocolEra, - makeMcpModernRequestRouter, - mcpCorsPreflightResponse, - requireMcpRequestStateKey, -} from "@executor-js/cloudflare/mcp/modern-request-router"; -import { mcpExecutionOwnerDirectoryFromNamespace } from "@executor-js/cloudflare/mcp/execution-owner-directory"; -import { createMcpSessionStub, mcpSessionStub } from "@executor-js/cloudflare/mcp/session-stub"; +import { mcpSessionStub } from "@executor-js/cloudflare/mcp/session-stub"; import type { CloudflareConfig, CloudflareEnv } from "../config"; import { cloudflareAccessMcpAuth } from "./auth"; - -const DEAD_SESSION_CACHE_TTL_MS = 5 * 60 * 1_000; -const DEAD_SESSION_CACHE_MAX_ENTRIES = 4_096; -const deadSessionExpiries = new Map(); -const timedOutSessionIds = new Set(); - -type DeadSessionReason = "not_found" | "timed_out"; - -const isDeadSessionCached = (sessionId: string, now = Date.now()): boolean => { - const expiry = deadSessionExpiries.get(sessionId); - if (expiry === undefined) return false; - if (expiry > now) return true; - deadSessionExpiries.delete(sessionId); - timedOutSessionIds.delete(sessionId); - return false; -}; - -const cacheDeadSession = (sessionId: string, reason: DeadSessionReason, now = Date.now()): void => { - deadSessionExpiries.delete(sessionId); - if (deadSessionExpiries.size >= DEAD_SESSION_CACHE_MAX_ENTRIES) { - const oldestSessionId = deadSessionExpiries.keys().next().value; - if (oldestSessionId !== undefined) { - deadSessionExpiries.delete(oldestSessionId); - timedOutSessionIds.delete(oldestSessionId); - } - } - deadSessionExpiries.set(sessionId, now + DEAD_SESSION_CACHE_TTL_MS); - if (reason === "timed_out") timedOutSessionIds.add(sessionId); - else timedOutSessionIds.delete(sessionId); -}; - -const cachedDeadSessionMessage = (sessionId: string): string => - timedOutSessionIds.has(sessionId) ? "Session timed out, please reconnect" : "Session not found"; - -/** Test-only access to reset and verify the isolate-local dead-session cache. */ -export const cloudflareDeadSessionCacheForTest = { - clear: (): void => { - deadSessionExpiries.clear(); - timedOutSessionIds.clear(); - }, - remember: (sessionId: string, now?: number): void => - cacheDeadSession(sessionId, "not_found", now), - has: isDeadSessionCached, - size: (): number => deadSessionExpiries.size, -}; +import { McpSessionDO } from "./session-durable-object"; + +const corsPreflightResponse = (): Response => + new Response(null, { + status: 204, + headers: { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, DELETE, OPTIONS", + "access-control-allow-headers": + "content-type, authorization, mcp-session-id, accept, mcp-protocol-version", + "access-control-expose-headers": "mcp-session-id, WWW-Authenticate", + }, + }); const jsonRpcResponse = ( status: number, @@ -86,25 +42,6 @@ const jsonRpcResponse = ( ? jsonRpcErrorBody(status, code, message) : jsonRpcErrorBody(status, code, message, { challenge }); -/** - * A dead session id answers by request method. POST/DELETE keep the 404 that - * tells a compliant client to re-initialize. A standalone GET gets 405: the - * v1 SDK treats that as "no SSE stream offered" and stops retrying quietly, - * which breaks the reconnect loops of pre-cutover always-on deployments — - * their GET-404 path never re-initialized, it just retried forever. - */ -const deadSessionResponse = (method: string, message: string): Response => - method === "GET" - ? new Response(JSON.stringify({ jsonrpc: "2.0", error: { code: -32001, message }, id: null }), { - status: 405, - headers: { - "content-type": "application/json", - allow: "POST, DELETE", - "access-control-allow-origin": "*", - }, - }) - : jsonRpcResponse(404, -32001, message); - const renderAuthError = ( auth: McpAuthProvider["Service"], request: Request, @@ -124,12 +61,12 @@ const renderAuthError = ( return jsonRpcResponse(503, -32001, outcome.message); }; -const authenticate = (request: Request, authProvider: Layer.Layer) => +const authenticate = (request: Request, config: CloudflareConfig) => Effect.gen(function* () { const auth = yield* McpAuthProvider; const outcome = yield* auth.authenticate(request); return { auth, outcome }; - }).pipe(Effect.provide(authProvider)); + }).pipe(Effect.provide(cloudflareAccessMcpAuth(config))); const propsForPrincipal = ( request: Request, @@ -143,8 +80,8 @@ const propsForPrincipal = ( userId: principal.accountId, elicitationMode: readElicitationMode(request), artifactsEnabled: readArtifactsEnabled(request), - // host-cloudflare only routes the bare `/mcp` endpoint to the session - // Durable Object (see worker.ts), so it always serves the default + // host-cloudflare only routes the bare `/mcp` endpoint to the Agent + // bridge (see worker.ts), so the session always serves the default // resource. resource: defaultMcpResource, webOrigin: new URL(request.url).origin, @@ -153,122 +90,62 @@ const propsForPrincipal = ( }; }); -interface CloudflareMcpAgentHandlerOptions { - readonly makeModernServerBuilder: ( - env: CloudflareEnv, - config: CloudflareConfig, - session: McpSessionProps["session"], - ) => McpModernServerBuilder["Service"]; - readonly authProvider?: Layer.Layer; -} +export const makeCloudflareMcpAgentHandler = (config: CloudflareConfig) => { + const serve = McpSessionDO.serve("/mcp", { + binding: "MCP_SESSION", + transport: "streamable-http", + }); -/** Build the standalone Cloudflare worker's authenticated MCP request handler. */ -export const makeCloudflareMcpAgentHandler = ( - config: CloudflareConfig, - options: CloudflareMcpAgentHandlerOptions, -) => { - const authProvider = options.authProvider ?? cloudflareAccessMcpAuth(config); - const modern = makeMcpModernRequestRouter(); return async (request: Request, env: CloudflareEnv, ctx: ExecutionContext): Promise => { - if (request.method === "OPTIONS") { - return mcpCorsPreflightResponse(request.headers.get("access-control-request-headers")); - } + if (request.method === "OPTIONS") return corsPreflightResponse(); const sessionId = request.headers.get("mcp-session-id"); - if (sessionId && isDeadSessionCached(sessionId)) { - return Effect.runPromise( - Effect.gen(function* () { - const { auth, outcome } = yield* authenticate(request, authProvider); - return Predicate.isTagged(outcome, "Authenticated") - ? deadSessionResponse(request.method, cachedDeadSessionMessage(sessionId)) - : renderAuthError(auth, request, outcome); - }).pipe(Effect.withTracerEnabled(false)), - ); - } - - const { auth, outcome } = await Effect.runPromise(authenticate(request, authProvider)); + const { auth, outcome } = await Effect.runPromise(authenticate(request, config)); if (!Predicate.isTagged(outcome, "Authenticated")) { if (Predicate.isTagged(outcome, "Forbidden") && sessionId) { - const session = mcpSessionStub(env.MCP_SESSION, sessionId); await Effect.runPromise( Effect.ignore( - session ? Effect.tryPromise(() => session._cf_scheduleDestroy()) : Effect.void, + Effect.tryPromise(() => + mcpSessionStub(env.MCP_SESSION, sessionId)._cf_scheduleDestroy(), + ), ), ); } return renderAuthError(auth, request, outcome); } - const parsedBody = await Effect.runPromise(requestBodyFromRequest(request)); - const era = await classifyMcpProtocolEra(request, parsedBody); - if (era === "modern") { - if (env.MCP_2026_07_28_ENABLED === "false") { - return mcpModernDisabledResponse(); - } - const props = await Effect.runPromise(propsForPrincipal(request, outcome.principal)); - (ctx as ExecutionContext & { props?: McpSessionProps }).props = props; - const forwarded = withVerifiedIdentityHeaders( - request, - { - accountId: outcome.principal.accountId, - organizationId: outcome.principal.organizationId, - }, - defaultMcpResource, - ); - return modern.fetch({ - request: forwarded, - parsedBody, - principal: outcome.principal, - resource: defaultMcpResource, - props, - requestStateSigningKey: requireMcpRequestStateKey(env.MCP_REQUEST_STATE_KEY), - builder: options.makeModernServerBuilder(env, config, props.session), - sessions: env.MCP_SESSION, - executionOwners: mcpExecutionOwnerDirectoryFromNamespace(env.MCP_EXECUTION_OWNER), - }); - } - if (!sessionId && request.method === "DELETE") { return new Response(null, { status: 204, headers: { "access-control-allow-origin": "*" } }); } - const existingSession = sessionId ? mcpSessionStub(env.MCP_SESSION, sessionId) : null; - if (sessionId && !existingSession) { - return deadSessionResponse(request.method, "Session not found"); - } - if (existingSession && sessionId) { - const owner = await existingSession.validateMcpSessionOwner({ + if (sessionId) { + const owner = await mcpSessionStub(env.MCP_SESSION, sessionId).validateMcpSessionOwner({ accountId: outcome.principal.accountId, organizationId: outcome.principal.organizationId, }); if (owner === "not_found") { - cacheDeadSession(sessionId, "not_found"); - return deadSessionResponse(request.method, "Session not found"); + return jsonRpcResponse(404, -32001, "Session not found"); } if (owner === "terminated") { // DELETE-condemned but the deferred destroy alarm hasn't wiped storage // yet; the terminated id must read as dead immediately. - cacheDeadSession(sessionId, "timed_out"); - return deadSessionResponse(request.method, "Session timed out, please reconnect"); + return jsonRpcResponse(404, -32001, "Session timed out, please reconnect"); } if (owner === "forbidden") { return jsonRpcResponse(403, -32003, "MCP session does not belong to the current bearer"); } } - const propagation = await Effect.runPromise(currentPropagationHeaders(request)); - const forwarded = withPropagationHeaders( - withVerifiedIdentityHeaders( - request, - { - accountId: outcome.principal.accountId, - organizationId: outcome.principal.organizationId, - }, - defaultMcpResource, - ), - propagation, + const props = await Effect.runPromise(propsForPrincipal(request, outcome.principal)); + (ctx as ExecutionContext & { props?: McpSessionProps }).props = props; + const forwarded = withVerifiedIdentityHeaders( + request, + { + accountId: outcome.principal.accountId, + organizationId: outcome.principal.organizationId, + }, + defaultMcpResource, ); - const target = existingSession ?? createMcpSessionStub(env.MCP_SESSION).stub; - return withMcpResponseHeaders(await target.fetch(forwarded)); + return serve.fetch(forwarded, env, ctx); }; }; diff --git a/apps/host-cloudflare/src/mcp/index.ts b/apps/host-cloudflare/src/mcp/index.ts index a37a5a8023..1de283c205 100644 --- a/apps/host-cloudflare/src/mcp/index.ts +++ b/apps/host-cloudflare/src/mcp/index.ts @@ -35,9 +35,7 @@ export const makeCloudflareApprovalHandler = ( const paused = PAUSED_PATH.exec(pathname); if (paused && request.method === "GET") { - const stub = stubFor(decodeURIComponent(paused[1]!)); - if (!stub) return jsonResponse({ error: "Paused execution not found" }, 404); - const result = await stub.getPausedExecutionForApproval( + const result = await stubFor(decodeURIComponent(paused[1]!)).getPausedExecutionForApproval( decodeURIComponent(paused[2]!), owner, ); @@ -55,9 +53,7 @@ export const makeCloudflareApprovalHandler = ( const response = raw === null ? null : decodeResumeResponse(raw); if (!response) return jsonResponse({ error: "Invalid approval response" }, 400); - const stub = stubFor(decodeURIComponent(resume[1]!)); - if (!stub) return jsonResponse({ error: "Paused execution not found" }, 404); - const result = await stub.resumeExecutionForApproval( + const result = await stubFor(decodeURIComponent(resume[1]!)).resumeExecutionForApproval( decodeURIComponent(resume[2]!), owner, response, diff --git a/apps/host-cloudflare/src/mcp/session-durable-object.ts b/apps/host-cloudflare/src/mcp/session-durable-object.ts index 766b1ed18c..e75199dc07 100644 --- a/apps/host-cloudflare/src/mcp/session-durable-object.ts +++ b/apps/host-cloudflare/src/mcp/session-durable-object.ts @@ -2,12 +2,8 @@ import { Data, Effect } from "effect"; import { PAUSED_APPROVAL_TIMEOUT_MS, - buildMcpServer, - mcpRequestStatePrincipal, - type PausedExecutionHooks, - type ResumeFallbackOutcome, + createExecutorMcpServer, } from "@executor-js/host-mcp/tool-server"; -import type { McpModernServerBuilder, Principal } from "@executor-js/host-mcp"; import { buildResumeApprovalUrl } from "@executor-js/host-mcp/browser-approval"; import { artifactUrlFor } from "@executor-js/host-mcp/create-artifact"; import { makeAssetsShellHtmlLoader } from "@executor-js/mcp-apps-shell/worker"; @@ -16,20 +12,18 @@ import type { ExecutorDbHandle } from "@executor-js/api/server"; import { McpAgentSessionDOBase, type BuiltMcpServer, - type BuiltModernMcpRuntime, type McpApprovalOwner, type McpSessionModelResumeResult, type McpSessionInit, type SessionMeta, } from "@executor-js/cloudflare/mcp/agent-durable-object"; -import { requireMcpRequestStateKey } from "@executor-js/cloudflare/mcp/modern-request-router"; import { mcpExecutionOwnerDirectoryFromNamespace, type McpExecutionOwnerDirectory, type McpExecutionOwnerRoute, } from "@executor-js/cloudflare/mcp/execution-owner-directory"; -import { mcpSessionStubForOwner } from "@executor-js/cloudflare/mcp/session-stub"; -import { buildExecuteDescription, type ResumeResponse } from "@executor-js/execution"; +import { mcpSessionStub } from "@executor-js/cloudflare/mcp/session-stub"; +import type { ResumeResponse } from "@executor-js/execution"; import { loadConfig, type CloudflareConfig, type CloudflareEnv } from "../config"; import { createD1ExecutorDb } from "../db/d1"; @@ -60,124 +54,6 @@ class McpModelResumeForwardError extends Data.TaggedError("McpModelResumeForward readonly cause: unknown; }> {} -class CloudflareModernMcpBuildError extends Data.TaggedError("CloudflareModernMcpBuildError")<{ - readonly cause: unknown; -}> {} - -const makeCloudflareExecutionRuntime = ( - sessionMeta: SessionMeta, - dbHandle: CfSessionDbHandle, - config: CloudflareConfig, -) => - Effect.gen(function* () { - yield* Effect.promise(() => preloadQuickJs()); - const { engine, executor } = yield* makeExecutionStack( - sessionMeta.userId, - sessionMeta.organizationId, - sessionMeta.organizationName, - { mcpResource: sessionMeta.resource }, - ).pipe(Effect.provide(makeCloudflareExecutionStackLayer(config, dbHandle))); - const description = yield* buildExecuteDescription(executor); - return { engine, executor, description }; - }); - -type CloudflareExecutionRuntime = Effect.Success>; - -type CloudflareModernLifecycle = { - readonly pausedExecutionHooks?: PausedExecutionHooks; - readonly resumeFallback?: ( - executionId: string, - response: ResumeResponse, - ) => Effect.Effect; -}; - -const makeCloudflareModernRuntime = ( - sessionMeta: SessionMeta, - runtime: CloudflareExecutionRuntime, - loadAppShellHtml: () => Promise, - config: CloudflareConfig, - lifecycle: CloudflareModernLifecycle = {}, -): BuiltModernMcpRuntime => { - const artifactOrigin = sessionMeta.webOrigin ?? config.webBaseUrl; - return { - engine: runtime.engine, - buildServer: (options) => - buildMcpServer({ - engine: runtime.engine, - description: runtime.description, - artifacts: runtime.executor.artifacts, - connections: runtime.executor.connections, - artifactsEnabled: sessionMeta.artifactsEnabled ?? true, - loadAppShellHtml, - smokeRenderArtifact, - ...(artifactOrigin - ? { artifactUrl: artifactUrlFor(artifactOrigin, sessionMeta.organizationSlug) } - : {}), - elicitationMode: { mode: "native" }, - ...(lifecycle.pausedExecutionHooks - ? { - pausedExecutionHooks: lifecycle.pausedExecutionHooks, - pausedExecutionLeaseMs: PAUSED_APPROVAL_TIMEOUT_MS, - } - : {}), - ...(lifecycle.resumeFallback ? { resumeFallback: lifecycle.resumeFallback } : {}), - ...options, - }), - }; -}; - -const closeModernServerWithDb = Promise }>( - server: Server, - dbHandle: CfSessionDbHandle, -): Server => { - const closeServer = server.close.bind(server); - server.close = () => - Effect.runPromise( - Effect.promise(closeServer).pipe(Effect.ensuring(Effect.promise(() => dbHandle.end()))), - ); - return server; -}; - -/** Build the worker-side MCP server over a fresh D1 execution runtime. */ -export const makeCloudflareModernMcpServerBuilder = ( - env: CloudflareEnv, - config: CloudflareConfig, - session: McpSessionInit, -): McpModernServerBuilder["Service"] => ({ - build: (principal: Principal, options) => - Effect.promise(async () => { - const handle = await createD1ExecutorDb(env.DB, env.BLOBS); - return { ...handle, end: () => handle.close() } satisfies CfSessionDbHandle; - }).pipe( - Effect.flatMap((dbHandle) => { - const { resource, ...requestOptions } = options; - const sessionMeta: SessionMeta = { - organizationId: principal.organizationId, - organizationName: config.organizationName, - organizationSlug: config.organizationSlug, - userId: principal.accountId, - resource, - elicitationMode: session.elicitationMode, - artifactsEnabled: session.artifactsEnabled, - webOrigin: session.webOrigin, - }; - return makeCloudflareExecutionRuntime(sessionMeta, dbHandle, config).pipe( - Effect.flatMap((runtime) => - makeCloudflareModernRuntime( - sessionMeta, - runtime, - makeAssetsShellHtmlLoader({ assets: env.ASSETS }), - config, - ).buildServer(requestOptions), - ), - Effect.map((server) => closeModernServerWithDb(server, dbHandle)), - Effect.tapCause(() => Effect.promise(() => dbHandle.end())), - Effect.mapError((cause) => new CloudflareModernMcpBuildError({ cause })), - ); - }), - ), -}); - export class McpSessionDO extends McpAgentSessionDOBase { private readonly cfEnv: CloudflareEnv; private readonly cfConfig: CloudflareConfig; @@ -210,12 +86,13 @@ export class McpSessionDO extends McpAgentSessionDOBase { - const ownerSession = mcpSessionStubForOwner(this.cfEnv.MCP_SESSION, owner); - if (!ownerSession) { - return Effect.succeed({ status: "execution_expired", ttlMs: PAUSED_APPROVAL_TIMEOUT_MS }); - } return Effect.tryPromise({ - try: () => ownerSession.resumeExecutionForModel(executionId, identity, response), + try: () => + mcpSessionStub(this.cfEnv.MCP_SESSION, owner.sessionId).resumeExecutionForModel( + executionId, + identity, + response, + ), catch: (cause) => new McpModelResumeForwardError({ cause }), }); } @@ -236,7 +113,6 @@ export class McpSessionDO extends McpAgentSessionDOBase preloadQuickJs()); + const { engine, executor } = yield* makeExecutionStack( + sessionMeta.userId, + sessionMeta.organizationId, + sessionMeta.organizationName, + { mcpResource: sessionMeta.resource }, + ).pipe(Effect.provide(makeCloudflareExecutionStackLayer(config, dbHandle))); // Browser elicitation mode (the base owns the approval store + the HTTP // approval RPCs): a gated execution pauses and returns an approvalUrl into // the console resume page. The URL origin is the create request's origin @@ -268,9 +141,8 @@ export class McpSessionDO extends McpAgentSessionDOBase self.persistAppsEnabled(appsEnabled), - appsEnabled: false, - sessionful: true, - requestStateSigningKey: self.modernRequestStateSigningKey(), - requestStatePrincipal: mcpRequestStatePrincipal({ - accountId: sessionMeta.userId, - organizationId: sessionMeta.organizationId, - }), loadAppShellHtml: self.loadAppShellHtml, smokeRenderArtifact, ...(artifactOrigin @@ -323,33 +188,11 @@ export class McpSessionDO extends McpAgentSessionDOBase { - const self = this; - return makeCloudflareExecutionRuntime(sessionMeta, dbHandle, this.cfConfig).pipe( - Effect.map((runtime) => - makeCloudflareModernRuntime(sessionMeta, runtime, self.loadAppShellHtml, self.cfConfig, { - pausedExecutionHooks: self.modernPausedExecutionHooks, - resumeFallback: self.modernModelResumeFallback, - }), - ), - Effect.withSpan("McpSessionDO.buildModernMcpRuntime"), - // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: runtime-build failures surface through the base RPC cleanup path - Effect.orDie, - ); - } - - protected override modernRequestStateSigningKey(): string { - return requireMcpRequestStateKey(this.cfEnv.MCP_REQUEST_STATE_KEY); - } } diff --git a/apps/host-cloudflare/src/worker.e2e.node.test.ts b/apps/host-cloudflare/src/worker.e2e.node.test.ts index cd3e2da9ed..738a358827 100644 --- a/apps/host-cloudflare/src/worker.e2e.node.test.ts +++ b/apps/host-cloudflare/src/worker.e2e.node.test.ts @@ -102,7 +102,6 @@ describe("cloudflare host e2e (workerd/miniflare)", () => { experimental: { disableExperimentalWarning: true }, vars: { EXECUTOR_SECRET_KEY: "test-secret-key-0123456789abcdef", - MCP_REQUEST_STATE_KEY: "test-mcp-request-state-key-0123456789abcdef", ENABLE_DEV_AUTH: "true", }, }); diff --git a/apps/host-cloudflare/src/worker.ts b/apps/host-cloudflare/src/worker.ts index b8808c73cf..ac9c1b30b7 100644 --- a/apps/host-cloudflare/src/worker.ts +++ b/apps/host-cloudflare/src/worker.ts @@ -11,8 +11,9 @@ export { McpExecutionOwnerDirectoryDO, McpSessionDO } from "./mcp"; // --------------------------------------------------------------------------- // The Worker fetch entry. Most requests go to `ExecutorApp.make`'s Effect web -// handler. `/mcp` stays at this edge boundary so the Worker authenticates and -// binds ownership before forwarding the request to its session Durable Object. +// handler. `/mcp` stays at this edge boundary because `McpAgent.serve()` needs +// the Cloudflare `ExecutionContext` to pass authenticated session props into the +// hibernatable Durable Object bridge. // --------------------------------------------------------------------------- let handlerPromise: Promise<{ diff --git a/apps/host-cloudflare/wrangler.jsonc b/apps/host-cloudflare/wrangler.jsonc index 26d8471189..f97e19507e 100644 --- a/apps/host-cloudflare/wrangler.jsonc +++ b/apps/host-cloudflare/wrangler.jsonc @@ -67,15 +67,10 @@ ], // Cloudflare Access is the entire auth layer. ACCESS_TEAM_DOMAIN, ACCESS_AUD, // and ADMIN_EMAILS are installation-specific live vars, set after the first - // deploy and preserved by keep_vars. EXECUTOR_SECRET_KEY (at-rest encryption) - // and MCP_REQUEST_STATE_KEY (MCP 2026-07-28 continuation signing, 32+ bytes) - // are SECRETS, set with `wrangler secret put `, never in vars. The - // MCP key is a deployment prerequisite shared by Worker and session DOs; - // never generate it independently per isolate. + // deploy and preserved by keep_vars. EXECUTOR_SECRET_KEY (the at-rest + // secret-encryption key) is a SECRET, set it with + // `wrangler secret put EXECUTOR_SECRET_KEY`, never in vars. "vars": { - // MCP_2026_07_28_ENABLED is intentionally absent: unset enables modern - // inbound serving. Set the Worker var to "false" for emergency rollback; - // legacy serving remains available. "ACCESS_NAME_CLAIM": "name", "ACCESS_GROUPS_CLAIM": "groups", // Never preserve a production dev-auth override through keep_vars. diff --git a/apps/host-selfhost/package.json b/apps/host-selfhost/package.json index a7c66c2691..3b64081aa4 100644 --- a/apps/host-selfhost/package.json +++ b/apps/host-selfhost/package.json @@ -40,6 +40,7 @@ "@executor-js/sdk": "workspace:*", "@libsql/client": "catalog:", "@libsql/kysely-libsql": "catalog:", + "@modelcontextprotocol/sdk": "^1.29.0", "@tanstack/react-router": "catalog:", "better-auth": "^1.6.11", "drizzle-orm": "catalog:", @@ -52,7 +53,6 @@ "devDependencies": { "@effect/vitest": "catalog:", "@executor-js/vite-plugin": "workspace:*", - "@modelcontextprotocol/client": "2.0.0", "@tailwindcss/vite": "catalog:", "@tanstack/router-plugin": "^1.167.12", "@tanstack/virtual-file-routes": "^1.162.0", diff --git a/apps/host-selfhost/src/app.ts b/apps/host-selfhost/src/app.ts index 8753eec0a5..4eaf631f54 100644 --- a/apps/host-selfhost/src/app.ts +++ b/apps/host-selfhost/src/app.ts @@ -78,12 +78,7 @@ export const makeSelfHostApp = async (options: MakeSelfHostAppOptions = {}) => { // ---- the in-process MCP serving seams (+ shutdown hook) ---------------- // Pass the pinned public origin so browser-approval URLs are reachable behind // a reverse proxy (not the internal 127.0.0.1 bind from the request URL). - const mcp = makeSelfHostMcpSeams( - dbHandle, - betterAuth, - config.webBaseUrl, - config.mcp20260728Enabled, - ); + const mcp = makeSelfHostMcpSeams(dbHandle, betterAuth, config.webBaseUrl); // CLI device-login discovery (`executor login`). Points the CLI at Better // Auth's device endpoints; `requestFormat: "json"` because those endpoints @@ -115,12 +110,7 @@ export const makeSelfHostApp = async (options: MakeSelfHostAppOptions = {}) => { // plane's decorator is wired in mcp/session-store.ts's stack layer). decorator: SelfHostAnalyticsEngineDecorator, }, - mcp: { - auth: mcp.auth, - sessions: mcp.sessions, - modern: mcp.modern, - reporter: mcp.reporter, - }, + mcp: { auth: mcp.auth, sessions: mcp.sessions, reporter: mcp.reporter }, plugins: { provider: SelfHostPluginsProvider, config: SelfHostHostConfig }, errorCapture: ErrorCaptureLive, }, diff --git a/apps/host-selfhost/src/config.ts b/apps/host-selfhost/src/config.ts index 20728fabff..dae13a5e16 100644 --- a/apps/host-selfhost/src/config.ts +++ b/apps/host-selfhost/src/config.ts @@ -32,8 +32,6 @@ export interface SelfHostConfig { * internal network unless an operator opts in. */ readonly allowLocalNetwork: boolean; - /** Emergency rollback for inbound MCP 2026-07-28 traffic only. */ - readonly mcp20260728Enabled: boolean; // Better Auth session secret. Always resolved (env, else generated + persisted // under the data dir) so a single-container deploy boots with no env; the auth // layer still validates an explicitly-set env secret is long enough. @@ -152,7 +150,6 @@ export const loadConfig = (): SelfHostConfig => { dbPath: process.env.EXECUTOR_DB_PATH ?? join(dataDir, "data.db"), webBaseUrl: resolveWebBaseUrl(port), allowLocalNetwork: process.env.EXECUTOR_ALLOW_LOCAL_NETWORK === "true", - mcp20260728Enabled: process.env.MCP_2026_07_28_ENABLED !== "false", authSecret: resolveAuthSecret(), bootstrapAdminEmail: process.env.EXECUTOR_BOOTSTRAP_ADMIN_EMAIL, bootstrapAdminPassword: process.env.EXECUTOR_BOOTSTRAP_ADMIN_PASSWORD, diff --git a/apps/host-selfhost/src/mcp/index.ts b/apps/host-selfhost/src/mcp/index.ts index a11d5cd8c9..52287518cd 100644 --- a/apps/host-selfhost/src/mcp/index.ts +++ b/apps/host-selfhost/src/mcp/index.ts @@ -4,7 +4,6 @@ import { IdentityProvider } from "@executor-js/api/server"; import type { McpAuthProvider, McpErrorReporter, - McpModernServerBuilder, McpSessionStore, Principal, } from "@executor-js/host-mcp"; @@ -14,7 +13,6 @@ import type { SelfHostDbHandle } from "../db/self-host-db"; import { selfHostMcpAuth } from "./auth"; import { makeSelfHostMcpSessionStore, - makeSelfHostMcpModernServerBuilder, selfHostMcpReporter, selfHostMcpSessions, } from "./session-store"; @@ -22,7 +20,6 @@ import { export { selfHostMcpAuth } from "./auth"; export { makeSelfHostMcpSessionStore, - makeSelfHostMcpModernServerBuilder, selfHostMcpReporter, selfHostMcpSessions, McpEngineBuildError, @@ -37,15 +34,13 @@ export { // own auth + session handling and is mounted OUTSIDE the API's execution // middleware, like /api/auth. // -// Self-host provides both era seams plus auth and an error-reporter override: +// Self-host provides the TWO envelope seams plus an error-reporter override: // - McpAuthProvider -> `selfHostMcpAuth` (Better Auth mcp() OAuth). It still // requires `IdentityProvider`, which `make` provides from // the resolved identity seam. // - McpSessionStore -> `selfHostMcpSessions`: in-process Map. The store owns // dispatch (create + forward + ownership) and builds its // engine internally over the shared SelfHostDb. -// - McpModernServerBuilder -> one stateless MCP server per request over -// the same scoped execution stack and tool config. // - McpErrorReporter -> `selfHostMcpReporter`: route 500 defects through the // host's console capture. // @@ -58,8 +53,6 @@ export interface SelfHostMcpSeams { readonly auth: Layer.Layer; /** The in-process session store seam (dispatch + lifetime). */ readonly sessions: Layer.Layer; - /** Stateless MCP server construction for modern requests. */ - readonly modern: Layer.Layer; /** Route 500 defects through the host's console `ErrorCapture`. */ readonly reporter: Layer.Layer; /** @@ -133,14 +126,13 @@ const makeApprovalHandler = * Build the self-host MCP serving seams over the long-lived DB handle. The auth * seam is `selfHostMcpAuth` (Better Auth mcp() OAuth), with the Better Auth * instance provided; it still requires `IdentityProvider` from the resolved - * identity seam. Returns the four seam Layers plus the `close()` lifetime hook + * identity seam. Returns the three seam Layers plus the `close()` lifetime hook * the app wires into shutdown. */ export const makeSelfHostMcpSeams = ( dbHandle: SelfHostDbHandle, betterAuth: BetterAuthHandle, webBaseUrl?: string, - modernEnabled = true, ): SelfHostMcpSeams => { const sessionStore = makeSelfHostMcpSessionStore(dbHandle, webBaseUrl); const auth: Layer.Layer = selfHostMcpAuth.pipe( @@ -149,7 +141,6 @@ export const makeSelfHostMcpSeams = ( return { auth, sessions: selfHostMcpSessions(sessionStore), - modern: makeSelfHostMcpModernServerBuilder(dbHandle, modernEnabled), reporter: selfHostMcpReporter, approvalHandler: makeApprovalHandler(sessionStore, betterAuth), close: sessionStore.close, diff --git a/apps/host-selfhost/src/mcp/mcp.test.ts b/apps/host-selfhost/src/mcp/mcp.test.ts index 4bda4bbf10..42a9379744 100644 --- a/apps/host-selfhost/src/mcp/mcp.test.ts +++ b/apps/host-selfhost/src/mcp/mcp.test.ts @@ -3,7 +3,6 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, expect, test } from "@effect/vitest"; -import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; import { mintInviteCode } from "../testing/mint-invite"; @@ -88,40 +87,6 @@ test("an authenticated MCP client initializes, lists tools, and executes code", expect(JSON.stringify(await call.json())).toContain("42"); }); -test("an authenticated modern MCP client discovers, lists tools, and executes code", async () => { - const token = await signUp("modern@mcp.test"); - const seenMethods: string[] = []; - const transport = new StreamableHTTPClientTransport(new URL(`${BASE}/mcp`), { - fetch: async (input, init) => { - const request = - input instanceof Request ? new Request(input, init) : new Request(input.toString(), init); - const body = (await request.clone().json()) as { readonly method?: string }; - if (body.method) seenMethods.push(body.method); - const headers = new Headers(request.headers); - headers.set("authorization", `Bearer ${token}`); - return handler(new Request(request, { headers })); - }, - }); - const client = new Client( - { name: "selfhost-modern-test", version: "1.0.0" }, - { capabilities: {}, versionNegotiation: { mode: { pin: "2026-07-28" } } }, - ); - - await client.connect(transport); - // oxlint-disable-next-line executor/no-try-catch-or-throw -- test boundary: always close the authenticated modern client - try { - expect(seenMethods).toContain("server/discover"); - expect((await client.listTools()).tools.map(({ name }) => name)).toContain("execute"); - const result = await client.callTool({ - name: "execute", - arguments: { code: "export default 6 * 7" }, - }); - expect(JSON.stringify(result)).toContain("42"); - } finally { - await client.close(); - } -}); - test("an MCP session cannot be reused by another user, and unauth is rejected", async () => { const alice = await signUp("alice2@mcp.test"); const bob = await signUp("bob2@mcp.test"); diff --git a/apps/host-selfhost/src/mcp/session-store.ts b/apps/host-selfhost/src/mcp/session-store.ts index 436671f3a2..c17a8fa4db 100644 --- a/apps/host-selfhost/src/mcp/session-store.ts +++ b/apps/host-selfhost/src/mcp/session-store.ts @@ -1,7 +1,7 @@ import { Layer } from "effect"; import { makeConsoleMcpErrorReporter, makeMcpBuildServer } from "@executor-js/api/server"; -import { McpModernServerBuilder, type McpErrorReporter } from "@executor-js/host-mcp"; +import type { McpErrorReporter } from "@executor-js/host-mcp"; import { inMemoryMcpSessionsLayer, makeInMemoryMcpSessionStore, @@ -19,8 +19,8 @@ import { SelfHostExecutionStackLayer } from "../execution"; // ALL shared (`@executor-js/host-mcp/in-memory-session-store` + `makeMcpBuildServer` // / `makeConsoleMcpErrorReporter` in `@executor-js/api/server`). Self-host // supplies only its fully-provided execution-stack layer (QuickJS over the -// long-lived `SelfHostDb`) and its `ErrorCapture`; the builder creates the -// connection-lifetime assembly used by the shared store. +// long-lived `SelfHostDb`) and its `ErrorCapture`. The Cloudflare host wires the +// identical seam with its own stack layer. // --------------------------------------------------------------------------- import { loadMcpAppsShellHtml } from "@executor-js/mcp-apps-shell"; @@ -51,24 +51,6 @@ export const makeSelfHostMcpSessionStore = ( { webBaseUrl }, ); -/** Build the stateless MCP server seam over the same self-host stack/config. */ -export const makeSelfHostMcpModernServerBuilder = ( - db: SelfHostDbHandle, - enabled = true, -): Layer.Layer => - Layer.succeed(McpModernServerBuilder)({ - enabled, - build: makeMcpBuildServer( - SelfHostExecutionStackLayer.pipe(Layer.provide(Layer.succeed(SelfHostDb)(db))), - { - loadAppShellHtml: loadMcpAppsShellHtml, - smokeRenderArtifact, - onArtifactUsage: (action) => - selfHostAnalytics.record(`artifact_${action}`, { via: "agent" }), - }, - ), - }); - /** The `McpSessionStore` envelope seam over a freshly built in-process store. */ export const selfHostMcpSessions = inMemoryMcpSessionsLayer; diff --git a/apps/host-selfhost/src/testing/test-app.ts b/apps/host-selfhost/src/testing/test-app.ts index 480a1e03f2..2261de31c8 100644 --- a/apps/host-selfhost/src/testing/test-app.ts +++ b/apps/host-selfhost/src/testing/test-app.ts @@ -28,7 +28,6 @@ import { import executorConfig from "../../executor.config"; import { loadConfig, SELF_HOST_NAMESPACE, SELF_HOST_SCHEMA_VERSION } from "../config"; import { - makeSelfHostMcpModernServerBuilder, makeSelfHostMcpSessionStore, selfHostMcpReporter, selfHostMcpSessions, @@ -237,7 +236,6 @@ export const makeSelfHostTestApp = async ( mcp: { auth: stubMcpAuth, sessions: selfHostMcpSessions(sessionStore), - modern: makeSelfHostMcpModernServerBuilder(dbHandle), reporter: selfHostMcpReporter, }, plugins: { provider: pluginsProvider, config: SelfHostHostConfig }, diff --git a/apps/local/package.json b/apps/local/package.json index fae1bc4a4e..43b22005ff 100644 --- a/apps/local/package.json +++ b/apps/local/package.json @@ -46,7 +46,7 @@ "@executor-js/sdk": "workspace:*", "@executor-js/vite-plugin": "workspace:*", "@libsql/client": "catalog:", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "@tanstack/react-router": "catalog:", "drizzle-orm": "catalog:", "effect": "catalog:", @@ -55,8 +55,6 @@ "react-dom": "catalog:" }, "devDependencies": { - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/sdk": "^1.29.0", "@rhyssul/portless": "^0.13.0", "@tailwindcss/vite": "catalog:", "@tanstack/router-plugin": "^1.167.12", diff --git a/apps/local/src/main.ts b/apps/local/src/main.ts index 0e74cec5d8..2ef674c572 100644 --- a/apps/local/src/main.ts +++ b/apps/local/src/main.ts @@ -119,7 +119,6 @@ export const createServerHandlers = async (token: string): Promise Effect.succeed({ result: `ran: ${code}` }), - executeWithPause: (code) => - Effect.succeed({ status: "completed", result: { result: `ran: ${code}` } }), - resume: () => Effect.succeed(null), - isExecutionSettled: () => Effect.succeed(false), - getPausedExecution: () => Effect.succeed(null), - pausedExecutionCount: () => Effect.succeed(0), - hasPausedExecutions: () => Effect.succeed(false), - getDescription: Effect.succeed("local modern MCP test executor"), -}; - -describe("local modern MCP HTTP", () => { - it("discovers, lists tools, and executes without creating a legacy session", async () => { - const mcp = createMcpRequestHandler({ engine }); - const sessionHeaders: Array = []; - const transport = new StreamableHTTPClientTransport(new URL("http://local.test/mcp"), { - fetch: async (input, init) => { - const request = - input instanceof Request ? new Request(input, init) : new Request(input.toString(), init); - const response = await mcp.handleRequest(request); - sessionHeaders.push(response.headers.get("mcp-session-id")); - return response; - }, - }); - const client = new Client( - { name: "local-modern-test", version: "1.0.0" }, - { capabilities: {}, versionNegotiation: { mode: { pin: "2026-07-28" } } }, - ); - - await client.connect(transport); - // oxlint-disable-next-line executor/no-try-catch-or-throw -- test boundary: always close the client and local handler - try { - expect((await client.listTools()).tools.map(({ name }) => name)).toContain("execute"); - const result = await client.callTool({ - name: "execute", - arguments: { code: "2 + 2" }, - }); - expect(result.content).toEqual([{ type: "text", text: "ran: 2 + 2" }]); - expect(sessionHeaders.every((sessionId) => sessionId === null)).toBe(true); - } finally { - await client.close(); - await mcp.close(); - } - }); - - it("rejects a pinned modern client with the unsupported-version protocol error", async () => { - const mcp = createMcpRequestHandler({ defaultConfig: { engine }, modernEnabled: false }); - const transport = new StreamableHTTPClientTransport(new URL("http://local.test/mcp"), { - fetch: (input, init) => - mcp.handleRequest( - input instanceof Request ? new Request(input, init) : new Request(input.toString(), init), - ), - }); - const client = new Client( - { name: "local-modern-disabled-test", version: "1.0.0" }, - { capabilities: {}, versionNegotiation: { mode: { pin: "2026-07-28" } } }, - ); - - // oxlint-disable-next-line executor/no-try-catch-or-throw -- test boundary: always close a client whose pinned negotiation is expected to fail - try { - await expect(client.connect(transport)).rejects.toThrow(/version negotiation failed/i); - } finally { - await client.close(); - await mcp.close(); - } - }); - - it("lets an auto-mode v2 client fall back to legacy when modern inbound is disabled", async () => { - const mcp = createMcpRequestHandler({ defaultConfig: { engine }, modernEnabled: false }); - const transport = new StreamableHTTPClientTransport(new URL("http://local.test/mcp"), { - fetch: (input, init) => - mcp.handleRequest( - input instanceof Request ? new Request(input, init) : new Request(input.toString(), init), - ), - }); - const client = new Client( - { name: "local-auto-fallback-test", version: "1.0.0" }, - { capabilities: {}, versionNegotiation: { mode: "auto" } }, - ); - - await client.connect(transport); - // oxlint-disable-next-line executor/no-try-catch-or-throw -- test boundary: always close the fallback client and local handler - try { - expect(client.getProtocolEra()).toBe("legacy"); - expect((await client.listTools()).tools.map(({ name }) => name)).toContain("execute"); - const result = await client.callTool({ - name: "execute", - arguments: { code: "3 + 4" }, - }); - expect(result.content).toEqual([{ type: "text", text: "ran: 3 + 4" }]); - expect(transport.sessionId).toBeTruthy(); - } finally { - await client.close(); - await mcp.close(); - } - }); -}); diff --git a/apps/local/src/mcp-stdio-test-server.ts b/apps/local/src/mcp-stdio-test-server.ts deleted file mode 100644 index 043df7c8a6..0000000000 --- a/apps/local/src/mcp-stdio-test-server.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { Effect } from "effect"; - -import type { ExecutionEngine, ExecutionResult } from "@executor-js/execution"; -import { FormElicitation, ToolAddress } from "@executor-js/sdk"; - -import { runMcpStdioServer } from "./mcp"; - -const TOOL_ADDRESS = ToolAddress.make("tools.test.org.main.approve"); -const paused: Extract = { - status: "paused", - execution: { - id: "stdio-execution", - elicitationContext: { - address: TOOL_ADDRESS, - args: {}, - request: FormElicitation.make({ - message: "Approve the stdio action?", - requestedSchema: { - type: "object", - properties: { value: { type: "string" } }, - required: ["value"], - }, - }), - }, - }, -}; - -const engine: ExecutionEngine = { - execute: () => Effect.succeed({ result: "unused" }), - executeWithPause: (code) => - code === "needs approval" - ? Effect.succeed(paused) - : Effect.succeed({ status: "completed", result: { result: 4 } }), - resume: (_executionId, response) => - Effect.succeed({ status: "completed", result: { result: response.content?.value } }), - isExecutionSettled: () => Effect.succeed(false), - getPausedExecution: (executionId) => - Effect.succeed(executionId === paused.execution.id ? paused.execution : null), - pausedExecutionCount: () => Effect.succeed(1), - hasPausedExecutions: () => Effect.succeed(true), - getDescription: Effect.succeed("stdio integration test executor"), -}; - -await runMcpStdioServer({ engine, elicitationMode: { mode: "native" } }); diff --git a/apps/local/src/mcp.ts b/apps/local/src/mcp.ts index c7efd3c179..780782c19c 100644 --- a/apps/local/src/mcp.ts +++ b/apps/local/src/mcp.ts @@ -1,27 +1,17 @@ import { Effect, type Cause } from "effect"; -import { - createMcpHandler, - isLegacyRequest, - McpServer, - WebStandardStreamableHTTPServerTransport, - type McpHttpHandler, -} from "@modelcontextprotocol/server"; -import { serveStdio } from "@modelcontextprotocol/server/stdio"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"; import { defaultMcpResource, jsonRpcErrorBody, - mcpModernDisabledResponse, mcpResourceKey, type McpResource, } from "@executor-js/host-mcp"; import { - appsEnabledForClientCapabilities, - buildMcpServer, - clientCapabilitiesFromRequest, - mcpRequestStateBindingFromBody, - requestBodyFromRequest, - type ExecutorMcpToolConfig, + createExecutorMcpServer, + type ExecutorMcpServerConfig, } from "@executor-js/host-mcp/tool-server"; import { approvalUrlForRequest, @@ -55,14 +45,12 @@ export type McpRequestHandler = { }; export interface LocalMcpServerConfig { - readonly config: ExecutorMcpToolConfig; + readonly config: ExecutorMcpServerConfig; readonly close?: () => Promise; } export interface LocalMcpRequestHandlerConfig { - readonly defaultConfig: ExecutorMcpToolConfig; - /** Emergency rollback for inbound MCP 2026-07-28 traffic only. */ - readonly modernEnabled?: boolean; + readonly defaultConfig: ExecutorMcpServerConfig; readonly createConfigForResource?: ( resource: McpResource, ) => Promise | LocalMcpServerConfig; @@ -125,15 +113,15 @@ const resourceFromRequest = (request: Request): McpResource | null => { return { kind: "toolkit", slug: decodeURIComponent(match[1]) }; }; -const engineFromConfig = (config: ExecutorMcpToolConfig): AnyExecutionEngine | null => +const engineFromConfig = (config: ExecutorMcpServerConfig): AnyExecutionEngine | null => "engine" in config ? config.engine : null; const normalizeHandlerConfig = ( - input: ExecutorMcpToolConfig | LocalMcpRequestHandlerConfig, + input: ExecutorMcpServerConfig | LocalMcpRequestHandlerConfig, ): LocalMcpRequestHandlerConfig => ("defaultConfig" in input ? input : { defaultConfig: input }); export const createMcpRequestHandler = ( - input: ExecutorMcpToolConfig | LocalMcpRequestHandlerConfig, + input: ExecutorMcpServerConfig | LocalMcpRequestHandlerConfig, ): McpRequestHandler => { const handlerConfig = normalizeHandlerConfig(input); const transports = new Map(); @@ -141,14 +129,8 @@ export const createMcpRequestHandler = ( const resources = new Map(); const sessionEngines = new Map(); const sessionClosers = new Map Promise>(); - const modernHandlers = new Map(); - const modernRequestBodies = new WeakMap(); const approvals = makeInProcessBrowserApprovalStore(); const defaultEngine = engineFromConfig(handlerConfig.defaultConfig); - let requestStateSigningKey: Uint8Array | undefined; - - const signingKey = (): Uint8Array => - (requestStateSigningKey ??= crypto.getRandomValues(new Uint8Array(32))); const pausedDetail = ( sessionId: string, @@ -182,71 +164,10 @@ export const createMcpRequestHandler = ( await ignoreClose(close); }; - const modernHandlerFor = (resource: McpResource): McpHttpHandler => { - const key = mcpResourceKey(resource); - const cached = modernHandlers.get(key); - if (cached) return cached; - - const handler = createMcpHandler( - (context) => { - const request = context.requestInfo; - if (!request) { - // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: the third-party McpServerFactory Promise contract has no typed failure channel; missing documented request context is an SDK defect - return Effect.runPromise(Effect.die("Modern MCP request context has no request")); - } - const parsedBody = modernRequestBodies.get(request); - return Effect.runPromise( - Effect.gen(function* () { - const resourceConfig = yield* Effect.promise(() => configForResource(resource)); - const clientCapabilities = yield* clientCapabilitiesFromRequest(request); - const requestStateBinding = yield* Effect.promise(() => - mcpRequestStateBindingFromBody({ - body: parsedBody, - principal: "local", - resource, - }), - ); - const server = yield* buildMcpServer({ - ...resourceConfig.config, - artifactsEnabled: readArtifactsEnabled(request), - appsEnabled: appsEnabledForClientCapabilities(clientCapabilities), - requestStateSigningKey: signingKey(), - requestStatePrincipal: "local", - ...(requestStateBinding === null ? {} : { requestStateBinding }), - }); - if (resourceConfig.close) { - const closeServer = server.close.bind(server); - const closeConfig = resourceConfig.close; - let closed = false; - server.close = async () => { - if (closed) return; - closed = true; - await ignoreClose(closeServer); - await ignoreClose(closeConfig); - }; - } - return server; - }), - ); - }, - { legacy: "reject" }, - ); - modernHandlers.set(key, handler); - return handler; - }; - return { handleRequest: async (request) => { const resource = resourceFromRequest(request); if (!resource) return jsonError(404, -32001, "MCP resource not found"); - if (!(await isLegacyRequest(request))) { - if (handlerConfig.modernEnabled === false) { - return mcpModernDisabledResponse({ cors: false }); - } - const parsedBody = await Effect.runPromise(requestBodyFromRequest(request)); - modernRequestBodies.set(request, parsedBody); - return modernHandlerFor(resource).fetch(request, { parsedBody }); - } const sessionId = request.headers.get("mcp-session-id"); if (sessionId) { @@ -295,14 +216,10 @@ export const createMcpRequestHandler = ( const elicitationMode = readElicitationMode(request); resourceConfig = await configForResource(resource); created = await Effect.runPromise( - buildMcpServer({ + createExecutorMcpServer({ ...resourceConfig.config, browserApprovalStore: approvals.store, artifactsEnabled: readArtifactsEnabled(request), - appsEnabled: resourceConfig.config.restoredAppsEnabled ?? false, - requestStateSigningKey: signingKey(), - requestStatePrincipal: "local", - sessionful: true, elicitationMode: elicitationMode === "browser" ? { @@ -366,10 +283,7 @@ export const createMcpRequestHandler = ( close: async () => { const ids = new Set([...transports.keys(), ...servers.keys()]); - await Promise.all([ - ...[...ids].map((id) => dispose(id, { transport: true, server: true })), - ...[...modernHandlers.values()].map((handler) => handler.close()), - ]); + await Promise.all([...ids].map((id) => dispose(id, { transport: true, server: true }))); }, }; }; @@ -378,21 +292,11 @@ export const createMcpRequestHandler = ( // Stdio transport // --------------------------------------------------------------------------- -export const runMcpStdioServer = async (config: ExecutorMcpToolConfig): Promise => { +export const runMcpStdioServer = async (config: ExecutorMcpServerConfig): Promise => { startIntegrationsRefresh(); - const requestStateSigningKey = crypto.getRandomValues(new Uint8Array(32)); - const stdio = serveStdio(() => - Effect.runPromise( - buildMcpServer({ - ...config, - appsEnabled: config.restoredAppsEnabled ?? false, - requestStateSigningKey, - requestStatePrincipal: "local", - sessionful: true, - }), - ), - ); + const server = await Effect.runPromise(createExecutorMcpServer(config)); + const transport = new StdioServerTransport(); const waitForExit = () => new Promise((resolve) => { @@ -411,8 +315,10 @@ export const runMcpStdioServer = async (config: ExecutorMcpToolConfig): Promise< // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: stdio server lifetime uses Promise-based SDK/process APIs and always closes resources try { + await server.connect(transport); await waitForExit(); } finally { - await ignoreClose(() => stdio.close()); + await ignoreClose(() => transport.close()); + await ignoreClose(() => server.close()); } }; diff --git a/bun.lock b/bun.lock index d2bafcad45..46d91d7cee 100644 --- a/bun.lock +++ b/bun.lock @@ -43,7 +43,6 @@ "@executor-js/runtime-quickjs": "workspace:*", "@executor-js/sdk": "workspace:*", "@jitl/quickjs-wasmfile-release-sync": "catalog:", - "@modelcontextprotocol/client": "2.0.0", "@modelcontextprotocol/sdk": "^1.29.0", "@sentry/bun": "^10.57.0", "effect": "catalog:", @@ -245,6 +244,7 @@ "@executor-js/sdk": "workspace:*", "@libsql/client": "catalog:", "@libsql/kysely-libsql": "catalog:", + "@modelcontextprotocol/sdk": "^1.29.0", "@tanstack/react-router": "catalog:", "better-auth": "^1.6.11", "drizzle-orm": "catalog:", @@ -257,7 +257,6 @@ "devDependencies": { "@effect/vitest": "catalog:", "@executor-js/vite-plugin": "workspace:*", - "@modelcontextprotocol/client": "2.0.0", "@tailwindcss/vite": "catalog:", "@tanstack/router-plugin": "^1.167.12", "@tanstack/virtual-file-routes": "^1.162.0", @@ -301,7 +300,7 @@ "@executor-js/sdk": "workspace:*", "@executor-js/vite-plugin": "workspace:*", "@libsql/client": "catalog:", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "@tanstack/react-router": "catalog:", "drizzle-orm": "catalog:", "effect": "catalog:", @@ -310,8 +309,6 @@ "react-dom": "catalog:", }, "devDependencies": { - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/sdk": "^1.29.0", "@rhyssul/portless": "^0.13.0", "@tailwindcss/vite": "catalog:", "@tanstack/router-plugin": "^1.167.12", @@ -366,10 +363,7 @@ "@executor-js/plugin-toolkits": "workspace:*", "@executor-js/sdk": "workspace:*", "@kitlangton/terminal-control": "^0.3.0", - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/core": "2.0.0", "@modelcontextprotocol/sdk": "^1.29.0", - "@modelcontextprotocol/server": "2.0.0", "asciinema-player": "^3.15.1", "effect": "catalog:", "monaco-editor": "^0.55.1", @@ -688,7 +682,7 @@ "@executor-js/host-mcp": "workspace:*", "@executor-js/sdk": "workspace:*", "@modelcontextprotocol/sdk": "^1.29.0", - "@modelcontextprotocol/server": "2.0.0", + "agents": "0.17.3", "effect": "catalog:", }, "devDependencies": { @@ -705,17 +699,16 @@ "name": "@executor-js/host-mcp", "version": "1.4.4", "dependencies": { + "@cfworker/json-schema": "^4.1.1", "@executor-js/execution": "workspace:*", "@executor-js/sdk": "workspace:*", - "@modelcontextprotocol/core": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.7.4", + "@modelcontextprotocol/sdk": "^1.29.0", "effect": "catalog:", "zod": "4.3.6", }, "devDependencies": { "@effect/vitest": "catalog:", - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/sdk": "^1.29.0", "@types/node": "catalog:", "bun-types": "catalog:", "vitest": "catalog:", @@ -1249,6 +1242,7 @@ "@electric-sql/pglite-socket@0.1.4": "patches/@electric-sql%2Fpglite-socket@0.1.4.patch", "libsql@0.5.29": "patches/libsql@0.5.29.patch", "@1password/sdk-core@0.4.1-beta.1": "patches/@1password%2Fsdk-core@0.4.1-beta.1.patch", + "agents@0.17.3": "patches/agents@0.17.3.patch", "postgres@3.4.9": "patches/postgres@3.4.9.patch", }, "catalog": { @@ -1420,16 +1414,28 @@ "@babel/generator": ["@babel/generator@7.29.1", "", { "dependencies": { "@babel/parser": "^7.29.0", "@babel/types": "^7.29.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw=="], + "@babel/helper-annotate-as-pure": ["@babel/helper-annotate-as-pure@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" } }, "sha512-NSpMkMsvvZqzThJ0p1B02cbtA2ObEyfBvq950bmNkyxsxvcxwhvvCB036rKhlEnuBBo30bOrk13u3FzlKSoRrw=="], + "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.28.6", "", { "dependencies": { "@babel/compat-data": "^7.28.6", "@babel/helper-validator-option": "^7.27.1", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA=="], + "@babel/helper-create-class-features-plugin": ["@babel/helper-create-class-features-plugin@8.0.1", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^8.0.0", "@babel/helper-member-expression-to-functions": "^8.0.0", "@babel/helper-optimise-call-expression": "^8.0.0", "@babel/helper-replace-supers": "^8.0.1", "@babel/helper-skip-transparent-expression-wrappers": "^8.0.0", "@babel/traverse": "^8.0.0", "semver": "^7.7.3" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-++t3ZktzlLmASAxIlxeXQK9Z2YwUafYGYcvGBFevqOqt16HozVHStUoQvWD09fzAZOb/uJGpUTBuGK41AJAuOA=="], + "@babel/helper-globals": ["@babel/helper-globals@7.28.0", "", {}, "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw=="], + "@babel/helper-member-expression-to-functions": ["@babel/helper-member-expression-to-functions@8.0.0", "", { "dependencies": { "@babel/traverse": "^8.0.0", "@babel/types": "^8.0.0" } }, "sha512-xkXrMbtk87Gk7+oKBVmBc6EORg/Qwx++AHESldmHkpvG8wgccdhJJFwrzqlF382Fk8wfXhJHWE/g/43QvEGNPQ=="], + "@babel/helper-module-imports": ["@babel/helper-module-imports@7.28.6", "", { "dependencies": { "@babel/traverse": "^7.28.6", "@babel/types": "^7.28.6" } }, "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw=="], "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.28.6", "", { "dependencies": { "@babel/helper-module-imports": "^7.28.6", "@babel/helper-validator-identifier": "^7.28.5", "@babel/traverse": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA=="], + "@babel/helper-optimise-call-expression": ["@babel/helper-optimise-call-expression@8.0.0", "", { "dependencies": { "@babel/types": "^8.0.0" } }, "sha512-3W6satvtPuCUkUx63S2jMoW9EQNYkADgs1HTfufmL7gCmAulHMKupA/12WNz4A0GMMFn/YnWWwqOT9IZrJHQjg=="], + "@babel/helper-plugin-utils": ["@babel/helper-plugin-utils@7.28.6", "", {}, "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug=="], + "@babel/helper-replace-supers": ["@babel/helper-replace-supers@8.0.1", "", { "dependencies": { "@babel/helper-member-expression-to-functions": "^8.0.0", "@babel/helper-optimise-call-expression": "^8.0.0", "@babel/traverse": "^8.0.0" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-B1SZADIcy3tmH8CmWvj4SHi/oAPom4UL3uknTc2QRNsPVLFk/sPnZvQL/8kj7Y5omvjMqie0vklvs6XM4OLW5Q=="], + + "@babel/helper-skip-transparent-expression-wrappers": ["@babel/helper-skip-transparent-expression-wrappers@8.0.0", "", { "dependencies": { "@babel/traverse": "^8.0.0", "@babel/types": "^8.0.0" } }, "sha512-xmCA9kP3IhySsqhzwIdWGlDN/1A4cCKNBO/uwZx/3YzmDoMePwno2Q5/Bq0q+tYaKbeF940YiKV/kaW8Mzvpjw=="], + "@babel/helper-string-parser": ["@babel/helper-string-parser@7.27.1", "", {}, "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA=="], "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="], @@ -1440,6 +1446,10 @@ "@babel/parser": ["@babel/parser@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="], + "@babel/plugin-proposal-decorators": ["@babel/plugin-proposal-decorators@8.0.2", "", { "dependencies": { "@babel/helper-create-class-features-plugin": "^8.0.1", "@babel/helper-plugin-utils": "^8.0.1", "@babel/plugin-syntax-decorators": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-+C6O6KKXU7BBq1GNaIkFJxrALUVGRcr+WeWm4OcuRl3h+l/CmNfcTLMrT2Lm3uvGBimBH/8pEBRrXJFLoO67Gg=="], + + "@babel/plugin-syntax-decorators": ["@babel/plugin-syntax-decorators@8.0.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^8.0.1" }, "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-NI+0S/6MvR6GlcQFwjDZ+WIc2qvG6TXN534lYs9llNldwW4b7Dh6KTtk030FA0xWdYGs4t1lWo+OEWN8wGB+Nw=="], + "@babel/plugin-syntax-jsx": ["@babel/plugin-syntax-jsx@7.28.6", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-wgEmr06G6sIpqr8YDwA2dSRTE3bJ+V0IfpzfSY3Lfgd7YWOaAdlykvJi13ZKBt8cZHfgH1IXN+CL656W3uUa4w=="], "@babel/plugin-syntax-typescript": ["@babel/plugin-syntax-typescript@7.28.6", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-+nDNmQye7nlnuuHDboPbGm00Vqg3oO8niRRL27/4LYHUsHYh0zJ1xWOz0uRwNFmM1Avzk8wZbc6rdiYhomzv/A=="], @@ -1452,6 +1462,8 @@ "@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], + "@babel/runtime-corejs3": ["@babel/runtime-corejs3@7.29.7", "", { "dependencies": { "core-js-pure": "^3.48.0" } }, "sha512-ppj9ouYku+RX0ljtgZd+KMO5mkM2bCqg8H2PYAFWnLsHEIKIdRojqbJ2i3eVHrisuxy7nOFCmngTDdWtUCdXUQ=="], + "@babel/template": ["@babel/template@7.28.6", "", { "dependencies": { "@babel/code-frame": "^7.28.6", "@babel/parser": "^7.28.6", "@babel/types": "^7.28.6" } }, "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ=="], "@babel/traverse": ["@babel/traverse@7.29.0", "", { "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", "@babel/helper-globals": "^7.28.0", "@babel/parser": "^7.29.0", "@babel/template": "^7.28.6", "@babel/types": "^7.29.0", "debug": "^4.3.1" } }, "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA=="], @@ -1544,6 +1556,8 @@ "@clerk/shared": ["@clerk/shared@4.22.0", "", { "dependencies": { "@tanstack/query-core": "^5.100.6", "dequal": "2.0.3", "glob-to-regexp": "0.4.1", "js-cookie": "3.0.7" }, "peerDependencies": { "react": "^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0", "react-dom": "^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0" }, "optionalPeers": ["react", "react-dom"] }, "sha512-GZ56kzUB2UBb8MCF+Eo8WIey+W4RP1tAkyOL+geiHxrQxJlUcgD+xalY2YPJLH8WVFwtOnfIl8KPEo0M0e/DRg=="], + "@cloudflare/codemode": ["@cloudflare/codemode@0.4.4", "", { "dependencies": { "@types/json-schema": "^7.0.15", "acorn": "^8.17.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.0", "@tanstack/ai": ">=0.8.0 <1.0.0", "ai": "^6.0.0", "zod": "^4.0.0" }, "optionalPeers": ["@modelcontextprotocol/sdk", "@tanstack/ai", "ai", "zod"] }, "sha512-GL0IF7NiHwAC222riEYGX75NHcnhTornAPfRI0Mj3Ig7C1y9H89FL0xs+pdflIF74eecNkzynsA+JdCIkGvKeA=="], + "@cloudflare/kv-asset-handler": ["@cloudflare/kv-asset-handler@0.5.0", "", {}, "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg=="], "@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.16.1", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw=="], @@ -2106,16 +2120,10 @@ "@mishieck/ink-titled-box": ["@mishieck/ink-titled-box@0.3.0", "", { "peerDependencies": { "ink": "^6.0.0", "react": "^19.1.0", "typescript": "^5" } }, "sha512-ugzVH9hixp3hwKfQ8On/qnsrdAxS3y9rTu/aGOFed4zVUvtZyGZNIR4rxAwXult8HKI4vJEh0OM8wib9NPrwUg=="], - "@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw=="], - - "@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.0.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="], - "@modelcontextprotocol/ext-apps": ["@modelcontextprotocol/ext-apps@1.7.5", "", { "dependencies": { "@standard-schema/spec": "^1.1.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.29.0", "react": "^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0", "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["react", "react-dom"] }, "sha512-TjPH2S2y5UEGKhmI6+XGFuqfqOV4ppe1x6DA3txnUaEWkgtA4G5vo14jGKFZmegdkZ1H4QMLyujLvoU1BEdnAg=="], "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="], - "@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" } }, "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw=="], - "@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="], "@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="], @@ -3122,6 +3130,10 @@ "@types/js-yaml": ["@types/js-yaml@4.0.9", "", {}, "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg=="], + "@types/jsesc": ["@types/jsesc@2.5.1", "", {}, "sha512-9VN+6yxLOPLOav+7PwjZbxiID2bVaeq0ED4qSQmdQTdjnXJSaCVKTR58t15oqH1H5t8Ng2ZX1SabJVoN9Q34bw=="], + + "@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="], + "@types/katex": ["@types/katex@0.16.8", "", {}, "sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg=="], "@types/keyv": ["@types/keyv@3.1.4", "", { "dependencies": { "@types/node": "*" } }, "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg=="], @@ -3292,6 +3304,8 @@ "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], + "agents": ["agents@0.17.3", "", { "dependencies": { "@babel/plugin-proposal-decorators": "^8.0.2", "@cfworker/json-schema": "^4.1.1", "@cloudflare/codemode": "^0.4.2", "@modelcontextprotocol/sdk": "1.29.0", "@rolldown/plugin-babel": "^0.2.3", "cron-schedule": "^6.0.0", "esbuild": "^0.28.1", "mimetext": "^3.0.28", "nanoid": "^5.1.16", "partyserver": "^0.5.8", "partysocket": "1.3.0", "yaml": "^2.9.0", "yargs": "^18.0.0" }, "peerDependencies": { "@ai-sdk/react": "^3.0.204", "@tanstack/ai": ">=0.10.2 <1.0.0", "@x402/core": "^2.0.0", "@x402/evm": "^2.0.0", "ai": "^6.0.0", "chat": "^4.29.0", "just-bash": "^3.0.0", "react": "^19.0.0", "vite": ">=6.0.0 <9.0.0", "zod": "^4.0.0" }, "optionalPeers": ["@ai-sdk/react", "@tanstack/ai", "@x402/core", "@x402/evm", "ai", "chat", "just-bash", "vite"], "bin": { "agents": "dist/cli/index.js" } }, "sha512-h0rc+dXwe/B6WblHH+Q3625nN/aryZntj6NIJX7tf+VSjmnI1EZyWtVBYMdX4FJZLShpl/vcx/A1AkxytWCPNQ=="], + "ahooks": ["ahooks@3.9.7", "", { "dependencies": { "@babel/runtime": "^7.21.0", "@types/js-cookie": "^3.0.6", "dayjs": "^1.9.1", "intersection-observer": "^0.12.0", "js-cookie": "^3.0.5", "lodash": "^4.17.21", "react-fast-compare": "^3.2.2", "resize-observer-polyfill": "^1.5.1", "screenfull": "^5.0.0", "tslib": "^2.4.1" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-S0lvzhbdlhK36RFBkGv+RbOM/dbbweym+BIHM/bwwuWVSVN5TuVErHPMWo4w0t1NDYg5KPp2iEf7Y7E5LASYiw=="], "ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="], @@ -3614,6 +3628,8 @@ "core-js": ["core-js@3.49.0", "", {}, "sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg=="], + "core-js-pure": ["core-js-pure@3.50.0", "", {}, "sha512-6GP3Pxz4IKyWjAfa747vIu/jilB5z29JWROLqH/b+pXVcpgh6tM06ZIBwSuglgVqzDYURhOK6oEzTrG0bCHitA=="], + "core-util-is": ["core-util-is@1.0.2", "", {}, "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ=="], "cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="], @@ -3624,6 +3640,8 @@ "crc": ["crc@3.8.0", "", { "dependencies": { "buffer": "^5.1.0" } }, "sha512-iX3mfgcTMIq3ZKLIsVFAbv7+Mc10kxabAGQb8HvjA1o3T1PIYprbakQ65d3I+2HGHt6nSKkM9PYjgoJO2KcFBQ=="], + "cron-schedule": ["cron-schedule@6.0.0", "", {}, "sha512-BoZaseYGXOo5j5HUwTaegIog3JJbuH4BbrY9A1ArLjXpy+RWb3mV28F/9Gv1dDA7E2L8kngWva4NWisnLTyfgQ=="], + "cross-dirname": ["cross-dirname@0.1.0", "", {}, "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q=="], "cross-inspect": ["cross-inspect@1.0.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Pcw1JTvZLSJH83iiGWt6fRcT+BjZlCDRVwYLbUcHzv/CRpB7r0MlSrGbIyQvVSNyGnbt7G4AXuyCiDR3POvZ1A=="], @@ -3936,6 +3954,8 @@ "etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="], + "event-target-polyfill": ["event-target-polyfill@0.0.4", "", {}, "sha512-Gs6RLjzlLRdT8X9ZipJdIZI/Y6/HhRLyq9RdDlCsnpxr/+Nn6bU2EFGuC94GjxqhM+Nmij2Vcq98yoHrU8uNFQ=="], + "event-target-shim": ["event-target-shim@5.0.1", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="], "eventemitter3": ["eventemitter3@5.0.4", "", {}, "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="], @@ -4698,6 +4718,8 @@ "mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], + "mimetext": ["mimetext@3.0.28", "", { "dependencies": { "@babel/runtime": "^7.26.0", "@babel/runtime-corejs3": "^7.26.0", "js-base64": "^3.7.7", "mime-types": "^2.1.35" } }, "sha512-eQXpbNrtxLCjUtiVbR/qR09dbPgZ2o+KR1uA7QKqGhbn8QV7HIL16mXXsobBL4/8TqoYh1us31kfz+dNfCev9g=="], + "mimic-fn": ["mimic-fn@2.1.0", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="], "mimic-function": ["mimic-function@5.0.1", "", {}, "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA=="], @@ -4750,7 +4772,7 @@ "mz": ["mz@2.7.0", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="], - "nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], + "nanoid": ["nanoid@5.1.16", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="], "nanostores": ["nanostores@1.3.0", "", {}, "sha512-XPUa/jz+P1oJvN9VBxw4L9MtdFfaH3DAryqPssqhb2kXjmb9npz0dly6rCsgFWOPr4Yg9mTfM3MDZgZZ+7A3lA=="], @@ -4902,6 +4924,10 @@ "parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="], + "partyserver": ["partyserver@0.5.10", "", { "dependencies": { "nanoid": "^5.1.9" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20260424.1 || ^5.20260703.1" } }, "sha512-t2B3mhTL1IOxCsj8rZgn4TxTuub7oLhypjc1/fGPNsbgnn9OsHms6uR3QEd5bFJ/7xrFo771j3DdUlll8cxgBg=="], + + "partysocket": ["partysocket@1.3.0", "", { "dependencies": { "event-target-polyfill": "^0.0.4" }, "peerDependencies": { "react": ">=17" }, "optionalPeers": ["react"] }, "sha512-1zToNyolZFK/7nuAw/K2bZrNzFqaZyRoCEkS+9vG6WSC5ikrN6qWRe96q6ImU51uptz2r+dAwSkwhJVdQi4LiA=="], + "patch-console": ["patch-console@2.0.0", "", {}, "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA=="], "path-data-parser": ["path-data-parser@0.1.0", "", {}, "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w=="], @@ -5854,12 +5880,32 @@ "@babel/generator/@babel/parser": ["@babel/parser@7.29.2", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA=="], + "@babel/helper-annotate-as-pure/@babel/types": ["@babel/types@8.0.4", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.4" } }, "sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g=="], + "@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "@babel/helper-create-class-features-plugin/@babel/traverse": ["@babel/traverse@8.0.4", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.4", "@babel/template": "^8.0.0", "@babel/types": "^8.0.4", "obug": "^2.1.1" } }, "sha512-bZnmqzGG8UZneG1lLxBoWIH0G6Gr1D846Yu4/3XnY6FhCndMR49u26nTY08u/dAxWmLWF9vGQOuC+84FfIUoeg=="], + + "@babel/helper-member-expression-to-functions/@babel/traverse": ["@babel/traverse@8.0.4", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.4", "@babel/template": "^8.0.0", "@babel/types": "^8.0.4", "obug": "^2.1.1" } }, "sha512-bZnmqzGG8UZneG1lLxBoWIH0G6Gr1D846Yu4/3XnY6FhCndMR49u26nTY08u/dAxWmLWF9vGQOuC+84FfIUoeg=="], + + "@babel/helper-member-expression-to-functions/@babel/types": ["@babel/types@8.0.4", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.4" } }, "sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g=="], + + "@babel/helper-optimise-call-expression/@babel/types": ["@babel/types@8.0.4", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.4" } }, "sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g=="], + + "@babel/helper-replace-supers/@babel/traverse": ["@babel/traverse@8.0.4", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.4", "@babel/template": "^8.0.0", "@babel/types": "^8.0.4", "obug": "^2.1.1" } }, "sha512-bZnmqzGG8UZneG1lLxBoWIH0G6Gr1D846Yu4/3XnY6FhCndMR49u26nTY08u/dAxWmLWF9vGQOuC+84FfIUoeg=="], + + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse": ["@babel/traverse@8.0.4", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/generator": "^8.0.0", "@babel/helper-globals": "^8.0.0", "@babel/parser": "^8.0.4", "@babel/template": "^8.0.0", "@babel/types": "^8.0.4", "obug": "^2.1.1" } }, "sha512-bZnmqzGG8UZneG1lLxBoWIH0G6Gr1D846Yu4/3XnY6FhCndMR49u26nTY08u/dAxWmLWF9vGQOuC+84FfIUoeg=="], + + "@babel/helper-skip-transparent-expression-wrappers/@babel/types": ["@babel/types@8.0.4", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.4" } }, "sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g=="], + "@babel/parser/@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], + "@babel/plugin-proposal-decorators/@babel/helper-plugin-utils": ["@babel/helper-plugin-utils@8.0.1", "", { "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-3PKFgjTyPlhFhorfP+SjKQxLViIL++zWjFOO4hGriYU+Bsm983DxEM1JmDRJVWXV0O9npu+xXRqz7Pbd3mh70g=="], + + "@babel/plugin-syntax-decorators/@babel/helper-plugin-utils": ["@babel/helper-plugin-utils@8.0.1", "", { "peerDependencies": { "@babel/core": "^8.0.0" } }, "sha512-3PKFgjTyPlhFhorfP+SjKQxLViIL++zWjFOO4hGriYU+Bsm983DxEM1JmDRJVWXV0O9npu+xXRqz7Pbd3mh70g=="], + "@babel/template/@babel/parser": ["@babel/parser@7.29.2", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA=="], "@babel/traverse/@babel/parser": ["@babel/parser@7.29.2", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA=="], @@ -5882,6 +5928,8 @@ "@clerk/shared/js-cookie": ["js-cookie@3.0.7", "", {}, "sha512-z/wZZgDrkNV1eA0ULjM/F9/50Ya8fbzgKneSpoPsXSGd0KnpdtHfOZWK+GcwLk+EZbS4F9RBhU+K2RgzuDaItw=="], + "@cloudflare/codemode/acorn": ["acorn@8.18.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="], + "@cloudflare/vite-plugin/@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.16.0", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": "1.20260301.1 || ~1.20260302.1 || ~1.20260303.1 || ~1.20260304.1 || >1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-8ovsRpwzPoEqPUzoErAYVv8l3FMZNeBVQfJTvtzP4AgLSRGZISRfuChFxHWUQd3n6cnrwkuTGxT+2cGo8EsyYg=="], "@cloudflare/vite-plugin/miniflare": ["miniflare@4.20260415.0", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "^0.34.5", "undici": "7.24.8", "workerd": "1.20260415.1", "ws": "8.18.0", "youch": "4.1.0-beta.10" }, "bin": { "miniflare": "bootstrap.js" } }, "sha512-JoExRWN4YBI2luA5BoSMFEgi8rQWXUGzo3mtE+58VXCLV3jj/Xnk5Yeqs/IXWz8Es5GJIaq6BtsixDvAxXSIng=="], @@ -6058,16 +6106,8 @@ "@manypkg/get-packages/fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="], - "@modelcontextprotocol/client/jose": ["jose@6.2.2", "", {}, "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ=="], - - "@modelcontextprotocol/client/zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], - - "@modelcontextprotocol/core/zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], - "@modelcontextprotocol/sdk/jose": ["jose@6.2.2", "", {}, "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ=="], - "@modelcontextprotocol/server/zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], - "@octokit/request/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], "@opentelemetry/exporter-logs-otlp-proto/@opentelemetry/resources": ["@opentelemetry/resources@2.6.1", "", { "dependencies": { "@opentelemetry/core": "2.6.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-lID/vxSuKWXM55XhAKNoYXu9Cutoq5hFdkbTdI/zDKQktXzcWBVhNsOkiZFTMU9UtEWuGRNe0HUgmsFldIdxVA=="], @@ -6370,6 +6410,12 @@ "@vercel/sdk/zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], + "agents/esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="], + + "agents/yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="], + + "agents/yargs": ["yargs@18.1.0", "", { "dependencies": { "cliui": "^9.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "string-width": "^8.2.1", "y18n": "^5.0.5", "yargs-parser": "^22.0.0" } }, "sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg=="], + "ajv-keywords/ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="], "anymatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], @@ -6578,6 +6624,8 @@ "micromatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + "mimetext/mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], + "miniflare/undici": ["undici@7.24.8", "", {}, "sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ=="], "miniflare/workerd": ["workerd@1.20260424.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260424.1", "@cloudflare/workerd-darwin-arm64": "1.20260424.1", "@cloudflare/workerd-linux-64": "1.20260424.1", "@cloudflare/workerd-linux-arm64": "1.20260424.1", "@cloudflare/workerd-windows-64": "1.20260424.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-oKsB0Xo/mfkYMdSACoS06XZg09VUK4rXwHfF/1t3P++sMbwzf4UHQvMO57+zxpEB2nVrY/ZkW0bYFGq4GdAFSQ=="], @@ -6616,6 +6664,8 @@ "playwright/fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="], + "postcss/nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], + "posthog-js/@opentelemetry/api-logs": ["@opentelemetry/api-logs@0.208.0", "", { "dependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-CjruKY9V6NMssL/T1kAFgzosF1v9o6oeN+aX5JB/C/xPNtmgIJqcXHG7fA82Ou1zCpWGl4lROQUKwUNE1pMCyg=="], "posthog-js/@opentelemetry/exporter-logs-otlp-http": ["@opentelemetry/exporter-logs-otlp-http@0.208.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.208.0", "@opentelemetry/core": "2.2.0", "@opentelemetry/otlp-exporter-base": "0.208.0", "@opentelemetry/otlp-transformer": "0.208.0", "@opentelemetry/sdk-logs": "0.208.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-jOv40Bs9jy9bZVLo/i8FwUiuCvbjWDI+ZW13wimJm4LjnlwJxGgB+N/VWOZUTpM+ah/awXeQqKdNlpLf2EjvYg=="], @@ -6754,8 +6804,68 @@ "@azure/identity/@azure/msal-node/uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="], + "@babel/helper-annotate-as-pure/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@8.0.0", "", {}, "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg=="], + + "@babel/helper-annotate-as-pure/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.4", "", {}, "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg=="], + "@babel/helper-compilation-targets/lru-cache/yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/code-frame": ["@babel/code-frame@8.0.0", "", { "dependencies": { "@babel/helper-validator-identifier": "^8.0.0", "js-tokens": "^10.0.0" } }, "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw=="], + + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/parser": ["@babel/parser@8.0.4", "", { "dependencies": { "@babel/types": "^8.0.4" }, "bin": "./bin/babel-parser.js" }, "sha512-srpptsAkEbbNIC/q8nT7o+m6CQe8CJUTV/t7MYc9NnWlgYVtHOb7JH6SorxMhN0kuRJjVqXbKClG6xSbPtzz+g=="], + + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/template": ["@babel/template@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0" } }, "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ=="], + + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/types": ["@babel/types@8.0.4", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.4" } }, "sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g=="], + + "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/code-frame": ["@babel/code-frame@8.0.0", "", { "dependencies": { "@babel/helper-validator-identifier": "^8.0.0", "js-tokens": "^10.0.0" } }, "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw=="], + + "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + + "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + + "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/parser": ["@babel/parser@8.0.4", "", { "dependencies": { "@babel/types": "^8.0.4" }, "bin": "./bin/babel-parser.js" }, "sha512-srpptsAkEbbNIC/q8nT7o+m6CQe8CJUTV/t7MYc9NnWlgYVtHOb7JH6SorxMhN0kuRJjVqXbKClG6xSbPtzz+g=="], + + "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/template": ["@babel/template@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0" } }, "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ=="], + + "@babel/helper-member-expression-to-functions/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@8.0.0", "", {}, "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg=="], + + "@babel/helper-member-expression-to-functions/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.4", "", {}, "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg=="], + + "@babel/helper-optimise-call-expression/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@8.0.0", "", {}, "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg=="], + + "@babel/helper-optimise-call-expression/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.4", "", {}, "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg=="], + + "@babel/helper-replace-supers/@babel/traverse/@babel/code-frame": ["@babel/code-frame@8.0.0", "", { "dependencies": { "@babel/helper-validator-identifier": "^8.0.0", "js-tokens": "^10.0.0" } }, "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw=="], + + "@babel/helper-replace-supers/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + + "@babel/helper-replace-supers/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + + "@babel/helper-replace-supers/@babel/traverse/@babel/parser": ["@babel/parser@8.0.4", "", { "dependencies": { "@babel/types": "^8.0.4" }, "bin": "./bin/babel-parser.js" }, "sha512-srpptsAkEbbNIC/q8nT7o+m6CQe8CJUTV/t7MYc9NnWlgYVtHOb7JH6SorxMhN0kuRJjVqXbKClG6xSbPtzz+g=="], + + "@babel/helper-replace-supers/@babel/traverse/@babel/template": ["@babel/template@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0" } }, "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ=="], + + "@babel/helper-replace-supers/@babel/traverse/@babel/types": ["@babel/types@8.0.4", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.4" } }, "sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g=="], + + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/code-frame": ["@babel/code-frame@8.0.0", "", { "dependencies": { "@babel/helper-validator-identifier": "^8.0.0", "js-tokens": "^10.0.0" } }, "sha512-dYYg153EyN2Ekbqw2zAsbd6/JR+9N2SEoC7YV2GyyqMM7x9bLDTjBD6XBhSMLH0wtIVyJj03jWNriQhaN+eoCw=="], + + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/generator": ["@babel/generator@8.0.0", "", { "dependencies": { "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-NT9NrVwJsbSV6Y2FSstWa71EETOnzrjkL5/wX3D2mYHtKM+qvqB1DvR4D0Setb/gDBsHzRICifwEWMO8CnTF6g=="], + + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@8.0.0", "", {}, "sha512-lLozHOM6sWWlxNo8CYqHy4MBZeTvHXNgVPBfPOGsjPKUzHC2Az9QwB6gxdQmpwHl6GlQtbGgS+lj5887guDiLw=="], + + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/parser": ["@babel/parser@8.0.4", "", { "dependencies": { "@babel/types": "^8.0.4" }, "bin": "./bin/babel-parser.js" }, "sha512-srpptsAkEbbNIC/q8nT7o+m6CQe8CJUTV/t7MYc9NnWlgYVtHOb7JH6SorxMhN0kuRJjVqXbKClG6xSbPtzz+g=="], + + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/template": ["@babel/template@8.0.0", "", { "dependencies": { "@babel/code-frame": "^8.0.0", "@babel/parser": "^8.0.0", "@babel/types": "^8.0.0" } }, "sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ=="], + + "@babel/helper-skip-transparent-expression-wrappers/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@8.0.0", "", {}, "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg=="], + + "@babel/helper-skip-transparent-expression-wrappers/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.4", "", {}, "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg=="], + "@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], "@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], @@ -7086,6 +7196,62 @@ "@types/yauzl/@types/node/undici-types": ["undici-types@7.19.2", "", {}, "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg=="], + "agents/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="], + + "agents/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.28.2", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="], + + "agents/esbuild/@esbuild/android-arm64": ["@esbuild/android-arm64@0.28.2", "", { "os": "android", "cpu": "arm64" }, "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A=="], + + "agents/esbuild/@esbuild/android-x64": ["@esbuild/android-x64@0.28.2", "", { "os": "android", "cpu": "x64" }, "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q=="], + + "agents/esbuild/@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.28.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw=="], + + "agents/esbuild/@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.28.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw=="], + + "agents/esbuild/@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.28.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw=="], + + "agents/esbuild/@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.28.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg=="], + + "agents/esbuild/@esbuild/linux-arm": ["@esbuild/linux-arm@0.28.2", "", { "os": "linux", "cpu": "arm" }, "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w=="], + + "agents/esbuild/@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.28.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug=="], + + "agents/esbuild/@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.28.2", "", { "os": "linux", "cpu": "ia32" }, "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ=="], + + "agents/esbuild/@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ=="], + + "agents/esbuild/@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA=="], + + "agents/esbuild/@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.28.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ=="], + + "agents/esbuild/@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA=="], + + "agents/esbuild/@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.28.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg=="], + + "agents/esbuild/@esbuild/linux-x64": ["@esbuild/linux-x64@0.28.2", "", { "os": "linux", "cpu": "x64" }, "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ=="], + + "agents/esbuild/@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw=="], + + "agents/esbuild/@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.28.2", "", { "os": "none", "cpu": "x64" }, "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw=="], + + "agents/esbuild/@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.28.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ=="], + + "agents/esbuild/@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.28.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw=="], + + "agents/esbuild/@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q=="], + + "agents/esbuild/@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.28.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g=="], + + "agents/esbuild/@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.28.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ=="], + + "agents/esbuild/@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.28.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA=="], + + "agents/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="], + + "agents/yargs/cliui": ["cliui@9.0.1", "", { "dependencies": { "string-width": "^7.2.0", "strip-ansi": "^7.1.0", "wrap-ansi": "^9.0.0" } }, "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w=="], + + "agents/yargs/string-width": ["string-width@8.2.2", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg=="], + "ajv-keywords/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], "app-builder-lib/@electron/get/env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="], @@ -7298,6 +7464,8 @@ "kayvee/js-yaml/argparse": ["argparse@1.0.10", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="], + "mimetext/mime-types/mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], + "miniflare/workerd/@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260424.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-yFR1XaJbSDLg/qbwtrYaU2xwFXatIPKR5nrMQCN1q/m6+Qe/j6r+kCnFEvOJjMZOm9iCKsE6Qly5clgl4u32qw=="], "miniflare/workerd/@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260424.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-LqWKcE7x/9KyC2iQvKPeb20hKST3dYXDZlYTvFymgR1DfLS0OFOCzVGTloVNd7WqvK4SkdzBYfxo7QMIAeBK0w=="], @@ -7430,6 +7598,30 @@ "yargs/string-width/is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.4", "", {}, "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg=="], + + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/code-frame/js-tokens": ["js-tokens@10.0.0", "", {}, "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q=="], + + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@8.0.0", "", {}, "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg=="], + + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.4", "", {}, "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg=="], + + "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.4", "", {}, "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg=="], + + "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/code-frame/js-tokens": ["js-tokens@10.0.0", "", {}, "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q=="], + + "@babel/helper-replace-supers/@babel/traverse/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.4", "", {}, "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg=="], + + "@babel/helper-replace-supers/@babel/traverse/@babel/code-frame/js-tokens": ["js-tokens@10.0.0", "", {}, "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q=="], + + "@babel/helper-replace-supers/@babel/traverse/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@8.0.0", "", {}, "sha512-6mJgmFFFIIO82vvoLt9XtRC7/TkzXfts1t/SpRX4IHSzMgqoPYCWesVu1udUPUWioAE/2fcG6WuI8zrkE1gwrg=="], + + "@babel/helper-replace-supers/@babel/traverse/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.4", "", {}, "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg=="], + + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@8.0.4", "", {}, "sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg=="], + + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/code-frame/js-tokens": ["js-tokens@10.0.0", "", {}, "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q=="], + "@cloudflare/vite-plugin/miniflare/workerd/@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260415.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-dsxaKsQm3LnPGNPEdsRv09QN3Y4DqCw7kX5j6noKqbAtro2jTr95sVlYM1jUxZ5FkOl1f7SXgaKKB9t5H5Nkbg=="], "@cloudflare/vite-plugin/miniflare/workerd/@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260415.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-+JgSgVA49KyKteHRA1SnonE4Zn5Ei5zdAp5FQMxFmXI8qulZw4Hl7safXxRyK4i9sTO8gl7TFOKO5Q64VPvSDQ=="], @@ -7568,6 +7760,12 @@ "@tanstack/router-plugin/chokidar/readdirp/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + "agents/yargs/cliui/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], + + "agents/yargs/cliui/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + + "agents/yargs/string-width/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + "astro/@clack/prompts/fast-string-width/fast-string-truncated-width": ["fast-string-truncated-width@1.2.1", "", {}, "sha512-Q9acT/+Uu3GwGj+5w/zsGuQjh9O1TyywhIwAxHudtWrgF09nHOPrvTLhQevPbttcxjr/SNN7mJmfOw/B1bXgow=="], "dir-compare/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], @@ -7608,6 +7806,12 @@ "@react-grab/cli/ora/cli-cursor/restore-cursor/onetime": ["onetime@7.0.0", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="], + "agents/yargs/cliui/string-width/emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], + + "agents/yargs/cliui/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + + "agents/yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + "temp/rimraf/glob/minimatch/brace-expansion": ["brace-expansion@1.1.14", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g=="], "@executor-js/motel/@opentelemetry/exporter-trace-otlp-http/@opentelemetry/otlp-transformer/protobufjs/@types/node/undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], diff --git a/e2e/cloud/mcp-modern-protocol.test.ts b/e2e/cloud/mcp-modern-protocol.test.ts deleted file mode 100644 index 752c014472..0000000000 --- a/e2e/cloud/mcp-modern-protocol.test.ts +++ /dev/null @@ -1,235 +0,0 @@ -import { randomBytes, randomUUID } from "node:crypto"; - -import { expect } from "@effect/vitest"; -import { Effect } from "effect"; -import { composePluginApi } from "@executor-js/api/server"; -import { isInputRequiredResult } from "@modelcontextprotocol/client"; - -import { scenario } from "../src/scenario"; -import { Api, Mcp, Target } from "../src/services"; -import { - callModernToolWithInputRequired, - connectModernMcpClient, - MODERN_MCP_PROTOCOL_VERSION, - modernToolText, - readModernMcpAuthChallenge, -} from "../src/surfaces/modern-mcp"; -import type { Identity } from "../src/target"; - -const coreApi = composePluginApi([] as const); -const LEGACY_PROTOCOL_VERSION = "2025-03-26"; -const JSON_AND_SSE = "application/json, text/event-stream"; - -const emailOf = (identity: Identity): string => identity.credentials?.email ?? identity.label; - -const legacyInitialize = { - jsonrpc: "2.0" as const, - id: 1, - method: "initialize", - params: { - protocolVersion: LEGACY_PROTOCOL_VERSION, - capabilities: {}, - clientInfo: { name: "executor-modern-e2e-control", version: "1.0.0" }, - }, -}; - -const postLegacy = ( - url: string, - body: unknown, - options?: { readonly bearer?: string; readonly sessionId?: string }, -): Promise => - fetch(url, { - method: "POST", - headers: { - accept: JSON_AND_SSE, - "content-type": "application/json", - "mcp-protocol-version": LEGACY_PROTOCOL_VERSION, - ...(options?.bearer ? { authorization: `Bearer ${options.bearer}` } : {}), - ...(options?.sessionId ? { "mcp-session-id": options.sessionId } : {}), - }, - body: JSON.stringify(body), - }); - -scenario( - "MCP modern protocol · a pinned 2026 client discovers, lists, and executes while legacy isolation stays intact", - {}, - Effect.scoped( - Effect.gen(function* () { - const target = yield* Target; - const mcp = yield* Mcp; - const identity = yield* target.newIdentity(); - const bearer = yield* mcp.mintBearer(emailOf(identity)); - const client = yield* connectModernMcpClient({ - url: target.mcpUrl, - bearer, - mode: { pin: MODERN_MCP_PROTOCOL_VERSION }, - }); - - expect(client.getProtocolEra(), "the pinned client selected the modern era").toBe("modern"); - expect(client.getNegotiatedProtocolVersion(), "the exact revision was selected").toBe( - MODERN_MCP_PROTOCOL_VERSION, - ); - expect( - client.getDiscoverResult()?.supportedVersions, - "server/discover advertises the pinned revision", - ).toContain(MODERN_MCP_PROTOCOL_VERSION); - - const tools = yield* Effect.promise(() => client.listTools()); - expect( - tools.tools.map((tool) => tool.name), - "the modern catalog advertises Executor's execute tool", - ).toContain("execute"); - - const result = yield* Effect.promise(() => - client.callTool({ name: "execute", arguments: { code: "return 6 * 7;" } }), - ); - expect(result.isError, "the modern execute call completes successfully").not.toBe(true); - expect(modernToolText(result), "the sandbox result crosses the modern wire").toBe("42"); - - const foreignSession = yield* Effect.promise(() => - postLegacy( - target.mcpUrl, - { jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }, - { bearer, sessionId: `foreign-${randomUUID()}` }, - ), - ); - expect( - foreignSession.status, - "a foreign legacy session id remains a clean not-found response", - ).toBe(404); - const foreignBody = (yield* Effect.promise(() => foreignSession.json())) as { - readonly error?: { readonly code?: number; readonly message?: string }; - }; - expect(foreignBody.error?.code, "the legacy rejection remains a JSON-RPC error").toBe(-32001); - expect( - foreignBody.error?.message, - "the unknown legacy session stays a clean not-found error", - ).toBe("Session not found"); - - const [modernChallenge, legacyChallenge] = yield* Effect.all([ - readModernMcpAuthChallenge(target.mcpUrl), - Effect.promise(() => postLegacy(target.mcpUrl, legacyInitialize)), - ]); - expect(modernChallenge.status, "the unauthenticated modern probe is challenged").toBe(401); - expect(legacyChallenge.status, "the unauthenticated legacy initialize is challenged").toBe( - 401, - ); - expect( - modernChallenge.wwwAuthenticate, - "modern and legacy entry paths publish the same Bearer challenge", - ).toBe(legacyChallenge.headers.get("www-authenticate")); - }), - ), -); - -scenario( - "MCP modern protocol · a default v2 auto client probes Executor and selects modern", - {}, - Effect.scoped( - Effect.gen(function* () { - const target = yield* Target; - const mcp = yield* Mcp; - const identity = yield* target.newIdentity(); - const bearer = yield* mcp.mintBearer(emailOf(identity)); - const client = yield* connectModernMcpClient({ - url: target.mcpUrl, - bearer, - mode: "auto", - }); - - expect(client.getProtocolEra(), "auto negotiation selected the modern path").toBe("modern"); - expect(client.getNegotiatedProtocolVersion(), "auto selected the current revision").toBe( - MODERN_MCP_PROTOCOL_VERSION, - ); - expect( - client.getDiscoverResult()?.supportedVersions, - "the probe result records the server's modern offer", - ).toContain(MODERN_MCP_PROTOCOL_VERSION); - expect( - (yield* Effect.promise(() => client.listTools())).tools.map((tool) => tool.name), - "the selected path is usable", - ).toContain("execute"); - }), - ), -); - -scenario( - "MCP modern protocol · native input_required resumes an approval-gated execution", - {}, - Effect.scoped( - Effect.gen(function* () { - const target = yield* Target; - const { client: makeApiClient } = yield* Api; - const mcp = yield* Mcp; - const identity = yield* target.newIdentity(); - const api = yield* makeApiClient(coreApi, identity); - const bearer = yield* mcp.mintBearer(emailOf(identity)); - const pattern = `modern-native-${randomBytes(4).toString("hex")}.*`; - const code = ` -const result = await tools.executor.coreTools.policies.create({ - owner: "user", - pattern: ${JSON.stringify(pattern)}, - action: "block", -}); -return JSON.stringify(result); -`; - - const cleanup = api.policies.list().pipe( - Effect.flatMap((policies) => - Effect.forEach( - policies.filter((policy) => policy.pattern === pattern), - (policy) => - api.policies - .remove({ params: { policyId: policy.id }, payload: { owner: "user" } }) - .pipe(Effect.ignore), - ), - ), - Effect.ignore, - ); - - yield* Effect.gen(function* () { - const nativeUrl = new URL(target.mcpUrl); - nativeUrl.searchParams.set("elicitation_mode", "native"); - const client = yield* connectModernMcpClient({ - url: nativeUrl.toString(), - bearer, - mode: { pin: MODERN_MCP_PROTOCOL_VERSION }, - manualInputRequired: true, - }); - - const first = yield* callModernToolWithInputRequired(client, { - name: "execute", - arguments: { code }, - }); - expect(isInputRequiredResult(first), "the gated action requests native input").toBe(true); - if (!isInputRequiredResult(first)) return; - expect( - first.inputRequests?.elicitation, - "the pause carries an elicitation request", - ).toMatchObject({ method: "elicitation/create" }); - expect(first.requestState, "the continuation state is opaque and present").toEqual( - expect.any(String), - ); - - const completed = yield* callModernToolWithInputRequired(client, { - name: "execute", - arguments: { code }, - inputResponses: { elicitation: { action: "accept", content: {} } }, - requestState: first.requestState, - }); - expect(isInputRequiredResult(completed), "the accepted round completes").toBe(false); - if (isInputRequiredResult(completed)) return; - expect(completed.isError, "the resumed execution succeeds").not.toBe(true); - expect( - modernToolText(completed), - "the tool result returns after the second round", - ).toContain('"ok":true'); - - expect( - (yield* api.policies.list()).map((policy) => policy.pattern), - "the approved side effect ran", - ).toContain(pattern); - }).pipe(Effect.ensuring(cleanup)); - }), - ), -); diff --git a/e2e/local/cli-mcp-protocol.test.ts b/e2e/local/cli-mcp-protocol.test.ts deleted file mode 100644 index 0d002eefc7..0000000000 --- a/e2e/local/cli-mcp-protocol.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -// Regression for #1449: a modern MCP client starts stdio negotiation with -// `server/discover`, before `initialize`. This crosses the real CLI bridge: -// -// v2/v1 stdio client -> `executor mcp` -> local daemon HTTP MCP endpoint -// -// It reconnects with the v1 SDK too, proving discovery forwarding does not -// regress established legacy stdio clients. -import { expect } from "@effect/vitest"; -import { Client as ModernClient } from "@modelcontextprotocol/client"; -import { StdioClientTransport as ModernStdioClientTransport } from "@modelcontextprotocol/client/stdio"; -import { Client as LegacyClient } from "@modelcontextprotocol/sdk/client/index.js"; -import { StdioClientTransport as LegacyStdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; -import { Effect } from "effect"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { fileURLToPath } from "node:url"; - -import { scenario } from "../src/scenario"; -import { stopAutoSpawnedDaemon } from "./daemon-process"; - -const repoRoot = fileURLToPath(new URL("../../", import.meta.url)); -const testScope = join(repoRoot, "apps/local"); - -const bridgeCommand = (dataDir: string) => ({ - command: "bun", - args: ["run", "dev:cli", "mcp", "--scope", testScope], - cwd: repoRoot, - env: { - ...process.env, - EXECUTOR_DATA_DIR: dataDir, - EXECUTOR_DISABLE_INTEGRATIONS_FETCH: "1", - } as Record, - stderr: "pipe" as const, -}); - -const withTempData = Effect.acquireRelease( - Effect.sync(() => { - const root = mkdtempSync(join(tmpdir(), "executor-mcp-protocol-")); - return { root, dataDir: join(root, "data") }; - }), - ({ root, dataDir }) => - Effect.promise(async () => { - await stopAutoSpawnedDaemon(dataDir); - rmSync(root, { recursive: true, force: true }); - }), -); - -scenario( - "Local CLI MCP · modern discovery and legacy initialize cross the stdio bridge", - { timeout: 240_000 }, - Effect.gen(function* () { - const { dataDir } = yield* withTempData; - - const modernTransport = new ModernStdioClientTransport(bridgeCommand(dataDir)); - const modernClient = new ModernClient( - { name: "executor-cli-modern-e2e", version: "1.0.0" }, - { versionNegotiation: { mode: "auto" } }, - ); - - yield* Effect.promise(async () => { - // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: always reap the real CLI child when an assertion fails - try { - await modernClient.connect(modernTransport); - expect(modernClient.getProtocolEra()).toBe("modern"); - expect((await modernClient.listTools()).tools.map(({ name }) => name)).toContain("execute"); - const executed = await modernClient.callTool({ - name: "execute", - arguments: { code: "return 42" }, - }); - expect(executed.structuredContent).toMatchObject({ - status: "completed", - result: 42, - }); - } finally { - await modernClient.close(); - } - }); - - const legacyTransport = new LegacyStdioClientTransport(bridgeCommand(dataDir)); - const legacyClient = new LegacyClient({ - name: "executor-cli-legacy-e2e", - version: "1.0.0", - }); - - yield* Effect.promise(async () => { - // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: always reap the real CLI child when an assertion fails - try { - await legacyClient.connect(legacyTransport); - expect((await legacyClient.listTools()).tools.map(({ name }) => name)).toContain("execute"); - const executed = await legacyClient.callTool({ - name: "execute", - arguments: { code: "return 42" }, - }); - expect(executed.structuredContent).toMatchObject({ - status: "completed", - result: 42, - }); - } finally { - await legacyClient.close(); - } - }); - }).pipe(Effect.scoped), -); diff --git a/e2e/package.json b/e2e/package.json index 91be6b0d13..040a042ebb 100644 --- a/e2e/package.json +++ b/e2e/package.json @@ -31,10 +31,7 @@ "@executor-js/plugin-toolkits": "workspace:*", "@executor-js/sdk": "workspace:*", "@kitlangton/terminal-control": "^0.3.0", - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/core": "2.0.0", "@modelcontextprotocol/sdk": "^1.29.0", - "@modelcontextprotocol/server": "2.0.0", "asciinema-player": "^3.15.1", "effect": "catalog:", "monaco-editor": "^0.55.1", diff --git a/e2e/scenarios/mcp-modern-only-server.test.ts b/e2e/scenarios/mcp-modern-only-server.test.ts deleted file mode 100644 index 4e4eb71934..0000000000 --- a/e2e/scenarios/mcp-modern-only-server.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { randomBytes } from "node:crypto"; - -import { expect } from "@effect/vitest"; -import { Effect } from "effect"; -import { composePluginApi } from "@executor-js/api/server"; -import { mcpHttpPlugin } from "@executor-js/plugin-mcp/api"; -import { AuthTemplateSlug, ConnectionName, IntegrationSlug } from "@executor-js/sdk/shared"; - -import { serveModernOnlyMcp } from "../src/fixtures/modern-only-mcp"; -import { scenario } from "../src/scenario"; -import { Api, Target } from "../src/services"; - -const api = composePluginApi([mcpHttpPlugin()] as const); -const LEGACY_PROTOCOL_VERSION = "2025-03-26"; - -const legacyInitialize = { - jsonrpc: "2.0" as const, - id: 1, - method: "initialize", - params: { - protocolVersion: LEGACY_PROTOCOL_VERSION, - capabilities: {}, - clientInfo: { name: "executor-e2e-negative-control", version: "1.0.0" }, - }, -}; - -scenario( - "MCP outbound · Executor discovers and invokes a modern-only server that rejects legacy", - {}, - Effect.scoped( - Effect.gen(function* () { - const target = yield* Target; - const { client: makeApiClient } = yield* Api; - const identity = yield* target.newIdentity(); - const client = yield* makeApiClient(api, identity); - const fixture = yield* serveModernOnlyMcp(); - const slug = IntegrationSlug.make(`modern_only_${randomBytes(4).toString("hex")}`); - const connectionName = ConnectionName.make("main"); - - const legacy = yield* Effect.promise(() => - fetch(fixture.url, { - method: "POST", - headers: { - accept: "application/json, text/event-stream", - "content-type": "application/json", - }, - body: JSON.stringify(legacyInitialize), - }), - ); - expect(legacy.status, "the fixture rejects the legacy handshake on the wire").toBe(400); - expect( - yield* Effect.promise(() => legacy.json()), - "the negative control is the SDK's unsupported-version error", - ).toEqual({ - jsonrpc: "2.0", - id: 1, - error: { - code: -32022, - message: `Unsupported protocol version: ${LEGACY_PROTOCOL_VERSION}`, - data: { - requested: LEGACY_PROTOCOL_VERSION, - supported: ["2026-07-28"], - }, - }, - }); - - yield* client.mcp.addServer({ - payload: { - transport: "remote", - name: "Modern-only MCP", - endpoint: fixture.url, - slug: String(slug), - remoteTransport: "streamable-http", - }, - }); - - yield* Effect.gen(function* () { - yield* client.connections.create({ - payload: { - owner: "org", - name: connectionName, - integration: slug, - template: AuthTemplateSlug.make("none"), - value: "", - }, - }); - - const catalog = yield* client.tools.list({ query: { integration: slug } }); - expect( - catalog.map((tool) => String(tool.name)).sort(), - "catalog sync discovered both modern-only tools", - ).toEqual(["modern_identity", "modern_ping"]); - - const executed = yield* client.executions.execute({ - payload: { - code: ` -const result = await tools.${String(slug)}.org.main.modern_ping({}); -return { ok: result.ok, value: result.ok ? result.data : result.error }; -`, - autoApprove: true, - }, - }); - expect(executed.status, "the invocation completed through Executor").toBe("completed"); - const outcome = JSON.parse(executed.text) as { - readonly ok?: boolean; - readonly value?: unknown; - }; - expect(outcome.ok, `modern-only invocation result: ${executed.text}`).toBe(true); - expect( - JSON.stringify(outcome.value), - "the modern-only server's tool result returns through the sandbox", - ).toContain("pong-modern"); - }).pipe( - Effect.ensuring( - Effect.gen(function* () { - yield* client.connections - .remove({ - params: { - owner: "org", - integration: slug, - name: connectionName, - }, - }) - .pipe(Effect.ignore); - yield* client.mcp.removeServer({ params: { slug } }).pipe(Effect.ignore); - }), - ), - ); - }), - ), -); diff --git a/e2e/selfhost/mcp-modern-protocol.test.ts b/e2e/selfhost/mcp-modern-protocol.test.ts deleted file mode 100644 index 88f2e60f7d..0000000000 --- a/e2e/selfhost/mcp-modern-protocol.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { expect } from "@effect/vitest"; -import { Effect } from "effect"; - -import { scenario } from "../src/scenario"; -import { Mcp, Target } from "../src/services"; -import { - connectModernMcpClient, - MODERN_MCP_PROTOCOL_VERSION, - modernToolText, -} from "../src/surfaces/modern-mcp"; -import type { Identity } from "../src/target"; - -const emailOf = (identity: Identity): string => identity.credentials?.email ?? identity.label; - -scenario( - "MCP modern protocol · self-host accepts a pinned 2026 client end to end", - {}, - Effect.scoped( - Effect.gen(function* () { - const target = yield* Target; - const mcp = yield* Mcp; - const identity = yield* target.newIdentity(); - const bearer = yield* mcp.mintBearer(emailOf(identity)); - const client = yield* connectModernMcpClient({ - url: target.mcpUrl, - bearer, - mode: { pin: MODERN_MCP_PROTOCOL_VERSION }, - }); - - expect(client.getProtocolEra(), "the self-host endpoint selects modern").toBe("modern"); - expect(client.getNegotiatedProtocolVersion(), "the pinned revision is exact").toBe( - MODERN_MCP_PROTOCOL_VERSION, - ); - expect( - client.getDiscoverResult()?.supportedVersions, - "self-host server/discover offers the pinned revision", - ).toContain(MODERN_MCP_PROTOCOL_VERSION); - - const tools = yield* Effect.promise(() => client.listTools()); - expect( - tools.tools.map((tool) => tool.name), - "self-host advertises Executor's tools over modern MCP", - ).toContain("execute"); - - const result = yield* Effect.promise(() => - client.callTool({ name: "execute", arguments: { code: "return 20 + 22;" } }), - ); - expect(result.isError, "the self-host modern call succeeds").not.toBe(true); - expect(modernToolText(result), "the sandbox result crosses the modern wire").toBe("42"); - }), - ), -); diff --git a/e2e/setup/cloud.boot.ts b/e2e/setup/cloud.boot.ts index 191fdebde3..799c1cfa47 100644 --- a/e2e/setup/cloud.boot.ts +++ b/e2e/setup/cloud.boot.ts @@ -90,7 +90,6 @@ export const bootCloud = async (options: CloudBootOptions): Promise // The AuthKit domain (MCP OAuth metadata + JWKS) is the emulator too. MCP_AUTHKIT_DOMAIN: workosUrl, MCP_RESOURCE_ORIGIN: options.publicUrl, - MCP_REQUEST_STATE_KEY: "e2e-mcp-request-state-key-0123456789abcdef", MCP_SESSION_TIMEOUT_MS: process.env.MCP_SESSION_TIMEOUT_MS, MCP_PAUSED_SESSION_IDLE_TIMEOUT_MS: process.env.MCP_PAUSED_SESSION_IDLE_TIMEOUT_MS, ALLOW_LOCAL_NETWORK: "true", diff --git a/e2e/setup/cloudflare.boot.ts b/e2e/setup/cloudflare.boot.ts index fa0eb70ce1..109c85b6ed 100644 --- a/e2e/setup/cloudflare.boot.ts +++ b/e2e/setup/cloudflare.boot.ts @@ -48,8 +48,6 @@ export const bootCloudflare = async (options: CloudflareBootOptions): Promise { - const headers = new Headers(); - for (const [name, value] of Object.entries(source)) { - if (Array.isArray(value)) { - for (const item of value) headers.append(name, item); - } else if (value !== undefined) { - headers.set(name, value); - } - } - return headers; -}; - -const requestBody = (request: IncomingMessage): Promise => - new Promise((resolve) => { - const chunks: Uint8Array[] = []; - request.on("data", (chunk: Uint8Array) => chunks.push(chunk)); - request.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); - }); - -const makeServer = (): McpServer => { - const server = new McpServer({ name: "executor-modern-only-e2e", version: "1.0.0" }); - server.registerTool( - "modern_ping", - { description: "Answers from a modern-only MCP server" }, - async () => ({ content: [{ type: "text", text: "pong-modern" }] }), - ); - server.registerTool( - "modern_identity", - { description: "Names the fixture's protocol posture" }, - async () => ({ content: [{ type: "text", text: "modern-only" }] }), - ); - return server; -}; - -/** - * Serve a real v2 MCP handler that rejects every legacy-classified request. - * The fixture follows the e2e suite's scoped, ephemeral localhost convention. - */ -export const serveModernOnlyMcp = (): Effect.Effect => - Effect.acquireRelease( - Effect.callback Promise }>((resume) => { - const handler = createMcpHandler(makeServer, { legacy: "reject" }); - const server = createServer((incoming, outgoing) => { - void requestBody(incoming).then(async (body) => { - const host = incoming.headers.host ?? "127.0.0.1"; - const request = new Request(new URL(incoming.url ?? "/", `http://${host}`), { - method: incoming.method, - headers: requestHeaders(incoming.headers), - ...(incoming.method === "GET" || incoming.method === "HEAD" ? {} : { body }), - }); - const response = await handler.fetch(request); - outgoing.writeHead(response.status, Object.fromEntries(response.headers)); - outgoing.end(Buffer.from(await response.arrayBuffer())); - }); - }); - - server.listen(0, "127.0.0.1", () => { - const address = server.address(); - const port = typeof address === "object" && address ? address.port : 0; - resume( - Effect.succeed({ - url: `http://127.0.0.1:${port}/mcp`, - close: async () => { - server.close(); - server.closeAllConnections(); - await handler.close(); - }, - }), - ); - }); - }), - (fixture) => Effect.promise(fixture.close).pipe(Effect.ignore), - ); diff --git a/e2e/src/surfaces/modern-mcp.ts b/e2e/src/surfaces/modern-mcp.ts deleted file mode 100644 index 720f5605f3..0000000000 --- a/e2e/src/surfaces/modern-mcp.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { Effect } from "effect"; -import { - Client, - StreamableHTTPClientTransport, - withInputRequired, - type InputRequiredResult, - type Request as McpRequest, -} from "@modelcontextprotocol/client"; -import { CallToolResultSchema } from "@modelcontextprotocol/core"; - -/** The first MCP revision served through the modern per-request protocol. */ -export const MODERN_MCP_PROTOCOL_VERSION = "2026-07-28"; - -/** Negotiation postures covered by the modern e2e client. */ -export type ModernMcpNegotiationMode = - | "auto" - | { readonly pin: typeof MODERN_MCP_PROTOCOL_VERSION }; - -/** Connection inputs for a scoped modern MCP client. */ -export type ModernMcpClientOptions = { - readonly url: string; - readonly bearer: string; - readonly mode: ModernMcpNegotiationMode; - readonly manualInputRequired?: boolean; -}; - -const makeClient = (mode: ModernMcpNegotiationMode, manualInputRequired: boolean): Client => - new Client( - { name: "executor-modern-e2e", version: "1.0.0" }, - { - capabilities: { elicitation: { form: {} } }, - versionNegotiation: { mode }, - ...(manualInputRequired ? { inputRequired: { autoFulfill: false } } : {}), - }, - ); - -/** - * Connect a real v2 MCP client and close it when the surrounding Effect scope - * ends. The caller selects pinned or auto negotiation explicitly. - */ -export const connectModernMcpClient = (options: ModernMcpClientOptions) => - Effect.acquireRelease( - Effect.promise(async () => { - const client = makeClient(options.mode, options.manualInputRequired ?? false); - const transport = new StreamableHTTPClientTransport(new URL(options.url), { - requestInit: { headers: { authorization: `Bearer ${options.bearer}` } }, - }); - await client.connect(transport); - return client; - }), - (client) => Effect.promise(() => client.close()).pipe(Effect.ignore), - ); - -/** - * Issue a modern tool call in manual input-required mode, returning either the - * completed tool result or the server's next input request. - */ -export const callModernToolWithInputRequired = ( - client: Client, - params: Record, -): Effect.Effect>> => { - const request: McpRequest = { method: "tools/call", params }; - return Effect.promise(() => - client.request(request, withInputRequired(CallToolResultSchema), { - allowInputRequired: true, - }), - ); -}; - -/** Join the text content returned by an MCP tool call. */ -export const modernToolText = (result: Awaited>): string => - result.content - .filter((part) => part.type === "text") - .map((part) => part.text) - .join("\n"); - -/** The authentication response observed during an unauthenticated modern probe. */ -export type ModernMcpAuthChallenge = { - readonly status: number | undefined; - readonly wwwAuthenticate: string | null; -}; - -/** - * Drive the real pinned-modern probe without credentials and capture the HTTP - * authentication challenge that prevented the connection. - */ -export const readModernMcpAuthChallenge = (url: string): Effect.Effect => - Effect.promise(async () => { - let challenge: ModernMcpAuthChallenge = { - status: undefined, - wwwAuthenticate: null, - }; - const client = makeClient({ pin: MODERN_MCP_PROTOCOL_VERSION }, false); - const transport = new StreamableHTTPClientTransport(new URL(url), { - fetch: async (input, init) => { - const response = await fetch(input, init); - if (response.status === 401) { - challenge = { - status: response.status, - wwwAuthenticate: response.headers.get("www-authenticate"), - }; - } - return response; - }, - }); - await client.connect(transport).then( - () => undefined, - () => undefined, - ); - await client.close(); - return challenge; - }); diff --git a/package.json b/package.json index f3ca8e7237..6f8ab54ab4 100644 --- a/package.json +++ b/package.json @@ -135,6 +135,7 @@ "@1password/sdk-core@0.4.1-beta.1": "patches/@1password%2Fsdk-core@0.4.1-beta.1.patch", "postgres@3.4.9": "patches/postgres@3.4.9.patch", "@cloudflare/vite-plugin@1.31.2": "patches/@cloudflare%2Fvite-plugin@1.31.2.patch", + "agents@0.17.3": "patches/agents@0.17.3.patch", "libsql@0.5.29": "patches/libsql@0.5.29.patch", "@electric-sql/pglite-socket@0.1.4": "patches/@electric-sql%2Fpglite-socket@0.1.4.patch" } diff --git a/packages/core/api/src/server.ts b/packages/core/api/src/server.ts index 5425e1d8c7..104d841c39 100644 --- a/packages/core/api/src/server.ts +++ b/packages/core/api/src/server.ts @@ -59,7 +59,6 @@ export { export { makeMcpBuildServer, makeConsoleMcpErrorReporter, - type McpBuildServer, type McpExecutionStackLayer, } from "./server/mcp-build"; // Host-composition seams re-homed out of `@executor-js/sdk` (the plugin-author diff --git a/packages/core/api/src/server/executor-app.ts b/packages/core/api/src/server/executor-app.ts index 01cf3f933a..382e72efe1 100644 --- a/packages/core/api/src/server/executor-app.ts +++ b/packages/core/api/src/server/executor-app.ts @@ -15,8 +15,8 @@ // + that stack + plugin tuple + failure strategy) (auth + per-request executor) // 3. the protected (plugin) API = makeProtectedApiLayer(plugins, { errorCapture, // router: prefixed(mountPrefix) }) wrapped by (2) -// 4. the MCP serving envelope = McpServingRoutes + the auth/session/modern -// builder/reporter seams (the seams) +// 4. the MCP serving envelope = McpServingRoutes + the 2-3 seams (auth/sessions +// /reporter), double-provided like the host did (the seams) // 5. the account API = makeAccountApiLayer(accountMiddleware, { router }) // 6. each extensions.route (Better Auth handler, Swagger, marketing, /autumn) // 7. provideMerge(boot) (+ optional requestScoped) -> the AppLayer @@ -53,7 +53,6 @@ import { McpErrorReporterNoop, type McpAuthProvider, type McpErrorReporter, - type McpModernServerBuilder, type McpSessionStore, } from "@executor-js/host-mcp"; @@ -133,32 +132,19 @@ export interface EngineProviders { * identity fallback sets `RMcpAuth = IdentityProvider` (self-host) and one whose * MCP plane is a separate credential surface leaves it `never` (cloud). */ -interface McpProviderBase { +export interface McpProviders { /** Resolve a request to an MCP `AuthOutcome` + declare the discovery routes. */ readonly auth: Layer.Layer; + /** + * Owns the entire serving-session lifecycle (in-process Map vs DO). Optional: + * a host that serves `/mcp` transport outside this envelope (the Cloudflare + * Agent bridge) omits it, and only the discovery routes are mounted. + */ + readonly sessions?: Layer.Layer; /** Forward an orchestration defect to the host's capture; default no-op. */ readonly reporter?: Layer.Layer; } -/** MCP providers either serve discovery alone or provide both protocol eras. */ -export type McpProviders = McpProviderBase & - ( - | { - /** - * Owns the legacy serving-session lifecycle (in-process Map vs DO). - */ - readonly sessions: Layer.Layer; - /** Builds one stateless MCP server for each modern request. */ - readonly modern: Layer.Layer; - } - | { - /** Omitted when another platform surface serves `/mcp` transport. */ - readonly sessions?: undefined; - /** Discovery-only providers do not construct modern servers here. */ - readonly modern?: undefined; - } - ); - /** * The provider seams common to BOTH execution models (scoped + fixed): identity, * the optional account API, the optional MCP envelope, and error capture. The @@ -560,12 +546,12 @@ export const make = < : pluginApiLive; // ---- (4) the MCP serving envelope (optional) -------------------------- - // The serving providers, by design (mirrors makeSelfHostMcp): + // The two providers, by design (mirrors makeSelfHostMcp): // - `Layer.provide(mcpAuth)` satisfies the `HttpRouter.use` callback's // build-time `McpAuthProvider` requirement (it registers a GET per // provider-declared discovery path). // - `HttpRouter.provideRequest(McpSeams)` clears the route handlers' - // per-request `Requires` markers (auth + both eras + reporter) so the + // per-request `Requires` markers (auth + session store + reporter) so the // /mcp routes carry no leftover requirements when merged into the router. // The auth seam may require the neutral `IdentityProvider` (`RMcpAuth = // IdentityProvider` for self-host, whose MCP auth genuinely reads the fallback; @@ -617,7 +603,7 @@ export const make = < }; /** - * Compose the MCP serving routes over the auth/legacy/modern/reporter seams. The auth + * Compose the MCP serving routes over the auth/sessions/reporter seams. The auth * seam may require the neutral `IdentityProvider` (`RMcpAuth`); the facade provides * the complete identity seam ONCE (memoized) and shares it across the build-time * `Layer.provide` AND the per-request `HttpRouter.provideRequest`, so a single @@ -639,15 +625,10 @@ const buildMcpRoutes = ( // No session store: the host serves `/mcp` transport elsewhere (the Cloudflare // Agent bridge), so mount only the auth-declared discovery routes. The discovery // handlers are captured from the auth seam at build, so no per-request seams. - if (mcp.sessions === undefined) { + if (!mcp.sessions) { return McpDiscoveryRoutes.pipe(Layer.provide(mcpAuthLive)); } - const mcpSeams = Layer.mergeAll( - mcpAuthLive, - mcp.sessions, - mcp.modern, - mcp.reporter ?? McpErrorReporterNoop, - ); + const mcpSeams = Layer.mergeAll(mcpAuthLive, mcp.sessions, mcp.reporter ?? McpErrorReporterNoop); return McpServingRoutes.pipe(HttpRouter.provideRequest(mcpSeams), Layer.provide(mcpAuthLive)); }; diff --git a/packages/core/api/src/server/mcp-build.ts b/packages/core/api/src/server/mcp-build.ts index 2db2ced06e..3b9302faca 100644 --- a/packages/core/api/src/server/mcp-build.ts +++ b/packages/core/api/src/server/mcp-build.ts @@ -1,17 +1,12 @@ import { Effect, Layer } from "effect"; -import { - McpErrorReporter, - type McpModernServerBuilder, - type McpModernServerBuildOptions, - type Principal, -} from "@executor-js/host-mcp"; +import { McpErrorReporter, type Principal } from "@executor-js/host-mcp"; import { McpEngineBuildError, - type McpBuildServer as McpSessionBuildServer, - type McpBuildServerOptions as McpSessionBuildOptions, + type McpBuildServer, + type McpBuildServerOptions, } from "@executor-js/host-mcp/in-memory-session-store"; -import { buildMcpServer } from "@executor-js/host-mcp/tool-server"; +import { createExecutorMcpServer } from "@executor-js/host-mcp/tool-server"; import { artifactUrlFor, type ArtifactSmokeRenderResult, @@ -25,8 +20,14 @@ import { HostConfig, PluginsProvider, RequestOrgSlug } from "./scoped-executor"; // --------------------------------------------------------------------------- // Shared in-process MCP host helpers. // -// Neutral hosts build both sessionful legacy-wire connections and stateless -// modern requests from the same assembly over a scoped execution stack. +// Every host that serves MCP from one isolate (self-host, the Cloudflare QuickJS +// host) builds its per-session McpServer the same way — assemble the scoped +// engine via `makeExecutionStack`, wrap it with `createExecutorMcpServer` — and +// reports orchestration defects through the same console `ErrorCapture` seam. +// These two factories are the single home for that logic; a host supplies ONLY +// its fully-provided execution-stack layer and its `ErrorCapture` layer. The +// cross-isolate variant (cloud's Durable Object store) is the exception that +// builds its engine inside the DO. // --------------------------------------------------------------------------- /** The five execution-stack seams a host fully provides (no residual). */ @@ -34,55 +35,36 @@ export type McpExecutionStackLayer = Layer.Layer< DbProvider | PluginsProvider | HostConfig | CodeExecutorProvider | EngineDecorator >; -type McpSessionBuildEffect = ReturnType; -type McpModernBuildEffect = ReturnType; - -/** A single build seam accepted by both the session store and modern envelope. */ -export interface McpBuildServer { - /** Build a connection-lifetime server and retain its engine for session-owned approvals. */ - (principal: Principal, options: McpSessionBuildOptions): McpSessionBuildEffect; - /** Build a stateless server for one modern request. */ - (principal: Principal, options: McpModernServerBuildOptions): McpModernBuildEffect; -} - /** - * Build the unified MCP server factory over a host's execution stack. - * Session callers receive the server plus its approval-owning engine; modern - * request callers receive the server directly. + * Build the per-session MCP server factory over a host's execution stack: + * `makeExecutionStack` → engine → `createExecutorMcpServer`. Hosts differ only + * in the injected stack layer (libSQL vs D1, etc.). */ -export const makeMcpBuildServer = ( - executionStack: McpExecutionStackLayer, - hostOptions?: McpBuildHostOptions, -): McpBuildServer => { - function build(principal: Principal, options: McpSessionBuildOptions): McpSessionBuildEffect; - function build(principal: Principal, options: McpModernServerBuildOptions): McpModernBuildEffect; - function build( - principal: Principal, - options: McpSessionBuildOptions | McpModernServerBuildOptions, - ): Effect.Effect< - Effect.Success | Effect.Success, - Effect.Error | Effect.Error - > { - const { resource, ...serverOptions } = options; - return Effect.gen(function* () { +export const makeMcpBuildServer = + (executionStack: McpExecutionStackLayer, hostOptions?: McpBuildHostOptions): McpBuildServer => + (principal: Principal, options?: McpBuildServerOptions) => + Effect.gen(function* () { const { engine, executor } = yield* makeExecutionStack( principal.accountId, principal.organizationId, principal.organizationName, - { mcpResource: resource }, + { mcpResource: options?.resource }, ).pipe(Effect.withSpan("mcp.execution_stack.build")); // Read inside the provided boundary: `webBaseUrl` is a host seam, and - // hosts that cannot know their public URL at boot leave it unset. + // hosts that can't know their public URL at boot leave it unset — in + // which case artifacts still persist but carry no deep link. const hostConfig = yield* HostConfig; return { engine, executor, webBaseUrl: hostConfig.webBaseUrl }; }).pipe( + // Pin browser-handoff URLs to the principal's org slug when present; + // absent slug leaves the service unprovided and the URL stays bare. principal.organizationSlug !== undefined ? Effect.provideService(RequestOrgSlug, { slug: principal.organizationSlug }) : (effect) => effect, Effect.provide(executionStack), Effect.mapError((cause) => new McpEngineBuildError({ cause })), Effect.flatMap(({ engine, executor, webBaseUrl }) => - buildMcpServer({ + createExecutorMcpServer({ engine, artifacts: executor.artifacts, connections: executor.connections, @@ -93,20 +75,20 @@ export const makeMcpBuildServer = ( ? { smokeRenderArtifact: hostOptions.smokeRenderArtifact } : {}), ...(hostOptions?.onArtifactUsage ? { onArtifactUsage: hostOptions.onArtifactUsage } : {}), + // Same org pinning as `RequestOrgSlug` above: self-host serves its + // console under `/` (`default` when unconfigured), so the + // deep link carries the principal's slug rather than relying on the + // browser's active org to canonicalize a bare path after landing. ...(webBaseUrl ? { artifactUrl: artifactUrlFor(webBaseUrl, principal.organizationSlug) } : {}), - ...serverOptions, + ...(options ?? {}), }).pipe( Effect.withSpan("mcp.server.create"), - Effect.map((mcpServer) => ("sessionful" in options ? { mcpServer, engine } : mcpServer)), + Effect.map((mcpServer) => ({ mcpServer, engine })), ), ), ); - } - - return build; -}; /** Per-host (not per-session) MCP wiring. Kept separate from * `McpBuildServerOptions`, which the session store fills in per request. */ diff --git a/packages/hosts/cloudflare/package.json b/packages/hosts/cloudflare/package.json index 5d12172fb1..79eba80ac5 100644 --- a/packages/hosts/cloudflare/package.json +++ b/packages/hosts/cloudflare/package.json @@ -23,10 +23,6 @@ "./mcp/session-stub": { "types": "./src/mcp/session-stub.ts", "default": "./src/mcp/session-stub.ts" - }, - "./mcp/modern-request-router": { - "types": "./src/mcp/modern-request-router.ts", - "default": "./src/mcp/modern-request-router.ts" } }, "scripts": { @@ -40,7 +36,7 @@ "@executor-js/host-mcp": "workspace:*", "@executor-js/sdk": "workspace:*", "@modelcontextprotocol/sdk": "^1.29.0", - "@modelcontextprotocol/server": "2.0.0", + "agents": "0.17.3", "effect": "catalog:" }, "devDependencies": { diff --git a/packages/hosts/cloudflare/src/mcp/agent-session-durable-object.test.ts b/packages/hosts/cloudflare/src/mcp/agent-session-durable-object.test.ts index f0d579217b..8072df7e54 100644 --- a/packages/hosts/cloudflare/src/mcp/agent-session-durable-object.test.ts +++ b/packages/hosts/cloudflare/src/mcp/agent-session-durable-object.test.ts @@ -1,619 +1,485 @@ -import { afterEach, describe, expect, it, vi } from "@effect/vitest"; +import { describe, expect, it } from "@effect/vitest"; import { Cause, Effect } from "effect"; -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { JSONRPCMessage, MessageExtraInfo } from "@modelcontextprotocol/sdk/types.js"; -import type { ExecutionEngine } from "@executor-js/execution"; import { defaultMcpResource } from "@executor-js/host-mcp"; -import { buildMcpServer, mcpRequestStatePrincipal } from "@executor-js/host-mcp/tool-server"; +import type { ExecutionEngine, ExecutionResult, ResumeResponse } from "@executor-js/execution"; -import { withVerifiedIdentityHeaders } from "./do-headers"; import { McpAgentSessionDOBase, - type BuiltMcpServer, - type McpSessionInit, + type McpApprovalOwner, + type McpSessionModelResumeResult, type SessionMeta, } from "./agent-session-durable-object"; -const SESSION_ID = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; -const ACCOUNT_ID = "acct_test"; -const ORGANIZATION_ID = "org_test"; -const REQUEST_STATE_KEY = "0123456789abcdef0123456789abcdef"; - -class MemoryStorage implements DurableObjectStorage, DurableObjectTransaction { - private readonly values = new Map(); - readonly sql = {} as DurableObjectStorage["sql"]; - readonly kv = {} as DurableObjectStorage["kv"]; - alarmAt: number | null = null; - - async get(key: string): Promise; - async get(keys: string[]): Promise>; - async get(keyOrKeys: string | string[]): Promise> { - if (Array.isArray(keyOrKeys)) { - return new Map(keyOrKeys.map((key) => [key, this.values.get(key) as T])); - } - return this.values.get(keyOrKeys) as T | undefined; - } +class MemoryStorage { + private readonly data = new Map(); + alarm: number | undefined; - async put(key: string, value: T): Promise; - async put(entries: Record | Map): Promise; - async put( - keyOrEntries: string | Record | Map, - value?: T, - ): Promise { - if (typeof keyOrEntries === "string") { - this.values.set(keyOrEntries, value); - return; - } - const entries = - keyOrEntries instanceof Map ? keyOrEntries.entries() : Object.entries(keyOrEntries); - for (const [key, entry] of entries) this.values.set(key, entry); - } + readonly sql = { + exec: () => [], + }; - async delete(key: string): Promise; - async delete(keys: string[]): Promise; - async delete(keyOrKeys: string | string[]): Promise { - if (!Array.isArray(keyOrKeys)) return this.values.delete(keyOrKeys); - let deleted = 0; - for (const key of keyOrKeys) { - if (this.values.delete(key)) deleted += 1; - } - return deleted; + async get(key: string): Promise { + return this.data.get(key) as T | undefined; } - async list(options: DurableObjectListOptions = {}): Promise> { - let keys = [...this.values.keys()] - .filter((key) => (options.prefix === undefined ? true : key.startsWith(options.prefix))) - .filter((key) => (options.start === undefined ? true : key >= options.start)) - .filter((key) => (options.startAfter === undefined ? true : key > options.startAfter)) - .sort(); - if (options.reverse) keys = keys.reverse(); - if (options.limit !== undefined) keys = keys.slice(0, options.limit); - return new Map(keys.map((key) => [key, this.values.get(key) as T])); + async put(key: string, value: unknown): Promise { + this.data.set(key, value); } - async deleteAll(): Promise { - this.values.clear(); - this.alarmAt = null; + async setAlarm(time: number | Date): Promise { + this.alarm = typeof time === "number" ? time : time.getTime(); } - transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise { - return closure(this); + async deleteAlarm(): Promise { + this.alarm = undefined; } - rollback(): void {} - - transactionSync(closure: () => T): T { - return closure(); + async delete(key: string | readonly string[]): Promise { + if (typeof key === "string") { + this.data.delete(key); + return; + } + for (const entry of key) { + this.data.delete(entry); + } } - async sync(): Promise {} - - async getAlarm(): Promise { - return this.alarmAt; + async deleteAll(): Promise { + this.data.clear(); } - async setAlarm(scheduledTime: number | Date): Promise { - this.alarmAt = scheduledTime instanceof Date ? scheduledTime.getTime() : scheduledTime; + async list( + options: { readonly prefix?: string; readonly limit?: number } = {}, + ): Promise> { + const rows = new Map(); + for (const [key, value] of this.data) { + if (options.prefix && !key.startsWith(options.prefix)) continue; + rows.set(key, value as T); + if (options.limit && rows.size >= options.limit) break; + } + return rows; } - async deleteAlarm(): Promise { - this.alarmAt = null; + async blockConcurrencyWhile(callback: () => T | Promise): Promise { + return callback(); } - async getCurrentBookmark(): Promise { - return "test-bookmark"; + get id(): { readonly name: string } { + return { name: "streamable-http:session-reconnect" }; } - async getBookmarkForTime(_timestamp: number | Date): Promise { - return "test-bookmark"; + get storage(): MemoryStorage { + return this; } - onNextSessionRestoreBookmark(_bookmark: string): Promise { - return Promise.resolve("test-bookmark"); - } + waitUntil(_promise: Promise): void {} } -class MemoryDurableObjectState implements DurableObjectState { - readonly id: DurableObjectId; - readonly props: unknown = undefined; - readonly facets = {} as DurableObjectState["facets"]; - readonly storage: MemoryStorage; - private waitUntilPromises: Promise[] = []; - abortedWith: string | undefined; - - constructor(storage = new MemoryStorage()) { - this.storage = storage; - const id: Pick = { - equals: (other) => other.toString() === SESSION_ID, - toString: () => SESSION_ID, - }; - this.id = id as DurableObjectId; - } +type HarnessSession = { + alarm: () => Promise; + ctx: MemoryStorage; + dbHandle: { readonly end: () => void } | null; + engine: ExecutionEngine | null; + getConnections?: () => Iterable; + getSessionId: () => string; + initialized: boolean; + lastActivityMs: number; + maxPausedSessionIdleMs: () => number; + onStart: () => Promise; + pendingApprovalLeases: Map; + props: Record; + runMcpAgentOnStart: () => Promise; + server?: McpServer; + sessionMeta: SessionMeta; + sessionTimeoutMs: () => number; + resumeExecutionForModel: ( + executionId: string, + identity: McpApprovalOwner, + response: ResumeResponse, + ) => Promise; + validateMcpSessionOwner: (identity: { + readonly accountId: string; + readonly organizationId: string; + }) => Promise<"ok" | "not_found" | "forbidden" | "terminated">; +}; - waitUntil(promise: Promise): void { - this.waitUntilPromises.push(promise); - } +class StaleCloseTransport implements Transport { + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; - async flushWaitUntil(): Promise { - while (this.waitUntilPromises.length > 0) { - const pending = this.waitUntilPromises.splice(0); - await Promise.all(pending); - } - } + async start(): Promise {} - blockConcurrencyWhile(callback: () => Promise): Promise { - return callback(); - } + async close(): Promise {} - acceptWebSocket(_ws: WebSocket, _tags?: string[]): void {} - getWebSockets(_tag?: string): WebSocket[] { - return []; - } - getTags(_ws: WebSocket): string[] { - return []; - } - setWebSocketAutoResponse(_pair?: WebSocketRequestResponsePair): void {} - getWebSocketAutoResponse(): WebSocketRequestResponsePair | null { - return null; - } - getWebSocketAutoResponseTimestamp(_ws: WebSocket): Date | null { - return null; - } - setHibernatableWebSocketEventTimeout(_timeoutMs?: number): void {} - getHibernatableWebSocketEventTimeout(): number | null { - return null; - } - abort(reason?: string): void { - this.abortedWith = reason; - } + async send(_message: JSONRPCMessage): Promise {} } -const engine: ExecutionEngine = { - execute: (code) => Effect.succeed({ result: code }), - executeWithPause: (code) => - Effect.succeed({ status: "completed" as const, result: { result: code } }), - resume: () => Effect.succeed(null), - isExecutionSettled: () => Effect.succeed(false), - getPausedExecution: () => Effect.succeed(null), - pausedExecutionCount: () => Effect.succeed(0), - hasPausedExecutions: () => Effect.succeed(false), - getDescription: Effect.succeed("test Durable Object executor"), -}; +class RestoredTransport implements Transport { + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; -class HarnessSession extends McpAgentSessionDOBase< - Cloudflare.Env, - { readonly end: () => void | Promise } -> { - constructor( - ctx: DurableObjectState, - env: Cloudflare.Env, - private readonly sessionEngine: ExecutionEngine = engine, - private readonly runtimeOptions: { - readonly end?: () => void | Promise; - readonly sessionTimeoutMs?: number; - } = {}, - ) { - super(ctx, env); - } + async start(): Promise {} - protected override openSessionDb(): { readonly end: () => void | Promise } { - return { end: this.runtimeOptions.end ?? (() => undefined) }; + async close(): Promise { + this.onclose?.(); } - protected override sessionTimeoutMs(): number { - return this.runtimeOptions.sessionTimeoutMs ?? super.sessionTimeoutMs(); - } + async send(_message: JSONRPCMessage): Promise {} +} - protected override resolveSessionMeta(token: McpSessionInit): Effect.Effect { - return Effect.succeed({ - organizationId: token.organizationId, - organizationName: "Test Org", - userId: token.userId, - elicitationMode: token.elicitationMode, - artifactsEnabled: token.artifactsEnabled, - resource: token.resource, - webOrigin: token.webOrigin, - }); - } +const makeServer = () => new McpServer({ name: "executor-test", version: "1.0.0" }); - protected override buildMcpServer(sessionMeta: SessionMeta): Effect.Effect { - const elicitationMode = sessionMeta.elicitationMode ?? "model"; - return buildMcpServer({ - engine: this.sessionEngine, - appsEnabled: false, - restoredAppsEnabled: sessionMeta.appsEnabled, - onAppsEnabledChange: (appsEnabled) => this.persistAppsEnabled(appsEnabled), - requestStateSigningKey: REQUEST_STATE_KEY, - requestStatePrincipal: mcpRequestStatePrincipal({ - accountId: sessionMeta.userId, - organizationId: sessionMeta.organizationId, - }), - sessionful: true, - elicitationMode: - elicitationMode === "browser" - ? { mode: "browser", approvalUrl: () => "https://executor.test/approve" } - : { mode: elicitationMode }, - }).pipe(Effect.map((mcpServer) => ({ mcpServer, engine: this.sessionEngine }))); - } -} +const makeDeferred = (): { readonly promise: Promise; readonly resolve: () => void } => { + let resolve: () => void = () => undefined; + const promise = new Promise((settle) => { + resolve = settle; + }); + return { promise, resolve }; +}; -const verifiedRequest = (request: Request): Request => - withVerifiedIdentityHeaders( - request, - { accountId: ACCOUNT_ID, organizationId: ORGANIZATION_ID }, - defaultMcpResource, - ); - -const makeClientHarness = (state = new MemoryDurableObjectState()) => { - let session = new HarnessSession(state, {} as Cloudflare.Env); - const fetch = async (input: string | URL | Request, init?: RequestInit): Promise => { - const request = - input instanceof Request ? new Request(input, init) : new Request(input.toString(), init); - return session.fetch(verifiedRequest(request)); - }; - const transport = new StreamableHTTPClientTransport( - new URL("https://executor.test/mcp?elicitation_mode=model"), - { fetch }, - ); - const client = new Client({ name: "legacy-do-client", version: "1.0.0" }); +type ResumeCall = { + readonly executionId: string; + readonly response: ResumeResponse; +}; + +const completed = (result: unknown): ExecutionResult => ({ + status: "completed", + result: { result }, +}); + +const makeEngine = ( + resultForResume: (executionId: string, response: ResumeResponse) => ExecutionResult | null = () => + completed("resume-result"), +): { readonly calls: ResumeCall[]; readonly engine: ExecutionEngine } => { + const calls: ResumeCall[] = []; return { - client, - state, - transport, - evict: () => { - session = new HarnessSession(state, {} as Cloudflare.Env); + calls, + engine: { + execute: () => Effect.succeed({ result: "execute-result" }), + executeWithPause: () => Effect.succeed(completed("execute-result")), + resume: (executionId, response) => + Effect.sync(() => { + calls.push({ executionId, response }); + return resultForResume(executionId, response); + }), + getPausedExecution: () => Effect.succeed(null), + pausedExecutionCount: () => Effect.succeed(0), + hasPausedExecutions: () => Effect.succeed(false), + getDescription: Effect.succeed("test engine"), }, }; }; -describe("McpAgentSessionDOBase session serving", () => { - afterEach(() => { - vi.restoreAllMocks(); - }); +const approval = { + action: "accept", + content: { approved: true }, +} satisfies ResumeResponse; + +const makeHarnessSession = async (): Promise => { + const sessionId = "session-reconnect"; + const sessionMeta: SessionMeta = { + organizationId: "org-1", + organizationName: "Org 1", + userId: "user-1", + resource: defaultMcpResource, + }; + const storage = new MemoryStorage(); + const server = makeServer(); + await server.connect(new StaleCloseTransport()); + + const session = Object.create(McpAgentSessionDOBase.prototype) as HarnessSession; + session.ctx = storage; + session.dbHandle = { end: () => undefined }; + session.engine = makeEngine().engine; + session.getSessionId = () => sessionId; + session.initialized = true; + session.lastActivityMs = Date.now() - 10; + session.maxPausedSessionIdleMs = () => 1_000; + session.pendingApprovalLeases = new Map(); + session.props = {}; + session.server = server; + session.sessionMeta = sessionMeta; + session.sessionTimeoutMs = () => 1; + session.runMcpAgentOnStart = async () => { + const restored = session.server ?? makeServer(); + session.server = restored; + await restored.connect(new RestoredTransport()); + session.engine = makeEngine().engine; + session.initialized = true; + }; - it("serves and reuses a legacy v1 SDK client through the Durable Object", async () => { - const harness = makeClientHarness(); - await harness.client.connect(harness.transport); - - // oxlint-disable-next-line executor/no-try-catch-or-throw -- test boundary: always release the MCP client's streamed transport after assertions - try { - const tools = await harness.client.listTools(); - expect(tools.tools.map(({ name }) => name)).toContain("execute"); - - const result = await harness.client.callTool({ - name: "execute", - arguments: { code: "return 42" }, - }); - expect(result.content).toEqual([{ type: "text", text: "return 42" }]); - expect(harness.transport.sessionId).toBe(SESSION_ID); - } finally { - await harness.client.close(); - } + return session; +}; + +// The negotiated MCP-Apps capability arrives once, at `initialize`, and lives +// in the rebuilt server's memory. These pin the storage round-trip that lets a +// cold-restored session rebuild with it instead of silently downgrading every +// artifact to a deep link. +describe("McpAgentSessionDOBase apps capability persistence", () => { + type CapabilitySession = HarnessSession & { + persistAppsEnabled: (appsEnabled: boolean) => Effect.Effect; + loadSessionMeta: () => Effect.Effect; + resolveSessionMeta: (token: unknown) => Effect.Effect; + resolveAndStoreSessionMeta: (token: unknown) => Effect.Effect; + }; + + const baseMeta: SessionMeta = { + organizationId: "org-1", + organizationName: "Org 1", + userId: "user-1", + resource: defaultMcpResource, + }; + + const makeCapabilitySession = async ( + stored: SessionMeta = baseMeta, + ): Promise<{ session: CapabilitySession; storage: MemoryStorage }> => { + const storage = new MemoryStorage(); + await storage.put("session-meta", stored); + const session = Object.create(McpAgentSessionDOBase.prototype) as CapabilitySession; + session.ctx = storage; + session.getSessionId = () => "session-caps"; + return { session, storage }; + }; + + it("persists the negotiated capability so a later restore can read it back", async () => { + const { session, storage } = await makeCapabilitySession(); + + await Effect.runPromise(session.persistAppsEnabled(true)); + + expect(await storage.get("session-meta")).toMatchObject({ + organizationId: "org-1", + appsEnabled: true, + }); }); - it("cold-restores the same v1 session without replaying initialize", async () => { - const harness = makeClientHarness(); - await harness.client.connect(harness.transport); - - // oxlint-disable-next-line executor/no-try-catch-or-throw -- test boundary: always release the MCP client's streamed transport after assertions - try { - await harness.client.listTools(); - harness.evict(); - const tools = await harness.client.listTools(); - expect(tools.tools.map(({ name }) => name)).toContain("execute"); - } finally { - await harness.client.close(); - } + it("records a client that loses apps support just as durably", async () => { + const { session, storage } = await makeCapabilitySession({ ...baseMeta, appsEnabled: true }); + + await Effect.runPromise(session.persistAppsEnabled(false)); + + expect(await storage.get("session-meta")).toMatchObject({ appsEnabled: false }); }); - it("primes a slow legacy tool stream and replays its result after disconnect", async () => { - let startExecution = (): void => undefined; - const executionStarted = new Promise((resolve) => { - startExecution = resolve; - }); - let finishExecution = (): void => undefined; - const executionResult = new Promise<{ readonly result: string }>((resolve) => { - finishExecution = () => resolve({ result: "slow result" }); - }); - const slowEngine: ExecutionEngine = { - ...engine, - execute: () => - Effect.promise(() => { - startExecution(); - return executionResult; - }), - executeWithPause: () => - Effect.promise(() => { - startExecution(); - return executionResult; - }).pipe(Effect.map((result) => ({ status: "completed" as const, result }))), - }; - const state = new MemoryDurableObjectState(); - const session = new HarnessSession(state, {} as Cloudflare.Env, slowEngine); - const post = (body: unknown, sessionId?: string): Request => - verifiedRequest( - new Request("https://executor.test/mcp?elicitation_mode=model", { - method: "POST", - headers: { - accept: "application/json, text/event-stream", - "content-type": "application/json", - ...(sessionId - ? { "mcp-session-id": sessionId, "mcp-protocol-version": "2025-06-18" } - : {}), - }, - body: JSON.stringify(body), - }), - ); - - const initialize = await session.fetch( - post({ - jsonrpc: "2.0", - id: 1, - method: "initialize", - params: { - protocolVersion: "2025-06-18", - capabilities: {}, - clientInfo: { name: "legacy-reconnect-test", version: "1.0.0" }, - }, - }), + // `init` runs again on every cold restore and rebuilds meta from the bearer + // token, which carries no capabilities. If that overwrite won, restoring the + // session would erase the very bit meant to survive it. + it("carries the stored capability through the re-resolve on cold restore", async () => { + const { session, storage } = await makeCapabilitySession({ ...baseMeta, appsEnabled: true }); + // What the token resolves to: no `appsEnabled` anywhere in sight. + session.resolveSessionMeta = () => Effect.succeed(baseMeta); + + const resolved = await Effect.runPromise( + session.resolveAndStoreSessionMeta({ organizationId: "org-1", userId: "user-1" }), ); - expect(initialize.headers.get("mcp-session-id")).toBe(SESSION_ID); - await initialize.text(); - await session.fetch( - post({ jsonrpc: "2.0", method: "notifications/initialized", params: {} }, SESSION_ID), + + expect(resolved.appsEnabled).toBe(true); + expect(await storage.get("session-meta")).toMatchObject({ appsEnabled: true }); + }); + + it("leaves a session with no negotiated capability untouched", async () => { + const { session, storage } = await makeCapabilitySession(); + session.resolveSessionMeta = () => Effect.succeed(baseMeta); + + const resolved = await Effect.runPromise( + session.resolveAndStoreSessionMeta({ organizationId: "org-1", userId: "user-1" }), ); - const toolResponse = await session.fetch( - post( - { - jsonrpc: "2.0", - id: 2, - method: "tools/call", - params: { name: "execute", arguments: { code: "return slow" } }, + expect(resolved.appsEnabled).toBeUndefined(); + expect(await storage.get("session-meta")).not.toHaveProperty("appsEnabled"); + }); + + // Persistence is best-effort observation of a capability, never a reason to + // fail the session that was merely trying to render something. + it("stays silent when there is no stored meta to merge into", async () => { + const storage = new MemoryStorage(); + const session = Object.create(McpAgentSessionDOBase.prototype) as CapabilitySession; + session.ctx = storage; + session.getSessionId = () => "session-caps"; + + await expect(Effect.runPromise(session.persistAppsEnabled(true))).resolves.toBeUndefined(); + expect(await storage.get("session-meta")).toBeUndefined(); + }); +}); + +describe("McpAgentSessionDOBase transport restore", () => { + it("preserves hibernated response streams when a cold isolate starts", async () => { + const session = await makeHarnessSession(); + let closeCalls = 0; + + session.initialized = false; + session.engine = null; + session.dbHandle = null; + delete session.server; + session.getConnections = () => [ + { + close: () => { + closeCalls += 1; }, - SESSION_ID, - ), - ); - const reader = toolResponse.body?.getReader(); - const first = await reader?.read(); - const primingFrame = new TextDecoder().decode(first?.value); - expect(primingFrame).toContain("event: mcp-priming"); - const eventId = /^id: (.+)$/m.exec(primingFrame)?.[1]; - const replayEventId = eventId ?? ""; - expect(replayEventId).not.toBe(""); - await reader?.cancel("simulated network drop"); - - await executionStarted; - finishExecution(); - await Promise.resolve(); - await Promise.resolve(); + }, + ]; + session.runMcpAgentOnStart = async () => { + session.server = makeServer(); + session.engine = makeEngine().engine; + session.initialized = true; + }; - const replay = await session.fetch( - verifiedRequest( - new Request("https://executor.test/mcp", { - method: "GET", - headers: { - accept: "text/event-stream", - "mcp-session-id": SESSION_ID, - "mcp-protocol-version": "2025-06-18", - "last-event-id": replayEventId, - }, - }), - ), - ); - const replayBody = await replay.text(); - expect(replayBody).toContain("slow result"); - expect(replayBody).toContain(`id: ${replayEventId.slice(0, replayEventId.lastIndexOf(":"))}:`); - - const standaloneReplay = await session.fetch( - verifiedRequest( - new Request("https://executor.test/mcp", { - method: "GET", - headers: { - accept: "text/event-stream", - "mcp-session-id": SESSION_ID, - "mcp-protocol-version": "2025-06-18", - }, - }), - ), - ); - // The standalone listener replays undelivered responses as its opening - // frames and then STAYS OPEN (a close-after-replay here put every active - // client into a permanent reconnect loop), so read incrementally instead - // of draining to EOF. - const standaloneReader = standaloneReplay.body?.getReader(); - const decoder = new TextDecoder(); - let standaloneReplayBody = ""; - while (!standaloneReplayBody.includes("slow result")) { - const next = await standaloneReader?.read(); - if (!next || next.done) break; - standaloneReplayBody += decoder.decode(next.value, { stream: true }); - } - expect(standaloneReplayBody).toContain("slow result"); - expect(standaloneReplayBody).toContain("event: message"); - await standaloneReader?.cancel("test complete"); - await state.flushWaitUntil(); + await session.onStart(); + + expect(closeCalls).toBe(0); + expect(session.initialized).toBe(true); }); - it("restores once while an idle runtime generation is still closing", async () => { - let now = 1_000; - vi.spyOn(Date, "now").mockImplementation(() => now); - let closeStarted = (): void => undefined; - const closing = new Promise((resolve) => { - closeStarted = resolve; - }); - let finishClose = (): void => undefined; - const closeGate = new Promise((resolve) => { - finishClose = resolve; - }); - let closeCount = 0; - const state = new MemoryDurableObjectState(); - const session = new HarnessSession(state, {} as Cloudflare.Env, engine, { - sessionTimeoutMs: 10, - end: () => { - closeCount += 1; - if (closeCount !== 1) return; - closeStarted(); - return closeGate; + it("closes response streams when an in-memory runtime restarts", async () => { + const session = await makeHarnessSession(); + let closeCalls = 0; + + session.getConnections = () => [ + { + close: () => { + closeCalls += 1; + }, }, - }); - const post = (body: unknown): Request => - verifiedRequest( - new Request("https://executor.test/mcp", { - method: "POST", - headers: { - accept: "application/json, text/event-stream", - "content-type": "application/json", - "mcp-session-id": SESSION_ID, - "mcp-protocol-version": "2025-06-18", - }, - body: JSON.stringify(body), - }), - ); - - const initialize = await session.fetch( - verifiedRequest( - new Request("https://executor.test/mcp", { - method: "POST", - headers: { - accept: "application/json, text/event-stream", - "content-type": "application/json", - }, - body: JSON.stringify({ - jsonrpc: "2.0", - id: "initialize", - method: "initialize", - params: { - protocolVersion: "2025-06-18", - capabilities: {}, - clientInfo: { name: "restore-race", version: "1.0.0" }, - }, - }), - }), - ), - ); - await initialize.text(); - await session.fetch(post({ jsonrpc: "2.0", method: "notifications/initialized", params: {} })); - - now += 100; - const alarm = session.alarm(); - await closing; - - const get = session.fetch( - verifiedRequest( - new Request("https://executor.test/mcp", { - method: "GET", - headers: { - accept: "text/event-stream", - "mcp-session-id": SESSION_ID, - "mcp-protocol-version": "2025-06-18", - }, - }), - ), - ); - const list = session.fetch( - post({ jsonrpc: "2.0", id: "concurrent-list", method: "tools/list", params: {} }), - ); + ]; + session.runMcpAgentOnStart = async () => { + session.server = makeServer(); + session.engine = makeEngine().engine; + session.initialized = true; + }; - finishClose(); - const [getResponse, listResponse] = await Promise.all([get, list]); - expect(getResponse.status).toBe(200); - await getResponse.body?.cancel(); - expect(listResponse.status).toBe(200); - expect(await listResponse.text()).toContain("execute"); - await alarm; - await expect(state.storage.get("executor:mcp:v2:last-activity-ms")).resolves.toBe(now); - await expect(state.storage.getAlarm()).resolves.toBe(now + 10); - - const followUp = await session.fetch( - post({ jsonrpc: "2.0", id: "follow-up-list", method: "tools/list", params: {} }), - ); - expect(followUp.status).toBe(200); - expect(await followUp.text()).toContain("execute"); + await session.onStart(); + + expect(closeCalls).toBe(1); + expect(session.initialized).toBe(true); }); - it("persists session metadata and rejects a different principal", async () => { - const harness = makeClientHarness(); - await harness.client.connect(harness.transport); - - // oxlint-disable-next-line executor/no-try-catch-or-throw -- test boundary: always release the MCP client's streamed transport after assertions - try { - const stored = await harness.state.storage.get("executor:mcp:v2:session-meta"); - expect(stored).toMatchObject({ - organizationId: ORGANIZATION_ID, - userId: ACCOUNT_ID, - elicitationMode: "model", - appsEnabled: false, - }); - expect(stored?.createdAtMs).toEqual(expect.any(Number)); - - const session = new HarnessSession(harness.state, {} as Cloudflare.Env); - await expect( - session.validateMcpSessionOwner({ - accountId: "acct_other", - organizationId: ORGANIZATION_ID, - }), - ).resolves.toBe("forbidden"); - } finally { - await harness.client.close(); - } + it("restores a same-session request after idle disposal leaves a stale server transport", async () => { + const session = await makeHarnessSession(); + + await session.alarm(); + + await expect( + session.validateMcpSessionOwner({ accountId: "user-1", organizationId: "org-1" }), + ).resolves.toBe("ok"); }); - it("returns a clean 404 for storage created by the retired Agent stack", async () => { - const state = new MemoryDurableObjectState(); - await state.storage.put("session-meta", { - organizationId: ORGANIZATION_ID, - organizationName: "Old Agent Org", - userId: ACCOUNT_ID, - resource: defaultMcpResource, - } satisfies SessionMeta); - const session = new HarnessSession(state, {} as Cloudflare.Env); - const request = verifiedRequest( - new Request("https://executor.test/mcp", { - method: "POST", - headers: { - accept: "application/json, text/event-stream", - "content-type": "application/json", - "mcp-session-id": SESSION_ID, - }, - body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }), - }), - ); + it("single-flights concurrent same-session restore after idle disposal", async () => { + const session = await makeHarnessSession(); + const firstRestoreEntered = makeDeferred(); + const finishRestore = makeDeferred(); + let onStartCalls = 0; + let restoredServer: McpServer | undefined; + + session.runMcpAgentOnStart = async () => { + onStartCalls += 1; + const restored = session.server ?? makeServer(); + restoredServer ??= restored; + session.server = restored; + firstRestoreEntered.resolve(); + await finishRestore.promise; + await restored.connect(new RestoredTransport()); + session.initialized = true; + }; + + await session.alarm(); + + const first = session.validateMcpSessionOwner({ + accountId: "user-1", + organizationId: "org-1", + }); + const second = session.validateMcpSessionOwner({ + accountId: "user-1", + organizationId: "org-1", + }); - const response = await session.fetch(request); + await firstRestoreEntered.promise; + await Promise.resolve(); + finishRestore.resolve(); + + await expect(Promise.all([first, second])).resolves.toEqual(["ok", "ok"]); + expect(onStartCalls).toBe(1); + expect(session.server).toBe(restoredServer); + }); + + it("single-flights SDK onStart callers with same-session restore", async () => { + const session = await makeHarnessSession(); + const firstStartEntered = makeDeferred(); + const finishStart = makeDeferred(); + let onStartCalls = 0; + + session.runMcpAgentOnStart = async () => { + onStartCalls += 1; + const restored = session.server ?? makeServer(); + session.server = restored; + firstStartEntered.resolve(); + await finishStart.promise; + await restored.connect(new RestoredTransport()); + session.initialized = true; + }; - expect(response.status).toBe(404); - await expect(response.json()).resolves.toMatchObject({ - error: { code: -32001, message: "Session not found" }, + await session.alarm(); + + const restore = session.validateMcpSessionOwner({ + accountId: "user-1", + organizationId: "org-1", }); + const sdkStart = session.onStart(); + + await firstStartEntered.promise; + await Promise.resolve(); + finishStart.resolve(); + + await expect(Promise.all([restore, sdkStart])).resolves.toEqual(["ok", undefined]); + expect(onStartCalls).toBe(1); }); - it("answers a dead-session standalone GET with 405 so old clients stop retrying", async () => { - const state = new MemoryDurableObjectState(); - await state.storage.put("session-meta", { - organizationId: ORGANIZATION_ID, - organizationName: "Old Agent Org", - userId: ACCOUNT_ID, - resource: defaultMcpResource, - } satisfies SessionMeta); - const session = new HarnessSession(state, {} as Cloudflare.Env); - const request = verifiedRequest( - new Request("https://executor.test/mcp", { - method: "GET", - headers: { - accept: "text/event-stream", - "mcp-session-id": SESSION_ID, - }, - }), - ); + it("single-flights model resume restore with SDK onStart", async () => { + const session = await makeHarnessSession(); + const firstStartEntered = makeDeferred(); + const finishStart = makeDeferred(); + const restoredEngine = makeEngine(() => completed("model-result")); + let onStartCalls = 0; + + session.runMcpAgentOnStart = async () => { + onStartCalls += 1; + const restored = session.server ?? makeServer(); + session.server = restored; + firstStartEntered.resolve(); + await finishStart.promise; + await restored.connect(new RestoredTransport()); + session.engine = restoredEngine.engine; + session.initialized = true; + }; + + await session.alarm(); - const response = await session.fetch(request); + const resume = session.resumeExecutionForModel( + "exec-model", + { accountId: "user-1", organizationId: "org-1" }, + approval, + ); + const sdkStart = session.onStart(); - expect(response.status).toBe(405); - expect(response.headers.get("allow")).toBe("POST, DELETE"); - await expect(response.json()).resolves.toMatchObject({ - error: { code: -32001, message: "Session not found" }, + await firstStartEntered.promise; + await Promise.resolve(); + finishStart.resolve(); + + const [resumeResult] = await Promise.all([resume, sdkStart]); + expect(resumeResult).toMatchObject({ + status: "result", + result: { + structuredContent: { + status: "completed", + result: "model-result", + }, + }, }); + expect(onStartCalls).toBe(1); + expect(restoredEngine.calls).toEqual([{ executionId: "exec-model", response: approval }]); }); }); diff --git a/packages/hosts/cloudflare/src/mcp/agent-session-durable-object.ts b/packages/hosts/cloudflare/src/mcp/agent-session-durable-object.ts index 63b84b5c5c..4ccc51965a 100644 --- a/packages/hosts/cloudflare/src/mcp/agent-session-durable-object.ts +++ b/packages/hosts/cloudflare/src/mcp/agent-session-durable-object.ts @@ -1,17 +1,8 @@ -import { DurableObject } from "cloudflare:workers"; -import { Cause, Data, Deferred, Effect, Option, Schema } from "effect"; -import * as Tracer from "effect/Tracer"; -import { - createMcpHandler, - DEFAULT_NEGOTIATED_PROTOCOL_VERSION, - type JSONRPCMessage, - type McpServer, - type MessageExtraInfo, - type McpHttpHandler, - type McpRequestContext, - type RequestId, - WebStandardStreamableHTTPServerTransport, -} from "@modelcontextprotocol/server"; +import { Cause, Deferred, Effect, Exit, Option, Schema } from "effect"; +import type * as Tracer from "effect/Tracer"; +import type { Connection, ConnectionContext } from "agents"; +import { McpAgent } from "agents/mcp"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { RequestOrgSlug, RequestWebOrigin } from "@executor-js/api/server"; import { @@ -22,37 +13,18 @@ import { type ResumeResponse, } from "@executor-js/execution"; import { - appsEnabledForClientCapabilities, - clientCapabilitiesFromRequestBody, - clientInfoFromRequestBody, - mcpRequestStateBindingFromBody, PAUSED_APPROVAL_TIMEOUT_MS, formatMcpExecutionOutcome, - mcpRequestStatePrincipal, - requestBodyFromRequest, - type McpClientInfo, type PausedExecutionHooks, type ResumeFallbackOutcome, } from "@executor-js/host-mcp/tool-server"; -import { - defaultMcpResource, - jsonRpcErrorBody, - mcpResourceKey, - type McpResource, -} from "@executor-js/host-mcp"; -import { - parseTraceparentHeader, - readArtifactsEnabled, - readElicitationMode, - verifiedMcpRequestHeaders, - type IncomingPropagationHeaders, - type McpElicitationMode, -} from "./do-headers"; -import { - modernMcpExecutionOwnerRoute, - type McpExecutionOwnerDirectory, - type McpExecutionOwnerRecord, - type McpExecutionOwnerRoute, +import { defaultMcpResource, type McpResource } from "@executor-js/host-mcp"; + +import type { IncomingPropagationHeaders, McpElicitationMode } from "./do-headers"; +import type { + McpExecutionOwnerDirectory, + McpExecutionOwnerRecord, + McpExecutionOwnerRoute, } from "./execution-owner-directory"; import { MAX_PAUSED_SESSION_IDLE_MS, @@ -61,8 +33,6 @@ import { pausedLeaseExtensionLog, runningLeaseExtensionLog, } from "./session-alarm-policy"; -import { DurableObjectMcpEventStore } from "./do-event-store"; -import { rotateSseResponse } from "./sse-response-rotation"; export type IncomingTraceHeaders = IncomingPropagationHeaders; @@ -150,41 +120,11 @@ export interface SessionMeta { * unknown, which behaves as disabled until the next `initialize`. */ readonly appsEnabled?: boolean; - /** - * The client identity (`clientInfo`) self-reported at `initialize` or in a - * modern request's `_meta`. Persisted for the same reason as - * {@link appsEnabled}: a cold-restored server never sees an `initialize`, - * and without this the execution spans' `mcp.client.*` attribution vanishes - * mid-conversation. Telemetry/display only, never behavior. - */ - readonly clientInfo?: McpClientInfo; - /** Creation time of this session, retained across isolate eviction. */ - readonly createdAtMs?: number; } export interface BuiltMcpServer { readonly mcpServer: McpServer; readonly engine: ExecutionEngine; - /** Modern per-request server factory sharing this legacy runtime's engine. */ - readonly modernRuntime?: BuiltModernMcpRuntime; -} - -/** Request-specific inputs added to a DO-local MCP server. */ -export interface ModernMcpServerRequestOptions { - readonly appsEnabled: boolean; - readonly requestStateSigningKey: Uint8Array | string; - readonly requestStatePrincipal: string; - readonly requestStateBinding?: string; - /** Client identity for span attribution: this request's `_meta`, else the session's persisted copy. */ - readonly restoredClientInfo?: McpClientInfo; -} - -/** Long-lived DO execution runtime shared by per-request MCP servers. */ -export interface BuiltModernMcpRuntime { - readonly engine: ExecutionEngine; - readonly buildServer: ( - options: ModernMcpServerRequestOptions, - ) => Effect.Effect; } export interface BrowserApprovalStore { @@ -192,21 +132,15 @@ export interface BrowserApprovalStore { readonly waitForResponse: (executionId: string) => Effect.Effect; } -type ModernRuntimeAccess = - | { readonly status: "ok"; readonly runtime: BuiltModernMcpRuntime } - | { readonly status: "forbidden" }; - -class ModernMcpRuntimeNotConfigured extends Data.TaggedError("ModernMcpRuntimeNotConfigured") {} - -const LEGACY_AGENT_SESSION_META_KEY = "executor:mcp:v2:session-meta"; -const LEGACY_AGENT_LAST_ACTIVITY_KEY = "executor:mcp:v2:last-activity-ms"; -const MODERN_SESSION_META_KEY = "session-meta"; -const MODERN_LAST_ACTIVITY_KEY = "last-activity-ms"; -const MODERN_SESSION_KEY = "modern-session"; -const DESTROY_PENDING_KEY = "executor:mcp:v2:destroy-pending"; -const DESTROY_ALARM_DELAY_MS = 1_000; +const SESSION_META_KEY = "session-meta"; +const LAST_ACTIVITY_KEY = "last-activity-ms"; +const PARTYSERVER_NAME_KEY = "__ps_name"; +/** The agents SDK's durable "condemned" marker (`_cf_scheduleDestroy`). */ +const AGENTS_DESTROY_PENDING_KEY = "cf_agents_destroy_pending"; +const MCP_HTTP_METHOD_HEADER = "cf-mcp-method"; +const MCP_MESSAGE_HEADER = "cf-mcp-message"; const MODEL_RESUME_FORWARD_TIMEOUT_MS = 10_000; -const LEGACY_PRIMING_PROTOCOL_VERSION = "2025-11-25"; +const MCP_STREAM_REQS_KEY_PREFIX = "__mcp_stream_reqs__:"; const approvalResponseKey = (executionId: string) => `approval-response:${executionId}`; type JsonRpcRequestId = string | number; @@ -214,6 +148,8 @@ const JsonRpcRequestWithId = Schema.Struct({ id: Schema.Union([Schema.String, Schema.Number]), method: Schema.String, }); +const JsonRpcPostPayload = Schema.fromJsonString(Schema.Unknown); +const decodeJsonRpcPostPayload = Schema.decodeUnknownOption(JsonRpcPostPayload); const decodeJsonRpcRequestWithId = Schema.decodeUnknownOption(JsonRpcRequestWithId); const resumeApprovalResult = ( @@ -240,112 +176,59 @@ const resumeApprovalResult = ( }; }; -const jsonRpcMessages = (parsedBody: unknown): ReadonlyArray => - Array.isArray(parsedBody) ? parsedBody : [parsedBody]; - -const isInitializeBody = (parsedBody: unknown): boolean => - jsonRpcMessages(parsedBody).some((message) => { - const decoded = decodeJsonRpcRequestWithId(message); - return Option.isSome(decoded) && decoded.value.method === "initialize"; - }); - -const legacyToolCallRequestIds = (parsedBody: unknown): readonly JsonRpcRequestId[] => { +const isSessionProps = (props: unknown): props is McpSessionProps => + typeof props === "object" && + props !== null && + "session" in props && + typeof (props as { readonly session?: unknown }).session === "object" && + (props as { readonly session?: unknown }).session !== null; + +const readActivePostRequestIds = (request: Request): readonly JsonRpcRequestId[] => { + if (request.headers.get(MCP_HTTP_METHOD_HEADER) !== "POST") return []; + const encoded = request.headers.get(MCP_MESSAGE_HEADER); + if (!encoded) return []; + const decoded = Effect.runSyncExit( + Effect.try({ + try: () => atob(encoded), + catch: () => "invalid_base64" as const, + }), + ); + if (Exit.isFailure(decoded)) { + console.warn( + JSON.stringify({ + event: "mcp_active_post_response_wait_parse_failed", + reason: "invalid_base64", + }), + ); + return []; + } + const parsed = decodeJsonRpcPostPayload(decoded.value); + if (Option.isNone(parsed)) { + console.warn( + JSON.stringify({ + event: "mcp_active_post_response_wait_parse_failed", + reason: "invalid_json", + }), + ); + return []; + } + const messages = Array.isArray(parsed.value) ? parsed.value : [parsed.value]; const requestIds: JsonRpcRequestId[] = []; - for (const message of jsonRpcMessages(parsedBody)) { + for (const message of messages) { const decoded = decodeJsonRpcRequestWithId(message); - if (Option.isSome(decoded) && decoded.value.method === "tools/call") { - requestIds.push(decoded.value.id); - } + if (Option.isSome(decoded)) requestIds.push(decoded.value.id); } return requestIds; }; -const LEGACY_PRIMING_MESSAGE = { - jsonrpc: "2.0", - method: "notifications/message", - params: { level: "debug", data: "mcp-stream-priming" }, -} satisfies JSONRPCMessage; - -const legacyPrimingFrame = (eventId: string): Uint8Array => - new TextEncoder().encode( - `event: mcp-priming\nid: ${eventId}\ndata: ${JSON.stringify(LEGACY_PRIMING_MESSAGE)}\n\n`, - ); - -const replayFrame = (eventId: string, message: JSONRPCMessage): Uint8Array => - new TextEncoder().encode(`event: message\nid: ${eventId}\ndata: ${JSON.stringify(message)}\n\n`); - -const combineFrames = (frames: readonly Uint8Array[]): ArrayBuffer => { - const byteLength = frames.reduce((total, frame) => total + frame.byteLength, 0); - const buffer = new ArrayBuffer(byteLength); - const combined = new Uint8Array(buffer); - let offset = 0; - for (const frame of frames) { - combined.set(frame, offset); - offset += frame.byteLength; - } - return buffer; -}; - -const mcpResourceFromKey = (resourceKey: string): McpResource => - resourceKey.startsWith("toolkit:") && resourceKey.length > "toolkit:".length - ? { kind: "toolkit", slug: resourceKey.slice("toolkit:".length) } - : defaultMcpResource; - -type RuntimeKind = "legacy" | "modern"; - -type QueuedTransportMessage = { - readonly message: JSONRPCMessage; - readonly extra?: MessageExtraInfo; -}; - -/** - * Dead-session answer by method: POST/DELETE keep the 404 that drives client - * re-initialization; a standalone GET gets 405, which the v1 SDK reads as - * "no SSE stream offered" and stops retrying — breaking the reconnect loops - * of pre-cutover deployments whose GET-404 path never re-initialized. - */ -const deadSessionDoResponse = (method: string): Response => - method === "GET" - ? new Response( - JSON.stringify({ - jsonrpc: "2.0", - error: { code: -32001, message: "Session not found" }, - id: null, - }), - { status: 405, headers: { "content-type": "application/json", allow: "POST, DELETE" } }, - ) - : jsonRpcErrorBody(404, -32001, "Session not found", { cors: false }); - export abstract class McpAgentSessionDOBase< Env extends Cloudflare.Env = Cloudflare.Env, TDbHandle extends SessionDbHandle = SessionDbHandle, -> extends DurableObject { - server?: McpServer; - private transport: WebStandardStreamableHTTPServerTransport | null = null; - private readonly eventStore: DurableObjectMcpEventStore; +> extends McpAgent { + server!: McpServer; private engine: ExecutionEngine | null = null; private dbHandle: TDbHandle | null = null; private sessionMeta: SessionMeta | null = null; - private modernRuntime: BuiltModernMcpRuntime | null = null; - private modernRuntimePromise: Promise | null = null; - private modernHandler: McpHttpHandler | null = null; - private modernRunningRequestCount = 0; - private modernRequestBodies = new WeakMap(); - private modernRequestPropagation = new WeakMap(); - // Trace context of the most recently entered MCP request, kept for - // `currentParentSpan`. Deliberately not cleared when the request settles: - // deferred SDK callbacks fire after the response resolves, and parenting - // them under the latest request is right far more often than falling back - // to the session's construction-time span. Concurrent requests on one DO - // can mis-parent to each other's trace (last writer wins); threading a - // per-request context through the MCP SDK's callback surface is the - // rejected-for-now alternative. - private lastIncomingTrace: IncomingTraceHeaders | undefined; - private legacyRunningRequestCount = 0; - private activeLegacyStreamCount = 0; - private keepAliveCount = 0; - private transportRequestTail = Promise.resolve(); - private runtimeKind: RuntimeKind | null = null; private initialized = false; private onStartPromise: Promise | null = null; private lastActivityMs = 0; @@ -353,11 +236,6 @@ export abstract class McpAgentSessionDOBase< private approvalWaiters = new Map>(); private pendingApprovalLeases = new Map(); - constructor(ctx: DurableObjectState, env: Env) { - super(ctx, env); - this.eventStore = new DurableObjectMcpEventStore(ctx.storage); - } - protected abstract openSessionDb(): TDbHandle | Promise; protected abstract resolveSessionMeta(token: McpSessionInit): Effect.Effect; @@ -367,20 +245,6 @@ export abstract class McpAgentSessionDOBase< dbHandle: TDbHandle, ): Effect.Effect; - /** Build the engine and per-request MCP server factory for a modern-only DO. */ - protected buildModernMcpRuntime( - _sessionMeta: SessionMeta, - _dbHandle: TDbHandle, - ): Effect.Effect { - return Effect.fail(new ModernMcpRuntimeNotConfigured()); - } - - /** Read and validate the deployment-provided modern request-state signing key. */ - protected modernRequestStateSigningKey(): string { - // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- composition boundary: subclasses serving modern MCP must provide a shared deployment key - throw new Error("Modern MCP request-state signing is not configured"); - } - protected withTelemetry( effect: Effect.Effect, _incoming?: IncomingTraceHeaders, @@ -406,23 +270,11 @@ export abstract class McpAgentSessionDOBase< } protected get sessionId(): string { - return this.ctx.id.toString(); + return this.getSessionId(); } - // Parent for spans opened by deferred MCP SDK callbacks (tool handlers run - // through `runToolEffect`, which otherwise inherits the Effect context - // captured when the server was BUILT). The legacy sessionful runtime builds - // its server once per session and reuses it across every request, so - // without this the whole tool execution tree parents under the long-closed - // session-construction span instead of the request that triggered it. protected currentParentSpan(): Tracer.AnySpan | undefined { - const parsed = parseTraceparentHeader(this.lastIncomingTrace?.traceparent); - if (!parsed) return undefined; - return Tracer.externalSpan({ - traceId: parsed.traceId, - spanId: parsed.spanId, - sampled: (parsed.traceFlags & 1) === 1, - }); + return undefined; } protected sessionTimeoutMs(): number { @@ -441,18 +293,6 @@ export abstract class McpAgentSessionDOBase< return { sessionId: this.sessionId }; } - private modernExecutionOwnerRoute(): McpExecutionOwnerRoute { - return this.runtimeKind === "legacy" || this.ctx.id.name - ? this.executionOwnerRoute() - : modernMcpExecutionOwnerRoute(this.ctx.id.toString()); - } - - private runtimeOwnerId(): string { - return this.runtimeKind === "modern" - ? this.modernExecutionOwnerRoute().sessionId - : this.sessionId; - } - protected sameExecutionOwnerRoute(a: McpExecutionOwnerRoute, b: McpExecutionOwnerRoute): boolean { return a.sessionId === b.sessionId; } @@ -480,12 +320,6 @@ export abstract class McpAgentSessionDOBase< ): Effect.Effect => this.resumeFromExecutionOwnerDirectory(executionId, response); - protected readonly modernModelResumeFallback = ( - executionId: string, - response: ResumeResponse, - ): Effect.Effect => - this.resumeFromExecutionOwnerDirectory(executionId, response, this.modernExecutionOwnerRoute()); - protected readonly pausedExecutionHooks: PausedExecutionHooks = { onExecutionPaused: (executionId, deadline) => Effect.sync(() => { @@ -495,16 +329,18 @@ export abstract class McpAgentSessionDOBase< onResumeSettled: (executionId) => this.finishPendingApprovalResume(executionId), }; - /** - * Modern pause hooks await the directory write before the `input_required` - * result leaves the DO, so its signed continuation is immediately routable. - */ - protected readonly modernPausedExecutionHooks: PausedExecutionHooks = { - onExecutionPaused: (executionId, deadline) => - this.startPendingApprovalLease(executionId, deadline, this.modernExecutionOwnerRoute()), - onResumeStarted: (executionId) => this.beginPendingApprovalResume(executionId), - onResumeSettled: (executionId) => this.finishPendingApprovalResume(executionId), - }; + override async onConnect(conn: Connection, context: ConnectionContext): Promise { + const requestIds = readActivePostRequestIds(context.request); + if (requestIds.length === 0) { + await super.onConnect(conn, context); + return; + } + + await this.keepAliveWhile(async () => { + await this.setStreamRequestIds(conn.id, [...requestIds]); + await super.onConnect(conn, context); + }); + } private openSessionDbHandle(): Effect.Effect { return Effect.promise(() => Promise.resolve(this.openSessionDb())); @@ -513,20 +349,7 @@ export abstract class McpAgentSessionDOBase< private loadSessionMeta(): Effect.Effect { return Effect.promise(async () => { if (this.sessionMeta) return this.sessionMeta; - - const legacy = await this.ctx.storage.get(LEGACY_AGENT_SESSION_META_KEY); - if (legacy) { - this.runtimeKind = "legacy"; - this.sessionMeta = { ...legacy, resource: legacy.resource ?? defaultMcpResource }; - return this.sessionMeta; - } - - const isModern = - this.runtimeKind === "modern" || - (await this.ctx.storage.get(MODERN_SESSION_KEY)) === true; - if (!isModern) return null; - this.runtimeKind = "modern"; - const stored = await this.ctx.storage.get(MODERN_SESSION_META_KEY); + const stored = await this.ctx.storage.get(SESSION_META_KEY); // Backfill `resource` for sessions persisted before scoped toolkits added // the field. Their stored meta has no `resource`, and every such session // was minted against the default `/mcp` endpoint, so default it here @@ -540,15 +363,13 @@ export abstract class McpAgentSessionDOBase< private async saveSessionMeta(sessionMeta: SessionMeta): Promise { this.sessionMeta = sessionMeta; - const key = - this.runtimeKind === "modern" ? MODERN_SESSION_META_KEY : LEGACY_AGENT_SESSION_META_KEY; - await this.ctx.storage.put(key, sessionMeta); + await this.ctx.storage.put(SESSION_META_KEY, sessionMeta); } /** * Persist the MCP-Apps support negotiated at `initialize`, so a later cold * restore can rebuild the server with it. Subclasses hand this to - * `buildMcpServer` as `onAppsEnabledChange`. + * `createExecutorMcpServer` as `onAppsEnabledChange`. * * A no-op before meta exists: `initialize` always follows `init`, so there is * nothing to merge into and nothing worth failing the session over. @@ -567,70 +388,80 @@ export abstract class McpAgentSessionDOBase< ); } - /** - * Persist the client identity self-reported at `initialize` (or in a modern - * request's `_meta`), so a cold restore keeps span attribution. Subclasses - * hand this to `buildMcpServer` as `onClientInfoChange`; the modern request - * path calls it directly. Same no-op-before-meta contract as - * {@link persistAppsEnabled}. - */ - protected persistClientInfo(clientInfo: McpClientInfo): Effect.Effect { - const self = this; - return Effect.gen(function* () { - const stored = yield* self.loadSessionMeta(); - if ( - !stored || - (stored.clientInfo?.name === clientInfo.name && - stored.clientInfo?.version === clientInfo.version && - stored.clientInfo?.title === clientInfo.title) - ) { - return; - } - yield* Effect.promise(() => self.saveSessionMeta({ ...stored, clientInfo })); - }).pipe( - Effect.withSpan("mcp.session.persist_client_info", { - attributes: { "mcp.client.name": clientInfo.name }, - }), - Effect.ignoreCause({ log: false }), - ); - } - private async markActivity(now = Date.now()): Promise { this.lastActivityMs = now; - const key = - this.runtimeKind === "modern" ? MODERN_LAST_ACTIVITY_KEY : LEGACY_AGENT_LAST_ACTIVITY_KEY; await Promise.all([ - this.ctx.storage.put(key, now), + this.ctx.storage.put(LAST_ACTIVITY_KEY, now), this.ctx.storage.setAlarm(now + this.sessionTimeoutMs()), ]); } private async loadLastActivity(): Promise { if (this.lastActivityMs > 0) return this.lastActivityMs; - const key = - this.runtimeKind === "modern" ? MODERN_LAST_ACTIVITY_KEY : LEGACY_AGENT_LAST_ACTIVITY_KEY; - const stored = await this.ctx.storage.get(key); + const stored = await this.ctx.storage.get(LAST_ACTIVITY_KEY); this.lastActivityMs = stored ?? 0; return this.lastActivityMs; } - /** Hold the in-memory approval runtime until the matching pause settles. */ - protected keepAlive(): Promise<() => void> { - this.keepAliveCount += 1; - let disposed = false; - return Promise.resolve(() => { - if (disposed) return; - disposed = true; - this.keepAliveCount = Math.max(0, this.keepAliveCount - 1); - }); + private async hasPartyServerName(): Promise { + if (this.ctx.id.name) return true; + const stored = await this.ctx.storage.get(PARTYSERVER_NAME_KEY); + return !!stored; } private activeStreamCount(): number { - return this.activeLegacyStreamCount; + return this.connectionsOrNone().length; + } + + private async runningExecutionCount(): Promise { + // Only requests still awaiting a result count as running work. Undelivered + // response markers (the transport's __mcp_undelivered_stream__: keys) + // deliberately do NOT extend the lease: the response is persisted in storage, + // which survives disposeIdleRuntime, so a later reconnect GET re-inits the + // DO and replays it. Counting them would make every delivered-but-unacked + // POST response pin the runtime alive indefinitely. + const rows = await this.ctx.storage.list({ + prefix: MCP_STREAM_REQS_KEY_PREFIX, + limit: 1_000, + }); + let count = 0; + for (const requestIds of rows.values()) { + if (Array.isArray(requestIds)) count += requestIds.length; + } + return count; } - private runningExecutionCount(): number { - return this.legacyRunningRequestCount + this.modernRunningRequestCount; + private closeActiveStreams(): void { + for (const connection of this.connectionsOrNone()) { + // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: best-effort WebSocket close during runtime disposal. + try { + connection.close(1000, "Session closed"); + } catch {} + } + } + + /** + * partyserver's `getConnections` dereferences a `#connectionManager` + * private field that is only initialized once the DO has accepted a + * websocket (never in unit harnesses), and partyserver exposes no + * non-throwing probe for that state, so "it throws" IS the signal for + * "no connections yet". Treating that as an empty set is safe for both + * callers: `closeActiveStreams` then has nothing to close, and + * `activeStreamCount` feeds the idle-lease decision where zero at worst + * disposes an idle-looking runtime whose undelivered responses are + * persisted in durable storage and replayed by the next reconnect GET. + * Before this guard the alarm crashed and retried instead, which kept + * the session pinned without ever making progress. + */ + private connectionsOrNone(): ReadonlyArray { + const getConnections = (this as { getConnections?: () => Iterable }).getConnections; + if (!getConnections) return []; + // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: see doc comment; partyserver offers no non-throwing way to ask whether the connection manager exists. + try { + return Array.from(getConnections.call(this)); + } catch { + return []; + } } private async cleanupUnaddressableSessionAlarm(): Promise { @@ -638,39 +469,30 @@ export abstract class McpAgentSessionDOBase< await Effect.runPromise( Effect.all([ Effect.ignore(Effect.tryPromise(() => this.ctx.storage.deleteAlarm())), - Effect.ignore( - Effect.tryPromise(() => - this.ctx.storage.delete([LEGACY_AGENT_LAST_ACTIVITY_KEY, MODERN_LAST_ACTIVITY_KEY]), - ), - ), + Effect.ignore(Effect.tryPromise(() => this.ctx.storage.delete(LAST_ACTIVITY_KEY))), ]), ); } private async disposeIdleRuntime(input: { readonly idleMs: number; - readonly lastActivityMs: number; readonly pausedExecutionCount: number; }): Promise { console.info( JSON.stringify({ event: "mcp_session_idle_runtime_dispose", - sessionId: this.runtimeOwnerId(), + sessionId: this.sessionId, idleMs: input.idleMs, pausedExecutionCount: input.pausedExecutionCount, }), ); await Effect.runPromise(this.closeRuntime()); - const activityKey = - this.runtimeKind === "modern" ? MODERN_LAST_ACTIVITY_KEY : LEGACY_AGENT_LAST_ACTIVITY_KEY; - const cleared = await this.ctx.storage.transaction(async (transaction) => { - const current = await transaction.get(activityKey); - if (current !== input.lastActivityMs) return false; - await transaction.delete([LEGACY_AGENT_LAST_ACTIVITY_KEY, MODERN_LAST_ACTIVITY_KEY]); - await transaction.deleteAlarm(); - return true; - }); - if (cleared) this.lastActivityMs = 0; + await Effect.runPromise( + Effect.all([ + Effect.ignore(Effect.tryPromise(() => this.ctx.storage.deleteAlarm())), + Effect.ignore(Effect.tryPromise(() => this.ctx.storage.delete(LAST_ACTIVITY_KEY))), + ]), + ); } private resolveAndStoreSessionMeta(token: McpSessionInit) { @@ -685,9 +507,7 @@ export abstract class McpAgentSessionDOBase< const sessionMeta: SessionMeta = { ...resolved, ...(token.webOrigin ? { webOrigin: token.webOrigin } : {}), - appsEnabled: stored?.appsEnabled ?? false, - ...(stored?.clientInfo ? { clientInfo: stored.clientInfo } : {}), - createdAtMs: stored?.createdAtMs ?? Date.now(), + ...(stored?.appsEnabled === undefined ? {} : { appsEnabled: stored.appsEnabled }), }; yield* Effect.promise(() => self.saveSessionMeta(sessionMeta)).pipe( Effect.withSpan("mcp.session.save_meta"), @@ -720,7 +540,7 @@ export abstract class McpAgentSessionDOBase< event: "mcp_execution_owner_directory_error", operation: input.operation, executionId: input.executionId, - sessionId: self.runtimeOwnerId(), + sessionId: self.sessionId, exceptionType: first?.name ?? "Error", exceptionMessage: first?.message ?? "unknown", cause: Cause.pretty(input.cause), @@ -745,7 +565,7 @@ export abstract class McpAgentSessionDOBase< JSON.stringify({ event: "mcp_model_resume_forward_error", executionId: input.executionId, - sessionId: self.runtimeOwnerId(), + sessionId: self.sessionId, ownerSessionId: input.owner.sessionId, exceptionType: first?.name ?? "Error", exceptionMessage: first?.message ?? "unknown", @@ -771,7 +591,7 @@ export abstract class McpAgentSessionDOBase< event: "mcp_model_resume_forward_error", reason: "timeout", executionId: input.executionId, - sessionId: self.runtimeOwnerId(), + sessionId: self.sessionId, ownerSessionId: input.owner.sessionId, timeoutMs: input.timeoutMs, }), @@ -799,173 +619,26 @@ export abstract class McpAgentSessionDOBase< : built; } - private buildModernRuntime(sessionMeta: SessionMeta, dbHandle: TDbHandle) { - const built = sessionMeta.organizationSlug - ? this.buildModernMcpRuntime(sessionMeta, dbHandle).pipe( - Effect.provideService(RequestOrgSlug, { slug: sessionMeta.organizationSlug }), - ) - : this.buildModernMcpRuntime(sessionMeta, dbHandle); - return sessionMeta.webOrigin - ? built.pipe(Effect.provideService(RequestWebOrigin, { origin: sessionMeta.webOrigin })) - : built; - } - - private modernPropsOwnSession(sessionMeta: SessionMeta, props: McpSessionProps): boolean { - return ( - props.session.userId === sessionMeta.userId && - props.session.organizationId === sessionMeta.organizationId && - mcpResourceKey(props.session.resource) === mcpResourceKey(sessionMeta.resource) - ); - } - - private startModernRuntime(props: McpSessionProps): Promise { - if (this.modernRuntimePromise) return this.modernRuntimePromise; - - const self = this; - const program = Effect.gen(function* () { - yield* self.prepareErrorCaptureScope(); - const stored = yield* self.loadSessionMeta(); - if (stored && !self.modernPropsOwnSession(stored, props)) { - return { status: "forbidden" as const }; - } - if (!stored) self.runtimeKind = "modern"; - const sessionMeta = stored ?? (yield* self.resolveAndStoreSessionMeta(props.session)); - if (self.runtimeKind === "legacy" && (!self.modernRuntime || !self.engine)) { - yield* self.initializeLegacyRuntime(props, sessionMeta); - } - if (self.modernRuntime && self.engine) { - yield* Effect.promise(() => self.markActivity()); - return { status: "ok" as const, runtime: self.modernRuntime }; - } - - const dbHandle = self.dbHandle ?? (yield* self.openSessionDbHandle()); - self.dbHandle = dbHandle; - const runtime = yield* self.buildModernRuntime(sessionMeta, dbHandle); - self.modernRuntime = runtime; - self.engine = runtime.engine; - yield* Effect.promise(() => - self.runtimeKind === "modern" - ? Promise.all([self.ctx.storage.put(MODERN_SESSION_KEY, true), self.markActivity()]).then( - () => undefined, - ) - : self.markActivity(), - ); - return { status: "ok" as const, runtime }; - }).pipe( - Effect.tapCause((cause) => - Effect.gen(function* () { - console.error("[mcp-session] modern runtime init failed:", Cause.pretty(cause)); - yield* self.captureCauseEffect(cause); - yield* self.recordCauseOnSpan(cause); - yield* self.closeRuntime(); - }), - ), - Effect.withSpan("McpSessionDO.startModernRuntime", { - attributes: { "mcp.auth.organization_id": props.session.organizationId }, - }), - (effect) => self.withTelemetry(effect, props.propagation), - // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: Durable Object RPC methods can only reject their Promise - Effect.orDie, - (effect) => self.withSpanFlush(effect), - ); - - const starting = Effect.runPromise(program); - this.modernRuntimePromise = starting; - starting.then( - () => { - if (this.modernRuntimePromise === starting) this.modernRuntimePromise = null; - }, - () => { - if (this.modernRuntimePromise === starting) this.modernRuntimePromise = null; - }, - ); - return starting; - } - - private modernHandlerForRuntime(): McpHttpHandler { - if (this.modernHandler) return this.modernHandler; - const self = this; - this.modernHandler = createMcpHandler( - (context: McpRequestContext) => { - const request = context.requestInfo; - const runtime = self.modernRuntime; - const sessionMeta = self.sessionMeta; - if (!request || !runtime || !sessionMeta || !self.modernRequestBodies.has(request)) { - // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: the third-party factory Promise has no typed failure channel; absent DO request context is an SDK defect - return Effect.runPromise(Effect.die("Modern MCP Durable Object has no request runtime")); - } - const parsedBody = self.modernRequestBodies.get(request); - const propagation = self.modernRequestPropagation.get(request); - const capabilities = clientCapabilitiesFromRequestBody(parsedBody); - const clientInfo = clientInfoFromRequestBody(parsedBody) ?? sessionMeta.clientInfo; - return Effect.runPromise( - Effect.gen(function* () { - const requestStatePrincipal = mcpRequestStatePrincipal({ - accountId: sessionMeta.userId, - organizationId: sessionMeta.organizationId, - }); - const requestStateBinding = yield* Effect.promise(() => - mcpRequestStateBindingFromBody({ - body: parsedBody, - principal: requestStatePrincipal, - resource: sessionMeta.resource, - }), - ); - return yield* runtime.buildServer({ - appsEnabled: appsEnabledForClientCapabilities(capabilities), - requestStateSigningKey: self.modernRequestStateSigningKey(), - requestStatePrincipal, - ...(requestStateBinding === null ? {} : { requestStateBinding }), - ...(clientInfo === undefined ? {} : { restoredClientInfo: clientInfo }), - }); - }).pipe( - (effect) => self.withTelemetry(effect, propagation), - // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: the third-party factory Promise can only reject - Effect.orDie, - ), - ); - }, - { legacy: "reject" }, - ); - return this.modernHandler; - } - - private closeRuntime(): Effect.Effect { + private closeRuntime(options: { readonly closeStreams?: boolean } = {}): Effect.Effect { const self = this; return Effect.gen(function* () { - // Detach the complete generation before awaiting cleanup. A request that - // interleaves with a slow server/DB close must build a fresh generation, - // never observe initialized=true with a closing/null transport, and the - // old cleanup must never clear fields belonging to that fresh runtime. - const transport = self.transport; - const server = self.server; - const modernHandler = self.modernHandler; - const dbHandle = self.dbHandle; - self.transport = null; - delete (self as { server?: McpServer }).server; - self.modernHandler = null; - self.dbHandle = null; - self.engine = null; - self.modernRuntime = null; - self.activeLegacyStreamCount = 0; - self.legacyRunningRequestCount = 0; - self.modernRequestBodies = new WeakMap(); - self.modernRequestPropagation = new WeakMap(); - self.initialized = false; - yield* self.releaseAllPendingApprovalLeases(); - if (transport) { - yield* Effect.promise(() => transport.close()).pipe(Effect.ignore); + if (options.closeStreams ?? true) { + yield* Effect.sync(() => self.closeActiveStreams()); } - if (server) { + if (self.server) { + const server = self.server; + delete (self as { server?: McpServer }).server; yield* Effect.promise(() => server.close()).pipe(Effect.ignore); } - if (modernHandler) { - yield* Effect.promise(() => modernHandler.close()).pipe(Effect.ignore); - } - if (dbHandle) { + Reflect.set(self, "_transport", undefined); + self.engine = null; + if (self.dbHandle) { + const dbHandle = self.dbHandle; + self.dbHandle = null; yield* Effect.promise(() => Promise.resolve(dbHandle.end())).pipe(Effect.ignore); } + self.initialized = false; }); } @@ -984,66 +657,62 @@ export abstract class McpAgentSessionDOBase< }).pipe(Effect.withSpan("McpSessionDO.ensure_runtime_for_approval")); } - private propsFromSessionMeta( - sessionMeta: SessionMeta, - propagation?: IncomingTraceHeaders, - ): McpSessionProps { - return { - session: { - organizationId: sessionMeta.organizationId, - userId: sessionMeta.userId, - elicitationMode: sessionMeta.elicitationMode ?? "model", - artifactsEnabled: sessionMeta.artifactsEnabled, - resource: sessionMeta.resource, - webOrigin: sessionMeta.webOrigin, - }, - propagation, - }; + private startRuntimeFromOnStart(props?: McpSessionProps): Effect.Effect { + const self = this; + return Effect.gen(function* () { + // PartyServer can rehydrate WebSockets before onStart runs in a + // cold-restored isolate. With no in-memory runtime to replace, those + // sockets are the live MCP response streams that triggered the restore. + const hasInMemoryRuntime = + self.initialized || + self.engine !== null || + self.dbHandle !== null || + self.server !== undefined; + yield* self.closeRuntime({ closeStreams: hasInMemoryRuntime }); + const started = yield* Effect.exit(Effect.promise(() => self.runMcpAgentOnStart(props))); + if (Exit.isFailure(started)) { + yield* self.closeRuntime(); + return yield* Effect.failCause(started.cause); + } + }); } - private restoreTransportSession(transport: WebStandardStreamableHTTPServerTransport): void { - transport.sessionId = this.sessionId; - // SAFETY: the SDK exposes `sessionId` but not a public cold-restore setter. - // The installed transport's only additional session-validation bit is the - // runtime `_initialized` boolean. Restoring just those transport fields - // intentionally leaves McpServer client capabilities absent, so the - // sessionful assembly falls back to the persisted apps seed. - Reflect.set(transport, "_initialized", true); + protected runMcpAgentOnStart(props?: McpSessionProps): Promise { + return super.onStart(props); } - private makeLegacyTransport(restoring: boolean): WebStandardStreamableHTTPServerTransport { - const transport = new WebStandardStreamableHTTPServerTransport({ - sessionIdGenerator: () => this.sessionId, - enableJsonResponse: false, - eventStore: this.eventStore, - retryInterval: 1_000, - onsessionclosed: () => this._cf_scheduleDestroy(), - }); - transport.onerror = (error) => { - console.error("[mcp-session] transport error:", error); - }; - if (restoring) this.restoreTransportSession(transport); - return transport; + override async onStart(props?: McpSessionProps): Promise { + if (this.onStartPromise) return this.onStartPromise; + + const starting = Effect.runPromise(this.startRuntimeFromOnStart(props)); + this.onStartPromise = starting; + starting.then( + () => { + if (this.onStartPromise === starting) this.onStartPromise = null; + }, + () => { + if (this.onStartPromise === starting) this.onStartPromise = null; + }, + ); + return starting; } - private initializeLegacyRuntime( - props: McpSessionProps, - storedMeta: SessionMeta | null, - ): Effect.Effect { + async init(): Promise { + if (this.initialized) return; + const props = isSessionProps(this.props) ? this.props : null; + if (!props) { + // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- boundary: McpAgent.init is a Promise-only framework hook and props are required before any Effect runtime exists. + throw new Error("MCP session props are required"); + } const self = this; - return Effect.gen(function* () { + const program = Effect.gen(function* () { yield* self.prepareErrorCaptureScope(); - self.runtimeKind = "legacy"; - const sessionMeta = storedMeta ?? (yield* self.resolveAndStoreSessionMeta(props.session)); + const sessionMeta = yield* self.resolveAndStoreSessionMeta(props.session); const dbHandle = yield* self.openSessionDbHandle(); - const { mcpServer, engine, modernRuntime } = yield* self.buildRuntime(sessionMeta, dbHandle); - const transport = self.makeLegacyTransport(storedMeta !== null); + const { mcpServer, engine } = yield* self.buildRuntime(sessionMeta, dbHandle); self.dbHandle = dbHandle; self.server = mcpServer; self.engine = engine; - self.modernRuntime = modernRuntime ?? null; - self.transport = transport; - yield* Effect.promise(() => mcpServer.connect(transport)); self.initialized = true; yield* Effect.promise(() => self.markActivity()).pipe( Effect.withSpan("McpSessionDO.markActivity"), @@ -1051,407 +720,31 @@ export abstract class McpAgentSessionDOBase< }).pipe( Effect.tapCause((cause) => Effect.gen(function* () { - console.error("[mcp-session] legacy runtime init failed:", Cause.pretty(cause)); + console.error("[mcp-session] init failed:", Cause.pretty(cause)); yield* self.captureCauseEffect(cause); yield* self.recordCauseOnSpan(cause); }), ), Effect.catchCause((cause) => Effect.gen(function* () { - yield* self.closeRuntime(); + yield* Effect.promise(() => self.cleanup()); return yield* Effect.failCause(cause); }), ), - Effect.withSpan("McpSessionDO.initializeLegacyRuntime", { - attributes: { "mcp.auth.organization_id": props.session.organizationId }, + Effect.withSpan("McpSessionDO.init", { + attributes: { + "mcp.auth.organization_id": props?.session.organizationId ?? "", + }, }), - (effect) => self.withTelemetry(effect, props.propagation), - // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: Durable Object entrypoints can only reject their Promise - Effect.orDie, - (effect) => self.withSpanFlush(effect), ); - } - - async onStart(props?: McpSessionProps): Promise { - if (this.initialized && this.engine) return; - if (this.onStartPromise) return this.onStartPromise; - - const self = this; - const starting = Effect.runPromise( - Effect.gen(function* () { - const stored = yield* self.loadSessionMeta(); - const resolvedProps = props ?? (stored ? self.propsFromSessionMeta(stored) : null); - if (!resolvedProps) return; - if (self.runtimeKind === "modern") { - yield* Effect.promise(() => self.startModernRuntime(resolvedProps)); - return; - } - yield* self.initializeLegacyRuntime(resolvedProps, stored); - }), - ); - this.onStartPromise = starting; - starting.then( - () => { - if (this.onStartPromise === starting) this.onStartPromise = null; - }, - () => { - if (this.onStartPromise === starting) this.onStartPromise = null; - }, + const traced = this.withTelemetry(program, props?.propagation); + return Effect.runPromise( + traced.pipe( + // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: Durable Object init method can only reject its Promise + Effect.orDie, + (effect) => self.withSpanFlush(effect), + ), ); - return starting; - } - - private requestStreamId( - transport: WebStandardStreamableHTTPServerTransport, - requestId: RequestId, - ): string | null { - // SAFETY: the SDK currently has no public hook exposing the per-POST stream - // ID. The installed transport stores the exact request-id → stream-id map - // used by replay. Reading it lets the legacy compatibility prime share the - // same replay stream as the eventual result without changing SDK code. - const mapping: unknown = Reflect.get(transport, "_requestToStreamMapping"); - if (!(mapping instanceof Map)) return null; - const streamId: unknown = mapping.get(requestId); - return typeof streamId === "string" ? streamId : null; - } - - /** - * Whether the stream named by `lastEventId` still has a request awaiting - * its response. SAFETY: reads the transport's pinned - * `_requestToStreamMapping` for the same reason `requestStreamId` and - * `supersedeReplayStream` do — the SDK exposes no public pending-request - * probe. - */ - private async lastEventIdStreamHasPendingRequest( - transport: WebStandardStreamableHTTPServerTransport, - lastEventId: string, - ): Promise { - const streamId = await this.eventStore.getStreamIdForEventId(lastEventId); - if (!streamId) return false; - const mapping: unknown = Reflect.get(transport, "_requestToStreamMapping"); - if (!(mapping instanceof Map)) return false; - for (const mappedStreamId of mapping.values()) { - if (mappedStreamId === streamId) return true; - } - return false; - } - - private async supersedeReplayStream( - transport: WebStandardStreamableHTTPServerTransport, - lastEventId: string, - ): Promise { - const streamId = await this.eventStore.getStreamIdForEventId(lastEventId); - if (!streamId) return; - // SAFETY: the installed SDK exposes closeSSEStream(requestId), but not the - // reverse request-id map needed to supersede a stale POST connection before - // replay. This is the same pinned map used by requestStreamId above. - const mapping: unknown = Reflect.get(transport, "_requestToStreamMapping"); - if (!(mapping instanceof Map)) return; - for (const [requestId, mappedStreamId] of mapping) { - if ( - mappedStreamId === streamId && - (typeof requestId === "string" || typeof requestId === "number") - ) { - transport.closeSSEStream(requestId); - return; - } - } - } - - private trackedLegacyResponse = ( - response: Response, - options: { readonly initialFrame?: Uint8Array; readonly acknowledge?: readonly string[] } = {}, - ): Response => - rotateSseResponse(response, { - ...(options.initialFrame ? { initialFrame: options.initialFrame } : {}), - onOpen: () => { - this.activeLegacyStreamCount += 1; - }, - onClose: (reason) => { - this.activeLegacyStreamCount = Math.max(0, this.activeLegacyStreamCount - 1); - // "complete": the source body drained to its natural end. "rotate": - // the client stayed attached for the whole max-age window, so the - // initial replay frames were drained long before. Both count as - // delivered. "cancel"/"error" leave the streams replayable for the - // client's reconnect GET. - if ( - (reason === "complete" || reason === "rotate") && - options.acknowledge && - options.acknowledge.length > 0 - ) { - this.ctx.waitUntil(this.eventStore.acknowledgeUndeliveredStreams(options.acknowledge)); - } - }, - }); - - /** - * Collect every undelivered stream's events as one SSE frame block, for - * prepending onto the standalone GET stream. Returning a FINITE response - * here instead (the pre-2026-08-17 behavior) was catastrophic: the client's - * standalone listener closed the moment the replay flushed, and because - * every POST marks its stream undelivered until acknowledged, an active - * session ALWAYS had something to replay — so every listener GET became a - * ~3s reconnect short-poll. Fleet-wide, that reconnect storm multiplied - * /mcp volume ~15x, drove the worker into memory-limit kills, and (by - * recycling isolates) pushed homepage TTFB from ~15ms to ~3s. - */ - private async collectUndeliveredReplay(): Promise<{ - readonly frame: Uint8Array; - readonly streamIds: readonly string[]; - } | null> { - const frames: Uint8Array[] = []; - const streamIds = await this.eventStore.replayUndeliveredStreams({ - send: (eventId, message) => { - frames.push(replayFrame(eventId, message)); - return Promise.resolve(); - }, - }); - if (frames.length === 0) return null; - return { frame: new Uint8Array(combineFrames(frames)), streamIds }; - } - - private async serializedTransportRequest(run: () => Promise): Promise { - const previous = this.transportRequestTail; - let release = (): void => undefined; - this.transportRequestTail = new Promise((resolve) => { - release = resolve; - }); - await previous; - // oxlint-disable-next-line executor/no-try-catch-or-throw -- concurrency boundary: release the next DO transport request on both success and rejection - try { - return await run(); - } finally { - release(); - } - } - - private async handleLegacyTransportRequest( - request: Request, - parsedBody: unknown, - ): Promise { - return this.serializedTransportRequest(async () => { - const transport = this.transport; - if (!transport) { - return deadSessionDoResponse(request.method); - } - if (request.method === "GET") { - const lastEventId = request.headers.get("last-event-id"); - // A reconnect id is only "drained" when the stream has no stored - // events after it AND no request still in flight on it. An in-flight - // tool call has produced no events past the priming frame yet, but - // its POST stream must still be resumed so the eventual result lands - // on this connection (the severed-POST recovery contract). - const resumable = - lastEventId !== null && - ((await this.eventStore.hasEventsAfter(lastEventId)) || - (await this.lastEventIdStreamHasPendingRequest(transport, lastEventId))); - if (lastEventId && resumable) { - await this.supersedeReplayStream(transport, lastEventId); - } else { - // Standalone listener path — taken for a bare GET AND for a GET - // whose Last-Event-ID stream is fully drained. EventSource clients - // echo their last id on every reconnect, so a drained id must not - // enter the transport's resume (it closes a completed stream's - // resume immediately, turning the echo into a reconnect loop). - let serveRequest = request; - if (lastEventId) { - const headers = new Headers(request.headers); - headers.delete("last-event-id"); - serveRequest = new Request(request, { headers }); - } - // Latest-listener-wins. Client cancellation is not reliably relayed - // through every workerd/Vite streaming hop, so explicitly retire a - // stale standalone mapping before opening its replacement. - transport.closeStandaloneSSEStream(); - const replay = await this.collectUndeliveredReplay(); - // Replayed responses ride as the opening frames of the transport's - // own long-lived standalone stream — the stream MUST stay open - // afterwards (see collectUndeliveredReplay). Acknowledgement moves - // to stream end: "complete"/"rotate" imply the client stayed - // attached long enough to have drained the prepended frames. - const response = await transport.handleRequest(serveRequest); - return this.trackedLegacyResponse( - response, - replay ? { initialFrame: replay.frame, acknowledge: replay.streamIds } : {}, - ); - } - } - const toolCallIds = legacyToolCallRequestIds(parsedBody); - const protocolVersion = - request.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; - const needsLegacyPrime = - toolCallIds.length > 0 && protocolVersion < LEGACY_PRIMING_PROTOCOL_VERSION; - if (!needsLegacyPrime) { - const response = await transport.handleRequest(request); - const streamId = toolCallIds[0] ? this.requestStreamId(transport, toolCallIds[0]) : null; - if (streamId) await this.eventStore.markStreamUndelivered(streamId); - return this.trackedLegacyResponse(response); - } - - const originalOnMessage = transport.onmessage; - const queued: QueuedTransportMessage[] = []; - transport.onmessage = (message, extra) => { - queued.push(extra === undefined ? { message } : { message, extra }); - }; - let response: Response; - // oxlint-disable-next-line executor/no-try-catch-or-throw -- SDK adapter boundary: restore the connected server handler even when request parsing fails - try { - response = await transport.handleRequest(request); - } finally { - transport.onmessage = originalOnMessage; - } - - const streamId = this.requestStreamId(transport, toolCallIds[0]!); - const eventId = streamId - ? await this.eventStore.storeEvent(streamId, LEGACY_PRIMING_MESSAGE) - : null; - if (streamId) await this.eventStore.markStreamUndelivered(streamId); - const rotated = this.trackedLegacyResponse(response, { - ...(eventId ? { initialFrame: legacyPrimingFrame(eventId) } : {}), - }); - // ReadableStream.start enqueues the priming frame synchronously while - // building `rotated`; only then may the server see the tools/call. - for (const item of queued) originalOnMessage?.(item.message, item.extra); - return rotated; - }); - } - - private propsFromLegacyRequest( - request: Request, - verified: NonNullable>, - ): McpSessionProps { - return { - session: { - organizationId: verified.organizationId, - userId: verified.accountId, - elicitationMode: readElicitationMode(request), - artifactsEnabled: readArtifactsEnabled(request), - resource: mcpResourceFromKey(verified.resourceKey), - webOrigin: new URL(request.url).origin, - }, - propagation: { - traceparent: request.headers.get("traceparent") ?? undefined, - tracestate: request.headers.get("tracestate") ?? undefined, - baggage: request.headers.get("baggage") ?? undefined, - }, - }; - } - - /** Serve one authenticated legacy MCP exchange directly from this DO. */ - override async fetch(request: Request): Promise { - const verified = verifiedMcpRequestHeaders(request); - if (!verified) { - return jsonRpcErrorBody(403, -32003, "Invalid MCP Durable Object identity", { - cors: false, - }); - } - this.lastIncomingTrace = { - traceparent: request.headers.get("traceparent") ?? undefined, - tracestate: request.headers.get("tracestate") ?? undefined, - baggage: request.headers.get("baggage") ?? undefined, - }; - if ((await this.ctx.storage.get(DESTROY_PENDING_KEY)) === true) { - return jsonRpcErrorBody(404, -32001, "Session timed out, please reconnect", { - cors: false, - }); - } - - const parsedBody = await Effect.runPromise(requestBodyFromRequest(request)); - const stored = await Effect.runPromise(this.loadSessionMeta()); - if (!stored) { - if (!isInitializeBody(parsedBody)) { - return request.headers.has("mcp-session-id") - ? deadSessionDoResponse(request.method) - : jsonRpcErrorBody(400, -32000, "Bad Request: Server not initialized", { - cors: false, - }); - } - this.runtimeKind = "legacy"; - await this.onStart(this.propsFromLegacyRequest(request, verified)); - } else { - if ( - this.runtimeKind !== "legacy" || - stored.userId !== verified.accountId || - stored.organizationId !== verified.organizationId || - mcpResourceKey(stored.resource) !== verified.resourceKey - ) { - return jsonRpcErrorBody(403, -32003, "MCP session does not belong to the current bearer", { - cors: false, - }); - } - await this.onStart( - this.propsFromSessionMeta(stored, { - traceparent: request.headers.get("traceparent") ?? undefined, - tracestate: request.headers.get("tracestate") ?? undefined, - baggage: request.headers.get("baggage") ?? undefined, - }), - ); - } - - this.legacyRunningRequestCount += 1; - await this.markActivity(); - // oxlint-disable-next-line executor/no-try-catch-or-throw -- adapter boundary: running-request accounting must settle on transport failure too - try { - return await this.handleLegacyTransportRequest(request, parsedBody); - } finally { - this.legacyRunningRequestCount = Math.max(0, this.legacyRunningRequestCount - 1); - } - } - - /** - * Serve one authenticated modern request without entering the legacy - * sessionful streamable-HTTP transport. - */ - async serveModernMcp( - request: Request, - props: McpSessionProps, - parsedBody: unknown, - ): Promise { - this.modernRequestStateSigningKey(); - const verified = verifiedMcpRequestHeaders(request); - if ( - !verified || - verified.accountId !== props.session.userId || - verified.organizationId !== props.session.organizationId || - verified.resourceKey !== mcpResourceKey(props.session.resource) - ) { - return jsonRpcErrorBody(403, -32003, "Invalid MCP Durable Object identity", { - cors: false, - }); - } - const access = await this.startModernRuntime(props); - const sessionMeta = this.sessionMeta; - if ( - access.status === "forbidden" || - !sessionMeta || - !this.modernPropsOwnSession(sessionMeta, props) - ) { - return jsonRpcErrorBody(403, -32003, "MCP session does not belong to the current bearer", { - cors: false, - }); - } - - // Modern clients self-report identity per request (`_meta` clientInfo) or - // at `initialize`; persist it so meta-less requests and cold restores keep - // their span attribution. Best-effort by construction (persistClientInfo - // swallows failures) and a storage no-op unless the identity changed. - const reportedClientInfo = clientInfoFromRequestBody(parsedBody); - if (reportedClientInfo) { - await Effect.runPromise( - this.withTelemetry(this.persistClientInfo(reportedClientInfo), props.propagation), - ); - } - - this.modernRequestBodies.set(request, parsedBody); - this.modernRequestPropagation.set(request, props.propagation); - this.lastIncomingTrace = props.propagation; - this.modernRunningRequestCount += 1; - // oxlint-disable-next-line executor/no-try-catch-or-throw -- adapter boundary: the RPC must decrement its in-memory running lease on both handler resolution and rejection - try { - return await this.modernHandlerForRuntime().fetch(request, { parsedBody }); - } finally { - this.modernRunningRequestCount = Math.max(0, this.modernRunningRequestCount - 1); - } } async validateMcpSessionOwner( @@ -1462,13 +755,15 @@ export abstract class McpAgentSessionDOBase< Effect.gen(function* () { yield* self.prepareErrorCaptureScope(); // A DELETE-terminated session is condemned via `_cf_scheduleDestroy`, - // which writes a durable marker and defers the actual storage wipe to + // which writes a durable marker and defers the actual `destroy()` to // an alarm (~1s later). A request that races into that window still // sees the session's storage intact, so without this gate the session // would restore and answer — but the protocol contract is that a - // terminated id is dead the moment the DELETE returns. + // terminated id is dead the moment the DELETE returns. (The old code + // won this race by accident: its onConnect drain-wait stalled the + // request until the destroy alarm aborted the isolate.) const destroyPending = yield* Effect.promise(() => - self.ctx.storage.get(DESTROY_PENDING_KEY), + self.ctx.storage.get(AGENTS_DESTROY_PENDING_KEY), ); if (destroyPending === true) return "terminated" as const; const sessionMeta = yield* self.loadSessionMeta(); @@ -1622,17 +917,9 @@ export abstract class McpAgentSessionDOBase< ); } - /** Condemn this session and arm a fresh alarm invocation to wipe it. */ - async _cf_scheduleDestroy(): Promise { - await this.ctx.storage.put(DESTROY_PENDING_KEY, true); - await this.ctx.storage.setAlarm(Date.now() + DESTROY_ALARM_DELAY_MS); - } - - private async destroySession(): Promise { + override async destroy(): Promise { await this.cleanup(); - await this.ctx.storage.deleteAlarm(); - await this.ctx.storage.deleteAll(); - setTimeout(() => this.ctx.abort("destroyed"), 0); + await super.destroy(); } private async pausedExecutionCount(): Promise { @@ -1641,20 +928,14 @@ export abstract class McpAgentSessionDOBase< } override async alarm(): Promise { - if ((await this.ctx.storage.get(DESTROY_PENDING_KEY)) === true) { - await this.destroySession(); - return; - } - const sessionMeta = await Effect.runPromise(this.loadSessionMeta()); - if (!sessionMeta) { + if (!(await this.hasPartyServerName())) { await this.cleanupUnaddressableSessionAlarm(); return; } - const isModernSession = this.runtimeKind === "modern"; const lastActivityMs = await this.loadLastActivity(); const idleMs = lastActivityMs > 0 ? Date.now() - lastActivityMs : 0; const pausedExecutionCount = await this.pausedExecutionCount(); - const runningExecutionCount = this.runningExecutionCount(); + const runningExecutionCount = await this.runningExecutionCount(); const activeStreamCount = this.activeStreamCount(); const decision = decideSessionAlarm({ idleMs, @@ -1666,17 +947,15 @@ export abstract class McpAgentSessionDOBase< }); if (decision.kind === "idle_within_timeout") { - await this.ctx.storage.setAlarm(Date.now() + Math.max(1, this.sessionTimeoutMs() - idleMs)); + await super.alarm(); return; } - const ownerId = isModernSession ? this.modernExecutionOwnerRoute().sessionId : this.sessionId; - if (decision.kind === "extend_paused_lease") { console.info( JSON.stringify( pausedLeaseExtensionLog({ - sessionId: ownerId, + sessionId: this.sessionId, pausedExecutionCount, idleMs, leaseMs: decision.leaseMs, @@ -1691,7 +970,7 @@ export abstract class McpAgentSessionDOBase< console.info( JSON.stringify( runningLeaseExtensionLog({ - sessionId: ownerId, + sessionId: this.sessionId, runningExecutionCount, activeStreamCount, idleMs, @@ -1699,14 +978,15 @@ export abstract class McpAgentSessionDOBase< }), ), ); - // A direct streamed response represents work that can still deliver or - // replay a result. Cancellation, completion, and max-age rotation all - // decrement activeStreamCount, so dead streams stop extending the lease. + // Open streamable-HTTP bridges and persisted request ids represent work + // that can still deliver or replay a response. Buggy dead pipes are + // closed by the SSE writer's terminal failure path, so they stop + // extending the lease once the bridge observes the failure. await this.ctx.storage.setAlarm(Date.now() + decision.leaseMs); return; } - await this.disposeIdleRuntime({ idleMs, lastActivityMs, pausedExecutionCount }); + await this.disposeIdleRuntime({ idleMs, pausedExecutionCount }); } private validateApprovalIdentity( @@ -1750,7 +1030,6 @@ export abstract class McpAgentSessionDOBase< private writeExecutionOwnerEntry( executionId: string, deadline: PausedExecutionDeadline | undefined, - owner: McpExecutionOwnerRoute = this.executionOwnerRoute(), ): Effect.Effect { const directory = this.executionOwnerDirectory(); if (!directory || !deadline) return Effect.void; @@ -1760,7 +1039,7 @@ export abstract class McpAgentSessionDOBase< if (!sessionMeta) return; const record: McpExecutionOwnerRecord = { executionId, - owner, + owner: self.executionOwnerRoute(), accountId: sessionMeta.userId, organizationId: sessionMeta.organizationId, expiresAt: deadline.expiresAt, @@ -1803,7 +1082,6 @@ export abstract class McpAgentSessionDOBase< private resumeFromExecutionOwnerDirectory( executionId: string, response: ResumeResponse, - currentOwner: McpExecutionOwnerRoute = this.executionOwnerRoute(), ): Effect.Effect { const directory = this.executionOwnerDirectory(); if (!directory) return Effect.succeed(null); @@ -1830,7 +1108,7 @@ export abstract class McpAgentSessionDOBase< return { status: "execution_forbidden" } as const; } - if (self.sameExecutionOwnerRoute(record.owner, currentOwner)) { + if (self.sameExecutionOwnerRoute(record.owner, self.executionOwnerRoute())) { yield* self.deleteExecutionOwnerEntry(executionId); return { status: "execution_expired", ttlMs: record.ttlMs } as const; } @@ -1877,16 +1155,20 @@ export abstract class McpAgentSessionDOBase< private startPendingApprovalLease( executionId: string, deadline: PausedExecutionDeadline | undefined, - owner: McpExecutionOwnerRoute = this.executionOwnerRoute(), ): Effect.Effect { const self = this; return Effect.gen(function* () { yield* self.prepareErrorCaptureScope(); if (self.pendingApprovalLeases.has(executionId)) return; - // The base owns alarm arming now: record the in-memory lease first, then - // mark activity so the session alarm is durably scheduled for the idle / - // paused-expiry policy while this approval is outstanding. + // keepAlive BEFORE markActivity: acquiring the first keepAlive ref runs + // the SDK's _scheduleNextAlarm, which re-arms the DO alarm to its 30s + // heartbeat and would overwrite the idle alarm markActivity sets. With + // this ordering markActivity's setAlarm(now + sessionTimeoutMs) lands + // last, so the idle/paused-expiry clock keeps ticking while the lease + // holds the runtime alive. (Round 1 removed onConnect's drain-wait, + // which used to hold a ref across the pause and mask this by keeping + // the ref transition away from 0->1.) const disposeKeepAlive = yield* Effect.promise(() => self.keepAlive()); yield* Effect.promise(() => self.markActivity()).pipe( Effect.withSpan("McpSessionDO.markActivity"), @@ -1895,7 +1177,7 @@ export abstract class McpAgentSessionDOBase< self.queuePendingApprovalLeaseExpiration(executionId); }, PAUSED_APPROVAL_TIMEOUT_MS); self.pendingApprovalLeases.set(executionId, { disposeKeepAlive, timeout, expiring: false }); - yield* self.writeExecutionOwnerEntry(executionId, deadline, owner); + yield* self.writeExecutionOwnerEntry(executionId, deadline); }).pipe( Effect.withSpan("McpSessionDO.pending_approval_lease.start", { attributes: { "mcp.execution.id": executionId }, diff --git a/packages/hosts/cloudflare/src/mcp/agent-session-model-resume.test.ts b/packages/hosts/cloudflare/src/mcp/agent-session-model-resume.test.ts index 712b52eac1..3fa87cdc4c 100644 --- a/packages/hosts/cloudflare/src/mcp/agent-session-model-resume.test.ts +++ b/packages/hosts/cloudflare/src/mcp/agent-session-model-resume.test.ts @@ -1,6 +1,8 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest"; +import { afterEach, beforeEach, describe, expect, it } from "@effect/vitest"; +// oxlint-disable-next-line executor/no-vitest-import -- boundary: vi.mock must come from vitest itself for mock hoisting to resolve +import { vi } from "vitest"; import { Cause, Effect } from "effect"; -import { McpServer } from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { defaultMcpResource } from "@executor-js/host-mcp"; import { PAUSED_APPROVAL_TIMEOUT_MS, @@ -24,6 +26,7 @@ import { import { McpExecutionOwnerDirectoryDO, mcpExecutionOwnerDirectoryFromNamespace, + mcpSessionDurableObjectName, type McpExecutionOwnerDirectory, type McpExecutionOwnerDirectoryNamespace, type McpExecutionOwnerRecord, @@ -31,6 +34,40 @@ import { } from "./execution-owner-directory"; import { mcpSessionStub } from "./session-stub"; +vi.mock("agents/mcp", () => ({ + McpAgent: class { + protected readonly ctx: DurableObjectState; + + constructor(ctx: DurableObjectState) { + this.ctx = ctx; + } + + getSessionId(): string { + return this.ctx.id.toString(); + } + + keepAlive(): Promise<() => void> { + return Promise.resolve(() => undefined); + } + + getStreamRequestIds(): Promise { + return Promise.resolve([]); + } + + onConnect(): Promise { + return Promise.resolve(); + } + + alarm(): Promise { + return Promise.resolve(); + } + + destroy(): Promise { + return Promise.resolve(); + } + }, +})); + class FakeStorage implements DurableObjectStorage { private readonly values = new Map(); readonly sql = {} as DurableObjectStorage["sql"]; @@ -329,7 +366,7 @@ class HarnessSession extends McpAgentSessionDOBase } async storeSessionMeta(): Promise { - await this.fakeState.storage.put("executor:mcp:v2:session-meta", this.meta); + await this.fakeState.storage.put("session-meta", this.meta); } async startPause(executionId: string): Promise { @@ -393,6 +430,12 @@ const flushMicrotasks = async (): Promise => { await Promise.resolve(); }; +describe("mcpSessionDurableObjectName", () => { + it("uses the Agents streamable-http durable object name", () => { + expect(mcpSessionDurableObjectName("session_123")).toBe("streamable-http:session_123"); + }); +}); + describe("McpAgentSessionDOBase cross-session model resume", () => { beforeEach(() => { vi.useFakeTimers(); @@ -414,7 +457,7 @@ describe("McpAgentSessionDOBase cross-session model resume", () => { const requesterEngine = makeEngine(() => null); const sessions = new Map(); const sessionNamespace = { - idFromString: (id: string) => id, + idFromName: (name: string) => name, get: (id: string) => sessions.get(id), }; const forward = vi.fn( @@ -425,9 +468,11 @@ describe("McpAgentSessionDOBase cross-session model resume", () => { response: ResumeResponse, ) => Effect.promise(async () => { - const ownerSession = mcpSessionStub(sessionNamespace, owner.sessionId); - if (!ownerSession) return { status: "execution_expired" as const, ttlMs: 0 }; - return ownerSession.resumeExecutionForModel(executionId, identity, response); + return mcpSessionStub(sessionNamespace, owner.sessionId).resumeExecutionForModel( + executionId, + identity, + response, + ); }), ); @@ -442,7 +487,7 @@ describe("McpAgentSessionDOBase cross-session model resume", () => { directoryNamespace: namespace, forwardModelResumeToOwner: forward, }); - sessions.set("session-a", sessionA); + sessions.set(mcpSessionDurableObjectName("session-a"), sessionA); await sessionA.storeSessionMeta(); await sessionB.storeSessionMeta(); diff --git a/packages/hosts/cloudflare/src/mcp/agent-session-modern.test.ts b/packages/hosts/cloudflare/src/mcp/agent-session-modern.test.ts deleted file mode 100644 index fe13561e90..0000000000 --- a/packages/hosts/cloudflare/src/mcp/agent-session-modern.test.ts +++ /dev/null @@ -1,331 +0,0 @@ -import { describe, expect, it } from "@effect/vitest"; -import { Cause, Effect } from "effect"; - -import type { - ExecutionEngine, - ExecutionResult, - PausedExecution, - ResumeResponse, -} from "@executor-js/execution"; -import { defaultMcpResource } from "@executor-js/host-mcp"; -import { PAUSED_APPROVAL_TIMEOUT_MS } from "@executor-js/host-mcp/tool-server"; -import { buildMcpServer } from "@executor-js/host-mcp/tool-server"; -import { FormElicitation, ToolAddress } from "@executor-js/sdk"; - -import { - McpAgentSessionDOBase, - type BuiltMcpServer, - type BuiltModernMcpRuntime, - type McpSessionInit, - type McpSessionProps, - type ModernMcpServerRequestOptions, - type SessionMeta, -} from "./agent-session-durable-object"; -import { - modernMcpExecutionOwnerRoute, - type McpExecutionOwnerDirectory, - type McpExecutionOwnerRecord, - type McpExecutionOwnerRoute, -} from "./execution-owner-directory"; - -const REQUEST_STATE_KEY = "0123456789abcdef0123456789abcdef"; -const EXECUTION_ID = "exec-modern-pause"; - -class MemoryStorage { - private readonly values = new Map(); - alarm: number | undefined; - - async get(key: string): Promise { - return this.values.get(key) as T | undefined; - } - - async put(key: string, value: unknown): Promise { - this.values.set(key, value); - } - - async delete(key: string | readonly string[]): Promise { - if (typeof key === "string") { - this.values.delete(key); - return; - } - for (const entry of key) this.values.delete(entry); - } - - async list(options: { readonly prefix?: string } = {}): Promise> { - return new Map( - Array.from(this.values.entries()) - .filter(([key]) => !options.prefix || key.startsWith(options.prefix)) - .map(([key, value]) => [key, value as T]), - ); - } - - async setAlarm(time: number | Date): Promise { - this.alarm = typeof time === "number" ? time : time.getTime(); - } - - async deleteAlarm(): Promise { - this.alarm = undefined; - } -} - -class MemoryContext { - readonly storage = new MemoryStorage(); - readonly id = { - name: undefined, - toString: () => "modern-do-id", - }; - readonly waitUntilPromises: Promise[] = []; - - waitUntil(promise: Promise): void { - this.waitUntilPromises.push(promise); - } -} - -class MemoryDirectory implements McpExecutionOwnerDirectory { - readonly records = new Map(); - - put(record: McpExecutionOwnerRecord): Effect.Effect { - return Effect.sync(() => { - this.records.set(record.executionId, record); - }); - } - - get(executionId: string): Effect.Effect { - return Effect.sync(() => this.records.get(executionId) ?? null); - } - - delete(executionId: string): Effect.Effect { - return Effect.sync(() => { - this.records.delete(executionId); - }); - } -} - -type Harness = { - approvalResponses: Map; - approvalWaiters: Map; - beginPendingApprovalResume: (executionId: string) => Effect.Effect; - buildMcpServer: () => Effect.Effect; - buildModernMcpRuntime: () => Effect.Effect; - ctx: MemoryContext; - dbHandle: { readonly end: () => void } | null; - engine: ExecutionEngine | null; - executionOwnerDirectory: () => McpExecutionOwnerDirectory; - finishPendingApprovalResume: (executionId: string) => Effect.Effect; - initialized: boolean; - keepAlive: () => Promise<() => void>; - lastActivityMs: number; - modernHandler: null; - modernPausedExecutionHooks: { - readonly onExecutionPaused: ( - executionId: string, - deadline: { readonly expiresAt: string; readonly ttlMs: number } | undefined, - ) => Effect.Effect; - readonly onResumeStarted: (executionId: string) => Effect.Effect; - readonly onResumeSettled: (executionId: string) => Effect.Effect; - }; - modernRequestBodies: WeakMap; - modernRequestPropagation: WeakMap; - modernRequestStateSigningKey: () => string; - modernRunningRequestCount: number; - modernRuntime: BuiltModernMcpRuntime | null; - modernRuntimePromise: Promise | null; - onStartPromise: Promise | null; - openSessionDb: () => { readonly end: () => void }; - pendingApprovalLeases: Map; - resolveSessionMeta: (token: McpSessionInit) => Effect.Effect; - serveModernMcp: ( - request: Request, - props: McpSessionProps, - parsedBody: unknown, - ) => Promise; - server?: never; - sessionMeta: SessionMeta | null; - startPendingApprovalLease: ( - executionId: string, - deadline: { readonly expiresAt: string; readonly ttlMs: number } | undefined, - owner: McpExecutionOwnerRoute, - ) => Effect.Effect; -}; - -const makeEngine = (): { - readonly engine: ExecutionEngine; - readonly resumeCalls: ResumeResponse[]; -} => { - const paused = new Map(); - const resumeCalls: ResumeResponse[] = []; - const execution: PausedExecution = { - id: EXECUTION_ID, - elicitationContext: { - address: ToolAddress.make("tools.test.org.main.confirm"), - args: {}, - request: FormElicitation.make({ message: "Confirm?", requestedSchema: {} }), - }, - }; - const engine: ExecutionEngine = { - execute: () => Effect.succeed({ result: "unused" }), - executeWithPause: () => - Effect.sync(() => { - paused.set(execution.id, execution); - return { status: "paused" as const, execution }; - }), - resume: (executionId, response) => - Effect.sync((): ExecutionResult | null => { - if (!paused.delete(executionId)) return null; - resumeCalls.push(response); - return { status: "completed", result: { result: response.content?.approved } }; - }), - isExecutionSettled: () => Effect.succeed(false), - getPausedExecution: (executionId) => Effect.sync(() => paused.get(executionId) ?? null), - pausedExecutionCount: () => Effect.sync(() => paused.size), - hasPausedExecutions: () => Effect.sync(() => paused.size > 0), - getDescription: Effect.succeed("test engine"), - }; - return { engine, resumeCalls }; -}; - -const makeHarness = () => { - const ctx = new MemoryContext(); - const directory = new MemoryDirectory(); - const { engine, resumeCalls } = makeEngine(); - const session = Object.create(McpAgentSessionDOBase.prototype) as Harness; - session.ctx = ctx; - session.engine = null; - session.dbHandle = null; - session.sessionMeta = null; - session.modernRuntime = null; - session.modernRuntimePromise = null; - session.modernHandler = null; - session.modernRunningRequestCount = 0; - session.modernRequestBodies = new WeakMap(); - session.modernRequestPropagation = new WeakMap(); - session.initialized = false; - session.onStartPromise = null; - session.lastActivityMs = 0; - session.approvalResponses = new Map(); - session.approvalWaiters = new Map(); - session.pendingApprovalLeases = new Map(); - session.openSessionDb = () => ({ end: () => undefined }); - session.keepAlive = () => Promise.resolve(() => undefined); - session.executionOwnerDirectory = () => directory; - session.modernRequestStateSigningKey = () => REQUEST_STATE_KEY; - session.resolveSessionMeta = (token) => - Effect.succeed({ - organizationId: token.organizationId, - organizationName: "Test Org", - userId: token.userId, - resource: token.resource, - elicitationMode: token.elicitationMode, - artifactsEnabled: token.artifactsEnabled, - webOrigin: token.webOrigin, - }); - session.buildMcpServer = () => Effect.die("legacy build is not used by this harness"); - session.modernPausedExecutionHooks = { - onExecutionPaused: (executionId, deadline) => - session.startPendingApprovalLease( - executionId, - deadline, - modernMcpExecutionOwnerRoute(ctx.id.toString()), - ), - onResumeStarted: (executionId) => session.beginPendingApprovalResume(executionId), - onResumeSettled: (executionId) => session.finishPendingApprovalResume(executionId), - }; - session.buildModernMcpRuntime = () => - Effect.succeed({ - engine, - buildServer: (options: ModernMcpServerRequestOptions) => - buildMcpServer({ - engine, - elicitationMode: { mode: "native" }, - pausedExecutionHooks: session.modernPausedExecutionHooks, - pausedExecutionLeaseMs: PAUSED_APPROVAL_TIMEOUT_MS, - ...options, - }), - }); - return { session, directory, resumeCalls }; -}; - -const requestBody = (input?: { readonly requestState?: string }) => ({ - jsonrpc: "2.0", - id: input?.requestState ? 2 : 1, - method: "tools/call", - params: { - name: "execute", - arguments: { code: "await tools.test.confirm()" }, - ...(input?.requestState - ? { - requestState: input.requestState, - inputResponses: { - elicitation: { action: "accept", content: { approved: true } }, - }, - } - : {}), - _meta: { - "io.modelcontextprotocol/protocolVersion": "2026-07-28", - "io.modelcontextprotocol/clientCapabilities": { elicitation: { form: {} } }, - }, - }, -}); - -const requestFor = (body: ReturnType): Request => - new Request("https://executor.test/mcp", { - method: "POST", - headers: { - "content-type": "application/json", - "mcp-protocol-version": "2026-07-28", - "mcp-method": "tools/call", - "mcp-name": "execute", - "x-executor-mcp-account-id": "acct_1", - "x-executor-mcp-organization-id": "org_1", - "x-executor-mcp-resource-key": "default", - }, - body: JSON.stringify(body), - }); - -const isRecord = (value: unknown): value is Record => - typeof value === "object" && value !== null && !Array.isArray(value); - -const requestStateFromResponse = (value: unknown): string | null => { - if (!isRecord(value) || !isRecord(value.result)) return null; - return typeof value.result.requestState === "string" ? value.result.requestState : null; -}; - -describe("McpAgentSessionDOBase modern entry", () => { - it("serves a pause, registers modern ownership, and resumes in the same DO", async () => { - const { session, directory, resumeCalls } = makeHarness(); - const props: McpSessionProps = { - session: { - organizationId: "org_1", - userId: "acct_1", - elicitationMode: "native", - resource: defaultMcpResource, - webOrigin: "https://executor.test", - }, - }; - - const firstBody = requestBody(); - const first = await session.serveModernMcp(requestFor(firstBody), props, firstBody); - const firstPayload: unknown = await first.json(); - const requestState = requestStateFromResponse(firstPayload); - - expect(first.status).toBe(200); - expect(requestState).not.toBeNull(); - expect(directory.records.get(EXECUTION_ID)).toMatchObject({ - executionId: EXECUTION_ID, - owner: { sessionId: "modern:modern-do-id" }, - accountId: "acct_1", - organizationId: "org_1", - ttlMs: PAUSED_APPROVAL_TIMEOUT_MS, - }); - if (!requestState) return; - - const secondBody = requestBody({ requestState }); - const second = await session.serveModernMcp(requestFor(secondBody), props, secondBody); - const secondText = JSON.stringify(await second.json()); - - expect(second.status).toBe(200); - expect(secondText).toContain("true"); - expect(resumeCalls).toEqual([{ action: "accept", content: { approved: true } }]); - expect(directory.records.has(EXECUTION_ID)).toBe(false); - }); -}); diff --git a/packages/hosts/cloudflare/src/mcp/agents-event-store.test.ts b/packages/hosts/cloudflare/src/mcp/agents-event-store.test.ts new file mode 100644 index 0000000000..e97bbbbfe8 --- /dev/null +++ b/packages/hosts/cloudflare/src/mcp/agents-event-store.test.ts @@ -0,0 +1,176 @@ +// Unit coverage for the patched agents DurableObjectEventStore (see +// patches/agents@0.17.3.patch). The store is the durable half of the MCP +// result-replay fix: a final tool response persisted here is the only copy a +// recovery GET can replay after the client's POST response body died, so +// trimStream must never evict it. +import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest"; +import { DurableObjectEventStore } from "agents/mcp"; + +type ListOptions = { + readonly prefix?: string; + readonly start?: string; + readonly limit?: number; + readonly reverse?: boolean; +}; + +/** Minimal in-memory stand-in for DurableObjectStorage's sorted KV surface. */ +const makeFakeStorage = () => { + const entries = new Map(); + return { + entries, + put: (key: string, value: unknown) => { + entries.set(key, value); + return Promise.resolve(); + }, + delete: (keys: string | ReadonlyArray) => { + for (const key of Array.isArray(keys) ? keys : [keys]) entries.delete(key); + return Promise.resolve(); + }, + list: (options: ListOptions = {}) => { + const keys = [...entries.keys()] + .filter((key) => (options.prefix === undefined ? true : key.startsWith(options.prefix))) + .filter((key) => (options.start === undefined ? true : key >= options.start)) + .sort(); + if (options.reverse === true) keys.reverse(); + const limited = options.limit === undefined ? keys : keys.slice(0, options.limit); + return Promise.resolve(new Map(limited.map((key) => [key, entries.get(key)]))); + }, + }; +}; + +const makeStore = () => { + const storage = makeFakeStorage(); + // The store only touches put/list/delete; the fake covers exactly that. + const store = new DurableObjectEventStore(storage as never); + return { storage, store }; +}; + +const eventKeys = (storage: ReturnType): ReadonlyArray => + [...storage.entries.keys()].sort(); + +describe("DurableObjectEventStore trimStream", () => { + let warnings: string[] = []; + + beforeEach(() => { + warnings = []; + vi.spyOn(console, "warn").mockImplementation((line: string) => { + warnings.push(line); + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("skips storing a message beyond DO storage's per-value cap, returning no replay id", async () => { + // Real DO storage rejects any value over 128 KiB. This used to be + // discovered inside storage.put — thrown BEFORE the live SSE write, so an + // oversize response (the ~5MB ui:// shell document) was neither stored nor + // delivered and the client hung on keepalives. The pinned contract now: + // oversize messages skip persistence with a warning and resolve undefined, + // and the caller delivers them live without a replay id. + const { storage, store } = makeStore(); + const hugeResult = { + jsonrpc: "2.0" as const, + id: 1, + result: { content: [{ type: "text", text: "x".repeat(3 * 1024 * 1024) }] }, + }; + + const eventId = await store.storeEvent("post-stream", hugeResult); + + expect(eventId, "no replay id for an unstorable message").toBeUndefined(); + expect(eventKeys(storage), "nothing was persisted").toEqual([]); + expect(warnings.length, "the skip is logged").toBeGreaterThan(0); + expect(warnings.at(-1)).toContain("mcp_event_store_skipped_oversize"); + expect(warnings.at(-1)).toContain("post-stream"); + }); + + it("does not advance the stream sequence when an oversize message is skipped", async () => { + const { storage, store } = makeStore(); + await store.storeEvent("post-stream", { + jsonrpc: "2.0" as const, + method: "notifications/progress", + params: { blob: "x".repeat(3 * 1024 * 1024) }, + }); + + const eventId = await store.storeEvent("post-stream", { + jsonrpc: "2.0" as const, + id: 1, + result: { ok: true }, + }); + + expect(eventId, "the next storable event takes the first sequence slot").toBe( + "post-stream:0000000000000001", + ); + expect(eventKeys(storage)).toEqual(["__mcp_event__:post-stream:0000000000000001"]); + }); + + it("evicts oldest events at the byte cap but never the newest", async () => { + const { storage, store } = makeStore(); + // 100 KiB each: storable (under the 120 KiB per-value guard), but 25 of + // them exceed the 2 MB per-stream byte cap. + const bigMessage = (marker: string) => ({ + jsonrpc: "2.0" as const, + method: "notifications/progress", + params: { marker, blob: "y".repeat(100 * 1024) }, + }); + + const total = 25; + for (let index = 0; index < total; index += 1) { + await store.storeEvent("post-stream", bigMessage(`msg-${index}`)); + } + + const remaining = eventKeys(storage); + expect(remaining[remaining.length - 1], "the newest event is always retained").toBe( + `__mcp_event__:post-stream:${total.toString(16).padStart(16, "0")}`, + ); + expect( + remaining.length, + "older events were evicted to satisfy the 2MB stream cap", + ).toBeLessThan(total); + expect(warnings.length, "eviction logs a warning").toBeGreaterThan(0); + expect(warnings.at(-1)).toContain("mcp_event_store_evicted"); + expect(warnings.at(-1)).toContain("post-stream"); + }); + + it("evicts oldest events past the per-stream event-count cap", async () => { + const { storage, store } = makeStore(); + const total = 70; // MAX_EVENTS_PER_STREAM is 64 + for (let index = 0; index < total; index += 1) { + await store.storeEvent("chatty-stream", { + jsonrpc: "2.0" as const, + method: "notifications/progress", + params: { index }, + }); + } + + const remaining = eventKeys(storage); + expect(remaining.length, "stream is capped at 64 events").toBe(64); + expect(remaining[remaining.length - 1], "the newest event survives the count cap").toBe( + `__mcp_event__:chatty-stream:${total.toString(16).padStart(16, "0")}`, + ); + expect(remaining[0], "the oldest surviving event is the one just inside the cap").toBe( + `__mcp_event__:chatty-stream:${(total - 63).toString(16).padStart(16, "0")}`, + ); + }); + + it("leaves streams under both caps untouched", async () => { + const { storage, store } = makeStore(); + await store.storeEvent("quiet-stream", { + jsonrpc: "2.0" as const, + id: 1, + result: { ok: true }, + }); + await store.storeEvent("quiet-stream", { + jsonrpc: "2.0" as const, + id: 2, + result: { ok: true }, + }); + + expect(eventKeys(storage)).toEqual([ + "__mcp_event__:quiet-stream:0000000000000001", + "__mcp_event__:quiet-stream:0000000000000002", + ]); + expect(warnings).toEqual([]); + }); +}); diff --git a/packages/hosts/cloudflare/src/mcp/agents-priming-event.test.ts b/packages/hosts/cloudflare/src/mcp/agents-priming-event.test.ts new file mode 100644 index 0000000000..9edd16594c --- /dev/null +++ b/packages/hosts/cloudflare/src/mcp/agents-priming-event.test.ts @@ -0,0 +1,219 @@ +// Unit coverage for the POST-stream priming SSE event (see +// patches/agents@0.17.3.patch). Executor's POST tools/call stream used to emit +// its first and only event `id:` together with the final result, so the MCP TS +// SDK's StreamableHTTPClientTransport never set hasPrimingEvent and would not +// auto-reconnect a stream that dropped mid-call: callTool hung while the DO +// held the completed result. The patch writes a priming event as the first +// frame on the POST stream, carrying a real event-store id that sorts before +// the response so a `last-event-id: ` reconnect replays the result. +// +// Two properties are pinned here against real code: +// 1. Event-store ordering + replay: with the real DurableObjectEventStore, a +// priming event stored before the response sorts first, and +// replayEventsAfter(primingId) yields exactly the response. +// 2. Client contract: fed the exact priming frame the transport emits, the +// real SDK StreamableHTTPClientTransport records the priming id (so it +// would reconnect) WITHOUT dispatching it as a JSON-RPC message, then +// dispatches a following result frame normally. +import { describe, expect, it } from "@effect/vitest"; +import { DurableObjectEventStore } from "agents/mcp"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js"; + +type ListOptions = { + readonly prefix?: string; + readonly start?: string; + readonly limit?: number; + readonly reverse?: boolean; +}; + +/** Minimal in-memory stand-in for DurableObjectStorage's sorted KV surface. */ +const makeFakeStorage = () => { + const entries = new Map(); + return { + entries, + put: (key: string, value: unknown) => { + entries.set(key, value); + return Promise.resolve(); + }, + delete: (keys: string | ReadonlyArray) => { + for (const key of Array.isArray(keys) ? keys : [keys]) entries.delete(key); + return Promise.resolve(); + }, + list: (options: ListOptions = {}) => { + const keys = [...entries.keys()] + .filter((key) => (options.prefix === undefined ? true : key.startsWith(options.prefix))) + .filter((key) => (options.start === undefined ? true : key >= options.start)) + .sort(); + if (options.reverse === true) keys.reverse(); + const limited = options.limit === undefined ? keys : keys.slice(0, options.limit); + return Promise.resolve(new Map(limited.map((key) => [key, entries.get(key)]))); + }, + }; +}; + +// The exact priming notification the patched transport persists, and the exact +// SSE frame it writes to the client. Mirrors emitPrimingEvent / +// writePrimingSSEEvent in patches/agents@0.17.3.patch: a benign JSON-RPC +// notification stored (so a plain-GET replay via writeSSEEvent is ignorable), +// framed live under a non-`message` event type so the SDK primes but does not +// dispatch it. +const PRIMING_MESSAGE = { + jsonrpc: "2.0" as const, + method: "notifications/message", + params: { level: "debug", data: "mcp-stream-priming" }, +}; +const primingFrame = (eventId: string): string => + `event: mcp-priming\nid: ${eventId}\ndata: ${JSON.stringify(PRIMING_MESSAGE)}\n\n`; +const messageFrame = (eventId: string, message: unknown): string => + `event: message\nid: ${eventId}\ndata: ${JSON.stringify(message)}\n\n`; + +describe("POST-stream priming event: store ordering and replay", () => { + it("persists the priming event before the response so replayEventsAfter(primingId) yields the response", async () => { + const storage = makeFakeStorage(); + const store = new DurableObjectEventStore(storage as never); + const streamId = "post-stream"; + + // Transport order: priming event first, then the tool response. Both are + // tiny, so storeEvent always persists them and returns an id — the + // `undefined` arm of its signature is the oversize skip, pinned in + // agents-event-store.test.ts. + const primingId = await store.storeEvent(streamId, PRIMING_MESSAGE); + const response = { + jsonrpc: "2.0" as const, + id: 1, + result: { content: [{ type: "text", text: "MARKER" }] }, + }; + const responseId = await store.storeEvent(streamId, response); + + expect(primingId, "priming event is seq 1 for the stream").toBe(`${streamId}:0000000000000001`); + expect(responseId, "response is seq 2, after the priming id").toBe( + `${streamId}:0000000000000002`, + ); + expect( + (primingId ?? "") < (responseId ?? ""), + "priming id sorts strictly before the response id", + ).toBe(true); + + const replayed: Array<{ readonly eventId: string; readonly message: unknown }> = []; + await store.replayEventsAfter(primingId ?? "", { + send: async (eventId: string, message: unknown) => { + replayed.push({ eventId, message }); + }, + }); + + expect( + replayed.map((entry) => entry.eventId), + "a reconnect with last-event-id= replays exactly the response", + ).toEqual([responseId]); + expect(replayed[0]?.message).toEqual(response); + }); + + it("does not replay the priming event itself on a last-event-id reconnect", async () => { + const storage = makeFakeStorage(); + const store = new DurableObjectEventStore(storage as never); + const streamId = "post-stream"; + const primingId = await store.storeEvent(streamId, PRIMING_MESSAGE); + expect(primingId, "a tiny priming message always persists and gets an id").toBeDefined(); + + const replayed: string[] = []; + await store.replayEventsAfter(primingId ?? "", { + send: async (eventId: string) => { + replayed.push(eventId); + }, + }); + + expect(replayed, "nothing after the priming event yet, so replay is empty").toEqual([]); + }); +}); + +describe("POST-stream priming event: SDK client contract", () => { + // Drive the real SDK StreamableHTTPClientTransport with a controlled fetch + // that returns a POST tools/call SSE stream: priming frame first, then the + // result. Assert the SDK records the priming id as a resumption token (so it + // would reconnect) but only dispatches the result as a JSON-RPC message. + const drivePostStream = async (frames: ReadonlyArray) => { + const encoder = new TextEncoder(); + const body = new ReadableStream({ + start(controller) { + for (const frame of frames) controller.enqueue(encoder.encode(frame)); + controller.close(); + }, + }); + // oxlint-disable-next-line executor/no-double-cast -- boundary: a minimal fetch stub for a unit test; only the Response shape the SDK reads matters. + const fetchStub = (async () => + new Response(body, { + status: 200, + headers: { "content-type": "text/event-stream" }, + })) as unknown as typeof fetch; + + const transport = new StreamableHTTPClientTransport(new URL("https://executor.sh/mcp"), { + fetch: fetchStub, + }); + + const messages: JSONRPCMessage[] = []; + const resumptionTokens: string[] = []; + transport.onmessage = (message) => { + messages.push(message); + }; + + await transport.start(); + // POST a tools/call request; the stub returns the SSE stream above. + await transport.send( + { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "execute", arguments: {} } }, + { + onresumptiontoken: (token: string) => { + resumptionTokens.push(token); + }, + }, + ); + // Let the SSE stream drain. + for (let i = 0; i < 20; i += 1) await Promise.resolve(); + await transport.close(); + return { messages, resumptionTokens }; + }; + + it("records the priming id as a resumption token without dispatching it, then dispatches the result", async () => { + const primingId = "post-stream:0000000000000001"; + const responseId = "post-stream:0000000000000002"; + const result = { + jsonrpc: "2.0" as const, + id: 1, + result: { content: [{ type: "text", text: "MARKER" }] }, + }; + + const { messages, resumptionTokens } = await drivePostStream([ + primingFrame(primingId), + messageFrame(responseId, result), + ]); + + expect( + resumptionTokens, + "the SDK records the priming id first (this is what sets hasPrimingEvent), then the response id", + ).toEqual([primingId, responseId]); + expect( + messages, + "the priming frame is NOT dispatched as a JSON-RPC message; only the result is", + ).toEqual([result]); + }); + + it("would not prime on a stream whose first event id arrives only with the result (the old behavior)", async () => { + // Sanity anchor for the fix: without a priming frame, the first recorded + // resumption token is the result's own id, which the SDK only sees at the + // same instant it receives the result. There is no earlier id to reconnect + // from, which is exactly the hang this patch removes. + const responseId = "post-stream:0000000000000001"; + const result = { + jsonrpc: "2.0" as const, + id: 1, + result: { content: [{ type: "text", text: "MARKER" }] }, + }; + + const { messages, resumptionTokens } = await drivePostStream([ + messageFrame(responseId, result), + ]); + + expect(resumptionTokens, "the only id ever seen is the result's own id").toEqual([responseId]); + expect(messages).toEqual([result]); + }); +}); diff --git a/packages/hosts/cloudflare/src/mcp/agents-sse-max-age.test.ts b/packages/hosts/cloudflare/src/mcp/agents-sse-max-age.test.ts new file mode 100644 index 0000000000..5a603b47bf --- /dev/null +++ b/packages/hosts/cloudflare/src/mcp/agents-sse-max-age.test.ts @@ -0,0 +1,570 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest"; +import { MAX_SSE_AGE_MS, McpAgent } from "agents/mcp"; +import { Effect, Option, Schema } from "effect"; + +import { SESSION_TIMEOUT_MS } from "./session-alarm-policy"; + +const KEEPALIVE_INTERVAL_MS = 25_000; +const MAX_PENDING_SSE_BYTES = 8 * 1024 * 1024; + +type FakeWebSocket = EventTarget & { + accepted: boolean; + closeCode: number | undefined; + closeReason: string | undefined; + sent: string[]; + accept: () => void; + close: (code?: number, reason?: string) => void; + send: (message: string) => void; +}; + +type FakeAgentStub = { + readonly setName: (name: string, props?: unknown) => Promise; + readonly getInitializeRequest: () => Promise; + readonly fetch: (request: Request) => Promise<{ readonly webSocket: FakeWebSocket }>; +}; + +type RotationLog = { + readonly event: "sse_max_age_close"; + readonly sessionId: string; + readonly variant: "streamable-get" | "streamable-post" | "legacy-sse"; + readonly ageMs: number; + readonly pendingBytes: number; +}; + +const encoder = new TextEncoder(); +const RotationLogEvent = Schema.Struct({ + ageMs: Schema.Number, + event: Schema.Literal("sse_max_age_close"), + pendingBytes: Schema.Number, + sessionId: Schema.String, + variant: Schema.Union([ + Schema.Literal("streamable-get"), + Schema.Literal("streamable-post"), + Schema.Literal("legacy-sse"), + ]), +}); +const DeliveryAck = Schema.Struct({ + streamId: Schema.String, + type: Schema.Literal("cf_mcp_delivery_ack"), +}); +const decodeRotationLogEvent = Schema.decodeUnknownOption(Schema.fromJsonString(RotationLogEvent)); +const decodeDeliveryAck = Schema.decodeUnknownOption(Schema.fromJsonString(DeliveryAck)); +const deliveryAcks = (sent: ReadonlyArray): ReadonlyArray => + sent.flatMap((line) => { + const decoded = decodeDeliveryAck(line); + return Option.isSome(decoded) ? [decoded.value.streamId] : []; + }); + +const flushMicrotasks = async (): Promise => { + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); +}; + +const waitFor = async (predicate: () => boolean): Promise => { + for (let attempt = 0; attempt < 20; attempt += 1) { + if (predicate()) return; + await flushMicrotasks(); + } + expect(predicate()).toBe(true); +}; + +const drainResponse = async (response: Response): Promise => { + const decoder = new TextDecoder(); + let body = ""; + + await Effect.runPromise( + Effect.ignore( + Effect.tryPromise({ + try: () => + response.body?.pipeTo( + new WritableStream({ + close: () => { + body += decoder.decode(); + }, + write: (chunk) => { + body += decoder.decode(chunk, { stream: true }); + }, + }), + ) ?? Promise.resolve(), + catch: () => undefined, + }), + ), + ); + + return body; +}; + +const installStallingTransformStream = () => { + let abortReason: unknown; + let writeCount = 0; + let stalledWriteStarted: (() => void) | undefined; + const stalledWrite = new Promise((resolve) => { + stalledWriteStarted = resolve; + }); + const writer = { + abort: (reason: unknown) => { + abortReason = reason; + return Promise.resolve(); + }, + close: () => Promise.resolve(), + write: () => { + writeCount += 1; + stalledWriteStarted?.(); + return new Promise(() => {}); + }, + }; + + vi.stubGlobal( + "TransformStream", + class { + readonly readable = new ReadableStream(); + readonly writable = { + getWriter: () => writer, + }; + }, + ); + + return { + abortReason: () => abortReason, + stalledWrite, + writeCount: () => writeCount, + }; +}; + +const installRejectingTransformStream = () => { + let abortReason: unknown; + let writeCount = 0; + const writer = { + abort: (reason: unknown) => { + abortReason = reason; + return Promise.resolve(); + }, + close: () => Promise.resolve(), + write: () => { + writeCount += 1; + // oxlint-disable-next-line executor/no-promise-reject, executor/no-error-constructor -- boundary: fake writer models WHATWG stream write rejection in a unit test. + return Promise.reject(new Error("client disconnected")); + }, + }; + + vi.stubGlobal( + "TransformStream", + class { + readonly readable = new ReadableStream(); + readonly writable = { + getWriter: () => writer, + }; + }, + ); + + return { + abortReason: () => abortReason, + writeCount: () => writeCount, + }; +}; + +const installClosedRejectingTransformStream = () => { + let abortReason: unknown; + let rejectClosed: ((error: Error) => void) | undefined; + const closed = new Promise((_, reject) => { + rejectClosed = reject; + }); + const writer = { + abort: (reason: unknown) => { + abortReason = reason; + return Promise.resolve(); + }, + close: () => Promise.resolve(), + closed, + write: () => Promise.resolve(), + }; + + vi.stubGlobal( + "TransformStream", + class { + readonly readable = new ReadableStream(); + readonly writable = { + getWriter: () => writer, + }; + }, + ); + + return { + abortReason: () => abortReason, + // oxlint-disable-next-line executor/no-error-constructor -- boundary: fake writer models WHATWG writer.closed rejection in a unit test. + rejectClosed: () => rejectClosed?.(new Error("client canceled response body")), + }; +}; + +const makeExecutionContext = (): ExecutionContext => ({ + passThroughOnException: () => {}, + props: undefined, + waitUntil: () => {}, +}); + +const makeWebSocket = (): FakeWebSocket => { + const ws = new EventTarget() as FakeWebSocket; + ws.accepted = false; + ws.closeCode = undefined; + ws.closeReason = undefined; + ws.sent = []; + ws.accept = () => { + ws.accepted = true; + }; + ws.close = (code?: number, reason?: string) => { + ws.closeCode = code; + ws.closeReason = reason; + }; + ws.send = (message: string) => { + ws.sent.push(message); + }; + return ws; +}; + +const makeAgentStub = (ws: FakeWebSocket): FakeAgentStub => ({ + setName: async () => {}, + getInitializeRequest: async () => ({}), + fetch: async () => ({ webSocket: ws }), +}); + +const makeNamespace = (agent: FakeAgentStub) => ({ + newUniqueId: () => ({ toString: () => "generated-session" }), + idFromName: (name: string) => ({ + equals: () => true, + name, + toString: () => name, + }), + get: () => agent, +}); + +const openSse = async () => { + const ws = makeWebSocket(); + const agent = makeAgentStub(ws); + const namespace = makeNamespace(agent); + const handler = McpAgent.serve("/mcp", { + binding: "MCP_SESSION", + transport: "streamable-http", + }); + const response = await handler.fetch( + new Request("https://executor.sh/mcp", { + headers: { + accept: "text/event-stream", + "mcp-session-id": "session-1", + }, + method: "GET", + }), + { MCP_SESSION: namespace }, + makeExecutionContext(), + ); + + expect(response.status).toBe(200); + expect(ws.accepted).toBe(true); + expect(response.body).toBeDefined(); + + return { response, ws }; +}; + +const openPostSse = async () => { + const ws = makeWebSocket(); + const agent = makeAgentStub(ws); + const namespace = makeNamespace(agent); + const handler = McpAgent.serve("/mcp", { + binding: "MCP_SESSION", + transport: "streamable-http", + }); + const response = await handler.fetch( + new Request("https://executor.sh/mcp", { + body: JSON.stringify({ + id: 1, + jsonrpc: "2.0", + method: "tools/call", + params: { + arguments: {}, + name: "example", + }, + }), + headers: { + accept: "application/json, text/event-stream", + "content-type": "application/json", + "mcp-session-id": "session-1", + }, + method: "POST", + }), + { MCP_SESSION: namespace }, + makeExecutionContext(), + ); + + expect(response.status).toBe(200); + expect(ws.accepted).toBe(true); + expect(response.body).toBeDefined(); + + return { response, ws }; +}; + +const emitAgentEvent = ( + ws: FakeWebSocket, + event: string, + close?: true, + extra?: Record, +): void => { + ws.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + close, + event, + type: "cf_mcp_agent_event", + ...extra, + }), + }), + ); +}; + +const emitClose = (ws: FakeWebSocket): void => { + ws.dispatchEvent(new Event("close")); +}; + +const rotationLogs = (logs: ReadonlyArray): ReadonlyArray => + logs.flatMap((line) => { + const decoded = decodeRotationLogEvent(line); + return Option.isSome(decoded) ? [decoded.value] : []; + }); + +describe("agents SSE max-age rotation", () => { + let errorLogs: string[] = []; + let infoLogs: string[] = []; + + beforeEach(() => { + errorLogs = []; + infoLogs = []; + vi.useFakeTimers(); + vi.setSystemTime(0); + vi.spyOn(console, "error").mockImplementation((line) => { + errorLogs.push(String(line)); + }); + vi.spyOn(console, "log").mockImplementation((line) => { + infoLogs.push(String(line)); + }); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + it("keeps the default max age well above the session idle timeout", () => { + expect(MAX_SSE_AGE_MS).toBe(30 * 60 * 1000); + expect(MAX_SSE_AGE_MS).toBeGreaterThanOrEqual(6 * SESSION_TIMEOUT_MS); + }); + + it("closes a healthy draining SSE connection within one keepalive tick after max age", async () => { + const { response, ws } = await openSse(); + const drained = drainResponse(response); + + await vi.advanceTimersByTimeAsync(MAX_SSE_AGE_MS + KEEPALIVE_INTERVAL_MS); + await waitFor(() => ws.closeCode === 1000); + + expect(ws.closeReason).toBe("sse_max_age_rotation"); + const [rotationLog] = rotationLogs(infoLogs); + expect(rotationLog?.event).toBe("sse_max_age_close"); + expect(rotationLog?.ageMs).toBeGreaterThan(MAX_SSE_AGE_MS); + expect(rotationLog?.ageMs).toBeLessThanOrEqual(MAX_SSE_AGE_MS + KEEPALIVE_INTERVAL_MS); + expect(rotationLog?.pendingBytes).toBeGreaterThanOrEqual(0); + expect(errorLogs).toEqual([]); + expect(vi.getTimerCount()).toBe(0); + + await expect(drained).resolves.toContain(": max-age rotation, reconnect\n\n"); + }); + + it("does not rotate an in-flight POST response past max age", async () => { + const { response, ws } = await openPostSse(); + const drained = drainResponse(response); + + emitAgentEvent(ws, `event: message\ndata: {"jsonrpc":"2.0","id":1,"result":{}}\n\n`); + await vi.advanceTimersByTimeAsync(MAX_SSE_AGE_MS + KEEPALIVE_INTERVAL_MS * 4); + await flushMicrotasks(); + + expect(ws.closeCode).toBeUndefined(); + expect(ws.closeReason).toBeUndefined(); + expect(rotationLogs(infoLogs)).toEqual([]); + + emitAgentEvent( + ws, + `event: message\ndata: {"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n\n`, + true, + ); + await drained; + + expect(ws.closeCode).toBe(1000); + expect(ws.closeReason).toBe("SSE response delivered"); + expect(vi.getTimerCount()).toBe(0); + }); + + it("never acknowledges a POST response delivery, even after a clean drain", async () => { + // workerd resolves writer.close() even when the client canceled the POST + // response body, so a clean close is not proof of delivery. The bridge must + // NOT send cf_mcp_delivery_ack for POST streams: the DO keeps the response + // persisted and the client's reconnect GET replays and acks it instead. + const { response, ws } = await openPostSse(); + const drained = drainResponse(response); + + emitAgentEvent( + ws, + `event: message\nid: post-stream:0000000000000001\ndata: {"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n\n`, + true, + { + eventId: "post-stream:0000000000000001", + streamId: "post-stream", + }, + ); + await drained; + + expect(ws.closeCode).toBe(1000); + expect(ws.closeReason).toBe("SSE response delivered"); + expect(ws.sent).toEqual([]); + }); + + it("treats an SSE writer rejection as terminal and does not acknowledge delivery", async () => { + const transform = installRejectingTransformStream(); + const { ws } = await openPostSse(); + + emitAgentEvent( + ws, + `event: message\nid: post-stream:0000000000000001\ndata: {"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n\n`, + true, + { + eventId: "post-stream:0000000000000001", + streamId: "post-stream", + }, + ); + await waitFor(() => ws.closeCode === 1013); + + expect(transform.writeCount()).toBe(1); + expect(transform.abortReason()).toBeInstanceOf(Error); + expect(ws.closeReason).toBe("SSE client not draining"); + expect(ws.sent).toEqual([]); + expect(vi.getTimerCount()).toBe(0); + }); + + it("does not acknowledge a final POST response after the response body was canceled", async () => { + const transform = installClosedRejectingTransformStream(); + const { ws } = await openPostSse(); + + transform.rejectClosed(); + await flushMicrotasks(); + + emitAgentEvent( + ws, + `event: message\nid: post-stream:0000000000000001\ndata: {"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n\n`, + true, + { + eventId: "post-stream:0000000000000001", + streamId: "post-stream", + }, + ); + await flushMicrotasks(); + + expect(transform.abortReason()).toBeInstanceOf(Error); + expect(ws.closeCode).toBeUndefined(); + expect(ws.sent).toEqual([]); + expect(vi.getTimerCount()).toBe(0); + }); + + it("acks each replayed stream only after the recovery GET drained and closed", async () => { + // The replay path never clears storage on enqueue: the transport sends a + // replay-complete close frame and the bridge echoes one delivery ack per + // replayed stream only once writer.close() resolved with the client still + // attached. McpAgent.onMessage clears storage on those acks. + const { response, ws } = await openSse(); + const drained = drainResponse(response); + + emitAgentEvent( + ws, + `event: message\nid: stream-a:0000000000000001\ndata: {"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n\n`, + ); + emitAgentEvent(ws, ": replay-complete\n\n", true, { + ackStreamIds: ["stream-a", "stream-b"], + }); + await drained; + + expect(ws.closeCode).toBe(1000); + expect(ws.closeReason).toBe("SSE response delivered"); + expect(deliveryAcks(ws.sent), "one ack per replayed stream").toEqual(["stream-a", "stream-b"]); + }); + + it("does not ack replayed streams when the recovery GET body was canceled", async () => { + // A recovery GET can itself be a dead pipe (workerd surfaces nothing at + // write time). The bridge must not ack in that case, so the responses stay + // persisted and replayable for the next reconnect. + const transform = installClosedRejectingTransformStream(); + const { ws } = await openSse(); + + transform.rejectClosed(); + await flushMicrotasks(); + + emitAgentEvent( + ws, + `event: message\nid: stream-a:0000000000000001\ndata: {"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n\n`, + ); + emitAgentEvent(ws, ": replay-complete\n\n", true, { + ackStreamIds: ["stream-a"], + }); + await flushMicrotasks(); + + expect(transform.abortReason()).toBeInstanceOf(Error); + expect(deliveryAcks(ws.sent), "no acks for a dead recovery GET").toEqual([]); + expect(vi.getTimerCount()).toBe(0); + }); + + it("leaves an SSE connection younger than max age untouched", async () => { + const { response, ws } = await openSse(); + const drained = drainResponse(response); + + await vi.advanceTimersByTimeAsync(MAX_SSE_AGE_MS - KEEPALIVE_INTERVAL_MS * 2); + await flushMicrotasks(); + + expect(ws.closeCode).toBeUndefined(); + expect(rotationLogs(infoLogs)).toEqual([]); + + emitClose(ws); + await drained; + expect(vi.getTimerCount()).toBe(0); + }); + + it("still closes a stalled SSE writer at the byte cap without logging rotation", async () => { + const stalledFrame = `event: message\ndata: ${"x".repeat(2 * 1024 * 1024)}\n\n`; + const transform = installStallingTransformStream(); + const { ws } = await openSse(); + + emitAgentEvent(ws, stalledFrame); + await transform.stalledWrite; + expect(transform.writeCount()).toBe(1); + + const stalledFrameBytes = encoder.encode(stalledFrame).byteLength; + expect(stalledFrameBytes).toBeLessThan(MAX_PENDING_SSE_BYTES); + + for (let attempt = 0; attempt < 8 && ws.closeCode === undefined; attempt += 1) { + emitAgentEvent(ws, stalledFrame); + } + + expect(ws.closeCode).toBe(1013); + expect(ws.closeReason).toBe("SSE client not draining"); + expect(transform.abortReason()).toBeInstanceOf(Error); + expect(rotationLogs(infoLogs)).toEqual([]); + expect(vi.getTimerCount()).toBe(0); + }); + + it("cleans up timers when the client closes before max age", async () => { + const { response, ws } = await openSse(); + const drained = drainResponse(response); + + await vi.advanceTimersByTimeAsync(KEEPALIVE_INTERVAL_MS); + emitClose(ws); + await drained; + + expect(ws.closeCode).toBeUndefined(); + expect(rotationLogs(infoLogs)).toEqual([]); + expect(vi.getTimerCount()).toBe(0); + }); +}); diff --git a/packages/hosts/cloudflare/src/mcp/do-event-store.test.ts b/packages/hosts/cloudflare/src/mcp/do-event-store.test.ts deleted file mode 100644 index 938e9e12e5..0000000000 --- a/packages/hosts/cloudflare/src/mcp/do-event-store.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest"; - -import { DurableObjectMcpEventStore } from "./do-event-store"; - -type ListOptions = { - readonly prefix?: string; - readonly start?: string; - readonly startAfter?: string; - readonly limit?: number; - readonly reverse?: boolean; -}; - -const makeFakeStorage = () => { - const entries = new Map(); - let failWrites = false; - return { - entries, - failWrites: () => { - failWrites = true; - }, - put: async (key: string, value: unknown) => { - if (failWrites) { - // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- test boundary: simulate the Promise-based Durable Object storage API rejecting - throw new Error("storage unavailable"); - } - entries.set(key, value); - }, - delete: (keys: string | ReadonlyArray) => { - for (const key of Array.isArray(keys) ? keys : [keys]) entries.delete(key); - return Promise.resolve(true); - }, - list: (options: ListOptions = {}) => { - const keys = [...entries.keys()] - .filter((key) => (options.prefix === undefined ? true : key.startsWith(options.prefix))) - .filter((key) => (options.start === undefined ? true : key >= options.start)) - .filter((key) => (options.startAfter === undefined ? true : key > options.startAfter)) - .sort(); - if (options.reverse === true) keys.reverse(); - const limited = options.limit === undefined ? keys : keys.slice(0, options.limit); - return Promise.resolve(new Map(limited.map((key) => [key, entries.get(key)]))); - }, - }; -}; - -const makeStore = () => { - const storage = makeFakeStorage(); - const store = new DurableObjectMcpEventStore(storage as never); - return { storage, store }; -}; - -const eventKeys = (storage: ReturnType): ReadonlyArray => - [...storage.entries.keys()].sort(); - -describe("DurableObjectMcpEventStore", () => { - let warnings: string[] = []; - - beforeEach(() => { - warnings = []; - vi.spyOn(console, "warn").mockImplementation((line: string) => { - warnings.push(line); - }); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it("leaves an oversize event live-only without touching Durable Object storage", async () => { - const { storage, store } = makeStore(); - const eventId = await store.storeEvent("post-stream", { - jsonrpc: "2.0", - id: 1, - result: { content: [{ type: "text", text: "x".repeat(3 * 1024 * 1024) }] }, - }); - - expect(eventId).toBe("post-stream:0000000000000001"); - expect(eventKeys(storage)).toEqual([]); - expect(warnings.at(-1)).toContain("mcp_event_store_skipped_oversize"); - }); - - it("does not reject the send path when Durable Object storage fails", async () => { - const { storage, store } = makeStore(); - storage.failWrites(); - - await expect( - store.storeEvent("post-stream", { jsonrpc: "2.0", id: 1, result: { ok: true } }), - ).resolves.toBe("post-stream:0000000000000001"); - expect(warnings.at(-1)).toContain("mcp_event_store_put_failed"); - }); - - it("replays stored events strictly after the client's last event", async () => { - const { store } = makeStore(); - const first = await store.storeEvent("post-stream", { - jsonrpc: "2.0", - method: "notifications/progress", - params: { progress: 1 }, - }); - const second = await store.storeEvent("post-stream", { - jsonrpc: "2.0", - id: 1, - result: { ok: true }, - }); - const replayed: string[] = []; - - const streamId = await store.replayEventsAfter(first, { - send: (eventId) => { - replayed.push(eventId); - return Promise.resolve(); - }, - }); - - expect(streamId).toBe("post-stream"); - expect(replayed).toEqual([second]); - }); - - it("replays a marked POST stream on standalone recovery and clears it after acknowledgement", async () => { - const { storage, store } = makeStore(); - await store.markStreamUndelivered("post-stream"); - const prime = await store.storeEvent("post-stream", { - jsonrpc: "2.0", - method: "notifications/message", - params: { level: "debug", data: "prime" }, - }); - const result = await store.storeEvent("post-stream", { - jsonrpc: "2.0", - id: "call-1", - result: { content: [{ type: "text", text: "completed" }] }, - }); - const replayed: string[] = []; - - const streamIds = await store.replayUndeliveredStreams({ - send: (eventId) => { - replayed.push(eventId); - return Promise.resolve(); - }, - }); - - expect(streamIds).toEqual(["post-stream"]); - expect(replayed).toEqual([prime, result]); - - await store.acknowledgeUndeliveredStreams(streamIds); - await expect( - store.replayUndeliveredStreams({ send: () => Promise.resolve() }), - ).resolves.toEqual([]); - expect(eventKeys(storage)).toEqual([]); - }); - - it("evicts oldest events at the byte cap but never the newest", async () => { - const { storage, store } = makeStore(); - const bigMessage = (marker: string) => ({ - jsonrpc: "2.0" as const, - method: "notifications/progress", - params: { marker, blob: "y".repeat(100 * 1024) }, - }); - - const total = 25; - for (let index = 0; index < total; index += 1) { - await store.storeEvent("post-stream", bigMessage(`msg-${index}`)); - } - - const remaining = eventKeys(storage); - expect(remaining.at(-1)).toBe( - `executor:mcp:v2:event:post-stream:${total.toString(16).padStart(16, "0")}`, - ); - expect(remaining.length).toBeLessThan(total); - expect(warnings.at(-1)).toContain("mcp_event_store_evicted"); - }); - - it("retains only the newest 64 events from a chatty stream", async () => { - const { storage, store } = makeStore(); - const total = 70; - for (let index = 0; index < total; index += 1) { - await store.storeEvent("chatty-stream", { - jsonrpc: "2.0", - method: "notifications/progress", - params: { progress: index }, - }); - } - - const remaining = eventKeys(storage); - expect(remaining).toHaveLength(64); - expect(remaining[0]).toBe( - `executor:mcp:v2:event:chatty-stream:${(total - 63).toString(16).padStart(16, "0")}`, - ); - expect(remaining.at(-1)).toBe( - `executor:mcp:v2:event:chatty-stream:${total.toString(16).padStart(16, "0")}`, - ); - }); -}); diff --git a/packages/hosts/cloudflare/src/mcp/do-event-store.ts b/packages/hosts/cloudflare/src/mcp/do-event-store.ts deleted file mode 100644 index 7a9a0a7dd4..0000000000 --- a/packages/hosts/cloudflare/src/mcp/do-event-store.ts +++ /dev/null @@ -1,304 +0,0 @@ -import type { EventId, EventStore, JSONRPCMessage, StreamId } from "@modelcontextprotocol/server"; - -const EVENT_KEY_PREFIX = "executor:mcp:v2:event:"; -const UNDELIVERED_STREAM_KEY_PREFIX = "executor:mcp:v2:undelivered-stream:"; -const SEQUENCE_WIDTH = 16; -const REPLAY_LIMIT = 1_000; -const DELETE_CHUNK_SIZE = 128; - -/** Maximum number of replayable events retained for one SDK response stream. */ -export const MAX_EVENTS_PER_MCP_STREAM = 64; - -/** Maximum approximate JSON bytes retained for one SDK response stream. */ -export const MAX_BYTES_PER_MCP_STREAM = 2 * 1024 * 1024; - -/** - * Conservative payload ceiling below Durable Object storage's 128 KiB - * per-value limit. Larger events remain live-deliverable but are not persisted. - */ -export const MAX_STORABLE_MCP_EVENT_BYTES = 120 * 1024; - -type McpEventStorage = Pick; - -type StoredEntry = { - readonly key: string; - readonly bytes: number; -}; - -const eventPrefix = (streamId: StreamId): string => `${EVENT_KEY_PREFIX}${streamId}:`; - -const undeliveredStreamKey = (streamId: StreamId): string => - `${UNDELIVERED_STREAM_KEY_PREFIX}${streamId}`; - -const eventIdFromKey = (key: string): EventId => key.slice(EVENT_KEY_PREFIX.length); - -const streamIdFromEventId = (eventId: EventId): StreamId | undefined => { - const separator = eventId.lastIndexOf(":"); - return separator > 0 ? eventId.slice(0, separator) : undefined; -}; - -const messageBytes = (message: JSONRPCMessage): number | null => { - // oxlint-disable-next-line executor/no-try-catch-or-throw -- serialization boundary: an unstringifiable SDK payload is live-only - try { - return new TextEncoder().encode(JSON.stringify(message)).byteLength; - } catch { - return null; - } -}; - -const logStoreWarning = (event: string, fields: Record): void => { - console.warn(JSON.stringify({ event, ...fields })); -}; - -/** - * MCP replay storage backed by one session Durable Object's KV store. - * - * Writes are deliberately best-effort: storage limits or outages never escape - * into the transport's send path. Every call still returns a monotonic event - * ID so the SDK can deliver the message live; an event whose persistence failed - * simply has no replayable payload behind that ID. - */ -export class DurableObjectMcpEventStore implements EventStore { - private readonly sequenceByStream = new Map(); - private readonly sequenceLoads = new Map>(); - - constructor(private readonly storage: McpEventStorage) {} - - private async ensureSequenceLoaded(streamId: StreamId): Promise { - if (this.sequenceByStream.has(streamId)) return; - const existing = this.sequenceLoads.get(streamId); - if (existing) return existing; - - const loading = (async () => { - let sequence = 0; - // oxlint-disable-next-line executor/no-try-catch-or-throw -- storage boundary: sequence recovery is best-effort and falls back to this isolate's monotonic counter - try { - const rows = await this.storage.list({ - prefix: eventPrefix(streamId), - reverse: true, - limit: 1, - }); - const newestKey = rows.keys().next().value; - if (typeof newestKey === "string") { - const encoded = newestKey.slice(eventPrefix(streamId).length); - const parsed = Number.parseInt(encoded, 16); - if (Number.isSafeInteger(parsed) && parsed >= 0) sequence = parsed; - } - } catch { - logStoreWarning("mcp_event_store_list_failed", { - operation: "load_sequence", - streamId, - }); - } - this.sequenceByStream.set(streamId, sequence); - })(); - this.sequenceLoads.set(streamId, loading); - await loading; - this.sequenceLoads.delete(streamId); - } - - private nextEventId(streamId: StreamId): EventId { - const sequence = (this.sequenceByStream.get(streamId) ?? 0) + 1; - this.sequenceByStream.set(streamId, sequence); - return `${streamId}:${sequence.toString(16).padStart(SEQUENCE_WIDTH, "0")}`; - } - - private async trimStream(streamId: StreamId): Promise { - const rows = await this.storage.list({ - prefix: eventPrefix(streamId), - limit: REPLAY_LIMIT, - }); - let totalBytes = 0; - const entries: StoredEntry[] = Array.from(rows, ([key, message]) => { - const bytes = messageBytes(message) ?? MAX_BYTES_PER_MCP_STREAM; - totalBytes += bytes; - return { key, bytes }; - }); - const deleteKeys: string[] = []; - - while ( - entries.length > 1 && - (entries.length > MAX_EVENTS_PER_MCP_STREAM || totalBytes > MAX_BYTES_PER_MCP_STREAM) - ) { - const evicted = entries.shift(); - if (!evicted) break; - deleteKeys.push(evicted.key); - totalBytes -= evicted.bytes; - } - - if (deleteKeys.length === 0) return; - logStoreWarning("mcp_event_store_evicted", { - streamId, - evictedCount: deleteKeys.length, - remainingCount: entries.length, - remainingBytes: totalBytes, - }); - for (let index = 0; index < deleteKeys.length; index += DELETE_CHUNK_SIZE) { - await this.storage.delete(deleteKeys.slice(index, index + DELETE_CHUNK_SIZE)); - } - } - - /** Store one event if it fits, returning its live-delivery ID in all cases. */ - async storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise { - await this.ensureSequenceLoaded(streamId); - const eventId = this.nextEventId(streamId); - const bytes = messageBytes(message); - if (bytes === null || bytes > MAX_STORABLE_MCP_EVENT_BYTES) { - logStoreWarning("mcp_event_store_skipped_oversize", { - streamId, - messageBytes: bytes, - limit: MAX_STORABLE_MCP_EVENT_BYTES, - }); - return eventId; - } - - // oxlint-disable-next-line executor/no-try-catch-or-throw -- storage boundary: persistence must never prevent the transport's subsequent live write - try { - await this.storage.put(`${EVENT_KEY_PREFIX}${eventId}`, message); - await this.trimStream(streamId); - } catch { - logStoreWarning("mcp_event_store_put_failed", { - streamId, - }); - } - return eventId; - } - - /** Resolve the stream encoded into an Executor event ID. */ - getStreamIdForEventId(eventId: EventId): Promise { - return Promise.resolve(streamIdFromEventId(eventId)); - } - - /** - * Mark a tool-call stream as requiring at-least-once delivery confirmation. - * - * Direct workerd streaming cannot prove that a completed POST body reached - * the remote client, so the marker remains until a later standalone GET - * drains the stream and its response body completes. - */ - async markStreamUndelivered(streamId: StreamId): Promise { - // oxlint-disable-next-line executor/no-try-catch-or-throw -- storage boundary: a marker failure cannot block the live tool request - try { - await this.storage.put(undeliveredStreamKey(streamId), true); - } catch { - logStoreWarning("mcp_event_store_put_failed", { - operation: "mark_undelivered", - streamId, - }); - } - } - - /** Replay every marked POST stream onto a standalone recovery response. */ - async replayUndeliveredStreams({ - send, - }: { - readonly send: (eventId: EventId, message: JSONRPCMessage) => Promise; - }): Promise { - const replayedStreamIds: StreamId[] = []; - // oxlint-disable-next-line executor/no-try-catch-or-throw -- storage/replay boundary: recovery is best-effort and leaves markers intact for a later GET - try { - const markers = await this.storage.list({ - prefix: UNDELIVERED_STREAM_KEY_PREFIX, - limit: REPLAY_LIMIT, - }); - for (const key of markers.keys()) { - const streamId = key.slice(UNDELIVERED_STREAM_KEY_PREFIX.length); - let replayed = false; - const rows = await this.storage.list({ - prefix: eventPrefix(streamId), - limit: REPLAY_LIMIT, - }); - for (const [eventKey, message] of rows) { - await send(eventIdFromKey(eventKey), message); - replayed = true; - } - if (replayed) replayedStreamIds.push(streamId); - } - } catch { - logStoreWarning("mcp_event_store_list_failed", { - operation: "replay_undelivered", - }); - } - return replayedStreamIds; - } - - /** Clear successfully drained recovery streams and their delivery markers. */ - async acknowledgeUndeliveredStreams(streamIds: readonly StreamId[]): Promise { - // oxlint-disable-next-line executor/no-try-catch-or-throw -- storage boundary: acknowledgement cleanup is best-effort and duplicate replay is safe - try { - for (const streamId of streamIds) { - const rows = await this.storage.list({ - prefix: eventPrefix(streamId), - limit: REPLAY_LIMIT, - }); - const keys = [undeliveredStreamKey(streamId), ...rows.keys()]; - for (let index = 0; index < keys.length; index += DELETE_CHUNK_SIZE) { - await this.storage.delete(keys.slice(index, index + DELETE_CHUNK_SIZE)); - } - } - } catch { - logStoreWarning("mcp_event_store_delete_failed", { - operation: "acknowledge_undelivered", - streamCount: streamIds.length, - }); - } - } - - /** Replay persisted events after the supplied ID, in storage-key order. */ - /** - * Whether the stream named by `lastEventId` still has stored events after - * it — i.e. whether a reconnect GET carrying this id has anything left to - * resume. EventSource clients echo the last id they saw on EVERY - * reconnect, so a drained id must route the connection to the standalone - * listener path instead of a resume (the transport closes a completed - * stream's resume immediately, which turns the echo into a reconnect - * loop). - */ - async hasEventsAfter(lastEventId: EventId): Promise { - const streamId = streamIdFromEventId(lastEventId); - if (!streamId) return false; - // oxlint-disable-next-line executor/no-try-catch-or-throw -- storage boundary: on probe failure fall back to resume semantics - try { - const rows = await this.storage.list({ - prefix: eventPrefix(streamId), - startAfter: `${EVENT_KEY_PREFIX}${lastEventId}`, - limit: 1, - }); - return rows.size > 0; - } catch { - logStoreWarning("mcp_event_store_list_failed", { - operation: "has_events_after", - streamId, - }); - return true; - } - } - - async replayEventsAfter( - lastEventId: EventId, - { send }: { readonly send: (eventId: EventId, message: JSONRPCMessage) => Promise }, - ): Promise { - const streamId = streamIdFromEventId(lastEventId); - if (!streamId) return ""; - // oxlint-disable-next-line executor/no-try-catch-or-throw -- storage/replay boundary: a failed replay is logged and leaves the live session usable - try { - const rows = await this.storage.list({ - prefix: eventPrefix(streamId), - startAfter: `${EVENT_KEY_PREFIX}${lastEventId}`, - limit: REPLAY_LIMIT, - }); - for (const [key, message] of rows) { - // oxlint-disable-next-line executor/no-try-catch-or-throw -- client replay callback failures must not prevent later stored events from being offered - try { - await send(eventIdFromKey(key), message); - } catch {} - } - } catch { - logStoreWarning("mcp_event_store_list_failed", { - operation: "replay", - streamId, - }); - } - return streamId; - } -} diff --git a/packages/hosts/cloudflare/src/mcp/do-headers.ts b/packages/hosts/cloudflare/src/mcp/do-headers.ts index 1a20b44715..ca101ba608 100644 --- a/packages/hosts/cloudflare/src/mcp/do-headers.ts +++ b/packages/hosts/cloudflare/src/mcp/do-headers.ts @@ -25,21 +25,6 @@ export type VerifiedTokenHeaders = { readonly organizationId: string; }; -/** Parsed worker-stamped identity and resource received by a session DO. */ -export type VerifiedMcpRequestHeaders = VerifiedTokenHeaders & { - readonly resourceKey: string; -}; - -/** Parse the complete worker-stamped modern identity header set. */ -export const verifiedMcpRequestHeaders = (request: Request): VerifiedMcpRequestHeaders | null => { - const accountId = request.headers.get(INTERNAL_ACCOUNT_ID_HEADER); - const organizationId = request.headers.get(INTERNAL_ORGANIZATION_ID_HEADER); - const resourceKey = request.headers.get(INTERNAL_RESOURCE_KEY_HEADER); - return accountId && organizationId && resourceKey - ? { accountId, organizationId, resourceKey } - : null; -}; - // Worker and DO run in separate isolates with independent WebSdk tracer // providers. Neither one can see the other's OTEL context, so the DO used // to emit a brand-new root trace on every stub call. Ferry the worker span @@ -131,7 +116,7 @@ export const withVerifiedIdentityHeaders = ( export const withMcpResponseHeaders = (response: Response): Response => { const headers = new Headers(response.headers); headers.set("access-control-allow-origin", "*"); - headers.set("access-control-expose-headers", "mcp-session-id, mcp-protocol-version"); + headers.set("access-control-expose-headers", "mcp-session-id"); return new Response(response.body, { status: response.status, statusText: response.statusText, diff --git a/packages/hosts/cloudflare/src/mcp/execution-owner-directory.ts b/packages/hosts/cloudflare/src/mcp/execution-owner-directory.ts index f40df95e8d..54583f2e55 100644 --- a/packages/hosts/cloudflare/src/mcp/execution-owner-directory.ts +++ b/packages/hosts/cloudflare/src/mcp/execution-owner-directory.ts @@ -5,21 +5,6 @@ export type McpExecutionOwnerRoute = { readonly sessionId: string; }; -/** Prefix distinguishing a modern request DO from a sessionful transport DO. */ -export const MODERN_MCP_EXECUTION_OWNER_PREFIX = "modern:"; - -/** Encode a unique modern session DO id in the existing owner route slot. */ -export const modernMcpExecutionOwnerRoute = (durableObjectId: string): McpExecutionOwnerRoute => ({ - sessionId: `${MODERN_MCP_EXECUTION_OWNER_PREFIX}${durableObjectId}`, -}); - -/** Decode the unique DO id from a modern owner route, or return null for sessionful owners. */ -export const modernMcpDurableObjectId = (route: McpExecutionOwnerRoute): string | null => { - if (!route.sessionId.startsWith(MODERN_MCP_EXECUTION_OWNER_PREFIX)) return null; - const id = route.sessionId.slice(MODERN_MCP_EXECUTION_OWNER_PREFIX.length); - return id.length > 0 ? id : null; -}; - export type McpExecutionOwnerRecord = { readonly executionId: string; readonly owner: McpExecutionOwnerRoute; @@ -51,6 +36,9 @@ type McpExecutionOwnerDirectoryStorage = DurableObjectState["storage"]; const toMcpExecutionOwnerDirectoryStub = (stub: unknown): McpExecutionOwnerDirectoryStub => stub as McpExecutionOwnerDirectoryStub; +export const mcpSessionDurableObjectName = (sessionId: string): string => + `streamable-http:${sessionId}`; + class McpExecutionOwnerDirectoryRpcError extends Data.TaggedError( "McpExecutionOwnerDirectoryRpcError", )<{ diff --git a/packages/hosts/cloudflare/src/mcp/modern-request-router.test.ts b/packages/hosts/cloudflare/src/mcp/modern-request-router.test.ts deleted file mode 100644 index b2bfa2004a..0000000000 --- a/packages/hosts/cloudflare/src/mcp/modern-request-router.test.ts +++ /dev/null @@ -1,479 +0,0 @@ -import { describe, expect, it } from "@effect/vitest"; -import { createRequestStateCodec } from "@modelcontextprotocol/server"; -import { Effect } from "effect"; - -import type { ExecutionEngine } from "@executor-js/execution"; -import { - defaultMcpResource, - type McpModernServerBuilder, - type McpResource, - type Principal, -} from "@executor-js/host-mcp"; -import { - buildMcpServer, - mcpRequestStateBindingFromBody, - mcpRequestStatePrincipal, -} from "@executor-js/host-mcp/tool-server"; - -import type { McpSessionProps } from "./agent-session-durable-object"; -import { - modernMcpExecutionOwnerRoute, - type McpExecutionOwnerDirectory, - type McpExecutionOwnerRecord, -} from "./execution-owner-directory"; -import { - classifyMcpProtocolEra, - makeMcpModernRequestRouter, - mcpCorsPreflightResponse, - requireMcpRequestStateKey, - type McpModernSessionNamespace, - type McpModernSessionStub, -} from "./modern-request-router"; - -const REQUEST_STATE_KEY = "0123456789abcdef0123456789abcdef"; - -const principal: Principal = { - accountId: "acct_1", - organizationId: "org_1", - organizationName: "Org 1", - email: "user@example.test", - name: "Test User", - avatarUrl: null, - roles: [], -}; - -const props: McpSessionProps = { - session: { - organizationId: principal.organizationId, - userId: principal.accountId, - elicitationMode: "native", - resource: defaultMcpResource, - webOrigin: "https://executor.test", - }, -}; - -const engine: ExecutionEngine = { - execute: (code) => Effect.succeed({ result: code }), - executeWithPause: (code) => - Effect.succeed({ status: "completed" as const, result: { result: code } }), - resume: () => Effect.succeed(null), - isExecutionSettled: () => Effect.succeed(false), - getPausedExecution: () => Effect.succeed(null), - pausedExecutionCount: () => Effect.succeed(0), - hasPausedExecutions: () => Effect.succeed(false), - getDescription: Effect.succeed("test engine"), -}; - -const modernBody = (input: { - readonly method: string; - readonly name?: string; - readonly arguments?: Record; - readonly requestState?: string; -}) => ({ - jsonrpc: "2.0", - id: 1, - method: input.method, - params: { - ...(input.name ? { name: input.name } : {}), - ...(input.arguments ? { arguments: input.arguments } : {}), - ...(input.requestState ? { requestState: input.requestState } : {}), - _meta: { - "io.modelcontextprotocol/protocolVersion": "2026-07-28", - "io.modelcontextprotocol/clientCapabilities": {}, - }, - }, -}); - -const modernRequest = (body: ReturnType): Request => - new Request("https://executor.test/mcp", { - method: "POST", - headers: { - "content-type": "application/json", - "mcp-protocol-version": "2026-07-28", - "mcp-method": body.method, - ...(typeof body.params.name === "string" ? { "mcp-name": body.params.name } : {}), - }, - body: JSON.stringify(body), - }); - -class MemoryDirectory implements McpExecutionOwnerDirectory { - readonly records = new Map(); - - put(record: McpExecutionOwnerRecord): Effect.Effect { - return Effect.sync(() => { - this.records.set(record.executionId, record); - }); - } - - get(executionId: string): Effect.Effect { - return Effect.sync(() => this.records.get(executionId) ?? null); - } - - delete(executionId: string): Effect.Effect { - return Effect.sync(() => { - this.records.delete(executionId); - }); - } -} - -type ForwardedRequest = { - readonly id: string; - readonly body: unknown; -}; - -class MemorySessions implements McpModernSessionNamespace { - readonly forwarded: ForwardedRequest[] = []; - uniqueIds = 0; - - constructor(private readonly rejectStringIds = false) {} - - newUniqueId(): string { - this.uniqueIds += 1; - return `unique-${this.uniqueIds}`; - } - - idFromName(name: string): string { - return `name:${name}`; - } - - idFromString(id: string): string { - if (this.rejectStringIds) { - // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- test boundary: model Cloudflare rejecting a foreign/checksum-invalid owner id - throw new Error("invalid Durable Object id"); - } - return `id:${id}`; - } - - get(id: string): McpModernSessionStub { - return { - serveModernMcp: async (_request, _props, parsedBody) => { - this.forwarded.push({ id, body: parsedBody }); - return new Response(JSON.stringify({ id }), { - headers: { "content-type": "application/json" }, - }); - }, - }; - } -} - -const makeBuilder = (builds: { count: number }): McpModernServerBuilder["Service"] => ({ - build: (_principal, options) => { - builds.count += 1; - const { resource: _resource, ...requestOptions } = options; - return buildMcpServer({ - engine, - elicitationMode: { mode: "native" }, - ...requestOptions, - }); - }, -}); - -const dispatch = async (input: { - readonly body: ReturnType; - readonly sessions: MemorySessions; - readonly directory: MemoryDirectory; - readonly builder: McpModernServerBuilder["Service"]; - readonly resource?: McpResource; -}) => { - const request = modernRequest(input.body); - return makeMcpModernRequestRouter().fetch({ - request, - parsedBody: input.body, - principal, - resource: input.resource ?? defaultMcpResource, - props, - requestStateSigningKey: REQUEST_STATE_KEY, - builder: input.builder, - sessions: input.sessions, - executionOwners: input.directory, - }); -}; - -const mintRequestState = async ( - executionId: string, - options: { - readonly code?: string; - readonly resource?: McpResource; - readonly ttlSeconds?: number; - } = {}, -): Promise => { - const body = modernBody({ - method: "tools/call", - name: "execute", - arguments: { code: options.code ?? "1 + 1" }, - }); - const binding = await mcpRequestStateBindingFromBody({ - body, - principal: mcpRequestStatePrincipal(principal), - resource: options.resource ?? defaultMcpResource, - }); - expect(binding).not.toBeNull(); - const codec = createRequestStateCodec<{ readonly executionId: string }>({ - key: REQUEST_STATE_KEY, - ttlSeconds: options.ttlSeconds ?? 60, - bind: () => binding ?? "", - }); - const encoded: unknown = await Reflect.apply(codec.mint, codec, [{ executionId }, {}]); - return typeof encoded === "string" ? encoded : ""; -}; - -describe("modern Cloudflare MCP worker routing", () => { - it("echoes dynamic preflight headers with a static modern fallback", () => { - const requested = "content-type, authorization, mcp-param-search"; - expect(mcpCorsPreflightResponse(requested).headers.get("access-control-allow-headers")).toBe( - requested, - ); - expect(mcpCorsPreflightResponse().headers.get("access-control-allow-headers")).toContain( - "mcp-method", - ); - }); - - it("fails clearly when the shared modern signing secret is missing or short", () => { - expect(() => requireMcpRequestStateKey(undefined)).toThrow("MCP_REQUEST_STATE_KEY"); - expect(() => requireMcpRequestStateKey("too-short")).toThrow("at least 32 bytes"); - expect(requireMcpRequestStateKey(REQUEST_STATE_KEY)).toBe(REQUEST_STATE_KEY); - }); - - it("keeps the canonical legacy classification on the existing transport branch", async () => { - const legacyBody = { jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }; - const legacy = new Request("https://executor.test/mcp", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify(legacyBody), - }); - const modern = modernRequest(modernBody({ method: "tools/list" })); - - await expect(classifyMcpProtocolEra(legacy, legacyBody)).resolves.toBe("legacy"); - await expect( - classifyMcpProtocolEra(modern, modernBody({ method: "tools/list" })), - ).resolves.toBe("modern"); - }); - - it("serves modern non-tools/call methods worker-side without touching a DO", async () => { - const sessions = new MemorySessions(); - const builds = { count: 0 }; - const response = await dispatch({ - body: modernBody({ method: "tools/list" }), - sessions, - directory: new MemoryDirectory(), - builder: makeBuilder(builds), - }); - - expect(response.status).toBe(200); - expect(builds.count).toBe(1); - expect(sessions.uniqueIds).toBe(0); - expect(sessions.forwarded).toEqual([]); - }); - - it("forwards a fresh modern execute call to a new unique DO", async () => { - const sessions = new MemorySessions(); - const builds = { count: 0 }; - const response = await dispatch({ - body: modernBody({ - method: "tools/call", - name: "execute", - arguments: { code: "1 + 1" }, - }), - sessions, - directory: new MemoryDirectory(), - builder: makeBuilder(builds), - }); - - expect(await response.json()).toEqual({ id: "unique-1" }); - expect(builds.count).toBe(0); - expect(sessions.forwarded.map(({ id }) => id)).toEqual(["unique-1"]); - }); - - it("forwards malformed modern tools/call requests to a new unique DO", async () => { - const sessions = new MemorySessions(); - const builds = { count: 0 }; - - await dispatch({ - body: modernBody({ method: "tools/call" }), - sessions, - directory: new MemoryDirectory(), - builder: makeBuilder(builds), - }); - - expect(builds.count).toBe(0); - expect(sessions.forwarded.map(({ id }) => id)).toEqual(["unique-1"]); - }); - - it("verifies continuation state and forwards to its modern owner DO", async () => { - const executionId = "exec-owned"; - const state = await mintRequestState(executionId); - const directory = new MemoryDirectory(); - directory.records.set(executionId, { - executionId, - owner: modernMcpExecutionOwnerRoute("owner-do-id"), - accountId: principal.accountId, - organizationId: principal.organizationId, - expiresAt: new Date(Date.now() + 60_000).toISOString(), - ttlMs: 60_000, - }); - const sessions = new MemorySessions(); - const builds = { count: 0 }; - - await dispatch({ - body: modernBody({ - method: "tools/call", - name: "execute", - arguments: { code: "1 + 1" }, - requestState: state, - }), - sessions, - directory, - builder: makeBuilder(builds), - }); - - expect(builds.count).toBe(0); - expect(sessions.uniqueIds).toBe(0); - expect(sessions.forwarded.map(({ id }) => id)).toEqual(["id:owner-do-id"]); - }); - - it("uses a fresh worker server for an unknown continuation owner", async () => { - const state = await mintRequestState("exec-missing"); - const sessions = new MemorySessions(); - const response = await dispatch({ - body: modernBody({ - method: "tools/call", - name: "execute", - arguments: { code: "1 + 1" }, - requestState: state, - }), - sessions, - directory: new MemoryDirectory(), - builder: makeBuilder({ count: 0 }), - }); - const body = await response.json(); - - expect(body).toMatchObject({ - result: { structuredContent: { status: "execution_not_found" } }, - }); - expect(sessions.uniqueIds).toBe(0); - expect(sessions.forwarded).toEqual([]); - }); - - it("routes modern resume calls to an existing legacy owner when recorded", async () => { - const executionId = "exec-legacy"; - const directory = new MemoryDirectory(); - directory.records.set(executionId, { - executionId, - owner: { sessionId: "legacy-session" }, - accountId: principal.accountId, - organizationId: principal.organizationId, - expiresAt: new Date(Date.now() + 60_000).toISOString(), - ttlMs: 60_000, - }); - const sessions = new MemorySessions(); - - await dispatch({ - body: modernBody({ - method: "tools/call", - name: "resume", - arguments: { executionId, action: "accept" }, - }), - sessions, - directory, - builder: makeBuilder({ count: 0 }), - }); - - expect(sessions.forwarded.map(({ id }) => id)).toEqual(["id:legacy-session"]); - }); - - it("falls back to the worker when a persisted modern owner id is invalid", async () => { - const executionId = "exec-invalid-owner"; - const directory = new MemoryDirectory(); - directory.records.set(executionId, { - executionId, - owner: modernMcpExecutionOwnerRoute("foreign-do-id"), - accountId: principal.accountId, - organizationId: principal.organizationId, - expiresAt: new Date(Date.now() + 60_000).toISOString(), - ttlMs: 60_000, - }); - const sessions = new MemorySessions(true); - const builds = { count: 0 }; - - const response = await dispatch({ - body: modernBody({ - method: "tools/call", - name: "resume", - arguments: { executionId, action: "accept" }, - }), - sessions, - directory, - builder: makeBuilder(builds), - }); - - expect(await response.json()).toMatchObject({ error: { code: -32602 } }); - expect(builds.count).toBe(1); - expect(sessions.forwarded).toEqual([]); - }); - - it("rejects tampered and expired continuation state without touching a DO", async () => { - const valid = await mintRequestState("exec-invalid"); - const middle = Math.floor(valid.length / 2); - const tampered = `${valid.slice(0, middle)}${valid[middle] === "A" ? "B" : "A"}${valid.slice(middle + 1)}`; - const expired = await mintRequestState("exec-expired", { ttlSeconds: -1 }); - - for (const requestState of [tampered, expired]) { - const sessions = new MemorySessions(); - const response = await dispatch({ - body: modernBody({ - method: "tools/call", - name: "execute", - arguments: { code: "1 + 1" }, - requestState, - }), - sessions, - directory: new MemoryDirectory(), - builder: makeBuilder({ count: 0 }), - }); - - const body = await response.json(); - expect(body).toMatchObject({ error: { code: -32602 } }); - expect(sessions.uniqueIds).toBe(0); - expect(sessions.forwarded).toEqual([]); - } - }); - - it("rejects continuation state when the resource or code digest binding changes", async () => { - const requestState = await mintRequestState("exec-bound"); - const cases = [ - { - body: modernBody({ - method: "tools/call", - name: "execute", - arguments: { code: "different code" }, - requestState, - }), - resource: defaultMcpResource, - }, - { - body: modernBody({ - method: "tools/call", - name: "execute", - arguments: { code: "1 + 1" }, - requestState, - }), - resource: { kind: "toolkit", slug: "other" } as const, - }, - ]; - - for (const { body, resource } of cases) { - const sessions = new MemorySessions(); - const response = await dispatch({ - body, - resource, - sessions, - directory: new MemoryDirectory(), - builder: makeBuilder({ count: 0 }), - }); - - expect(await response.json()).toMatchObject({ error: { code: -32602 } }); - expect(sessions.uniqueIds).toBe(0); - expect(sessions.forwarded).toEqual([]); - } - }); -}); diff --git a/packages/hosts/cloudflare/src/mcp/modern-request-router.ts b/packages/hosts/cloudflare/src/mcp/modern-request-router.ts deleted file mode 100644 index 1ea95e19b6..0000000000 --- a/packages/hosts/cloudflare/src/mcp/modern-request-router.ts +++ /dev/null @@ -1,269 +0,0 @@ -import { Effect, Exit, Option, Schema } from "effect"; -import { - createMcpHandler, - isLegacyRequest, - type McpHttpHandler, - type McpRequestContext, -} from "@modelcontextprotocol/server"; - -import { - jsonRpcErrorBody, - mcpResourceKey, - type McpModernServerBuilder, - type McpResource, - type Principal, -} from "@executor-js/host-mcp"; -import { - appsEnabledForClientCapabilities, - clientCapabilitiesFromRequestBody, - mcpRequestStateBindingFromBody, - mcpRequestStatePrincipal, - verifyNativeRequestState, -} from "@executor-js/host-mcp/tool-server"; - -import type { McpSessionProps } from "./agent-session-durable-object"; -import type { McpExecutionOwnerDirectory } from "./execution-owner-directory"; -import { mcpSessionStubForOwner } from "./session-stub"; - -const MCP_CORS_EXPOSED_HEADERS = "mcp-session-id, mcp-protocol-version, WWW-Authenticate"; -const MCP_CORS_ALLOWED_HEADERS = - "content-type, authorization, mcp-session-id, accept, mcp-protocol-version, mcp-method, mcp-name"; - -const UnknownRecord = Schema.Record(Schema.String, Schema.Unknown); -const ModernToolsCallMethod = Schema.Struct({ method: Schema.Literal("tools/call") }); -const ModernToolCall = Schema.Struct({ - method: Schema.Literal("tools/call"), - params: Schema.Struct({ - name: Schema.String, - arguments: Schema.optional(UnknownRecord), - requestState: Schema.optional(Schema.String), - }), -}); -type ModernToolCall = typeof ModernToolCall.Type; -const decodeModernToolsCallMethod = Schema.decodeUnknownOption(ModernToolsCallMethod); -const decodeModernToolCall = Schema.decodeUnknownOption(ModernToolCall); - -interface ModernRequestInputs { - readonly builder: McpModernServerBuilder["Service"]; - readonly parsedBody: unknown; - readonly principal: Principal; - readonly requestStateSigningKey: string; -} - -/** Durable Object namespace surface required by modern execution routing. */ -export interface McpModernSessionNamespace { - readonly newUniqueId: () => Id; - readonly idFromName: (name: string) => Id; - readonly idFromString: (id: string) => Id; - readonly get: (id: Id) => unknown; -} - -/** Worker-callable modern RPC exposed by the MCP session Durable Object. */ -export interface McpModernSessionStub { - readonly serveModernMcp: ( - request: Request, - props: McpSessionProps, - parsedBody: unknown, - ) => Promise; -} - -/** Inputs needed to dispatch one authenticated modern MCP request. */ -export interface McpModernRequestDispatch { - readonly request: Request; - readonly parsedBody: unknown; - readonly principal: Principal; - readonly resource: McpResource; - readonly props: McpSessionProps; - readonly requestStateSigningKey: string; - readonly builder: McpModernServerBuilder["Service"]; - readonly sessions: McpModernSessionNamespace; - readonly executionOwners: McpExecutionOwnerDirectory | null; -} - -/** Resource-cached worker router for authenticated 2026-07-28 requests. */ -export interface McpModernRequestRouter { - readonly fetch: (input: McpModernRequestDispatch) => Promise; - readonly close: () => Promise; -} - -/** Validate the shared request-state secret at the first modern request boundary. */ -export const requireMcpRequestStateKey = (value: string | undefined): string => { - if (value !== undefined && new TextEncoder().encode(value).byteLength >= 32) return value; - // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- composition boundary: modern MCP cannot safely serve or route continuation state without a deployment-provided HMAC key - throw new Error( - "MCP_REQUEST_STATE_KEY must be set to a secret of at least 32 bytes before serving MCP 2026-07-28 requests", - ); -}; - -/** Build the MCP preflight response, echoing dynamic modern header names. */ -export const mcpCorsPreflightResponse = (requestedHeaders?: string | null): Response => - new Response(null, { - status: 204, - headers: { - "access-control-allow-origin": "*", - "access-control-allow-methods": "GET, POST, DELETE, OPTIONS", - "access-control-allow-headers": - requestedHeaders && requestedHeaders.trim() !== "" - ? requestedHeaders - : MCP_CORS_ALLOWED_HEADERS, - "access-control-expose-headers": MCP_CORS_EXPOSED_HEADERS, - }, - }); - -/** Classify an already-parsed request with the SDK's canonical era predicate. */ -export const classifyMcpProtocolEra = ( - request: Request, - parsedBody: unknown, -): Promise<"legacy" | "modern"> => - isLegacyRequest(request, parsedBody).then((legacy) => (legacy ? "legacy" : "modern")); - -const withModernMcpCors = (response: Response): Response => { - const headers = new Headers(response.headers); - headers.set("access-control-allow-origin", "*"); - headers.set("access-control-expose-headers", MCP_CORS_EXPOSED_HEADERS); - return new Response(response.body, { - status: response.status, - statusText: response.statusText, - headers, - }); -}; - -const toModernSessionStub = (stub: unknown): McpModernSessionStub => - // oxlint-disable-next-line executor/no-double-cast -- boundary: Workers generates the RPC surface from the bound Durable Object class, while the portable namespace type exposes unknown. - stub as unknown as McpModernSessionStub; - -const stubForOwner = ( - sessions: McpModernSessionNamespace, - owner: { readonly sessionId: string }, -): McpModernSessionStub | null => { - const stub = mcpSessionStubForOwner(sessions, owner); - return stub ? toModernSessionStub(stub) : null; -}; - -const freshStub = (sessions: McpModernSessionNamespace): McpModernSessionStub => - toModernSessionStub(sessions.get(sessions.newUniqueId())); - -const resumeExecutionId = (call: ModernToolCall): string | null => { - if (call.params.name !== "resume") return null; - const executionId = call.params.arguments?.executionId; - return typeof executionId === "string" && executionId.length > 0 ? executionId : null; -}; - -/** Build the shared worker-side modern handler and DO-affinity router. */ -export const makeMcpModernRequestRouter = (): McpModernRequestRouter => { - const handlers = new Map(); - const requestInputs = new WeakMap(); - - const handlerFor = (resource: McpResource): McpHttpHandler => { - const resourceKey = mcpResourceKey(resource); - const cached = handlers.get(resourceKey); - if (cached) return cached; - - const handler = createMcpHandler( - (context: McpRequestContext) => { - const request = context.requestInfo; - const inputs = request ? requestInputs.get(request) : undefined; - if (!request || !inputs) { - // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: the third-party factory Promise has no typed failure channel; absent request context is an SDK defect - return Effect.runPromise(Effect.die("Modern MCP request has no authenticated context")); - } - const capabilities = clientCapabilitiesFromRequestBody(inputs.parsedBody); - return Effect.runPromise( - Effect.gen(function* () { - const requestStatePrincipal = mcpRequestStatePrincipal(inputs.principal); - const requestStateBinding = yield* Effect.promise(() => - mcpRequestStateBindingFromBody({ - body: inputs.parsedBody, - principal: requestStatePrincipal, - resource, - }), - ); - return yield* inputs.builder.build(inputs.principal, { - resource, - appsEnabled: appsEnabledForClientCapabilities(capabilities), - requestStateSigningKey: inputs.requestStateSigningKey, - requestStatePrincipal, - ...(requestStateBinding === null ? {} : { requestStateBinding }), - }); - }), - ); - }, - { legacy: "reject" }, - ); - handlers.set(resourceKey, handler); - return handler; - }; - - const serveWorker = async (input: McpModernRequestDispatch): Promise => { - requestInputs.set(input.request, { - builder: input.builder, - parsedBody: input.parsedBody, - principal: input.principal, - requestStateSigningKey: input.requestStateSigningKey, - }); - return handlerFor(input.resource).fetch(input.request, { parsedBody: input.parsedBody }); - }; - - const serveDo = ( - stub: McpModernSessionStub, - input: McpModernRequestDispatch, - ): Promise => stub.serveModernMcp(input.request, input.props, input.parsedBody); - - return { - fetch: async (input) => { - if (Option.isNone(decodeModernToolsCallMethod(input.parsedBody))) { - return withModernMcpCors(await serveWorker(input)); - } - - const decoded = decodeModernToolCall(input.parsedBody); - if (Option.isNone(decoded)) { - return withModernMcpCors(await serveDo(freshStub(input.sessions), input)); - } - - const call = decoded.value; - let executionId = resumeExecutionId(call); - if (call.params.name === "execute" && call.params.requestState !== undefined) { - const verified = await Effect.runPromiseExit( - verifyNativeRequestState({ - state: call.params.requestState, - body: input.parsedBody, - resource: input.resource, - requestStateSigningKey: input.requestStateSigningKey, - requestStatePrincipal: mcpRequestStatePrincipal(input.principal), - }), - ); - if (Exit.isFailure(verified)) { - return withModernMcpCors(await serveWorker(input)); - } - executionId = verified.value.executionId; - } - - if (executionId === null) { - return withModernMcpCors(await serveDo(freshStub(input.sessions), input)); - } - - const owner = input.executionOwners - ? await Effect.runPromise(input.executionOwners.get(executionId)) - : null; - if (!owner) { - return withModernMcpCors(await serveWorker(input)); - } - if ( - owner.accountId !== input.principal.accountId || - owner.organizationId !== input.principal.organizationId - ) { - return withModernMcpCors( - jsonRpcErrorBody(403, -32003, "MCP execution does not belong to the current bearer"), - ); - } - const ownerStub = stubForOwner(input.sessions, owner.owner); - return withModernMcpCors( - ownerStub ? await serveDo(ownerStub, input) : await serveWorker(input), - ); - }, - close: () => - Promise.all(Array.from(handlers.values(), (handler) => handler.close())).then( - () => undefined, - ), - }; -}; diff --git a/packages/hosts/cloudflare/src/mcp/session-alarm-policy.ts b/packages/hosts/cloudflare/src/mcp/session-alarm-policy.ts index e44a53502d..4502771c3d 100644 --- a/packages/hosts/cloudflare/src/mcp/session-alarm-policy.ts +++ b/packages/hosts/cloudflare/src/mcp/session-alarm-policy.ts @@ -18,8 +18,8 @@ export const RUNNING_EXECUTION_LEASE_MS = PAUSED_APPROVAL_TIMEOUT_MS; */ export const MAX_PAUSED_SESSION_IDLE_MS = SESSION_TIMEOUT_MS + PAUSED_EXECUTION_LEASE_MS; -/** Maximum lifetime of one client-facing SSE response before reconnect rotation. */ -export const SSE_MAX_AGE_MS = 30 * 60 * 1000; +/** Matches the patched agents transport's MAX_SSE_AGE_MS (30 minutes). */ +const SSE_MAX_AGE_MS = 30 * 60 * 1000; /** * Hard upper bound on idle time while running work or open streams keep diff --git a/packages/hosts/cloudflare/src/mcp/session-stub.test.ts b/packages/hosts/cloudflare/src/mcp/session-stub.test.ts deleted file mode 100644 index 23a6eb5e35..0000000000 --- a/packages/hosts/cloudflare/src/mcp/session-stub.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { describe, expect, it, vi } from "@effect/vitest"; - -import { mcpSessionStub } from "./session-stub"; - -describe("mcpSessionStub", () => { - it("returns null when Cloudflare rejects a client-supplied Durable Object id", () => { - const get = vi.fn(); - const namespace = { - idFromString: (_id: string): string => { - // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- test boundary: model Cloudflare's throwing namespace checksum parser - throw new Error("Durable Object ID is not valid for this namespace"); - }, - get, - }; - - expect(mcpSessionStub(namespace, "0".repeat(64))).toBeNull(); - expect(get).not.toHaveBeenCalled(); - }); - - it("resolves a namespace-validated id to its generated RPC stub", () => { - const stub = { fetch: vi.fn() }; - const namespace = { - idFromString: (id: string): string => `parsed:${id}`, - get: vi.fn(() => stub), - }; - - expect(mcpSessionStub(namespace, "issued-id")).toBe(stub); - expect(namespace.get).toHaveBeenCalledWith("parsed:issued-id"); - }); -}); diff --git a/packages/hosts/cloudflare/src/mcp/session-stub.ts b/packages/hosts/cloudflare/src/mcp/session-stub.ts index ede3e6d92c..3a003ff0cc 100644 --- a/packages/hosts/cloudflare/src/mcp/session-stub.ts +++ b/packages/hosts/cloudflare/src/mcp/session-stub.ts @@ -7,22 +7,14 @@ import type { McpSessionModelResumeResult, McpSessionResumeApprovalResult, } from "./agent-session-durable-object"; -import { modernMcpDurableObjectId, type McpExecutionOwnerRoute } from "./execution-owner-directory"; +import { mcpSessionDurableObjectName } from "./execution-owner-directory"; export interface McpSessionNamespace { - readonly idFromString: (id: string) => Id; + readonly idFromName: (name: string) => Id; readonly get: (id: Id) => unknown; } -/** Session namespace surface for unique sessionful and modern Durable Objects. */ -export type McpOwnerSessionNamespace = McpSessionNamespace; - -export interface McpSessionFactoryNamespace extends McpSessionNamespace { - readonly newUniqueId: () => Id; -} - export interface McpSessionStub { - readonly fetch: (request: Request) => Promise; readonly validateMcpSessionOwner: ( identity: McpApprovalOwner, ) => Promise<"ok" | "not_found" | "forbidden" | "terminated">; @@ -49,37 +41,8 @@ export interface McpSessionStub { export const mcpSessionStub = ( namespace: McpSessionNamespace, sessionId: string, -): McpSessionStub | null => { - let id: Id; - // oxlint-disable-next-line executor/no-try-catch-or-throw -- platform boundary: Cloudflare validates the namespace checksum only through throwing idFromString - try { - id = namespace.idFromString(sessionId); - } catch { - return null; - } - return ( - // oxlint-disable-next-line executor/no-double-cast -- boundary: Workers types expose only DurableObjectStub, but fetch and RPC methods are generated from the bound DO class. - namespace.get(id) as unknown as McpSessionStub - ); -}; - -/** Allocate one unique session DO and return its client-visible ID and stub. */ -export const createMcpSessionStub = ( - namespace: McpSessionFactoryNamespace, -): { readonly sessionId: string; readonly stub: McpSessionStub } => { - const id = namespace.newUniqueId(); - return { - sessionId: String(id), - // oxlint-disable-next-line executor/no-double-cast -- boundary: Workers generates fetch and RPC methods from the bound DO class. - stub: namespace.get(id) as unknown as McpSessionStub, - }; -}; - -/** Resolve an execution owner route to its unique modern or sessionful DO. */ -export const mcpSessionStubForOwner = ( - namespace: McpOwnerSessionNamespace, - owner: McpExecutionOwnerRoute, -): McpSessionStub | null => { - const modernId = modernMcpDurableObjectId(owner); - return mcpSessionStub(namespace, modernId ?? owner.sessionId); -}; +): McpSessionStub => + // oxlint-disable-next-line executor/no-double-cast -- boundary: Workers types expose only DurableObjectStub, but RPC methods are generated from the bound DO class. + namespace.get( + namespace.idFromName(mcpSessionDurableObjectName(sessionId)), + ) as unknown as McpSessionStub; diff --git a/packages/hosts/cloudflare/src/mcp/sse-response-rotation.test.ts b/packages/hosts/cloudflare/src/mcp/sse-response-rotation.test.ts deleted file mode 100644 index 85e31eadac..0000000000 --- a/packages/hosts/cloudflare/src/mcp/sse-response-rotation.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest"; - -import { SESSION_TIMEOUT_MS, SSE_MAX_AGE_MS } from "./session-alarm-policy"; -import { - SSE_MAX_AGE_RECONNECT_FRAME, - rotateSseResponse, - type SseResponseCloseReason, -} from "./sse-response-rotation"; - -const sseResponse = (cancelled: { value: boolean }): Response => - new Response( - new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode(": keepalive\n\n")); - }, - cancel() { - cancelled.value = true; - }, - }), - { headers: { "content-type": "text/event-stream", "content-length": "100" } }, - ); - -describe("rotateSseResponse", () => { - beforeEach(() => { - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - it("keeps the production max age well above the session idle timeout", () => { - expect(SSE_MAX_AGE_MS).toBe(30 * 60 * 1000); - expect(SSE_MAX_AGE_MS).toBeGreaterThanOrEqual(6 * SESSION_TIMEOUT_MS); - }); - - it("closes any still-open SSE response with a reconnect comment at max age", async () => { - const cancelled = { value: false }; - const closes: SseResponseCloseReason[] = []; - const response = rotateSseResponse(sseResponse(cancelled), { - maxAgeMs: 1_000, - onClose: (reason) => closes.push(reason), - }); - const bodyPromise = response.text(); - - await vi.advanceTimersByTimeAsync(1_000); - - await expect(bodyPromise).resolves.toBe(`: keepalive\n\n${SSE_MAX_AGE_RECONNECT_FRAME}`); - expect(cancelled.value).toBe(true); - expect(closes).toEqual(["rotate"]); - expect(vi.getTimerCount()).toBe(0); - }); - - it("prepends a compatibility frame before SDK stream bytes", async () => { - const source = new Response("event: message\ndata: {}\n\n", { - headers: { "content-type": "text/event-stream" }, - }); - const response = rotateSseResponse(source, { - maxAgeMs: 1_000, - initialFrame: new TextEncoder().encode("event: mcp-priming\nid: stream:1\ndata: {}\n\n"), - }); - - await expect(response.text()).resolves.toBe( - "event: mcp-priming\nid: stream:1\ndata: {}\n\nevent: message\ndata: {}\n\n", - ); - expect(vi.getTimerCount()).toBe(0); - }); - - it("cancels the max-age timer when the client closes first", async () => { - const cancelled = { value: false }; - const closes: SseResponseCloseReason[] = []; - const response = rotateSseResponse(sseResponse(cancelled), { - maxAgeMs: 1_000, - onClose: (reason) => closes.push(reason), - }); - const reader = response.body?.getReader(); - await reader?.read(); - await reader?.cancel(); - - await vi.advanceTimersByTimeAsync(1_000); - - expect(cancelled.value).toBe(true); - expect(closes).toEqual(["cancel"]); - expect(vi.getTimerCount()).toBe(0); - }); - - it("leaves non-SSE responses unchanged", () => { - const response = new Response("ok", { headers: { "content-type": "application/json" } }); - expect(rotateSseResponse(response)).toBe(response); - }); -}); diff --git a/packages/hosts/cloudflare/src/mcp/sse-response-rotation.ts b/packages/hosts/cloudflare/src/mcp/sse-response-rotation.ts deleted file mode 100644 index 0cc6c3758e..0000000000 --- a/packages/hosts/cloudflare/src/mcp/sse-response-rotation.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { SSE_MAX_AGE_MS } from "./session-alarm-policy"; - -/** Comment emitted immediately before a max-age close asks clients to resume. */ -export const SSE_MAX_AGE_RECONNECT_FRAME = ": max-age rotation, reconnect\n\n"; - -export type SseResponseCloseReason = "cancel" | "complete" | "error" | "rotate"; - -/** - * Comment frame emitted while the source is quiet so intermediaries and - * client idle timers see a live stream. The pre-v2 worker bridge sent one - * every 25s; without it, held-open standalone GET listeners die to ~30s - * client/proxy idle timeouts and every session reconnect-cycles at that - * cadence. - */ -export const SSE_KEEPALIVE_FRAME = ": keepalive\n\n"; -export const SSE_KEEPALIVE_INTERVAL_MS = 20_000; - -export interface SseResponseRotationOptions { - readonly maxAgeMs?: number; - readonly keepaliveMs?: number; - readonly initialFrame?: Uint8Array; - readonly onOpen?: () => void; - readonly onClose?: (reason: SseResponseCloseReason) => void; -} - -const isSseResponse = (response: Response): boolean => - response.body !== null && - (response.headers.get("content-type") ?? "").includes("text/event-stream"); - -/** - * Bound one streamed response's lifetime and preserve direct response - * streaming. Rotation emits a benign comment, closes this HTTP body, and - * cancels the SDK body so its stream bookkeeping is released; the event store - * supplies any later replay to the client's reconnect GET. - */ -export const rotateSseResponse = ( - response: Response, - options: SseResponseRotationOptions = {}, -): Response => { - if (!isSseResponse(response) || !response.body) return response; - - const reader = response.body.getReader(); - const encoder = new TextEncoder(); - const reconnectFrame = encoder.encode(SSE_MAX_AGE_RECONNECT_FRAME); - const keepaliveFrame = encoder.encode(SSE_KEEPALIVE_FRAME); - const maxAgeMs = options.maxAgeMs ?? SSE_MAX_AGE_MS; - const keepaliveMs = options.keepaliveMs ?? SSE_KEEPALIVE_INTERVAL_MS; - let controller: ReadableStreamDefaultController; - let closed = false; - let timer: ReturnType | undefined; - let keepaliveTimer: ReturnType | undefined; - - const finish = (reason: SseResponseCloseReason): void => { - if (closed) return; - closed = true; - if (timer !== undefined) clearTimeout(timer); - if (keepaliveTimer !== undefined) clearInterval(keepaliveTimer); - if (reason === "rotate") { - controller.enqueue(reconnectFrame); - controller.close(); - void reader.cancel("mcp_sse_max_age_rotation").then( - () => undefined, - () => undefined, - ); - } else if (reason === "complete") { - controller.close(); - } - options.onClose?.(reason); - }; - - const body = new ReadableStream({ - start(streamController) { - controller = streamController; - options.onOpen?.(); - if (options.initialFrame) controller.enqueue(options.initialFrame); - timer = setTimeout(() => finish("rotate"), maxAgeMs); - keepaliveTimer = setInterval(() => { - if (closed) return; - controller.enqueue(keepaliveFrame); - }, keepaliveMs); - }, - async pull() { - // oxlint-disable-next-line executor/no-try-catch-or-throw -- stream boundary: propagate the source body's rejected read to the response consumer - try { - const next = await reader.read(); - if (closed) return; - if (next.done) { - finish("complete"); - return; - } - controller.enqueue(next.value); - } catch (cause) { - if (closed) return; - closed = true; - if (timer !== undefined) clearTimeout(timer); - if (keepaliveTimer !== undefined) clearInterval(keepaliveTimer); - options.onClose?.("error"); - controller.error(cause); - } - }, - async cancel(reason) { - if (!closed) { - closed = true; - if (timer !== undefined) clearTimeout(timer); - if (keepaliveTimer !== undefined) clearInterval(keepaliveTimer); - options.onClose?.("cancel"); - } - await reader.cancel(reason); - }, - }); - - const headers = new Headers(response.headers); - headers.delete("content-length"); - return new Response(body, { - status: response.status, - statusText: response.statusText, - headers, - }); -}; diff --git a/packages/hosts/cloudflare/src/test-stubs/cloudflare-workers.ts b/packages/hosts/cloudflare/src/test-stubs/cloudflare-workers.ts index 2c68615b42..469f966902 100644 --- a/packages/hosts/cloudflare/src/test-stubs/cloudflare-workers.ts +++ b/packages/hosts/cloudflare/src/test-stubs/cloudflare-workers.ts @@ -1,14 +1,6 @@ export const env: Record = {}; -export class DurableObject { - protected readonly ctx: DurableObjectState; - protected readonly env: Env; - - constructor(ctx: DurableObjectState, env: Env) { - this.ctx = ctx; - this.env = env; - } -} +export class DurableObject {} export class RpcTarget {} diff --git a/packages/hosts/cloudflare/vitest.config.ts b/packages/hosts/cloudflare/vitest.config.ts index 3340719599..57bf3225ac 100644 --- a/packages/hosts/cloudflare/vitest.config.ts +++ b/packages/hosts/cloudflare/vitest.config.ts @@ -15,5 +15,10 @@ export default defineConfig({ include: ["src/**/*.test.ts"], passWithNoTests: true, setupFiles: ["./src/test-setup.ts"], + server: { + deps: { + inline: ["agents", "partyserver"], + }, + }, }, }); diff --git a/packages/hosts/mcp-apps-shell/src/shell-resource.smoke.test.ts b/packages/hosts/mcp-apps-shell/src/shell-resource.smoke.test.ts index d51d0afcc8..0461389684 100644 --- a/packages/hosts/mcp-apps-shell/src/shell-resource.smoke.test.ts +++ b/packages/hosts/mcp-apps-shell/src/shell-resource.smoke.test.ts @@ -4,7 +4,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { EXTENSION_ID, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server"; import type { ClientCapabilities } from "@modelcontextprotocol/sdk/types.js"; -import { buildMcpServer } from "@executor-js/host-mcp/tool-server"; +import { createExecutorMcpServer } from "@executor-js/host-mcp/tool-server"; import { MCP_APPS_SHELL_RESOURCE_URI } from "@executor-js/host-mcp/create-artifact"; import type { ExecutionEngine } from "@executor-js/execution"; @@ -40,12 +40,8 @@ describe("MCP-Apps shell resource", () => { const mcpServer = await Effect.runPromise( // Artifacts are opt-in per connection; the shell resource only exists on // a session that asked for them. - buildMcpServer({ + createExecutorMcpServer({ engine: stubEngine, - appsEnabled: false, - requestStateSigningKey: new Uint8Array(32).fill(17), - requestStatePrincipal: "shell-resource-test-principal", - sessionful: true, loadAppShellHtml: loadMcpAppsShellHtml, artifactsEnabled: true, }), diff --git a/packages/hosts/mcp-apps-shell/src/shell/mcp-app.browser.test.ts b/packages/hosts/mcp-apps-shell/src/shell/mcp-app.browser.test.ts index fa03cbbfc8..057684955e 100644 --- a/packages/hosts/mcp-apps-shell/src/shell/mcp-app.browser.test.ts +++ b/packages/hosts/mcp-apps-shell/src/shell/mcp-app.browser.test.ts @@ -38,7 +38,7 @@ import { chromium, type Browser, type Frame, type Page } from "playwright-core"; import { createServer as createViteServer } from "vite"; import type * as Cause from "effect/Cause"; -import { buildMcpServer } from "@executor-js/host-mcp/tool-server"; +import { createExecutorMcpServer } from "@executor-js/host-mcp/tool-server"; import { loadMcpAppsShellHtml } from "../shell-html"; @@ -1241,12 +1241,8 @@ const startMcpHarnessForEngine = async ( engine: ExecutionEngine, ): Promise => { const mcpServer = await Effect.runPromise( - buildMcpServer({ + createExecutorMcpServer({ engine, - appsEnabled: false, - requestStateSigningKey: new Uint8Array(32).fill(19), - requestStatePrincipal: "mcp-app-browser-test-principal", - sessionful: true, loadAppShellHtml: loadMcpAppsShellHtml, artifacts: makeInMemoryArtifacts(), // Artifacts are opt-in per connection; this harness drives the artifact diff --git a/packages/hosts/mcp/package.json b/packages/hosts/mcp/package.json index 43be1951b0..1e8dd7c4fc 100644 --- a/packages/hosts/mcp/package.json +++ b/packages/hosts/mcp/package.json @@ -12,10 +12,6 @@ "types": "./src/tool-server.ts", "default": "./src/tool-server.ts" }, - "./mcp-apps": { - "types": "./src/mcp-apps.ts", - "default": "./src/mcp-apps.ts" - }, "./create-artifact": { "types": "./src/create-artifact.ts", "default": "./src/create-artifact.ts" @@ -48,17 +44,16 @@ "typecheck:slow": "bunx tsc --noEmit -p tsconfig.json" }, "dependencies": { + "@cfworker/json-schema": "^4.1.1", "@executor-js/execution": "workspace:*", "@executor-js/sdk": "workspace:*", - "@modelcontextprotocol/core": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.7.4", + "@modelcontextprotocol/sdk": "^1.29.0", "effect": "catalog:", "zod": "4.3.6" }, "devDependencies": { "@effect/vitest": "catalog:", - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/sdk": "^1.29.0", "@types/node": "catalog:", "bun-types": "catalog:", "vitest": "catalog:" diff --git a/packages/hosts/mcp/src/artifacts-tools.test.ts b/packages/hosts/mcp/src/artifacts-tools.test.ts index 4a27dce2e9..a8a3b794b4 100644 --- a/packages/hosts/mcp/src/artifacts-tools.test.ts +++ b/packages/hosts/mcp/src/artifacts-tools.test.ts @@ -1,7 +1,9 @@ import { describe, expect, it, vi } from "@effect/vitest"; import { Data, Effect } from "effect"; -import { Client } from "@modelcontextprotocol/client"; -import { InMemoryTransport, type ClientCapabilities } from "@modelcontextprotocol/server"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import type { ClientCapabilities } from "@modelcontextprotocol/sdk/types.js"; +import { EXTENSION_ID, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server"; import type * as Cause from "effect/Cause"; import { @@ -16,8 +18,7 @@ import type { ExecutionEngine, ExecutionResult } from "@executor-js/execution"; import type { BindableConnection } from "./artifact-bindings"; import { readArtifactsEnabled } from "./browser-approval"; import { MCP_APPS_SHELL_RESOURCE_URI, artifactUrlFor } from "./create-artifact"; -import { EXTENSION_ID, RESOURCE_MIME_TYPE } from "./mcp-apps"; -import { buildMcpServer, type ExecutorMcpServerConfig } from "./tool-server"; +import { createExecutorMcpServer, type ExecutorMcpServerConfig } from "./tool-server"; /** The caller's connection inventory, as `create-artifact` sees it when it * binds an artifact's integration roles. */ @@ -129,14 +130,6 @@ const makeArtifactStore = () => { }; }; -const TEST_REQUEST_STATE_KEY = new Uint8Array(32).fill(11); -const SESSION_SERVER_OPTIONS = { - appsEnabled: false, - requestStateSigningKey: TEST_REQUEST_STATE_KEY, - requestStatePrincipal: "artifact-test-principal", - sessionful: true, -} as const; - const withClient = async ( engine: ExecutionEngine, capabilities: ClientCapabilities, @@ -144,9 +137,8 @@ const withClient = async ( config?: Partial>, ) => { const mcpServer = await Effect.runPromise( - buildMcpServer({ + createExecutorMcpServer({ engine, - ...SESSION_SERVER_OPTIONS, loadAppShellHtml: () => Promise.resolve(SHELL_HTML), // Artifacts are on by default and nearly every test in this file // exercises the artifact surface; spelled out here anyway so the cases @@ -172,10 +164,13 @@ const withClient = async ( const SHELL_HTML = "
"; -// What a client that renders MCP Apps advertises at `initialize`. +// What a client that renders MCP Apps advertises at `initialize`. The SDK's +// `ClientCapabilities` has no `extensions` field yet (pending SEP-1724), which +// is exactly why ext-apps ships `getUiCapability` to read it. +// oxlint-disable-next-line executor/no-double-cast -- boundary: MCP SDK ClientCapabilities predates the ext-apps `extensions` field const APPS_CAPS = { extensions: { [EXTENSION_ID]: { mimeTypes: [RESOURCE_MIME_TYPE] } }, -} satisfies ClientCapabilities; +} as unknown as ClientCapabilities; const NO_APPS_CAPS: ClientCapabilities = {}; @@ -249,9 +244,8 @@ describe("MCP host — artifact tool visibility", () => { it("keeps the app-only tools visible on a cold restore that replays no initialize", async () => { const store = makeArtifactStore(); const mcpServer = await Effect.runPromise( - buildMcpServer({ + createExecutorMcpServer({ engine: makeStubEngine({}), - ...SESSION_SERVER_OPTIONS, artifacts: store.port, artifactsEnabled: true, loadAppShellHtml: () => Promise.resolve(SHELL_HTML), @@ -313,9 +307,8 @@ describe("MCP host — artifact tool visibility", () => { it("renders inline on a restore that replays initialize without the initialized notification", async () => { const store = makeArtifactStore(); const mcpServer = await Effect.runPromise( - buildMcpServer({ + createExecutorMcpServer({ engine: makeStubEngine({}), - ...SESSION_SERVER_OPTIONS, artifacts: store.port, artifactsEnabled: true, loadAppShellHtml: () => Promise.resolve(SHELL_HTML), @@ -467,9 +460,8 @@ describe("MCP host — artifact tool visibility", () => { it("registers no ui tools at all when no shell loader is configured", async () => { const store = makeArtifactStore(); const mcpServer = await Effect.runPromise( - buildMcpServer({ + createExecutorMcpServer({ engine: makeStubEngine({}), - ...SESSION_SERVER_OPTIONS, artifacts: store.port, // Opted in, so the only thing withholding the surface is the missing // shell loader — otherwise this would pass on the connection default. @@ -1311,7 +1303,7 @@ describe("MCP host — artifact retrieval", () => { await client.callTool({ name: "create-artifact", - arguments: { code: COUNTER_CODE, title: "Revised dashboard", artifactId: "art_1" }, + arguments: { code: COUNTER_CODE, title: "Dashboard v2", artifactId: "art_1" }, }); expect(usage).toEqual(["created", "updated"]); diff --git a/packages/hosts/mcp/src/envelope.test.ts b/packages/hosts/mcp/src/envelope.test.ts index 65e2828376..523dc60a0b 100644 --- a/packages/hosts/mcp/src/envelope.test.ts +++ b/packages/hosts/mcp/src/envelope.test.ts @@ -10,7 +10,6 @@ // --------------------------------------------------------------------------- import { describe, expect, it } from "@effect/vitest"; -import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; import { Cause, Effect, Layer, Ref } from "effect"; import { HttpRouter, HttpServer } from "effect/unstable/http"; @@ -20,18 +19,13 @@ import { McpAuthProvider, McpErrorReporter, McpErrorReporterNoop, - McpModernServerBuilder, McpServingRoutes, McpDiscoveryRoutes, McpSessionStore, - unauthorized, type McpResource, type McpDispatchResult, type Principal, } from "./index"; -import type { ExecutionEngine } from "@executor-js/execution"; -import { EXTENSION_ID, RESOURCE_MIME_TYPE } from "./mcp-apps"; -import { buildMcpServer } from "./tool-server"; const DISCOVERY_PATH = "/.well-known/oauth-protected-resource" as const; @@ -45,25 +39,6 @@ const TEST_PRINCIPAL: Principal = { roles: ["user"], }; -const testEngine: ExecutionEngine = { - execute: (code) => Effect.succeed({ result: `ran: ${code}` }), - executeWithPause: (code) => - Effect.succeed({ status: "completed", result: { result: `ran: ${code}` } }), - resume: () => Effect.succeed(null), - isExecutionSettled: () => Effect.succeed(false), - getPausedExecution: () => Effect.succeed(null), - pausedExecutionCount: () => Effect.succeed(0), - hasPausedExecutions: () => Effect.succeed(false), - getDescription: Effect.succeed("envelope test executor"), -}; - -const ModernBuilderLive = Layer.succeed(McpModernServerBuilder)({ - build: (_principal, options) => { - const { resource: _resource, ...requestOptions } = options; - return buildMcpServer({ engine: testEngine, ...requestOptions }); - }, -}); - /** An auth provider that authenticates everything (so dispatch is reached). */ const AuthProviderLive = Layer.succeed(McpAuthProvider)({ discoveryRoutes: [ @@ -93,9 +68,8 @@ const buildHandler = ( store: Layer.Layer, reporter: Layer.Layer, authProvider: Layer.Layer = AuthProviderLive, - modernBuilder: Layer.Layer = ModernBuilderLive, ): ((request: Request) => Promise) => { - const Seams = Layer.mergeAll(authProvider, store, modernBuilder, reporter); + const Seams = Layer.mergeAll(authProvider, store, reporter); const RouteLive = McpServingRoutes.pipe( HttpRouter.provideRequest(Seams), Layer.provide(authProvider), @@ -140,159 +114,7 @@ describe("McpServingRoutes envelope", () => { expect(response.status).toBe(204); expect(response.headers.get("access-control-allow-origin")).toBe("*"); expect(response.headers.get("access-control-allow-methods")).toBe("GET, POST, DELETE, OPTIONS"); - const allowedHeaders = response.headers.get("access-control-allow-headers") ?? ""; - expect(allowedHeaders).toContain("authorization"); - expect(allowedHeaders).toContain("mcp-method"); - expect(allowedHeaders).toContain("mcp-name"); - }); - - it("echoes requested preflight headers so dynamic Mcp-Param names pass", async () => { - const handler = buildHandler(OkStoreLive, McpErrorReporterNoop); - const requested = "content-type, authorization, mcp-protocol-version, mcp-param-search"; - const response = await handler( - new Request("https://host.test/mcp", { - method: "OPTIONS", - headers: { - origin: "https://claude.ai", - "access-control-request-method": "POST", - "access-control-request-headers": requested, - }, - }), - ); - expect(response.status).toBe(204); - expect(response.headers.get("access-control-allow-headers")).toBe(requested); - }); - - it("serves modern list/call traffic without dispatching a legacy session", async () => { - const legacyDispatches = await Effect.runPromise(Ref.make(0)); - const appsEnabled = await Effect.runPromise(Ref.make(false)); - const RecordingStoreLive = Layer.succeed(McpSessionStore)({ - dispatch: () => - Ref.update(legacyDispatches, (count) => count + 1).pipe(Effect.as("not-found")), - dispose: () => Effect.void, - }); - const RecordingModernBuilder = Layer.succeed(McpModernServerBuilder)({ - build: (_principal, options) => { - const { resource: _resource, ...requestOptions } = options; - return Ref.set(appsEnabled, options.appsEnabled).pipe( - Effect.flatMap(() => buildMcpServer({ engine: testEngine, ...requestOptions })), - ); - }, - }); - const handler = buildHandler( - RecordingStoreLive, - McpErrorReporterNoop, - AuthProviderLive, - RecordingModernBuilder, - ); - const transport = new StreamableHTTPClientTransport(new URL("https://host.test/mcp"), { - fetch: (input, init) => - handler( - input instanceof Request ? new Request(input, init) : new Request(input.toString(), init), - ), - }); - const client = new Client( - { name: "envelope-modern-test", version: "1.0.0" }, - { - capabilities: { - extensions: { [EXTENSION_ID]: { mimeTypes: [RESOURCE_MIME_TYPE] } }, - }, - versionNegotiation: { mode: { pin: "2026-07-28" } }, - }, - ); - - await client.connect(transport); - // oxlint-disable-next-line executor/no-try-catch-or-throw -- test boundary: always close the in-process modern client - try { - expect((await client.listTools()).tools.map(({ name }) => name)).toContain("execute"); - const result = await client.callTool({ - name: "execute", - arguments: { code: "1 + 1" }, - }); - expect(result.content).toEqual([{ type: "text", text: "ran: 1 + 1" }]); - expect(await Effect.runPromise(Ref.get(legacyDispatches))).toBe(0); - expect(await Effect.runPromise(Ref.get(appsEnabled))).toBe(true); - } finally { - await client.close(); - } - }); - - it("returns the existing 401 challenge before routing a modern request", async () => { - const challenge = 'Bearer resource_metadata="https://host.test/custom-metadata"'; - const UnauthorizedAuthProviderLive = Layer.succeed(McpAuthProvider)({ - discoveryRoutes: [], - resourceMetadataUrl: () => "https://host.test/custom-metadata", - authenticate: () => Effect.succeed(unauthorized(challenge)), - }); - const handler = buildHandler(OkStoreLive, McpErrorReporterNoop, UnauthorizedAuthProviderLive); - const response = await handler(modernRequest("https://host.test/mcp")); - - expect(response.status).toBe(401); - expect(response.headers.get("www-authenticate")).toBe(challenge); - }); - - it("gracefully rejects modern discovery when inbound 2026-07-28 is disabled", async () => { - const DisabledModernBuilder = Layer.succeed(McpModernServerBuilder)({ - enabled: false, - build: () => Effect.die("disabled modern builder should not run"), - }); - const handler = buildHandler( - OkStoreLive, - McpErrorReporterNoop, - AuthProviderLive, - DisabledModernBuilder, - ); - - const response = await handler(modernRequest("https://host.test/mcp")); - expect(response.status).toBe(400); - expect(await response.json()).toEqual({ - jsonrpc: "2.0", - error: { code: -32022, message: "MCP 2026-07-28 support is disabled" }, - id: null, - }); - }); - - it("answers a dead-session standalone GET with 405 so old clients stop retrying", async () => { - const NotFoundStoreLive = Layer.succeed(McpSessionStore)({ - dispatch: (): Effect.Effect => Effect.succeed("not-found"), - dispose: () => Effect.void, - }); - const handler = buildHandler(NotFoundStoreLive, McpErrorReporterNoop); - - const get = await handler( - new Request("https://host.test/mcp", { - method: "GET", - headers: { - authorization: "Bearer x", - accept: "text/event-stream", - "mcp-session-id": "dead-session", - "mcp-protocol-version": "2025-06-18", - }, - }), - ); - expect(get.status).toBe(405); - expect(get.headers.get("allow")).toBe("POST, DELETE"); - expect(await get.json()).toMatchObject({ error: { code: -32001 } }); - - const post = await handler( - new Request("https://host.test/mcp", { - method: "POST", - headers: { - authorization: "Bearer x", - "content-type": "application/json", - "mcp-session-id": "dead-session", - "mcp-protocol-version": "2025-06-18", - }, - body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), - }), - ); - expect(post.status).toBe(404); - }); - - it("404s a modern request whose toolkit route is not served", async () => { - const handler = buildHandler(OkStoreLive, McpErrorReporterNoop); - const response = await handler(modernRequest("https://host.test/mcp/toolkits/unknown/extra")); - expect(response.status).toBe(404); + expect(response.headers.get("access-control-allow-headers") ?? "").toContain("authorization"); }); it("renders 500 -32603 + CORS and fires the reporter on an orchestration defect", async () => { @@ -356,27 +178,6 @@ describe("McpServingRoutes envelope", () => { }); }); -const modernRequest = (url: string): Request => - new Request(url, { - method: "POST", - headers: { - "content-type": "application/json", - "mcp-protocol-version": "2026-07-28", - "mcp-method": "server/discover", - }, - body: JSON.stringify({ - jsonrpc: "2.0", - id: 1, - method: "server/discover", - params: { - _meta: { - "io.modelcontextprotocol/protocolVersion": "2026-07-28", - "io.modelcontextprotocol/clientCapabilities": {}, - }, - }, - }), - }); - it("dispatches toolkit MCP routes with the parsed toolkit resource", async () => { const seen = await Effect.runPromise(Ref.make(null)); const RecordingStoreLive = Layer.succeed(McpSessionStore)({ diff --git a/packages/hosts/mcp/src/envelope.ts b/packages/hosts/mcp/src/envelope.ts index a32fd8213e..a2aa6756c2 100644 --- a/packages/hosts/mcp/src/envelope.ts +++ b/packages/hosts/mcp/src/envelope.ts @@ -1,31 +1,15 @@ import { Effect, Match, Predicate } from "effect"; import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; -import { - createMcpHandler, - isLegacyRequest, - type McpHttpHandler, - type McpRequestContext, -} from "@modelcontextprotocol/server"; import { defaultMcpResource, McpAuthProvider, McpErrorReporter, - McpModernServerBuilder, McpSessionStore, - mcpResourceKey, type AuthOutcome, type McpDispatchResult, type McpResource, - type Principal, } from "./seams"; -import { - appsEnabledForClientCapabilities, - clientCapabilitiesFromRequest, - mcpRequestStateBindingFromBody, - mcpRequestStatePrincipal, - requestBodyFromRequest, -} from "./tool-server"; // --------------------------------------------------------------------------- // Provider-neutral MCP serving envelope. @@ -46,7 +30,7 @@ import { // The envelope hard-codes ONLY the MCP serving paths and CORS. Everything else // — every `/.well-known/*` path, the resource-metadata URL, the authn/authz // semantics, and the entire session lifecycle (create + forward + ownership) — -// comes from the three seams. +// comes from the two seams. // // Runtime-agnostic: built on `effect/unstable/http` (HttpRouter), NO // platform-bun. The `/mcp` flow is fully Effect; the streamable-HTTP transport @@ -58,14 +42,6 @@ import { const MCP_PATH = "/mcp"; const TOOLKIT_MCP_PATH = "/mcp/toolkits/:toolkitSlug"; -// Static fallback only: the 2026-07-28 era mirrors request params into -// dynamic `Mcp-Param-` headers (SEP-2243), and CORS header names never -// glob — the preflight must echo `Access-Control-Request-Headers` verbatim to -// admit them. `*` would not help either: it is ignored for credentialed -// requests and never covers `Authorization`. -const MCP_CORS_ALLOWED_HEADERS = - "content-type, authorization, mcp-session-id, accept, mcp-protocol-version, mcp-method, mcp-name"; -const MCP_CORS_EXPOSED_HEADERS = "mcp-session-id, mcp-protocol-version, WWW-Authenticate"; /** The methods the streamable-HTTP transport accepts on `/mcp`. */ const ALLOWED_MCP_METHODS = new Set(["GET", "POST", "DELETE", "OPTIONS"]); @@ -92,19 +68,15 @@ const fromWebResponse = (response: Response): HttpServerResponse.HttpServerRespo * preflight against the metadata docs too (RFC 9728 discovery from a 401), so * the envelope answers OPTIONS for those paths, not only `/mcp`. */ -const corsPreflightResponse = (requestedHeaders?: string | null): Response => +const corsPreflightResponse = (): Response => new Response(null, { status: 204, headers: { "access-control-allow-origin": "*", "access-control-allow-methods": "GET, POST, DELETE, OPTIONS", - // Echo the browser's requested headers so dynamic `Mcp-Param-` - // names pass; the static list is the no-preflight-header fallback. "access-control-allow-headers": - requestedHeaders && requestedHeaders.trim() !== "" - ? requestedHeaders - : MCP_CORS_ALLOWED_HEADERS, - "access-control-expose-headers": MCP_CORS_EXPOSED_HEADERS, + "content-type, authorization, mcp-session-id, accept, mcp-protocol-version", + "access-control-expose-headers": "mcp-session-id, WWW-Authenticate", }, }); @@ -156,10 +128,6 @@ export const jsonRpcErrorBody = ( }); }; -/** Graceful rollback response that lets auto-negotiating v2 clients try legacy. */ -export const mcpModernDisabledResponse = (opts?: { readonly cors?: boolean }): Response => - jsonRpcErrorBody(400, -32022, "MCP 2026-07-28 support is disabled", opts); - /** * Advertised on transient-auth 503s (`Unavailable` outcomes) so clients back * off before retrying. Short: upstream auth-infra blips (JWKS fetch, IdP @@ -262,92 +230,8 @@ const renderDispatchError = (lookup: "not-found" | "forbidden", method: string): return jsonRpcResponse(404, -32001, "Session not found"); }; -const withModernMcpCors = (response: Response): Response => { - const headers = new Headers(response.headers); - headers.set("access-control-allow-origin", "*"); - headers.set("access-control-expose-headers", MCP_CORS_EXPOSED_HEADERS); - return new Response(response.body, { - status: response.status, - statusText: response.statusText, - headers, - }); -}; - -interface ModernRequestInputs { - readonly builder: McpModernServerBuilder["Service"]; - readonly parsedBody: unknown; - readonly principal: Principal; -} - -interface ModernMcpRouter { - readonly fetch: ( - request: Request, - principal: Principal, - resource: McpResource, - builder: McpModernServerBuilder["Service"], - ) => Promise; -} - -/** Build the resource-keyed, process-lifetime modern handler cache. */ -const makeModernMcpRouter = (): ModernMcpRouter => { - const handlers = new Map(); - const requestInputs = new WeakMap(); - let signingKey: Uint8Array | undefined; - - const getSigningKey = (): Uint8Array => - (signingKey ??= crypto.getRandomValues(new Uint8Array(32))); - - const handlerFor = (resource: McpResource): McpHttpHandler => { - const key = mcpResourceKey(resource); - const cached = handlers.get(key); - if (cached) return cached; - - const handler = createMcpHandler( - (context: McpRequestContext) => { - const request = context.requestInfo; - const inputs = request ? requestInputs.get(request) : undefined; - if (!request || !inputs) { - // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: the third-party McpServerFactory Promise contract has no typed failure channel; missing documented request context is an SDK defect - return Effect.runPromise(Effect.die("Modern MCP request has no authenticated context")); - } - return Effect.runPromise( - Effect.gen(function* () { - const clientCapabilities = yield* clientCapabilitiesFromRequest(request); - const requestStatePrincipal = mcpRequestStatePrincipal(inputs.principal); - const requestStateBinding = yield* Effect.promise(() => - mcpRequestStateBindingFromBody({ - body: inputs.parsedBody, - principal: requestStatePrincipal, - resource, - }), - ); - return yield* inputs.builder.build(inputs.principal, { - resource, - appsEnabled: appsEnabledForClientCapabilities(clientCapabilities), - requestStateSigningKey: getSigningKey(), - requestStatePrincipal, - ...(requestStateBinding === null ? {} : { requestStateBinding }), - }); - }), - ); - }, - { legacy: "reject" }, - ); - handlers.set(key, handler); - return handler; - }; - - return { - fetch: async (request, principal, resource, builder) => { - const parsedBody = await Effect.runPromise(requestBodyFromRequest(request)); - requestInputs.set(request, { builder, parsedBody, principal }); - return handlerFor(resource).fetch(request, { parsedBody }); - }, - }; -}; - /** Dispatch an MCP request through authenticate -> store.dispatch -> transport. */ -const mcpDispatch = (resource: McpResource, modern: ModernMcpRouter) => +const mcpDispatch = (resource: McpResource) => Effect.gen(function* () { const httpRequest = yield* HttpServerRequest.HttpServerRequest; const auth = yield* McpAuthProvider; @@ -356,9 +240,7 @@ const mcpDispatch = (resource: McpResource, modern: ModernMcpRouter) => // CORS preflight: answer before auth so unauthenticated clients can probe. if (request.method === "OPTIONS") { - return fromWebResponse( - corsPreflightResponse(request.headers.get("access-control-request-headers")), - ); + return fromWebResponse(corsPreflightResponse()); } // Streamable-HTTP only defines GET/POST/DELETE on the endpoint. Any other @@ -381,17 +263,6 @@ const mcpDispatch = (resource: McpResource, modern: ModernMcpRouter) => } const principal = outcome.principal; - if (!(yield* Effect.promise(() => isLegacyRequest(request)))) { - const builder = yield* McpModernServerBuilder; - if (builder.enabled === false) { - return fromWebResponse(mcpModernDisabledResponse()); - } - const response = yield* Effect.promise(() => - modern.fetch(request, principal, resource, builder), - ); - return fromWebResponse(withModernMcpCors(response)); - } - // No session id: per the streamable-HTTP transport contract, only POST opens // a session. A GET needs an existing id (400); a DELETE on nothing is a // no-op (204). Both short-circuit BEFORE dispatch so the store never spins up @@ -429,8 +300,8 @@ const mcpDispatch = (resource: McpResource, modern: ModernMcpRouter) => * otherwise, since the envelope returns a `Response`) and rendered as a stable * JSON-RPC 500 -32603 + CORS, rather than a bare platform 500 with no body. */ -const mcpRoute = (resource: McpResource, modern: ModernMcpRouter) => - mcpDispatch(resource, modern).pipe( +const mcpRoute = (resource: McpResource) => + mcpDispatch(resource).pipe( Effect.catchCause((cause) => Effect.gen(function* () { const reporter = yield* McpErrorReporter; @@ -440,16 +311,15 @@ const mcpRoute = (resource: McpResource, modern: ModernMcpRouter) => ), ); -const toolkitMcpRoute = (modern: ModernMcpRouter) => - Effect.gen(function* () { - const params = yield* HttpRouter.params; - const slug = params.toolkitSlug; - return yield* mcpRoute(slug ? { kind: "toolkit", slug } : defaultMcpResource, modern); - }); +const toolkitMcpRoute = Effect.gen(function* () { + const params = yield* HttpRouter.params; + const slug = params.toolkitSlug; + return yield* mcpRoute(slug ? { kind: "toolkit", slug } : defaultMcpResource); +}); /** * The shared MCP serving routes, as an `HttpRouter.use` Layer. A host merges - * this with its other routes and provides the three seam Layers + the HTTP + * this with its other routes and provides the two seam Layers + the HTTP * platform services. Provider-neutral: cloud adopts the same Layer next. * * The discovery `GET` routes come from `McpAuthProvider.discoveryRoutes`, so @@ -460,22 +330,16 @@ const toolkitMcpRoute = (modern: ModernMcpRouter) => export const McpServingRoutes = HttpRouter.use((router) => Effect.gen(function* () { const auth = yield* McpAuthProvider; - const modern = makeModernMcpRouter(); for (const route of auth.discoveryRoutes) { yield* router.add("GET", route.path, discoveryRoute(route.handler)); yield* router.add( "OPTIONS", route.path, - Effect.gen(function* () { - const preflight = yield* HttpServerRequest.HttpServerRequest; - return fromWebResponse( - corsPreflightResponse(preflight.headers["access-control-request-headers"] ?? null), - ); - }), + Effect.sync(() => fromWebResponse(corsPreflightResponse())), ); } - yield* router.add("*", MCP_PATH, mcpRoute(defaultMcpResource, modern)); - yield* router.add("*", TOOLKIT_MCP_PATH, toolkitMcpRoute(modern)); + yield* router.add("*", MCP_PATH, mcpRoute(defaultMcpResource)); + yield* router.add("*", TOOLKIT_MCP_PATH, toolkitMcpRoute); }), ); @@ -497,12 +361,7 @@ export const McpDiscoveryRoutes = HttpRouter.use((router) => yield* router.add( "OPTIONS", route.path, - Effect.gen(function* () { - const preflight = yield* HttpServerRequest.HttpServerRequest; - return fromWebResponse( - corsPreflightResponse(preflight.headers["access-control-request-headers"] ?? null), - ); - }), + Effect.sync(() => fromWebResponse(corsPreflightResponse())), ); } }), diff --git a/packages/hosts/mcp/src/in-memory-session-store.test.ts b/packages/hosts/mcp/src/in-memory-session-store.test.ts index 6c61e9bcab..8d87f56970 100644 --- a/packages/hosts/mcp/src/in-memory-session-store.test.ts +++ b/packages/hosts/mcp/src/in-memory-session-store.test.ts @@ -1,20 +1,12 @@ -import { describe, expect, it } from "@effect/vitest"; +import { expect, it } from "@effect/vitest"; import { Effect } from "effect"; -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; -import { ElicitRequestSchema } from "@modelcontextprotocol/sdk/types.js"; - -import type { ExecutionEngine, ExecutionResult, ResumeResponse } from "@executor-js/execution"; -import { FormElicitation, ToolAddress } from "@executor-js/sdk"; import { makeInMemoryMcpSessionStore, McpEngineBuildError, type McpBuildServerOptions, } from "./in-memory-session-store"; -import { EXTENSION_ID, RESOURCE_MIME_TYPE } from "./mcp-apps"; import { defaultMcpResource, type Principal } from "./seams"; -import { buildMcpServer } from "./tool-server"; const TEST_PRINCIPAL: Principal = { accountId: "acct_test", @@ -26,158 +18,37 @@ const TEST_PRINCIPAL: Principal = { roles: ["user"], }; -const TOOL_ADDRESS = ToolAddress.make("tools.test.org.main.approve"); - -const makeElicitingEngine = (): { - readonly engine: ExecutionEngine; - readonly resumedWith: () => ResumeResponse | undefined; -} => { - const request = FormElicitation.make({ - message: "Which value?", - requestedSchema: { - type: "object", - properties: { value: { type: "string" } }, - required: ["value"], - }, +it("preserves native elicitation mode when creating an in-memory MCP session", async () => { + let buildOptions: McpBuildServerOptions | undefined; + const sessions = makeInMemoryMcpSessionStore((_principal, options) => { + buildOptions = options; + return Effect.fail(new McpEngineBuildError({ cause: "stop after capturing options" })); }); - const paused: Extract = { - status: "paused", - execution: { - id: "execution-legacy", - elicitationContext: { address: TOOL_ADDRESS, args: {}, request }, - }, - }; - let resumedWith: ResumeResponse | undefined; - return { - engine: { - execute: () => Effect.succeed({ result: "unused" }), - executeWithPause: () => Effect.succeed(paused), - resume: (_executionId, response) => { - resumedWith = response; - return Effect.succeed({ - status: "completed", - result: { result: response.content?.value }, - }); - }, - isExecutionSettled: () => Effect.succeed(false), - getPausedExecution: (executionId) => - Effect.succeed(executionId === paused.execution.id ? paused.execution : null), - pausedExecutionCount: () => Effect.succeed(1), - hasPausedExecutions: () => Effect.succeed(true), - getDescription: Effect.succeed("store integration test executor"), - }, - resumedWith: () => resumedWith, - }; -}; - -describe("in-memory MCP session store", () => { - it("preserves native elicitation mode and supplies the session inputs", async () => { - let buildOptions: McpBuildServerOptions | undefined; - const sessions = makeInMemoryMcpSessionStore((_principal, options) => { - buildOptions = options; - return Effect.fail(new McpEngineBuildError({ cause: "stop after capturing options" })); - }); - const result = await Effect.runPromise( - sessions.store.dispatch({ - request: new Request("https://executor.test/mcp?elicitation_mode=native", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ - jsonrpc: "2.0", - id: 1, - method: "initialize", - params: { - protocolVersion: "2025-06-18", - capabilities: { elicitation: { form: {} } }, - clientInfo: { name: "test-client", version: "1.0.0" }, - }, - }), - }), - principal: TEST_PRINCIPAL, - resource: defaultMcpResource, - sessionId: null, + const result = await Effect.runPromise( + sessions.store.dispatch({ + request: new Request("https://executor.test/mcp?elicitation_mode=native", { method: "POST", - }), - ); - - expect(result).toBeInstanceOf(Response); - expect((result as Response).status).toBe(500); - expect(buildOptions?.elicitationMode).toEqual({ mode: "native" }); - expect(buildOptions).toMatchObject({ - appsEnabled: false, - requestStatePrincipal: `${TEST_PRINCIPAL.accountId}\u0000${TEST_PRINCIPAL.organizationId}`, - sessionful: true, - }); - expect(buildOptions?.requestStateSigningKey).toBeInstanceOf(Uint8Array); - }); - - it("serves a legacy client with live Apps capabilities, elicitation, and reuse", async () => { - const { engine, resumedWith } = makeElicitingEngine(); - const sessions = makeInMemoryMcpSessionStore((_principal, options) => - buildMcpServer({ - engine, - ...options, - loadAppShellHtml: async () => "", - }).pipe(Effect.map((mcpServer) => ({ mcpServer, engine }))), - ); - const fetch = async (input: string | URL | Request, init?: RequestInit): Promise => { - const request = - input instanceof Request ? new Request(input, init) : new Request(input.toString(), init); - const result = await Effect.runPromise( - sessions.store.dispatch({ - request, - principal: TEST_PRINCIPAL, - resource: defaultMcpResource, - sessionId: request.headers.get("mcp-session-id"), - method: request.method, + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: { elicitation: { form: {} } }, + clientInfo: { name: "test-client", version: "1.0.0" }, + }, }), - ); - return result instanceof Response - ? result - : new Response(result === "forbidden" ? "Forbidden" : "Not found", { - status: result === "forbidden" ? 403 : 404, - }); - }; - const transport = new StreamableHTTPClientTransport( - new URL("https://executor.test/mcp?elicitation_mode=native"), - { fetch }, - ); - const client = new Client( - { name: "legacy-store-client", version: "1.0.0" }, - { - capabilities: { - elicitation: { form: {} }, - extensions: { [EXTENSION_ID]: { mimeTypes: [RESOURCE_MIME_TYPE] } }, - }, - }, - ); - let elicitationRequests = 0; - client.setRequestHandler(ElicitRequestSchema, async (request) => { - elicitationRequests += 1; - expect(request.params).toMatchObject({ message: "Which value?" }); - return { action: "accept" as const, content: { value: "approved" } }; - }); - - await client.connect(transport); - // oxlint-disable-next-line executor/no-try-catch-or-throw -- test boundary: always close the sessionful client and store - try { - const tools = await client.listTools(); - expect(tools.tools.map(({ name }) => name)).toContain("execute"); - expect(tools.tools.map(({ name }) => name)).toContain("execute-action"); - - const result = await client.callTool({ - name: "execute", - arguments: { code: "await tools.test.approve()" }, - }); - expect(result.content).toEqual([{ type: "text", text: "approved" }]); - expect(result.isError).toBeFalsy(); - expect(elicitationRequests).toBe(1); - expect(resumedWith()).toEqual({ action: "accept", content: { value: "approved" } }); - expect(sessions.sessionCount()).toBe(1); - } finally { - await client.close(); - await sessions.close(); - } - }); + }), + principal: TEST_PRINCIPAL, + resource: defaultMcpResource, + sessionId: null, + method: "POST", + }), + ); + + expect(result).toBeInstanceOf(Response); + expect((result as Response).status).toBe(500); + expect(buildOptions?.elicitationMode).toEqual({ mode: "native" }); }); diff --git a/packages/hosts/mcp/src/in-memory-session-store.ts b/packages/hosts/mcp/src/in-memory-session-store.ts index 64ca5f9d92..2cd870fc1b 100644 --- a/packages/hosts/mcp/src/in-memory-session-store.ts +++ b/packages/hosts/mcp/src/in-memory-session-store.ts @@ -1,8 +1,6 @@ import { Cause, Data, Effect, Layer } from "effect"; -import { - type McpServer, - WebStandardStreamableHTTPServerTransport, -} from "@modelcontextprotocol/server"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"; import { formatPausedExecution, type ExecutionEngine } from "@executor-js/execution"; @@ -28,7 +26,7 @@ import { type Principal, type McpResource, } from "./seams"; -import { mcpRequestStatePrincipal, type BrowserApprovalStore } from "./tool-server"; +import type { BrowserApprovalStore } from "./tool-server"; // --------------------------------------------------------------------------- // In-process McpSessionStore — the single-node serving store, shared by every @@ -77,20 +75,12 @@ export interface McpBuildServerOptions { * with `?artifacts=false`; opted out, the built server registers none of * the artifact tools, resource, or skills. */ readonly artifactsEnabled?: boolean; - /** The sessionful assembly starts disabled and replaces this from initialize. */ - readonly appsEnabled: false; - /** Process-lifetime HMAC key for legacy-shim continuation state. */ - readonly requestStateSigningKey: Uint8Array; - /** Stable authenticated owner bound into continuation state. */ - readonly requestStatePrincipal: string; - /** Selects live negotiated capabilities instead of stateless request policy. */ - readonly sessionful: true; } /** Build the per-session `McpServer` + engine for a principal (the host's engine + tools). */ export type McpBuildServer = ( principal: Principal, - options: McpBuildServerOptions, + options?: McpBuildServerOptions, ) => Effect.Effect; export interface InMemoryMcpSessionStore { @@ -114,17 +104,10 @@ export interface InMemoryMcpSessionStore { request: Request, principal?: Principal, ) => Promise; - /** Number of live initialized sessions currently owned by this store. */ - readonly sessionCount: () => number; /** Dispose every live session — wire into the host's shutdown (not a seam). */ readonly close: () => Promise; } -type McpRequestBuildOptions = Pick< - McpBuildServerOptions, - "artifactsEnabled" | "browserApprovalStore" | "elicitationMode" ->; - const ignoreClose = (close: (() => Promise) | undefined): Promise => close ? Effect.runPromise(Effect.ignore(Effect.tryPromise({ try: close, catch: () => undefined }))) @@ -179,7 +162,6 @@ export const makeInMemoryMcpSessionStore = ( const owners = new Map(); const engines = new Map>(); const approvals: InProcessBrowserApprovalStore = makeInProcessBrowserApprovalStore(); - const requestStateSigningKey = crypto.getRandomValues(new Uint8Array(32)); const dispose = async (id: string, opts: { transport?: boolean; server?: boolean } = {}) => { const transport = transports.get(id); @@ -240,7 +222,7 @@ export const makeInMemoryMcpSessionStore = ( const buildOptionsFor = ( request: Request, sessionId: () => string | null, - ): McpRequestBuildOptions => { + ): McpBuildServerOptions => { const artifactsEnabled = readArtifactsEnabled(request); const mode = readElicitationMode(request); if (mode !== "browser") return { artifactsEnabled, elicitationMode: { mode } }; @@ -271,19 +253,12 @@ export const makeInMemoryMcpSessionStore = ( return buildServer(principal, { ...buildOptionsFor(request, () => createdSessionId), resource, - appsEnabled: false, - requestStateSigningKey, - requestStatePrincipal: mcpRequestStatePrincipal(principal), - sessionful: true, }).pipe( Effect.flatMap(({ mcpServer, engine }) => Effect.gen(function* () { const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: () => crypto.randomUUID(), - // Native mode needs an open SSE response for the legacy shim's - // server→client elicitation request. Other modes preserve the - // store's existing single-JSON response behavior. - enableJsonResponse: readElicitationMode(request) !== "native", + enableJsonResponse: true, onsessioninitialized: (sid) => { createdSessionId = sid; transports.set(sid, transport); @@ -401,7 +376,6 @@ export const makeInMemoryMcpSessionStore = ( store, handlePausedRequest, handleApprovalRequest, - sessionCount: () => transports.size, close: async () => { const ids = new Set([...transports.keys(), ...servers.keys()]); await Promise.all([...ids].map((id) => dispose(id, { transport: true, server: true }))); diff --git a/packages/hosts/mcp/src/index.ts b/packages/hosts/mcp/src/index.ts index 77da891a1f..2e536296d9 100644 --- a/packages/hosts/mcp/src/index.ts +++ b/packages/hosts/mcp/src/index.ts @@ -5,17 +5,17 @@ // its seams (`McpAuthProvider` / `McpSessionStore` / `McpErrorReporter` / // `Principal`) + the canonical JSON-RPC error renderer (`jsonRpcErrorBody`). // -// The executor tool assemblies (execute/resume tools, elicitation and browser -// approval bridges, Zod input schemas) are a different center of gravity. They -// live behind the `tool-server` subpath so this serving -// surface stays small and dependency-light. +// The executor TOOL factory (`createExecutorMcpServer` — the execute/resume +// tools, the elicitation/browser-approval bridge, the Zod input schemas) is a +// different center of gravity: a host's session store builds an `McpServer` +// from it. It lives behind the `@executor-js/host-mcp/tool-server` subpath so +// the serving surface stays small and dependency-light. // --------------------------------------------------------------------------- export { Principal, McpAuthProvider, McpSessionStore, - McpModernServerBuilder, McpErrorReporter, McpErrorReporterNoop, defaultMcpResource, @@ -33,7 +33,6 @@ export { type McpDiscoveryRoute, type McpDispatchInput, type McpDispatchResult, - type McpModernServerBuildOptions, type McpResource, } from "./seams"; @@ -41,6 +40,5 @@ export { McpServingRoutes, McpDiscoveryRoutes, jsonRpcErrorBody, - mcpModernDisabledResponse, UNAVAILABLE_RETRY_AFTER_SECONDS, } from "./envelope"; diff --git a/packages/hosts/mcp/src/mcp-apps.test.ts b/packages/hosts/mcp/src/mcp-apps.test.ts deleted file mode 100644 index ee95271a7b..0000000000 --- a/packages/hosts/mcp/src/mcp-apps.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { describe, expect, it } from "@effect/vitest"; -import { Client } from "@modelcontextprotocol/client"; -import { InMemoryTransport, McpServer } from "@modelcontextprotocol/server"; - -import { - EXTENSION_ID, - getUiCapability, - registerAppResource, - registerAppTool, - RESOURCE_MIME_TYPE, - RESOURCE_URI_META_KEY, -} from "./mcp-apps"; - -const APP_URI = "ui://executor/test.html"; - -const withClient = async ( - configure: (server: McpServer) => void, - run: (client: Client) => Promise, -) => { - const server = new McpServer( - { name: "apps-helper-test", version: "1.0.0" }, - { capabilities: { resources: {}, tools: {} } }, - ); - configure(server); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const client = new Client({ name: "apps-helper-client", version: "1.0.0" }); - await server.connect(serverTransport); - await client.connect(clientTransport); - // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: test helper owns both linked transports and always closes them - try { - await run(client); - } finally { - await clientTransport.close(); - await serverTransport.close(); - } -}; - -describe("vendored MCP Apps helpers", () => { - it("mirrors nested resourceUri metadata to the legacy key and preserves visibility", async () => { - await withClient( - (server) => { - registerAppTool( - server, - "nested-meta", - { - _meta: { - ui: { resourceUri: APP_URI, visibility: ["model"] }, - }, - }, - async () => ({ content: [{ type: "text", text: "ok" }] }), - ); - }, - async (client) => { - const tool = (await client.listTools()).tools.find(({ name }) => name === "nested-meta"); - expect(tool?._meta).toEqual({ - ui: { resourceUri: APP_URI, visibility: ["model"] }, - [RESOURCE_URI_META_KEY]: APP_URI, - }); - }, - ); - }); - - it("mirrors the legacy resourceUri key to nested UI metadata", async () => { - await withClient( - (server) => { - registerAppTool( - server, - "legacy-meta", - { _meta: { [RESOURCE_URI_META_KEY]: APP_URI } }, - async () => ({ content: [{ type: "text", text: "ok" }] }), - ); - }, - async (client) => { - const tool = (await client.listTools()).tools.find(({ name }) => name === "legacy-meta"); - expect(tool?._meta).toEqual({ - [RESOURCE_URI_META_KEY]: APP_URI, - ui: { resourceUri: APP_URI }, - }); - }, - ); - }); - - it("defaults app resources to the MCP Apps MIME type", async () => { - await withClient( - (server) => { - registerAppResource(server, "Test App", APP_URI, {}, async () => ({ - contents: [{ uri: APP_URI, text: "" }], - })); - }, - async (client) => { - const resource = (await client.listResources()).resources.find( - ({ uri }) => uri === APP_URI, - ); - expect(resource?.mimeType).toBe(RESOURCE_MIME_TYPE); - }, - ); - }); - - it("extracts the MCP Apps extension capability", () => { - const capability = { mimeTypes: [RESOURCE_MIME_TYPE] }; - expect( - getUiCapability({ - extensions: { [EXTENSION_ID]: capability }, - }), - ).toBe(capability); - expect(getUiCapability({})).toBeUndefined(); - expect(getUiCapability(undefined)).toBeUndefined(); - }); -}); diff --git a/packages/hosts/mcp/src/mcp-apps.ts b/packages/hosts/mcp/src/mcp-apps.ts deleted file mode 100644 index b73d042f59..0000000000 --- a/packages/hosts/mcp/src/mcp-apps.ts +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Temporary MCP Apps server helpers for the current MCP SDK. - * - * This is a wire-compatible local copy of the helpers currently published by - * the upstream ext-apps server package. Remove this module once - * https://github.com/modelcontextprotocol/ext-apps/issues/702 is resolved. - */ -import type { - ClientCapabilities, - McpServer, - ReadResourceCallback, - RegisteredResource, - RegisteredTool, - ResourceMetadata, - StandardSchemaWithJSON, - ToolAnnotations, - ToolCallback, -} from "@modelcontextprotocol/server"; - -/** The legacy flat metadata key understood by older MCP Apps hosts. */ -export const RESOURCE_URI_META_KEY = "ui/resourceUri"; - -/** MIME type used by MCP Apps HTML resources. */ -export const RESOURCE_MIME_TYPE = "text/html;profile=mcp-app"; - -/** MCP capability-extension identifier for MCP Apps support. */ -export const EXTENSION_ID = "io.modelcontextprotocol/ui"; - -/** Model/app visibility scopes supported by MCP Apps tool metadata. */ -export type McpAppToolVisibility = "model" | "app"; - -/** MCP Apps metadata attached to a tool. */ -export type McpAppToolMeta = { - readonly resourceUri?: string; - readonly visibility?: readonly McpAppToolVisibility[]; -}; - -/** MCP Apps capability data advertised by a client. */ -export type McpUiClientCapabilities = { - readonly mimeTypes?: readonly string[]; -}; - -/** Client capabilities shape carrying the MCP Apps extension. */ -export type McpAppsClientCapabilities = ClientCapabilities & { - readonly extensions?: Record; -}; - -/** Tool configuration accepted by {@link registerAppTool}. */ -export type McpAppToolConfig< - InputArgs extends StandardSchemaWithJSON | undefined = undefined, - OutputArgs extends StandardSchemaWithJSON | undefined = undefined, -> = { - readonly title?: string; - readonly description?: string; - readonly inputSchema?: InputArgs; - readonly outputSchema?: OutputArgs; - readonly annotations?: ToolAnnotations; - readonly _meta: Record & { - readonly ui?: McpAppToolMeta; - readonly [RESOURCE_URI_META_KEY]?: string; - }; -}; - -/** Resource configuration accepted by {@link registerAppResource}. */ -export type McpAppResourceConfig = ResourceMetadata & { - readonly _meta?: Record & { - readonly ui?: Record; - }; -}; - -/** - * Register an MCP Apps tool while mirroring nested and legacy resource URI - * metadata in both directions. - */ -export const registerAppTool = < - InputArgs extends StandardSchemaWithJSON | undefined = undefined, - OutputArgs extends StandardSchemaWithJSON | undefined = undefined, ->( - server: Pick, - name: string, - config: McpAppToolConfig, - callback: ToolCallback, -): RegisteredTool => { - const ui = config._meta.ui; - const legacyResourceUri = config._meta[RESOURCE_URI_META_KEY]; - let metadata = config._meta; - - if (ui?.resourceUri && !legacyResourceUri) { - metadata = { ...config._meta, [RESOURCE_URI_META_KEY]: ui.resourceUri }; - } else if (legacyResourceUri && !ui?.resourceUri) { - metadata = { ...config._meta, ui: { ...ui, resourceUri: legacyResourceUri } }; - } - - return server.registerTool( - name, - { - ...config, - _meta: metadata, - }, - callback, - ); -}; - -/** Register an MCP Apps resource, defaulting its MIME type when omitted. */ -export const registerAppResource = ( - server: Pick, - name: string, - uri: string, - config: McpAppResourceConfig, - readCallback: ReadResourceCallback, -): RegisteredResource => - server.registerResource(name, uri, { mimeType: RESOURCE_MIME_TYPE, ...config }, readCallback); - -/** Read MCP Apps extension data from a client's capabilities. */ -export const getUiCapability = ( - clientCapabilities: McpAppsClientCapabilities | null | undefined, -): McpUiClientCapabilities | undefined => clientCapabilities?.extensions?.[EXTENSION_ID]; diff --git a/packages/hosts/mcp/src/seams.ts b/packages/hosts/mcp/src/seams.ts index 45ee61b639..12e713dd91 100644 --- a/packages/hosts/mcp/src/seams.ts +++ b/packages/hosts/mcp/src/seams.ts @@ -1,11 +1,10 @@ import { Context, Effect, Layer, Schema } from "effect"; import type { Cause } from "effect"; -import type { McpServer } from "@modelcontextprotocol/server"; // --------------------------------------------------------------------------- // Provider-neutral MCP serving seams. // -// The shared MCP serving envelope (see `./envelope`) depends ONLY on these THREE +// The shared MCP serving envelope (see `./envelope`) depends ONLY on these TWO // seams. Each product (self-host, cloud, local) provides its own Layer // satisfying the same tags; the envelope never changes. The seams are kept // deliberately small — anything provider-specific (Durable-Object trace @@ -13,18 +12,17 @@ import type { McpServer } from "@modelcontextprotocol/server"; // per-org engine construction) is configured *inside* a provider's adapter and // never baked into the envelope. // -// Three seams, deliberately: +// Two seams, deliberately: // 1. McpAuthProvider — called on EVERY request. Authenticate AND authorize // (it may read the `mcp-session-id` header to do session-aware org-authz). // 2. McpSessionStore — owns the serving session lifecycle: create + forward + // ownership, end to end, via a single `dispatch`. The store builds/forwards // the transport and returns the transport `Response`. -// 3. McpModernServerBuilder — builds one stateless MCP server for each -// authenticated modern request. The envelope owns handler/bus lifetime. // -// There is deliberately NO envelope-level engine seam. Both server builders -// remain host adapters; the envelope only chooses the protocol era and supplies -// request/resource/auth context. +// There is deliberately NO envelope-level engine seam. Self-host's in-process +// store builds its engine via an INTERNAL dependency (its Layer provides it); +// cloud's Durable-Object store builds its engine inside the DO. The engine is a +// store implementation detail, not an envelope seam. // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- @@ -273,43 +271,7 @@ export class McpSessionStore extends Context.Service< >()("@executor-js/host-mcp/McpSessionStore") {} // =========================================================================== -// SEAM 3 — McpModernServerBuilder: one stateless MCP server per request. -// =========================================================================== - -/** Request-scoped inputs the envelope adds to a host's modern server config. */ -export interface McpModernServerBuildOptions { - /** The served endpoint whose capability policy the server must apply. */ - readonly resource: McpResource; - /** Whether this request's client advertised MCP Apps HTML support. */ - readonly appsEnabled: boolean; - /** Process-lifetime key used to sign opaque request continuation state. */ - readonly requestStateSigningKey: Uint8Array | string; - /** Stable authenticated-owner key bound into signed continuation state. */ - readonly requestStatePrincipal: string; - /** Closed resource/tool/code binding for this parsed modern request. */ - readonly requestStateBinding?: string; -} - -/** - * Build one stateless MCP server for an authenticated modern request. - * - * The envelope owns the cached `createMcpHandler` and its subscriptions bus; - * providers own execution-stack construction and tool configuration here. - */ -export class McpModernServerBuilder extends Context.Service< - McpModernServerBuilder, - { - /** Inbound-only emergency switch. Unset means modern serving is enabled. */ - readonly enabled?: boolean; - readonly build: ( - principal: Principal, - options: McpModernServerBuildOptions, - ) => Effect.Effect; - } ->()("@executor-js/host-mcp/McpModernServerBuilder") {} - -// =========================================================================== -// SEAM 4 (optional) — McpErrorReporter: observe a request-orchestration defect. +// SEAM 3 (optional) — McpErrorReporter: observe a request-orchestration defect. // // The envelope wraps the entire `/mcp` handling in a top-level `catchCause` and // renders a JSON-RPC 500 -32603 (the streamable-HTTP transport never sees the diff --git a/packages/hosts/mcp/src/stdio-integration.test.ts b/packages/hosts/mcp/src/stdio-integration.test.ts index 8b831b1b4b..d66f9893fc 100644 --- a/packages/hosts/mcp/src/stdio-integration.test.ts +++ b/packages/hosts/mcp/src/stdio-integration.test.ts @@ -1,90 +1,30 @@ import { describe, expect, it } from "@effect/vitest"; -import { Client as ModernClient } from "@modelcontextprotocol/client"; -import { StdioClientTransport as ModernStdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; -import { ElicitRequestSchema } from "@modelcontextprotocol/sdk/types.js"; -import { Effect, Schema } from "effect"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { Effect } from "effect"; +import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; const repoRoot = resolve(import.meta.dirname, "../../../.."); const cliEntry = resolve(repoRoot, "apps/cli/src/main.ts"); const testScope = resolve(repoRoot, "apps/local"); -const stdioServerEntry = resolve(repoRoot, "apps/local/src/mcp-stdio-test-server.ts"); -const stdioServer = { - command: "bun", - args: ["run", stdioServerEntry], -}; -const decodeDaemonManifest = Schema.decodeUnknownSync( - Schema.fromJsonString(Schema.Struct({ pid: Schema.Number })), -); - -const isProcessGroupAlive = (pid: number): boolean => { - // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: process liveness probing reports false after the test daemon is reaped - try { - process.kill(process.platform === "win32" ? pid : -pid, 0); - return true; - } catch { - return false; - } -}; - -const signalProcessGroup = (pid: number, signal: NodeJS.Signals): void => { - // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: Windows and pre-detach failures require a direct-pid fallback - try { - process.kill(process.platform === "win32" ? pid : -pid, signal); - } catch { - // oxlint-disable-next-line executor/no-try-catch-or-throw -- cleanup tolerates a daemon that exited between liveness check and signal - try { - process.kill(pid, signal); - } catch {} - } -}; - -const stopAutoSpawnedDaemon = async (dataDir: string): Promise => { - // oxlint-disable-next-line executor/no-try-catch-or-throw -- cleanup tolerates startup that failed before publishing a manifest - try { - const manifest = decodeDaemonManifest( - readFileSync(join(dataDir, "server-control", "server.json"), "utf8"), - ); - if (!Number.isSafeInteger(manifest.pid) || manifest.pid <= 0) return; - - const pid = manifest.pid; - signalProcessGroup(pid, "SIGTERM"); - const deadline = performance.now() + 10_000; - while (isProcessGroupAlive(pid) && performance.now() < deadline) { - await new Promise((resolve) => setTimeout(resolve, 50)); - } - if (isProcessGroupAlive(pid)) signalProcessGroup(pid, "SIGKILL"); - } catch { - // No manifest means there is no auto-started daemon to stop. - } -}; - -const withTempData = Effect.acquireRelease( - Effect.sync(() => mkdtempSync(join(tmpdir(), "executor-mcp-test-"))), - (dataDir) => - Effect.promise(async () => { - await stopAutoSpawnedDaemon(dataDir); - rmSync(dataDir, { recursive: true, force: true }); - }), -); describe("MCP stdio integration", () => { it.effect( - "execute tool returns result over the CLI stdio bridge", + "execute tool returns result over stdio transport", () => Effect.gen(function* () { // Fresh temp dir so the test doesn't migrate against the developer's // real ~/.executor/data.db. - const dataDir = yield* withTempData; + const dataDir = mkdtempSync(join(tmpdir(), "executor-mcp-test-")); + const transport = new StdioClientTransport({ command: "bun", args: ["run", cliEntry, "mcp", "--scope", testScope], env: { ...process.env, EXECUTOR_DATA_DIR: dataDir }, }); + const client = new Client({ name: "test-client", version: "1.0.0" }, { capabilities: {} }); yield* Effect.acquireRelease( @@ -93,7 +33,7 @@ describe("MCP stdio integration", () => { ); const { tools } = yield* Effect.promise(() => client.listTools()); - expect(tools.map(({ name }) => name)).toContain("execute"); + expect(tools.map((t) => t.name)).toContain("execute"); const result = yield* Effect.promise(() => client.callTool({ @@ -108,77 +48,4 @@ describe("MCP stdio integration", () => { }).pipe(Effect.scoped), { timeout: 30_000 }, ); - - it.effect( - "serves a legacy client and completes the native elicitation round-trip", - () => - Effect.gen(function* () { - const transport = new StdioClientTransport(stdioServer); - const client = new Client( - { name: "legacy-stdio-test-client", version: "1.0.0" }, - { capabilities: { elicitation: { form: {} } } }, - ); - let elicitationRequests = 0; - client.setRequestHandler(ElicitRequestSchema, async (request) => { - elicitationRequests += 1; - expect(request.params).toMatchObject({ message: "Approve the stdio action?" }); - return { action: "accept" as const, content: { value: "approved" } }; - }); - - yield* Effect.acquireRelease( - Effect.promise(() => client.connect(transport)), - () => Effect.promise(() => transport.close()), - ); - - const { tools } = yield* Effect.promise(() => client.listTools()); - expect(tools.map((t) => t.name)).toContain("execute"); - - const result = yield* Effect.promise(() => - client.callTool({ - name: "execute", - arguments: { code: "needs approval" }, - }), - ); - - const text = (result.content as Array<{ type: string; text: string }>)[0]?.text; - expect(text).toContain("approved"); - expect(result.isError).toBeFalsy(); - expect(elicitationRequests).toBe(1); - }).pipe(Effect.scoped), - { timeout: 30_000 }, - ); - - it.effect( - "serves a modern-pinned client over the same stdio entry", - () => - Effect.gen(function* () { - const transport = new ModernStdioClientTransport(stdioServer); - const client = new ModernClient( - { name: "modern-stdio-test-client", version: "1.0.0" }, - { - capabilities: {}, - versionNegotiation: { mode: { pin: "2026-07-28" } }, - }, - ); - - yield* Effect.acquireRelease( - Effect.promise(() => client.connect(transport)), - () => Effect.promise(() => transport.close()), - ); - - const { tools } = yield* Effect.promise(() => client.listTools()); - expect(tools.map(({ name }) => name)).toContain("execute"); - - const result = yield* Effect.promise(() => - client.callTool({ - name: "execute", - arguments: { code: "return 2+2" }, - }), - ); - - expect(result.content).toEqual([{ type: "text", text: "4" }]); - expect(result.isError).toBeFalsy(); - }).pipe(Effect.scoped), - { timeout: 30_000 }, - ); }); diff --git a/packages/hosts/mcp/src/tool-server-core.ts b/packages/hosts/mcp/src/tool-server-core.ts deleted file mode 100644 index a4cf5eab48..0000000000 --- a/packages/hosts/mcp/src/tool-server-core.ts +++ /dev/null @@ -1,2216 +0,0 @@ -import { Duration, Effect, Match, Option, Predicate, Result, Schema } from "effect"; -import * as Cause from "effect/Cause"; -import { ContentBlockSchema, ToolAnnotationsSchema } from "@modelcontextprotocol/core"; -import type { InputRequiredResult } from "@modelcontextprotocol/server"; -import * as z from "zod/v4"; - -import { isToolFile, sanitizeArtifactPreviewMarkup } from "@executor-js/sdk"; -import type { - Artifact, - ArtifactBinding, - ArtifactSummary, - ElicitationRequest, - SaveArtifactInput, - ToolFileValue, -} from "@executor-js/sdk"; -import type * as Tracer from "effect/Tracer"; -import { - createExecutionEngine, - formatExecuteResult, - formatPausedExecution, - formatTtlDuration, - findSkill, - renderSkillsIndex, - skillCatalogFor, - EXECUTE_SKILL, - INTEGRATION_INVENTORY_HEADER, - type Skill, - type ExecutionEngine, - type ExecutionEngineConfig, - type ResumeResponse, - type ExecutionResult, - type PausedExecution, - type PausedExecutionDeadline, -} from "@executor-js/execution"; -import { - MCP_APPS_SHELL_RESOURCE_URI, - applyArtifactEdits, - smokeRenderRejection, - validateArtifactCode, - type ArtifactEdit, - type ArtifactSmokeRenderResult, -} from "./create-artifact"; -import { TOOL_CALL_CONTRACT_MESSAGE } from "./tool-call-code"; -import { resolveArtifactAction } from "./artifact-action"; -import { - extractArtifactRoles, - resolveArtifactBindings, - type BindableConnection, -} from "./artifact-bindings"; -import { RESOURCE_MIME_TYPE } from "./mcp-apps"; - -// --------------------------------------------------------------------------- -// Shared config -// --------------------------------------------------------------------------- - -type SharedMcpServerConfig = { - /** - * Pre-built `execute` tool description. When provided, the factory skips - * its internal `engine.getDescription` yield. Useful when the caller - * wants to compute the description inside its own Effect tracer context - * so sub-spans (`executor.integrations.list`, `executor.tools.list`) nest as - * children of the caller's root span. - */ - readonly description?: string; - /** - * Parent span override for engine calls. The factory captures the - * caller's context at construction time, but `Effect.runPromiseWith` - * starts a fresh fiber per SDK callback — so the `currentSpan` - * FiberRef resets to root unless explicitly anchored. - * - * Accepts either a fixed span (per-request McpServer instances) or a - * getter (session-scoped instances that need to anchor each callback - * under whichever request triggered it; see the Cloud DO). - */ - readonly parentSpan?: Tracer.AnySpan | (() => Tracer.AnySpan | undefined); - /** - * Enable verbose MCP capability / elicitation debug logging. - */ - readonly debug?: boolean; - /** - * Controls how elicitation is handled for this MCP connection. The default - * is model-managed resume, where paused executions expose interaction - * metadata and the model can call `resume` with the user's response. - */ - readonly elicitationMode?: - | { - readonly mode: "browser"; - readonly approvalUrl: (executionId: string) => string; - } - | { - readonly mode: "model"; - } - | { - readonly mode: "native"; - }; - readonly browserApprovalStore?: BrowserApprovalStore; - /** - * Host-owned lifecycle for paused executions. The MCP server reports pause - * boundaries; the host decides whether that means a keepAlive lease, browser - * wait, durable record, or no-op. - */ - readonly pausedExecutionHooks?: PausedExecutionHooks; - /** - * Host-provided approval lease duration. When present, paused payloads carry - * an absolute deadline and hooks receive the same deadline. - */ - readonly pausedExecutionLeaseMs?: number; - /** - * Optional host-owned model resume fallback. Used by Cloudflare session - * Durable Objects to route a resume miss to the session that owns the pause. - */ - readonly resumeFallback?: ( - executionId: string, - response: ResumeResponse, - ) => Effect.Effect; - /** - * Loads the MCP-Apps shell HTML served as the `ui://executor/shell.html` - * resource. Injected rather than imported: the shell carries React, Recharts - * and Tailwind, and this package also runs on Workers. Hosts that can serve - * it pass `loadMcpAppsShellHtml` from `@executor-js/mcp-apps-shell`; hosts - * that leave it unset simply don't register the resource or the ui tools. - */ - readonly loadAppShellHtml?: () => Promise; - /** - * Per-connection artifacts opt-out. Defaults to true. A client that connects - * with `?artifacts=false` gets NO artifact surface at all: none of the five - * artifact tools, no `ui://` shell resource, and no artifact entries in the - * `skills` inventory — the same shape a host without `loadAppShellHtml` - * serves. `execute`, `skills` and `resume` are untouched. - */ - readonly artifactsEnabled?: boolean; - /** - * Renders an artifact once, server-side, before it is saved — so a component - * that throws on its first render is refused at create time with the real - * error instead of saving cleanly and dying on the user's page. - * - * Injected for the same reason `loadAppShellHtml` is: it needs React, - * react-dom/server and the whole component barrel, and this package must not - * drag any of that into the graph of a host that only ever calls `execute`. - * Hosts that can afford it pass `smokeRenderArtifact` from - * `@executor-js/mcp-apps-shell`, which loads it behind a dynamic import. - * - * Unset means no smoke check: creates are validated statically and saved, as - * they were before. That is also what happens when the check itself fails — - * see the fail-open path in `createArtifact`. - */ - readonly smokeRenderArtifact?: (code: string) => Promise; - /** - * The scoped executor's artifact operations, so `create-artifact` can persist what - * it renders and `list-artifacts` / `show-artifact` can read it back. Only - * the three operations the MCP surface needs, so hosts don't have to hand the - * whole `Executor` across this boundary. - */ - readonly artifacts?: McpArtifactsPort; - /** - * The caller's saved connections, for binding an artifact's integration roles - * at create time. Structurally satisfied by `executor.connections`; hosts pass - * the same scoped executor they pass `artifacts`. - * - * Absent means `create-artifact` cannot bind, so it refuses code that calls an - * integration rather than saving an artifact that could never run. - */ - readonly connections?: McpConnectionsPort; - /** - * Builds the web-app deep link for a saved artifact. Clients that can't - * render MCP Apps get this URL instead of an inline widget. Absent (stdio has - * no origin at all) means `create-artifact` still persists and reports the id, but - * has no URL to offer. - */ - readonly artifactUrl?: (artifactId: string) => string; - /** - * Notified when an agent-facing artifact tool completes a user-meaningful - * operation: `create-artifact` (created, or updated when it overwrote an - * existing id) and `show-artifact` (viewed). Internal artifact reads — - * binding resolution inside `execute-action` — deliberately do not notify. - * Best-effort observation: failures are swallowed and cannot affect the tool - * result. Hosts recording product analytics supply it; core stays agnostic. - */ - readonly onArtifactUsage?: (action: "created" | "viewed" | "updated") => Effect.Effect; - /** - * Whether the client this session belongs to can render MCP Apps, as - * negotiated at a previous `initialize`. - * - * Capabilities normally arrive from the client at `initialize` and live only - * in the server instance. A session whose host evicted and cold-restored it - * (deploy, idle) is rebuilt mid-conversation with no `initialize` to replay, - * so without this the rebuilt server assumes no apps support and silently - * downgrades every artifact to a deep link. Hosts that persist the - * negotiated value pass it back here; the next `initialize`, if one comes, - * overwrites it. - */ - readonly restoredAppsEnabled?: boolean; - /** - * Called when `initialize` negotiates the client's MCP-Apps support, so the - * host can persist it for {@link restoredAppsEnabled} on a later cold - * restore. Best-effort: failures are swallowed and never affect the session. - */ - readonly onAppsEnabledChange?: (appsEnabled: boolean) => Effect.Effect; - /** - * The client identity self-reported at a previous `initialize` (or in a - * modern request's `_meta`), restored for the same reason as - * {@link restoredAppsEnabled}. Feeds only the `mcp.client.*` span - * attributes on execution spans, never behavior or security decisions. - */ - readonly restoredClientInfo?: McpClientInfo; - /** - * Called when `initialize` reports the client identity, so the host can - * persist it for {@link restoredClientInfo} on a later cold restore. - * Best-effort: failures are swallowed and never affect the session. - */ - readonly onClientInfoChange?: (clientInfo: McpClientInfo) => Effect.Effect; -}; - -/** - * Client software identity as self-reported over MCP (`clientInfo` at - * `initialize`, `_meta` on modern requests). Display and telemetry vocabulary - * only: the spec forbids relying on it for behavior or security. - */ -export type McpClientInfo = { - readonly name: string; - readonly version?: string; - readonly title?: string; -}; - -/** - * The narrow artifact surface the MCP tools need. Structurally satisfied by - * `Executor["artifacts"]`, so hosts holding a scoped executor can pass - * `executor.artifacts` directly. - */ -export type McpArtifactsPort = { - readonly list: () => Effect.Effect; - readonly get: (id: string) => Effect.Effect; - readonly save: (input: SaveArtifactInput) => Effect.Effect; -}; - -/** - * The connection surface binding needs: list what this caller can reach. The - * scoped executor has already narrowed it, so an inferred binding can never - * name a connection the caller couldn't call themselves. - */ -export type McpConnectionsPort = { - readonly list: () => Effect.Effect; -}; - -export type ExecutorMcpToolConfig = - | (ExecutionEngineConfig & SharedMcpServerConfig) - | ({ readonly engine: ExecutionEngine } & SharedMcpServerConfig) - | (ExecutionEngineConfig & SharedMcpServerConfig & { readonly stateless: true }) - | ({ readonly engine: ExecutionEngine; readonly stateless: true } & SharedMcpServerConfig); - -export type BrowserApprovalStore = { - readonly takeResponse: (executionId: string) => Effect.Effect; - readonly waitForResponse?: (executionId: string) => Effect.Effect; -}; - -export const PAUSED_APPROVAL_TIMEOUT_MS = 4 * 60 * 1000; -const BROWSER_APPROVAL_WAIT_TIMEOUT_MS = PAUSED_APPROVAL_TIMEOUT_MS + 1000; - -export type PausedExecutionHooks = { - readonly onExecutionPaused?: ( - executionId: string, - deadline: PausedExecutionDeadline | undefined, - ) => Effect.Effect; - readonly onResumeStarted?: (executionId: string) => Effect.Effect; - readonly onResumeSettled?: (executionId: string) => Effect.Effect; -}; - -export type ResumeUnavailableStatus = - | "execution_not_found" - | "execution_expired" - | "execution_forbidden" - | "execution_already_settled"; - -export type ResumeFallbackOutcome = - | { - readonly status: "result"; - readonly result: McpToolResult; - } - | { - readonly status: Exclude; - readonly ttlMs?: number; - } - | { - readonly status: "execution_not_found"; - }; - -/** Request identity normalized from an MCP SDK callback context. */ -export type McpRequestJoinKeys = { - readonly requestId: string | number; - readonly sessionId?: string | undefined; -}; - -/** 2026-07-28 input-required result returned by the MCP assembly. */ -export type McpInputRequiredResult = InputRequiredResult; - -/** Result shape produced by Executor MCP handlers. */ -export type McpHandlerResult = McpToolResult | McpInputRequiredResult; - -/** Enable/disable controls returned by the MCP SDK for registered tools. */ -export type RegisteredMcpTool = { - readonly enable: () => void; - readonly disable: () => void; -}; - -type McpToolConfig = { - readonly title?: string; - readonly description?: string; - readonly inputSchema: Shape; - readonly annotations?: z.infer; - readonly _meta?: Record; -}; - -type MutableMcpToolShape = { - -readonly [Key in keyof Shape]: Shape[Key]; -}; - -type McpAppResourceConfig = { - readonly title?: string; - readonly description?: string; - readonly mimeType?: string; - readonly _meta?: Record; -}; - -type McpResourceResult = { - readonly contents: readonly ( - | { - readonly uri: string; - readonly mimeType?: string; - readonly text: string; - readonly _meta?: Record; - } - | { - readonly uri: string; - readonly mimeType?: string; - readonly blob: string; - readonly _meta?: Record; - } - )[]; -}; - -/** Services supplied to an assembly's SDK-specific native elicitation bridge. */ -export type NativeExecutionServices< - E extends Cause.YieldableError, - RequestContext extends McpRequestJoinKeys, -> = { - readonly engine: ExecutionEngine; - readonly code: string; - readonly requestContext: RequestContext; - readonly source: "execute" | "execute_action"; - readonly debugLog: (event: string, data: Record) => void; - readonly complete: (result: Parameters[0]) => McpToolResult; - readonly resume: ( - executionId: string, - response: ResumeResponse, - ) => Effect.Effect; - readonly executionPaused: (execution: PausedExecution) => Effect.Effect; -}; - -/** - * Minimal SDK-specific surface needed by the shared Executor tool assembly. - * Both SDK versions are adapted to this interface at their composition roots. - */ -export type ExecutorMcpAssembly = { - readonly server: Server; - readonly initialAppsEnabled: boolean; - readonly getClientCapabilities: () => unknown | null; - /** The live `initialize`-reported client identity, when the SDK has one. */ - readonly getClientInfo: () => McpClientInfo | null; - readonly getElicitationSupport: () => { readonly form: boolean; readonly url: boolean }; - readonly getUiCapability: () => { readonly mimeTypes?: readonly string[] } | undefined; - readonly onInitialized: (callback: () => void) => void; - readonly registerTool: ( - name: string, - config: McpToolConfig, - callback: ( - args: z.output>>, - requestContext: RequestContext, - ) => Promise, - ) => RegisteredMcpTool; - readonly registerAppTool: ( - name: string, - config: McpToolConfig & { readonly _meta: Record }, - callback: ( - args: z.output>>, - requestContext: RequestContext, - ) => Promise, - ) => RegisteredMcpTool; - readonly registerAppResource: ( - name: string, - uri: string, - config: McpAppResourceConfig, - callback: () => McpResourceResult | Promise, - ) => void; - readonly executeNative: ( - services: NativeExecutionServices, - ) => Effect.Effect; -}; - -// --------------------------------------------------------------------------- -// Shared elicitation helpers -// --------------------------------------------------------------------------- - -const readDebugDefault = (): boolean => { - if (typeof process === "undefined" || !process.env) return false; - const value = process.env.EXECUTOR_MCP_DEBUG; - return value === "1" || value === "true"; -}; - -export const elicitationRequestTag = (request: ElicitationRequest): ElicitationRequest["_tag"] => - Match.value(request).pipe( - Match.tag("UrlElicitation", () => "UrlElicitation" as const), - Match.tag("FormElicitation", () => "FormElicitation" as const), - Match.exhaustive, - ); - -const pausedInteractionKind = (request: ElicitationRequest): ElicitationRequest["_tag"] => - elicitationRequestTag(request); - -// --------------------------------------------------------------------------- -// MCP result formatting -// --------------------------------------------------------------------------- - -export type McpToolResult = { - content: ContentBlock[]; - structuredContent?: Record; - isError?: boolean; -}; - -type ContentBlock = z.infer; - -type FormattedExecuteInput = Parameters[0]; -type ExecuteOutputItem = NonNullable[number]; - -const TEXT_FILE_CONTENT_MAX_CHARS = 64_000; - -const isRecord = (value: unknown): value is Record => - typeof value === "object" && value !== null && !Array.isArray(value); - -const toolFileName = (file: ToolFileValue): string => file.name ?? "tool-output"; - -const fileResourceUri = (file: ToolFileValue): string => - `executor-file:///${encodeURIComponent(toolFileName(file))}`; - -const normalizedMimeType = (file: ToolFileValue): string => - file.mimeType.split(";")[0]?.trim().toLowerCase() ?? ""; - -const toolFileKind = (file: ToolFileValue): "image" | "audio" | "text" | "resource" => { - const mimeType = normalizedMimeType(file); - if (mimeType.startsWith("image/")) return "image"; - if (mimeType.startsWith("audio/")) return "audio"; - if ( - mimeType.startsWith("text/") || - mimeType === "application/json" || - mimeType.endsWith("+json") || - mimeType === "application/xml" || - mimeType.endsWith("+xml") || - mimeType === "application/javascript" || - mimeType === "application/x-javascript" || - mimeType === "application/yaml" || - mimeType === "application/x-yaml" - ) { - return "text"; - } - return "resource"; -}; - -const bytesFromBase64 = (base64: string): Uint8Array => { - const binary = atob(base64); - const bytes = new Uint8Array(binary.length); - for (let index = 0; index < binary.length; index += 1) { - bytes[index] = binary.charCodeAt(index); - } - return bytes; -}; - -const decodeTextFile = (file: ToolFileValue): string => { - const text = new TextDecoder("utf-8", { fatal: false }).decode(bytesFromBase64(file.data)); - if (text.length <= TEXT_FILE_CONTENT_MAX_CHARS) return text; - return `${text.slice(0, TEXT_FILE_CONTENT_MAX_CHARS)}\n\n[truncated ${ - text.length - TEXT_FILE_CONTENT_MAX_CHARS - } characters]`; -}; - -const toolFileContent = (file: ToolFileValue): ContentBlock[] => { - const kind = toolFileKind(file); - if (kind === "image") { - return [{ type: "image", data: file.data, mimeType: file.mimeType }]; - } - if (kind === "audio") { - return [{ type: "audio", data: file.data, mimeType: file.mimeType }]; - } - if (kind === "text") { - return [{ type: "text", text: decodeTextFile(file) }]; - } - return [ - { - type: "resource", - resource: { - uri: fileResourceUri(file), - mimeType: file.mimeType, - blob: file.data, - }, - }, - ]; -}; - -const toolFileSummaryLine = (file: ToolFileValue, index?: number): string => { - const prefix = index === undefined ? "" : `${index + 1}. `; - return `${prefix}${toolFileName(file)} (${file.mimeType}, ${file.byteLength} bytes)`; -}; - -const outputFileContent = (file: ToolFileValue): ContentBlock[] => [ - { - type: "text", - text: `File output: ${toolFileSummaryLine(file)}`, - }, - ...toolFileContent(file), -]; - -const isFileOutputItem = ( - item: ExecuteOutputItem, -): item is { readonly type: "file"; readonly file: ToolFileValue } => - isRecord(item) && item.type === "file" && isToolFile(item.file); - -const isMcpContentBlock = (value: unknown): value is ContentBlock => - ContentBlockSchema.safeParse(value).success; - -const isContentOutputItem = ( - item: ExecuteOutputItem, -): item is { readonly type: "content"; readonly content: ContentBlock } => - isRecord(item) && item.type === "content" && isMcpContentBlock(item.content); - -const outputItemContent = (item: ExecuteOutputItem): ContentBlock[] => { - if (isFileOutputItem(item)) { - return outputFileContent(item.file); - } - if (isContentOutputItem(item)) { - return [item.content]; - } - return [{ type: "text", text: "Invalid execution output item omitted." }]; -}; - -const toMcpOutputResult = ( - result: FormattedExecuteInput, - output: readonly ExecuteOutputItem[], -): McpToolResult => { - const formatted = formatExecuteResult(result); - const content = output.flatMap(outputItemContent); - const extraText: string[] = []; - if (result.error) { - extraText.push(formatted.text); - } else if (result.result != null) { - // A script may both emit() and return: keep the returned value in the - // content channel too, or clients that ignore structuredContent drop it. - // formatted.text already renders the return value plus any logs. - extraText.push(formatted.text); - } else if (result.logs && result.logs.length > 0) { - extraText.push(`Logs:\n${result.logs.join("\n")}`); - } - content.push(...extraText.map((text): ContentBlock => ({ type: "text", text }))); - - return { - content, - structuredContent: formatted.structured, - isError: formatted.isError || undefined, - }; -}; - -const toMcpResult = (result: FormattedExecuteInput): McpToolResult => { - if (result.output && result.output.length > 0) return toMcpOutputResult(result, result.output); - const formatted = formatExecuteResult(result); - return { - content: [{ type: "text", text: formatted.text }], - structuredContent: formatted.structured, - isError: formatted.isError || undefined, - }; -}; - -const toMcpPausedResult = (formatted: ReturnType): McpToolResult => ({ - content: [{ type: "text", text: formatted.text }], - structuredContent: formatted.structured, -}); - -export const formatMcpExecutionOutcome = ( - outcome: ExecutionResult, - options?: { readonly pausedDeadline?: PausedExecutionDeadline }, -): McpToolResult => - outcome.status === "completed" - ? toMcpResult(outcome.result) - : toMcpPausedResult( - formatPausedExecution(outcome.execution, { deadline: options?.pausedDeadline }), - ); - -// `execute` failures reaching the MCP host are infra defects — domain -// failures from tools are now expressed as `ToolResult` values (success -// channel) and flow through `formatExecuteResult`. Emit an opaque -// generic plus a fresh correlation id and log the cause out-of-band so -// the model can't read internal context off `.message`. -const newCorrelationId = (): string => - Math.floor(Math.random() * 0x1_0000_0000) - .toString(16) - .padStart(8, "0"); - -const defaultResumeApprovalUrl = (executionId: string): string => - `/resume/${encodeURIComponent(executionId)}`; - -const browserApprovalReturnPrompt = - "Return text to the user telling them to approve the action at this approvalUrl. Only after you have prompted the user, call the `resume` tool with this executionId; `resume` will wait for the user's browser decision."; - -const formatResumeApprovalRequired = (input: { - readonly executionId: string; - readonly approvalUrl: string; -}): McpToolResult => ({ - content: [ - { - type: "text", - text: [ - "User approval required.", - "", - "Tell the user to open this URL while signed in and approve or decline the paused interaction:", - input.approvalUrl, - "", - "Required next steps for this agent:", - browserApprovalReturnPrompt, - ].join("\n"), - }, - ], - structuredContent: { - status: "user_approval_required", - executionId: input.executionId, - approvalUrl: input.approvalUrl, - resumePrompt: browserApprovalReturnPrompt, - }, -}); - -const toMcpFailureResult = (cause: Cause.Cause): McpToolResult => { - const correlationId = newCorrelationId(); - const defect = Cause.findDefect(cause); - const nativeElicitationFailed = - Result.isSuccess(defect) && - Predicate.isTagged("McpNativeElicitationTransportError")(defect.success); - // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: best-effort defect logging must tolerate non-serializable causes - try { - console.error( - `[executor:mcp] execute defect correlation_id=${correlationId}`, - Cause.pretty(cause), - ); - } catch { - /* ignore logger failures */ - } - const text = nativeElicitationFailed - ? `Native elicitation transport failed [${correlationId}]. Reconnect the MCP client and try again.` - : `Internal tool error [${correlationId}]`; - return { - content: [{ type: "text", text: `Error: ${text}` }], - structuredContent: { - status: "error", - error: text, - ...(nativeElicitationFailed ? { errorCode: "native_elicitation_transport_failed" } : {}), - }, - isError: true, - }; -}; - -const recoveryText = - "To recover, run the execute tool again with the original code; if it pauses, a fresh executionId will be issued."; - -const resumeUnavailableResult = (input: { - readonly status: ResumeUnavailableStatus; - readonly executionId: string; - readonly ttlMs?: number; -}): McpToolResult => { - const windowMs = input.ttlMs ?? PAUSED_APPROVAL_TIMEOUT_MS; - const approvalWindow = formatTtlDuration(windowMs); - const textByStatus: Record = { - execution_not_found: [ - `Paused execution is unknown: ${input.executionId}.`, - `Paused executions are only resumable for a limited window; this id may have expired or never existed.`, - recoveryText, - ], - execution_expired: [ - `Paused execution expired: ${input.executionId}.`, - `Approval windows last ${approvalWindow}; the owning session no longer has a live pause for this executionId.`, - recoveryText, - ], - execution_forbidden: [ - `Paused execution cannot be resumed by this authenticated identity: ${input.executionId}.`, - "Resume must be called by the same account and organization that owns the paused session.", - ], - execution_already_settled: [ - `Paused execution has already settled: ${input.executionId}.`, - "The resume result is no longer available for replay.", - "Run execute again only if the result is still needed.", - ], - }; - return { - content: [ - { - type: "text" as const, - text: textByStatus[input.status].join(" "), - }, - ], - structuredContent: { - status: input.status, - executionId: input.executionId, - ...(input.status === "execution_expired" ? { ttlMs: windowMs } : {}), - ...(input.status === "execution_forbidden" ? {} : { recovery: "re_execute" }), - }, - isError: true, - }; -}; - -const missingExecutionResult = (executionId: string): McpToolResult => - resumeUnavailableResult({ status: "execution_not_found", executionId }); - -const alreadySettledResult = (executionId: string): McpToolResult => - resumeUnavailableResult({ status: "execution_already_settled", executionId }); - -const fallbackOutcomeResult = ( - executionId: string, - outcome: ResumeFallbackOutcome, -): McpToolResult => { - if (outcome.status === "result") return outcome.result; - return resumeUnavailableResult({ - status: outcome.status, - executionId, - ttlMs: "ttlMs" in outcome ? outcome.ttlMs : undefined, - }); -}; - -// The `skills` tool serves named, static how-to docs (see the execution -// package's skills registry). No name -> the index; a known name -> that -// skill's body; an unknown name -> the index plus a not-found note so the model -// retries with a listed name instead of the same miss. -// -// The skill body IS the payload, returned as plain text content. We do NOT -// attach `structuredContent`: a client that prefers structured output (Claude -// Code does) will surface only that and drop the text, so the long-form guide -// silently fails to load. The not-found case keeps `isError` (a separate field -// clients honor) so a bad name still reads as a failure. -// -// The `execute` skill also gets the live integration inventory appended, the -// same block the execute tool description carries, so a model reading the guide -// sees what is connected without a second round trip. -// -// The catalog is per-session: a connection that opted out of artifacts never -// sees the artifact skills, so the index cannot advertise a how-to for tools it -// does not have, and fetching one by name misses like any unknown skill. -const skillsResult = ( - name: string | undefined, - executeInventory: string, - catalog: readonly Skill[], -): McpToolResult => { - const trimmed = name?.trim(); - if (!trimmed) { - return { content: [{ type: "text", text: renderSkillsIndex(catalog) }] }; - } - const skill = findSkill(trimmed, catalog); - if (!skill) { - return { - content: [ - { type: "text", text: `No skill named "${trimmed}".\n\n${renderSkillsIndex(catalog)}` }, - ], - isError: true, - }; - } - const text = - skill.name === EXECUTE_SKILL.name && executeInventory.length > 0 - ? `${skill.body}\n\n${executeInventory}` - : skill.body; - return { content: [{ type: "text", text }] }; -}; - -/** Pull the live integration inventory block out of the built execute - * description (it runs from its header to the end), so the `skills` tool can - * re-use it without rebuilding the inventory from the executor. */ -const extractInventory = (description: string): string => { - const index = description.indexOf(INTEGRATION_INVENTORY_HEADER); - return index === -1 ? "" : description.slice(index).trimEnd(); -}; - -// --------------------------------------------------------------------------- -// Hang-visibility join keys -// --------------------------------------------------------------------------- -// A killed execution exports nothing: OTEL only ships a span when it ends, and -// a Cloudflare deploy/eviction cancels the request without an error, so a hung -// `execute` is invisible in the trace store. Two mitigations live here: -// 1. Every execution-path span carries the JSON-RPC id + transport session id -// (`mcp.rpc.id`, `mcp.request.session_id`), so a client's -// `notifications/cancelled` — which names the cancelled request id — can -// be joined to the exact call it gave up on. -// 2. A zero-duration start marker span (`.start`, a -// 1:1 pairing so "started without finishing" is a single unambiguous -// query) is emitted the moment execution begins. It ends immediately, so -// it becomes exportable while the execution is still running; whether it -// actually ships before a kill depends on the host's span processor -// draining first (cloud batches on a 1s timer, so markers for executions -// that survive >1s export, sub-second kills can still lose theirs). A -// start marker without a matching completion span is a true positive for -// an execution that died mid-flight. - -// `mcp.request.session_id` is emitted unconditionally (empty string when the -// transport carries none) to match the worker-side `annotateMcpRequest` -// producer: JSON-RPC ids are small per-session integers, so a row without the -// session key would make `mcp.rpc.id` globally ambiguous. -const joinKeyAttributes = (joinKeys: McpRequestJoinKeys): Record => ({ - "mcp.rpc.id": String(joinKeys.requestId), - "mcp.request.session_id": joinKeys.sessionId ?? "", -}); - -// Client identity uses the same `mcp.client.*` vocabulary as the cloud -// worker's `initialize` fingerprint (`annotateMcpRequest`), so execution spans -// segment by client directly instead of through a session join that `initialize` -// (which has no session id yet) cannot satisfy. Absent means no key at all, not -// an empty string, when no `initialize` was seen and nothing was restored: -// unknown is real state here, unlike the always-present session key above. -const clientInfoAttributes = (clientInfo: McpClientInfo | null): Record => - clientInfo === null - ? {} - : { - "mcp.client.name": clientInfo.name, - ...(clientInfo.version !== undefined ? { "mcp.client.version": clientInfo.version } : {}), - ...(clientInfo.title !== undefined ? { "mcp.client.title": clientInfo.title } : {}), - }; - -const startMarker = (name: string, attributes: Record): Effect.Effect => - Effect.void.pipe(Effect.withSpan(name, { attributes })); - -// --------------------------------------------------------------------------- -// Artifacts / MCP Apps result formatting -// --------------------------------------------------------------------------- -// -// Delivery is negotiated, not branched on by the model: an artifact reaches the -// user as an inline widget when the client renders MCP Apps, and as a link into -// the web app when it doesn't. Both carry `artifactId`, because either way the -// artifact was saved and can be reopened later. - -const renderRejectedResult = (reason: string): McpToolResult => ({ - content: [{ type: "text", text: `create-artifact rejected: ${reason}` }], - structuredContent: { status: "error", error: reason }, - isError: true, -}); - -/** An edit batch that could not be applied. Carries the current stored source - * so the model can rebuild its edits without a `show-artifact` round trip. */ -const editRejectedResult = (reason: string, currentCode: string): McpToolResult => ({ - content: [ - { - type: "text", - text: [ - `edit-artifact rejected: ${reason}`, - "Nothing was changed. The artifact's current source is in structuredContent.code — build the retry against it.", - ].join("\n"), - }, - ], - structuredContent: { status: "error", error: reason, code: currentCode }, - isError: true, -}); - -/** `execute-action` was handed something other than a single proxy-shaped tool - * call. Names the contract rather than just refusing, since the reader is - * either a confused iframe or someone probing the app channel by hand. */ -const actionRejectedResult = (): McpToolResult => ({ - content: [{ type: "text", text: TOOL_CALL_CONTRACT_MESSAGE }], - structuredContent: { status: "error", error: "invalid_action_code" }, - isError: true, -}); - -/** - * The artifact whose bindings a call must be resolved through is missing or - * isn't this caller's. - * - * One result for both, deliberately: distinguishing "no such artifact" from - * "not yours" would let the app channel probe for ids that exist. - */ -const actionArtifactUnavailableResult = (): McpToolResult => ({ - content: [ - { - type: "text", - text: "This action refers to an artifact that isn't available on this account.", - }, - ], - structuredContent: { status: "error", error: "artifact_unavailable" }, - isError: true, -}); - -/** - * A role in the artifact's code has no connection behind it. - * - * Structured rather than prose-only because the binding UI that ships with - * sharing renders exactly this: which role failed, for which integration, and - * what the viewer could bind it to instead. The apps plugin's `BindingError` - * carries the same three facts for the same reason. - */ -const bindingUnresolvedResult = (input: { - readonly role: string; - readonly integration: string; - readonly message: string; - readonly candidates: readonly string[]; -}): McpToolResult => ({ - content: [ - { - type: "text", - text: - input.candidates.length > 0 - ? `${input.message} Choose one of ${input.candidates.join(", ")}.` - : input.message, - }, - ], - structuredContent: { - status: "error", - error: "binding_unresolved", - role: input.role, - integration: input.integration, - candidates: input.candidates, - }, - isError: true, -}); - -const renderedInAppResult = (input: { - readonly code: string; - readonly artifactId: string; - readonly title: string; - readonly url?: string | undefined; -}): McpToolResult => ({ - content: [ - { - type: "text", - text: [ - `Rendered "${input.title}" as an interactive UI component. Saved as artifact ${input.artifactId}.`, - // The link rides along even though the widget rendered: clients lose - // rendered widgets in ways the server never sees (a transcript - // reopened without re-reading the ui:// resource shows raw JSON), and - // when that happens this URL in the conversation is the only path - // back to the artifact the model can offer. - ...(input.url ? [`It also stays available at ${input.url}`] : []), - ].join("\n"), - }, - ], - structuredContent: { - code: input.code, - artifactId: input.artifactId, - ...(input.url ? { url: input.url } : {}), - }, -}); - -const renderedAsLinkResult = (input: { - readonly url: string; - readonly artifactId: string; - readonly title: string; -}): McpToolResult => ({ - content: [ - { - type: "text", - text: [ - `Saved "${input.title}" as artifact ${input.artifactId}.`, - "This MCP client cannot display MCP Apps, so give the user this URL to open it:", - input.url, - ].join("\n"), - }, - ], - structuredContent: { - status: "fallback_url", - url: input.url, - artifactId: input.artifactId, - }, -}); - -const renderedWithoutSurfaceResult = (input: { - readonly artifactId: string; - readonly title: string; -}): McpToolResult => ({ - content: [ - { - type: "text", - text: [ - `Saved "${input.title}" as artifact ${input.artifactId}.`, - "This MCP client cannot display MCP Apps and this deployment has no web UI configured, so there is nowhere to show it right now.", - "Tell the user the artifact was saved and can be opened from a client that supports MCP Apps.", - ].join("\n"), - }, - ], - structuredContent: { - status: "fallback_unavailable", - reason: "mcp_apps_unsupported", - artifactId: input.artifactId, - }, -}); - -const artifactsUnavailableResult = (): McpToolResult => ({ - content: [ - { - type: "text", - text: "Artifacts are not available on this connection.", - }, - ], - structuredContent: { status: "error", error: "artifacts_unavailable" }, - isError: true, -}); - -const artifactListResult = (artifacts: readonly ArtifactSummary[]): McpToolResult => { - const items = artifacts.map((artifact) => ({ - id: artifact.id, - title: artifact.title, - description: artifact.description, - updatedAt: artifact.updatedAt.toISOString(), - })); - const text = - items.length === 0 - ? "No saved artifacts yet. Use create-artifact to make one." - : [ - "Saved artifacts:", - ...items.map( - (item) => - `- ${item.id} — ${item.title}${item.description ? `: ${item.description}` : ""} (updated ${item.updatedAt})`, - ), - ].join("\n"); - return { content: [{ type: "text", text }], structuredContent: { artifacts: items } }; -}; - -const artifactNotFoundResult = (id: string): McpToolResult => ({ - content: [ - { - type: "text", - text: `No artifact with id "${id}". Call list-artifacts to see what is saved.`, - }, - ], - structuredContent: { status: "error", error: "artifact_not_found", id }, - isError: true, -}); - -const JsonObjectFromString = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)); -const decodeJsonObjectString = Schema.decodeUnknownOption(JsonObjectFromString); - -const parseJsonContent = (raw: string): Record | undefined => { - if (raw === "{}") return undefined; - const parsed = decodeJsonObjectString(raw); - return Option.isSome(parsed) ? parsed.value : undefined; -}; - -// --------------------------------------------------------------------------- -// Server factory -// --------------------------------------------------------------------------- - -/** Assemble the shared Executor tools through one SDK-specific adapter. */ -export const buildExecutorMcpTools = < - E extends Cause.YieldableError, - Server, - RequestContext extends McpRequestJoinKeys, ->( - config: ExecutorMcpToolConfig, - createAssembly: () => ExecutorMcpAssembly, -): Effect.Effect => - Effect.gen(function* () { - const engine = "engine" in config ? config.engine : createExecutionEngine(config); - const description = - config.description ?? - (yield* engine.getDescription.pipe(Effect.withSpan("mcp.host.get_description"))); - // The same live integration inventory the description carries, re-used by - // the `skills` tool so the `execute` guide lists what is connected too. - const executeInventory = extractInventory(description); - // Artifacts are on unless this connection opted out (`?artifacts=false`). - // One flag decides the whole surface: the tools, the shell resource, and - // the skills catalog below. - const artifactsEnabled = config.artifactsEnabled ?? true; - const skillCatalog: readonly Skill[] = skillCatalogFor({ artifacts: artifactsEnabled }); - - // Captured at construction time. SDK callbacks fire later (often - // deferred past the outer Effect's await), so we use the runtime to - // re-enter Effect-land at each callback edge. - const context = yield* Effect.context(); - const debugEnabled = config.debug ?? readDebugDefault(); - const debugLog = (event: string, data: Record) => { - if (!debugEnabled) return; - // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: debug logging must tolerate non-serializable SDK capability snapshots - try { - console.error(`[executor:mcp] ${event} ${JSON.stringify(data)}`); - } catch { - console.error(`[executor:mcp] ${event}`, data); - } - }; - const elicitationMode = - config.elicitationMode ?? - ({ - mode: "model", - } as const); - const pauseDeadline = (): PausedExecutionDeadline | undefined => { - const ttlMs = config.pausedExecutionLeaseMs; - return ttlMs === undefined || ttlMs <= 0 - ? undefined - : { ttlMs, expiresAt: new Date(Date.now() + ttlMs).toISOString() }; - }; - const onExecutionPaused = ( - executionId: string, - deadline: PausedExecutionDeadline | undefined, - ): Effect.Effect => - config.pausedExecutionHooks?.onExecutionPaused?.(executionId, deadline) ?? Effect.void; - const onResumeStarted = (executionId: string): Effect.Effect => - config.pausedExecutionHooks?.onResumeStarted?.(executionId) ?? Effect.void; - const onResumeSettled = (executionId: string): Effect.Effect => - config.pausedExecutionHooks?.onResumeSettled?.(executionId) ?? Effect.void; - const resumeWithLifecycle = (executionId: string, response: ResumeResponse) => - Effect.gen(function* () { - yield* onResumeStarted(executionId); - return yield* engine.resume(executionId, response); - }).pipe(Effect.ensuring(onResumeSettled(executionId))); - - const localExecutionAlreadySettled = (executionId: string): Effect.Effect => - engine.isExecutionSettled?.(executionId) ?? Effect.succeed(false); - - const resumeFallback = ( - executionId: string, - response: ResumeResponse, - ): Effect.Effect => - config - .resumeFallback?.(executionId, response) - .pipe(Effect.catchCause(() => Effect.succeed(null))) ?? Effect.succeed(null); - - const formatPausedModelResult = ( - execution: PausedExecution, - source: "execute" | "execute_action" | "resume" | "browser_resume", - ): Effect.Effect => - Effect.gen(function* () { - const deadline = pauseDeadline(); - yield* Effect.annotateCurrentSpan({ - "mcp.execute.paused": true, - "mcp.execute.paused_execution_id": execution.id, - "mcp.execute.pause_source": source, - }); - yield* onExecutionPaused(execution.id, deadline); - return toMcpPausedResult(formatPausedExecution(execution, { deadline })); - }); - - const resolveParentSpan = (): Tracer.AnySpan | undefined => { - const ps = config.parentSpan; - return typeof ps === "function" ? ps() : ps; - }; - const anchor = (effect: Effect.Effect): Effect.Effect => { - const parent = resolveParentSpan(); - return parent ? Effect.withParentSpan(effect, parent) : effect; - }; - const runToolEffect = (effect: Effect.Effect) => - Effect.runPromiseWith(context)( - anchor(effect).pipe( - Effect.catchCause((cause) => Effect.succeed(toMcpFailureResult(cause))), - ), - ); - - const assembly = yield* Effect.sync(createAssembly); - const server = assembly.server; - - // Seeded from the host's persisted copy; a live `initialize` on this - // instance replaces it via `syncClientInfo` below. Read lazily at each - // tool call so spans always carry the newest identity. - let clientInfo: McpClientInfo | null = config.restoredClientInfo ?? null; - const requestSpanAttributes = (joinKeys: McpRequestJoinKeys): Record => ({ - ...joinKeyAttributes(joinKeys), - ...clientInfoAttributes(clientInfo), - }); - - const executeWithNativeElicitation = ( - code: string, - extra: RequestContext, - source: "execute" | "execute_action", - ): Effect.Effect => - assembly.executeNative({ - engine, - code, - requestContext: extra, - source, - debugLog, - complete: toMcpResult, - resume: resumeWithLifecycle, - executionPaused: (execution) => - Effect.gen(function* () { - const deadline = pauseDeadline(); - yield* Effect.annotateCurrentSpan({ - "mcp.execute.paused": true, - "mcp.execute.paused_execution_id": execution.id, - "mcp.execute.pause_source": source, - }); - yield* onExecutionPaused(execution.id, deadline); - }), - }); - - const executeCode = (code: string, extra: RequestContext): Effect.Effect => - Effect.gen(function* () { - yield* startMarker("mcp.host.tool.execute.start", { - "mcp.tool.name": "execute", - "mcp.execute.code_length": code.length, - }); - debugLog("execute.call", { - elicitationMode: elicitationMode.mode, - elicitationSupport: assembly.getElicitationSupport(), - clientCapabilities: assembly.getClientCapabilities(), - codeLength: code.length, - }); - if (elicitationMode.mode === "native") { - return yield* executeWithNativeElicitation(code, extra, "execute"); - } - const outcome = yield* engine.executeWithPause(code); - debugLog("execute.paused_flow_result", { - status: outcome.status, - executionId: outcome.status === "paused" ? outcome.execution.id : undefined, - interactionKind: - outcome.status === "paused" - ? pausedInteractionKind(outcome.execution.elicitationContext.request) - : undefined, - }); - if (outcome.status === "paused") { - const deadline = pauseDeadline(); - yield* Effect.annotateCurrentSpan({ - "mcp.execute.paused": true, - "mcp.execute.paused_execution_id": outcome.execution.id, - "mcp.execute.pause_source": "execute", - }); - yield* onExecutionPaused(outcome.execution.id, deadline); - return elicitationMode.mode === "browser" - ? yield* requireUserResumeApproval(outcome.execution.id) - : toMcpPausedResult(formatPausedExecution(outcome.execution, { deadline })); - } - return toMcpResult(outcome.result); - }).pipe( - Effect.withSpan("mcp.host.tool.execute", { - attributes: { - "mcp.tool.name": "execute", - "mcp.execute.code_length": code.length, - }, - }), - Effect.annotateSpans(requestSpanAttributes(extra)), - ); - - /** What the caller could bind an unresolved role to. Best effort: the - * connections port is optional, and a failure to enumerate must not - * replace the real error with a different one. */ - const bindingCandidates = (integration: string): Effect.Effect => - config.connections - ? config.connections.list().pipe( - Effect.map((all) => - all - .filter((connection) => connection.integration === integration) - .map( - (connection) => - `${connection.integration}.${connection.owner}.${connection.name}`, - ), - ), - Effect.catchCause(() => Effect.succeed([] as readonly string[])), - ) - : Effect.succeed([]); - - /** The artifact as THIS caller can read it. A miss and a row owned by - * someone else are the same answer, because they are the same query. */ - const loadArtifact = (id: string): Effect.Effect => - config.artifacts - ? config.artifacts.get(id).pipe(Effect.catchCause(() => Effect.succeed(null))) - : Effect.succeed(null); - - // `execute-action` is `execute` as called by the shell rather than by the - // model, and the difference is who owns approval. The shell renders the - // approval modal itself in its trusted outer frame, so a pause here must - // come back as the `waiting_for_interaction` payload the shell knows how to - // resolve — never as a browser approval URL, which the user would have no - // way to act on from inside a widget. That holds even when the session's - // elicitation mode is `browser`, which is why this doesn't just call - // `executeCode`. - // - // The other difference is WIDTH. `execute` takes arbitrary code because the - // model writes it; this channel takes exactly one proxy-shaped tool call, - // because that is all a declarative artifact can produce. See - // `tool-call-code.ts`. - // - // The third difference is that the incoming path is not yet an ADDRESS. - // Artifact code names an integration and, optionally, a role; the tier and - // connection are held on the artifact row. So this channel re-writes the - // call against those bindings before executing, and the executed code is - // built HERE, from a parsed path and a stored binding, never taken from the - // iframe verbatim. That is what makes the short form safe: an iframe that - // invented a five-segment address would only be naming a role the artifact - // has no binding for, and would be refused. - const executeCodeFromApp = ( - code: string, - artifactId: string | undefined, - extra: RequestContext, - ): Effect.Effect => - Effect.gen(function* () { - const resolution = yield* resolveArtifactAction({ code, artifactId, loadArtifact }); - debugLog("execute_action.call", { - elicitationMode: elicitationMode.mode, - elicitationSupport: assembly.getElicitationSupport(), - codeLength: code.length, - status: resolution.status, - artifactId: artifactId ?? null, - }); - if (resolution.status === "invalid_action_code") { - yield* Effect.annotateCurrentSpan({ "mcp.execute_action.rejected": true }); - return actionRejectedResult(); - } - if (resolution.status === "artifact_unavailable") { - return actionArtifactUnavailableResult(); - } - if (resolution.status === "binding_unresolved") { - yield* Effect.annotateCurrentSpan({ - "mcp.execute_action.binding_unresolved": true, - "mcp.execute_action.role": resolution.role, - }); - return bindingUnresolvedResult({ - role: resolution.role, - integration: resolution.integration, - message: resolution.message, - candidates: yield* bindingCandidates(resolution.integration), - }); - } - const boundCode = resolution.code; - - if (elicitationMode.mode === "native") { - return yield* executeWithNativeElicitation(boundCode, extra, "execute_action"); - } - const outcome = yield* engine.executeWithPause(boundCode); - debugLog("execute_action.paused_flow_result", { - status: outcome.status, - executionId: outcome.status === "paused" ? outcome.execution.id : undefined, - interactionKind: - outcome.status === "paused" - ? pausedInteractionKind(outcome.execution.elicitationContext.request) - : undefined, - }); - if (outcome.status === "paused") { - return yield* formatPausedModelResult(outcome.execution, "execute_action"); - } - return toMcpResult(outcome.result); - }).pipe( - Effect.withSpan("mcp.host.tool.execute_action", { - attributes: { - "mcp.tool.name": "execute-action", - "mcp.execute.code_length": code.length, - }, - }), - ); - - const resumeExecution = ( - executionId: string, - action: "accept" | "decline" | "cancel", - content: Record | undefined, - extra: RequestContext, - ): Effect.Effect => - Effect.gen(function* () { - yield* startMarker("mcp.host.tool.resume.start", { - "mcp.tool.name": "resume", - "mcp.execute.execution_id": executionId, - }); - debugLog("resume.call", { - executionId, - action, - hasContent: content !== undefined, - clientCapabilities: assembly.getClientCapabilities(), - }); - const outcome = yield* resumeWithLifecycle(executionId, { action, content }); - if (!outcome) { - debugLog("resume.missing_execution", { executionId }); - if (yield* localExecutionAlreadySettled(executionId)) { - return alreadySettledResult(executionId); - } - const fallback = yield* resumeFallback(executionId, { action, content }); - if (fallback) { - debugLog("resume.fallback_result", { executionId, status: fallback.status }); - return fallbackOutcomeResult(executionId, fallback); - } - return missingExecutionResult(executionId); - } - debugLog("resume.result", { - executionId, - status: outcome.status, - nextExecutionId: outcome.status === "paused" ? outcome.execution.id : undefined, - interactionKind: - outcome.status === "paused" - ? pausedInteractionKind(outcome.execution.elicitationContext.request) - : undefined, - }); - if (outcome.status === "paused") { - return yield* formatPausedModelResult(outcome.execution, "resume"); - } - return toMcpResult(outcome.result); - }).pipe( - Effect.withSpan("mcp.host.tool.resume", { - attributes: { - "mcp.tool.name": "resume", - "mcp.execute.resume.action": action, - "mcp.execute.execution_id": executionId, - }, - }), - Effect.annotateSpans(requestSpanAttributes(extra)), - ); - - const requireUserResumeApproval = (executionId: string): Effect.Effect => - Effect.sync(() => { - const approvalUrl = - elicitationMode.mode === "browser" - ? elicitationMode.approvalUrl(executionId) - : defaultResumeApprovalUrl(executionId); - debugLog("resume.user_approval_required", { - executionId, - approvalUrl, - clientCapabilities: assembly.getClientCapabilities(), - }); - return formatResumeApprovalRequired({ executionId, approvalUrl }); - }).pipe( - Effect.withSpan("mcp.host.tool.resume.user_approval_required", { - attributes: { - "mcp.tool.name": "resume", - "mcp.execute.execution_id": executionId, - }, - }), - ); - - const takeBrowserApprovalResponse = ( - executionId: string, - ): Effect.Effect => { - return config.browserApprovalStore?.takeResponse(executionId) ?? Effect.succeed(null); - }; - - const waitForBrowserApprovalResponse = ( - executionId: string, - ): Effect.Effect => { - const waitForResponse = config.browserApprovalStore?.waitForResponse; - if (!waitForResponse) return takeBrowserApprovalResponse(executionId); - - return waitForResponse(executionId).pipe( - Effect.timeoutOrElse({ - duration: Duration.millis(BROWSER_APPROVAL_WAIT_TIMEOUT_MS), - orElse: () => Effect.succeed(null), - }), - ); - }; - - const resumeAfterBrowserApproval = ( - executionId: string, - extra: RequestContext, - ): Effect.Effect => - Effect.gen(function* () { - yield* startMarker("mcp.host.tool.resume.browser_approval.start", { - "mcp.tool.name": "resume", - "mcp.execute.execution_id": executionId, - }); - const response = yield* waitForBrowserApprovalResponse(executionId); - if (!response) return yield* requireUserResumeApproval(executionId); - - const outcome = yield* resumeWithLifecycle(executionId, response); - if (!outcome) { - return missingExecutionResult(executionId); - } - if (outcome.status === "paused") { - const deadline = pauseDeadline(); - yield* Effect.annotateCurrentSpan({ - "mcp.execute.paused": true, - "mcp.execute.paused_execution_id": outcome.execution.id, - "mcp.execute.pause_source": "browser_resume", - }); - yield* onExecutionPaused(outcome.execution.id, deadline); - } - return outcome.status === "completed" - ? toMcpResult(outcome.result) - : yield* requireUserResumeApproval(outcome.execution.id); - }).pipe( - Effect.withSpan("mcp.host.tool.resume.browser_approval", { - attributes: { - "mcp.tool.name": "resume", - "mcp.execute.execution_id": executionId, - }, - }), - Effect.annotateSpans(requestSpanAttributes(extra)), - ); - - // --- tools --- - - yield* Effect.sync(() => - assembly.registerTool( - "execute", - { - description, - inputSchema: { code: z.string().trim().min(1) }, - }, - ({ code }, extra) => runToolEffect(executeCode(code, extra)), - ), - ); - - yield* Effect.sync(() => - assembly.registerTool( - "skills", - { - description: [ - "Fetch a named how-to skill. Skills hold the long-form guidance that would otherwise bloat another tool's always-loaded description.", - 'Call `skills({ name: "execute" })` for the full guide to writing code for the `execute` tool (search the catalog, call tools, emit results, resume paused runs).', - "Call with no name to list the available skills.", - ].join("\n"), - inputSchema: { - name: z - .string() - .optional() - .describe('The skill to fetch, e.g. "execute". Omit to list available skills.'), - }, - }, - ({ name }) => - runToolEffect(Effect.succeed(skillsResult(name, executeInventory, skillCatalog))), - ), - ); - - yield* Effect.sync(() => { - if (elicitationMode.mode === "native") { - return undefined; - } - - if (elicitationMode.mode === "model") { - return assembly.registerTool( - "resume", - { - description: [ - "Resume a paused execution using the executionId returned by execute.", - "This connection explicitly allows model-side resume via elicitation_mode=model.", - ].join("\n"), - inputSchema: { - executionId: z.string().describe("The execution ID from the paused result"), - action: z - .enum(["accept", "decline", "cancel"]) - .describe("How to respond to the interaction"), - content: z - .string() - .describe("Optional JSON-encoded response content for form elicitations") - .default("{}"), - }, - }, - ({ executionId, action, content: rawContent }, extra) => - runToolEffect( - resumeExecution(executionId, action, parseJsonContent(rawContent), extra), - ), - ); - } - - return assembly.registerTool( - "resume", - { - description: [ - "Request user approval to resume a paused execution.", - "Call this with the executionId returned by execute. If the user has not approved in the browser yet, tell them to open the returned approval URL. If they have approved, this returns the resumed execution result.", - "This connection does not allow the model to choose accept, decline, cancel, or content.", - ].join("\n"), - inputSchema: { - executionId: z.string().describe("The execution ID from the paused result"), - }, - }, - ({ executionId }, extra) => runToolEffect(resumeAfterBrowserApproval(executionId, extra)), - ); - }); - - // --- artifacts / MCP Apps --- - // - // These register unconditionally once a shell loader is configured. Whether - // the client can actually *render* an app is only known after `initialize`, - // so the app-only tools are toggled in `syncToolAvailability` below; the - // model-facing three stay enabled either way and fall back to a deep link. - - const artifacts = config.artifacts; - - // Set from the client's advertised capabilities at `initialize`. Read by - // the render handlers to choose inline widget vs. deep link. Seeded from - // the host's persisted value so a cold-restored session keeps rendering - // inline for a client that had already negotiated apps support. - // - // This is a cache, not the source of truth: `appsSupported()` below reads - // the live server on every render, because a cold restore re-establishes - // capabilities without ever running the hook that maintains this variable. - let appsEnabled = assembly.initialAppsEnabled; - let executeActionTool: { enable: () => void; disable: () => void } | undefined; - let executeActionResumeTool: { enable: () => void; disable: () => void } | undefined; - - /** - * Move the cached flag and the app-only tools together. - * - * `execute-action` is only callable from inside a rendered app, so a client - * that can't render one should never see it. `create-artifact`, - * `list-artifacts` and `show-artifact` stay visible regardless: they still - * persist, and still return something useful (a deep link). - */ - const applyAppsEnabled = (next: boolean): void => { - appsEnabled = next; - if (next) { - executeActionTool?.enable(); - executeActionResumeTool?.enable(); - } else { - executeActionTool?.disable(); - executeActionResumeTool?.disable(); - } - }; - - // Best-effort usage observation; a failing observer never affects the tool. - const notifyArtifactUsage = (action: "created" | "viewed" | "updated"): Effect.Effect => - config.onArtifactUsage - ? config.onArtifactUsage(action).pipe(Effect.ignoreCause({ log: false })) - : Effect.void; - - const saveAndDeliverArtifact = (input: { - readonly code: string; - readonly title: string; - readonly description?: string; - readonly existingId?: string; - readonly bindings?: Readonly>; - /** Sanitized layout markup from the smoke render, when it produced any. */ - readonly preview?: string | null; - }): Effect.Effect => - Effect.gen(function* () { - if (!artifacts) return artifactsUnavailableResult(); - const saved = yield* artifacts.save({ - ...(input.existingId === undefined ? {} : { id: input.existingId }), - title: input.title, - description: input.description ?? null, - code: input.code, - ...(input.bindings === undefined ? {} : { bindings: input.bindings }), - preview: input.preview ?? null, - }); - yield* notifyArtifactUsage(input.existingId === undefined ? "created" : "updated"); - // Resolve once and report the value actually used, so the span can - // never disagree with what the client received. - const delivered = deliverArtifact({ - code: saved.code, - artifactId: saved.id, - title: saved.title, - }); - yield* Effect.annotateCurrentSpan({ - "mcp.artifact.id": saved.id, - "mcp.artifact.apps_enabled": appsEnabled, - }); - return delivered; - }); - - /** - * Whether the client can render an app, resolved at render time. - * - * `appsEnabled` alone is not enough. On a cold restore the host replays the - * persisted `initialize` *request* — which does set the server's client - * capabilities — but never the `notifications/initialized` notification, - * and `oninitialized` (the only hook that re-runs `syncToolAvailability`) - * fires solely on that notification. So a restored session can hold full - * apps capabilities while `appsEnabled` still reads its seeded value, and - * the replay is dispatched un-awaited, so a tool call can land before it. - * - * Reading the live server here makes both orderings produce the same - * answer, and keeps the seeded value as the fallback for the window before - * any capabilities exist. - */ - const appsSupported = (): boolean => { - const live = assembly.getClientCapabilities(); - if (!live) return appsEnabled; - const uiCapability = assembly.getUiCapability(); - const supported = Boolean(uiCapability?.mimeTypes?.includes(RESOURCE_MIME_TYPE)); - // Reconcile the tools too: a restore that re-established capabilities - // without firing `oninitialized` would otherwise render inline while - // `execute-action` — the tool that rendered app calls back into — stayed - // hidden, leaving the widget unable to do anything. - if (supported !== appsEnabled) applyAppsEnabled(supported); - return supported; - }; - - const deliverArtifact = (input: { - readonly code: string; - readonly artifactId: string; - readonly title: string; - }): McpToolResult => { - const url = config.artifactUrl?.(input.artifactId); - if (appsSupported()) return renderedInAppResult({ ...input, url }); - return url - ? renderedAsLinkResult({ url, artifactId: input.artifactId, title: input.title }) - : renderedWithoutSurfaceResult({ artifactId: input.artifactId, title: input.title }); - }; - - /** - * The shared back half of `create-artifact` and `edit-artifact`: everything - * that happens once the full candidate source is in hand. Static checks, - * the smoke render, binding and the save are identical whether the code - * arrived whole or was assembled from stored source plus edits — sharing - * the pipeline is what guarantees an edit cannot save anything a create - * would have refused. - */ - const validateRenderAndSave = (input: { - readonly code: string; - readonly title: string; - readonly description?: string | undefined; - readonly connections?: Readonly> | undefined; - readonly existing: Artifact | null; - }): Effect.Effect => - Effect.gen(function* () { - const rejection = validateArtifactCode(input.code); - if (rejection) return renderRejectedResult(rejection); - - // Static checks first, then the real one: render it. See - // `smokeRenderRejection` for what the model is told. - // - // FAIL OPEN. The renderer is injected, runs on three different hosts, - // and is the newest thing in this path — if IT breaks (a missing - // module, an environment gap on some host), the right outcome is a - // saved artifact and a logged warning, never a refused create of code - // that is perfectly good. Only a definite `failed` blocks a save. - const smoke = config.smokeRenderArtifact; - // The render that validates the artifact is also the render that - // previews it: the same pass produces the loading-state markup the - // gallery draws, so a preview costs nothing beyond sanitizing it. - let preview: string | null = null; - if (smoke) { - const smokeResult: ArtifactSmokeRenderResult = yield* Effect.tryPromise(() => - smoke(input.code), - ).pipe( - Effect.catchCause((cause) => - Effect.as(Effect.logWarning("create-artifact smoke render was unavailable", cause), { - status: "ok", - } satisfies ArtifactSmokeRenderResult), - ), - ); - const renderRejection = smokeRenderRejection(smokeResult); - if (renderRejection) { - yield* Effect.annotateCurrentSpan({ "mcp.artifact.smoke_render": "failed" }); - return renderRejectedResult(renderRejection); - } - // Fail open, exactly as the verdict does: a preview that cannot be - // produced or cannot be sanitized is a card that falls back to its - // schematic, never a create that is refused. - preview = - smokeResult.status === "ok" && smokeResult.markup !== undefined - ? sanitizeArtifactPreviewMarkup(smokeResult.markup) - : null; - } - - const saveInput = { - code: input.code, - title: input.title, - preview, - ...(input.description === undefined ? {} : { description: input.description }), - ...(input.existing === null ? {} : { existingId: input.existing.id }), - }; - - const roles = extractArtifactRoles(input.code); - if (roles.length === 0 && input.connections === undefined) { - return yield* saveAndDeliverArtifact({ ...saveInput, bindings: {} }); - } - - if (!config.connections) { - return renderRejectedResult( - "This connection cannot bind integrations, so an artifact that calls one cannot be saved here.", - ); - } - - const available = yield* config.connections - .list() - .pipe(Effect.catchCause(() => Effect.succeed([] as readonly BindableConnection[]))); - const resolved = resolveArtifactBindings({ - roles, - connections: input.connections, - available, - }); - if (!resolved.ok) return renderRejectedResult(resolved.message); - - yield* Effect.annotateCurrentSpan({ - "mcp.artifact.role_count": roles.length, - }); - return yield* saveAndDeliverArtifact({ ...saveInput, bindings: resolved.bindings }); - }); - - /** - * Bind the integration roles an artifact's code uses, at create time. - * - * Binding happens HERE rather than at render time because this is the only - * moment the author, the code and their connections are all in hand — and - * because a create that can't bind is a create that would have saved a - * broken artifact. The model finds out now, with the candidate list, rather - * than the user finding out later through a query error inside the UI. - * - * `artifactId` turns the same call into an update in place — for a REWRITE, - * where the new source shares little with the old and edits would be longer - * than the code. A tweak belongs on `edit-artifact`, which patches the - * stored source instead of replacing it. Either way one row is kept: a copy - * per revision is the thing the model has to ask for, never the default. - * - * An update replaces the code outright — v1 keeps no version history — and - * re-extracts and re-resolves the bindings from the NEW source, because the - * roles the new code uses are not necessarily the ones the old code did. - * `title` and `description` are optional on an update and absent means keep - * what is stored, so a pure code tweak doesn't have to restate them. - */ - const createArtifact = (input: { - readonly code: string; - readonly title?: string; - readonly description?: string; - readonly connections?: Readonly>; - readonly artifactId?: string; - }): Effect.Effect => - Effect.gen(function* () { - // An update reads the existing row FIRST, both to carry its title and - // description forward and to refuse a foreign id before any work. The - // refusal is `artifact_unavailable` — the same answer `execute-action` - // gives — so create-artifact cannot be used to probe which ids exist. - const existing = - input.artifactId === undefined ? null : yield* loadArtifact(input.artifactId); - if (input.artifactId !== undefined && !existing) return actionArtifactUnavailableResult(); - - const title = input.title ?? existing?.title; - if (title === undefined) { - return renderRejectedResult( - "title is required when creating an artifact. Give it a short human-readable name.", - ); - } - // Only an update inherits; a create with no description stores none. - const description = input.description ?? existing?.description ?? undefined; - - return yield* validateRenderAndSave({ - code: input.code, - title, - description, - connections: input.connections, - existing, - }); - }).pipe( - Effect.withSpan("mcp.host.tool.create_artifact", { - attributes: { - "mcp.tool.name": "create-artifact", - "mcp.artifact.update": input.artifactId !== undefined, - "mcp.execute.code_length": input.code.length, - }, - }), - ); - - /** - * `edit-artifact`: the update path for tweaks, patching the stored source - * with exact find-and-replace edits so the call scales with the change - * rather than the component. The edited result runs the same - * validate → smoke-render → bind → save pipeline as a full create, so an - * edit cannot save anything a create would have refused. - * - * A failed edit hands the CURRENT source back in `structuredContent.code`. - * The model's usual recovery — `show-artifact`, re-read, retry — is a whole - * extra round trip to fetch a thing this call already loaded; giving it - * back here makes the retry immediate. - */ - const editArtifact = (input: { - readonly artifactId: string; - readonly edits: readonly ArtifactEdit[]; - readonly title?: string; - readonly description?: string; - readonly connections?: Readonly>; - }): Effect.Effect => - Effect.gen(function* () { - // Same probe-proof refusal as create-artifact's update arm. - const existing = yield* loadArtifact(input.artifactId); - if (!existing) return actionArtifactUnavailableResult(); - - const applied = applyArtifactEdits(existing.code, input.edits); - if (!applied.ok) return editRejectedResult(applied.message, existing.code); - - yield* Effect.annotateCurrentSpan({ - "mcp.artifact.edit_count": input.edits.length, - }); - return yield* validateRenderAndSave({ - code: applied.code, - title: input.title ?? existing.title, - description: input.description ?? existing.description ?? undefined, - connections: input.connections, - existing, - }); - }).pipe( - Effect.withSpan("mcp.host.tool.edit_artifact", { - attributes: { - "mcp.tool.name": "edit-artifact", - "mcp.artifact.id": input.artifactId, - }, - }), - ); - - const listArtifacts = (): Effect.Effect => - Effect.gen(function* () { - if (!artifacts) return artifactsUnavailableResult(); - return artifactListResult(yield* artifacts.list()); - }).pipe( - Effect.withSpan("mcp.host.tool.list_artifacts", { - attributes: { "mcp.tool.name": "list-artifacts" }, - }), - ); - - const showArtifact = (id: string): Effect.Effect => - Effect.gen(function* () { - if (!artifacts) return artifactsUnavailableResult(); - // A miss is the ordinary case (the model guessed an id, or the row was - // deleted), so it becomes an isError result rather than a defect. - const artifact: Artifact | null = yield* artifacts - .get(id) - .pipe(Effect.catchCause(() => Effect.succeed(null))); - if (!artifact) return artifactNotFoundResult(id); - yield* notifyArtifactUsage("viewed"); - return deliverArtifact({ - code: artifact.code, - artifactId: artifact.id, - title: artifact.title, - }); - }).pipe( - Effect.withSpan("mcp.host.tool.show_artifact", { - attributes: { "mcp.tool.name": "show-artifact", "mcp.artifact.id": id }, - }), - ); - - // Two independent reasons to serve no artifact surface: the host cannot - // (no shell loader), or this connection opted out (`?artifacts=false`). - // Either way nothing below registers, so a disabled session is byte-for-byte - // a session on a host that never had artifacts. - const loadAppShellHtml = artifactsEnabled ? config.loadAppShellHtml : undefined; - - if (loadAppShellHtml) { - yield* Effect.sync(() => { - assembly.registerAppResource( - "Executor Shell", - MCP_APPS_SHELL_RESOURCE_URI, - { mimeType: RESOURCE_MIME_TYPE }, - async () => ({ - contents: [ - { - uri: MCP_APPS_SHELL_RESOURCE_URI, - mimeType: RESOURCE_MIME_TYPE, - text: await loadAppShellHtml(), - // Zero allowed domains: the shell may open no network - // connection of its own. Every read and write goes back over - // the MCP bridge through `execute-action`. - _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] } } }, - }, - ], - }), - ); - }); - - yield* Effect.sync(() => - assembly.registerAppTool( - "create-artifact", - { - description: [ - "Render an interactive React UI component as an MCP app, and save it as a reusable artifact.", - 'Call `skills({ name: "create-artifact" })` for the full guide: the discovery-then-render protocol, TanStack Query rules, and every component already in scope. Call `skills({ name: "artifact-style" })` for how it must look — artifacts render inside the Executor console and must match its design system.', - "Write a component named `App` in `code`. Do not import anything and do not paste fetched data into JSX — read it live with `useQuery(tools...queryOptions(args))`.", - "Lay it out as an app, not a document: an artifact may be given the whole viewport, so make the root `flex h-full flex-col`, keep headers and filters as ordinary children, and give the one long table or list `flex-1 min-h-0 overflow-auto` — its header then stays put while the rows scroll under it.", - "Artifact code addresses an INTEGRATION, never a connection: write `tools.vercel.domains.getDomains`, not the full `tools.vercel.user.personalVercel.domains.getDomains` address `execute` uses for discovery. The connection is bound when the artifact is saved, so it stays portable. Code containing a `.user.` or `.org.` segment is rejected.", - 'To use two accounts of the same integration, tag each call site with a role — `tools.linear("prod").issues.list` and `tools.linear("staging").issues.list` — and map every role in `connections`.', - "All data access is declarative `tools.*`: `.queryOptions()` to read, `.infiniteQueryOptions()` to page through a cursor, `.mutationOptions()` to write. There is no `run()` and no arbitrary code — never hand-roll `useQuery({ queryKey, queryFn })`, or invalidation breaks.", - "To read every page of a paginated tool, call `useInfiniteQuery(tools...infiniteQueryOptions(args, { cursorKey, getNextPageParam }))` once and render `data.pages`. Never call hooks inside a loop — a `useQuery` per page is rejected.", - "To CHANGE an artifact that already exists, use `edit-artifact` — it patches the stored source with find-and-replace edits, so a tweak costs only the changed lines. Only use create-artifact with `artifactId` for a full rewrite, sending the complete new component. Never create a second artifact for a revision of an existing one.", - "Clients that cannot display MCP apps receive a link to the saved artifact instead; pass it to the user.", - ].join("\n"), - inputSchema: { - code: z.string().trim().min(1).describe("The React component source. Export `App`."), - artifactId: z - .string() - .trim() - .min(1) - .optional() - .describe( - "The artifact to REWRITE in place, from `list-artifacts` or a previous create. Omit to create a new one. `code` fully replaces the stored source and the connection bindings are re-resolved from it, so send the complete component, not a fragment. For a tweak, use `edit-artifact` instead.", - ), - connections: z - .record(z.string(), z.string()) - .optional() - .describe( - 'Which connection each integration role in `code` uses, as `..` (the address `connections.list` reports, minus the leading `tools.`). Keys are roles: the integration slug for an untagged `tools.linear.…`, or the tag for `tools.linear("prod").…`. Optional when you have exactly one connection per integration used — that one binds automatically. Required when you have several, and the error lists them.', - ), - title: z - .string() - .trim() - .min(1) - .optional() - .describe( - 'Short human-readable name for the artifact, e.g. "Active users dashboard". The user sees this and you match against it later. Required when creating; on an update, omit it to keep the current title.', - ), - description: z - .string() - .optional() - .describe( - "What this UI shows, in a sentence. Used to find the artifact again on a later request. On an update, omit it to keep the current description.", - ), - }, - _meta: { - ui: { resourceUri: MCP_APPS_SHELL_RESOURCE_URI, visibility: ["model"] }, - }, - }, - ({ code, title, description, connections, artifactId }) => - runToolEffect(createArtifact({ code, title, description, connections, artifactId })), - ), - ); - - yield* Effect.sync(() => - assembly.registerAppTool( - "edit-artifact", - { - description: [ - "Change an existing artifact by patching its stored source with exact find-and-replace edits, and re-render it.", - "PREFER THIS over create-artifact for tweaks — a new column, a fixed label, a restyled section — because you send only the changed lines, not the whole component. Use create-artifact with `artifactId` only for a rewrite where most of the code changes.", - "Each edit's `oldText` must appear EXACTLY ONCE in the current source, verbatim (whitespace included); include enough surrounding lines to make it unique, or set `replaceAll: true` to change every occurrence. Edits apply in order, each seeing the previous one's result.", - "The batch is atomic: if any edit fails to match, nothing is saved and the error returns the current source in structuredContent.code — rebuild the edits from that instead of calling show-artifact again.", - "The edited component is validated and smoke-rendered exactly like a create, and connection bindings are re-resolved from the result; pass `connections` if an edit introduces an ambiguous integration.", - ].join("\n"), - inputSchema: { - artifactId: z - .string() - .trim() - .min(1) - .describe("The artifact to edit, from `list-artifacts` or a previous create."), - edits: z - .array( - z.object({ - oldText: z - .string() - .min(1) - .describe( - "Exact text to find in the current source, whitespace included. Must match exactly once unless replaceAll is true.", - ), - newText: z.string().describe("The replacement text."), - replaceAll: z - .boolean() - .optional() - .describe("Replace every occurrence instead of requiring a unique match."), - }), - ) - .min(1) - .describe("Find-and-replace edits, applied in order. All-or-nothing."), - connections: z - .record(z.string(), z.string()) - .optional() - .describe( - "Connection for each integration role the EDITED code uses, exactly as on create-artifact. Only needed when an edit introduces an integration with several connections.", - ), - title: z - .string() - .trim() - .min(1) - .optional() - .describe("New title. Omit to keep the current one."), - description: z - .string() - .optional() - .describe("New description. Omit to keep the current one."), - }, - _meta: { - ui: { resourceUri: MCP_APPS_SHELL_RESOURCE_URI, visibility: ["model"] }, - }, - }, - ({ artifactId, edits, connections, title, description }) => - runToolEffect(editArtifact({ artifactId, edits, connections, title, description })), - ), - ); - - yield* Effect.sync(() => - assembly.registerTool( - "list-artifacts", - { - description: [ - "List the saved UI artifacts for this account, newest first.", - "Match the user's phrasing against the returned titles and descriptions, then call `show-artifact` with that id.", - ].join("\n"), - inputSchema: {}, - }, - () => runToolEffect(listArtifacts()), - ), - ); - - yield* Effect.sync(() => - assembly.registerAppTool( - "show-artifact", - { - description: [ - "Re-render a saved UI artifact by id.", - "Use `list-artifacts` first to find the id whose title or description matches what the user asked for.", - "Clients that cannot display MCP apps receive a link to the artifact instead.", - ].join("\n"), - inputSchema: { - id: z.string().trim().min(1).describe("The artifact id from `list-artifacts`."), - }, - _meta: { - ui: { resourceUri: MCP_APPS_SHELL_RESOURCE_URI, visibility: ["model"] }, - }, - }, - ({ id }) => runToolEffect(showArtifact(id)), - ), - ); - - yield* Effect.sync(() => { - executeActionTool = assembly.registerAppTool( - "execute-action", - { - description: - "Execute code from the UI shell. Used by interactive components to call tools and run mutations.", - inputSchema: { - code: z.string().trim().min(1), - artifactId: z - .string() - .trim() - .min(1) - .optional() - .describe( - "The artifact making the call. Its stored bindings resolve the integration role in `code` to a connection.", - ), - }, - _meta: { - ui: { resourceUri: MCP_APPS_SHELL_RESOURCE_URI, visibility: ["app"] }, - }, - }, - ({ code, artifactId }, extra) => - runToolEffect(executeCodeFromApp(code, artifactId, extra)), - ); - - executeActionResumeTool = assembly.registerAppTool( - "execute-action-resume", - { - description: "Resume an interactive UI action after shell-owned user approval.", - inputSchema: { - executionId: z.string().describe("The execution ID from the paused UI action"), - action: z - .enum(["accept", "decline", "cancel"]) - .describe("How to respond to the interaction"), - content: z - .string() - .describe("Optional JSON-encoded response content for form elicitations") - .default("{}"), - }, - _meta: { - ui: { resourceUri: MCP_APPS_SHELL_RESOURCE_URI, visibility: ["app"] }, - }, - }, - ({ executionId, action, content: rawContent }, extra) => - runToolEffect( - resumeExecution(executionId, action, parseJsonContent(rawContent), extra), - ), - ); - }); - } - - // Client capabilities only exist after `initialize`, and `tools/list` is - // answered from whatever is registered at that moment — so app-only tool - // visibility has to be re-synced from the `oninitialized` hook rather than - // decided at construction. - // - // This hook covers live clients only. It does NOT run on a cold restore: - // the host replays the persisted `initialize` request, but `oninitialized` - // fires on the `notifications/initialized` notification, which is never - // persisted. `appsSupported()` is what makes the restored case correct. - const syncToolAvailability = () => { - const clientCapabilities = assembly.getClientCapabilities(); - const uiCapability = assembly.getUiCapability(); - // Absent capabilities (the SDK returns `undefined`) mean `initialize` - // hasn't happened on THIS server instance — the construction-time call - // below, or a cold restore that resumed mid-conversation. Neither is - // evidence the client lost apps support, so the restored value stands - // until a real `initialize` replaces it. Reading `false` off an absent - // value here is exactly what made a cold-restored session fall back to - // deep links. - const negotiated = clientCapabilities - ? Boolean(uiCapability?.mimeTypes?.includes(RESOURCE_MIME_TYPE)) - : appsEnabled; - const changed = negotiated !== appsEnabled; - applyAppsEnabled(negotiated); - - // Persist only a real negotiation that moved the value, so the next cold - // restore seeds itself. Best-effort: the session must not fail on it. - // The `clientCapabilities` guard matters beyond skipping a no-op write: - // persisting an absent-capability reading would make a downgrade durable - // for every future restore of the session. - const onAppsEnabledChange = config.onAppsEnabledChange; - if (clientCapabilities && changed && onAppsEnabledChange) { - // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: `oninitialized` is a sync SDK hook; persistence is fire-and-forget and its failure must not fail the session - void Effect.runPromiseWith(context)( - onAppsEnabledChange(negotiated).pipe(Effect.ignoreCause({ log: false })), - ); - } - - debugLog("tool.visibility", { - clientCapabilities: clientCapabilities ?? null, - elicitationSupport: assembly.getElicitationSupport(), - elicitationMode: elicitationMode.mode, - resumeEnabled: elicitationMode.mode !== "native", - appsSupport: uiCapability ?? null, - appsEnabled, - executeActionEnabled: appsEnabled, - }); - }; - - // Client identity arrives with the same `initialize` that carries the - // capabilities above. An absent live value (cold restore, construction - // time) is not evidence the client changed, so the restored value stands, - // the same asymmetry `syncToolAvailability` documents for capabilities. - const syncClientInfo = () => { - const live = assembly.getClientInfo(); - if (live === null) return; - const changed = - live.name !== clientInfo?.name || - live.version !== clientInfo?.version || - live.title !== clientInfo?.title; - if (!changed) return; - clientInfo = live; - const onClientInfoChange = config.onClientInfoChange; - if (onClientInfoChange) { - // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: `oninitialized` is a sync SDK hook; persistence is fire-and-forget and its failure must not fail the session - void Effect.runPromiseWith(context)( - onClientInfoChange(live).pipe(Effect.ignoreCause({ log: false })), - ); - } - }; - - yield* Effect.sync(() => { - syncToolAvailability(); - syncClientInfo(); - assembly.onInitialized(() => { - syncToolAvailability(); - syncClientInfo(); - }); - }).pipe(Effect.withSpan("mcp.host.sync_tool_availability")); - - return server; - }).pipe(Effect.withSpan("mcp.host.create_executor_server")); diff --git a/packages/hosts/mcp/src/tool-server-protocol.test.ts b/packages/hosts/mcp/src/tool-server-protocol.test.ts deleted file mode 100644 index d3f536d031..0000000000 --- a/packages/hosts/mcp/src/tool-server-protocol.test.ts +++ /dev/null @@ -1,388 +0,0 @@ -import { describe, expect, it } from "@effect/vitest"; -import { - Client, - StreamableHTTPClientTransport, - withInputRequired, - type Request as McpRequest, -} from "@modelcontextprotocol/client"; -import { CallToolResultSchema } from "@modelcontextprotocol/core"; -import { - createMcpHandler, - isInputRequiredResult, - type InputRequiredResult, -} from "@modelcontextprotocol/server"; -import { Effect } from "effect"; - -import type { ExecutionEngine, ExecutionResult, ResumeResponse } from "@executor-js/execution"; -import { defaultMcpResource, type McpResource } from "./seams"; -import { FormElicitation, ToolAddress } from "@executor-js/sdk"; - -import { - appsEnabledForClientCapabilities, - buildMcpServer, - mcpRequestStateBindingFromBody, -} from "./tool-server"; -import { RESOURCE_MIME_TYPE, RESOURCE_URI_META_KEY } from "./mcp-apps"; - -const REQUEST_STATE_KEY = new Uint8Array(32).fill(7); -const TOOL_ADDRESS = ToolAddress.make("tools.test.org.main.echo"); -const APP_URI = "ui://executor/shell.html"; - -type TestServerConfig = { - readonly engine: ExecutionEngine; - readonly appsEnabled: boolean; - readonly elicitationMode?: { readonly mode: "model" } | { readonly mode: "native" }; - readonly loadAppShellHtml?: () => Promise; - /** Evaluated per request, so a test can swap principals between rounds. */ - readonly requestStatePrincipal?: () => string; - /** Evaluated per request, so a test can swap resources between rounds. */ - readonly requestStateResource?: () => McpResource; -}; - -const makeStubEngine = ( - overrides: { - readonly executeWithPause?: ExecutionEngine["executeWithPause"]; - readonly resume?: ExecutionEngine["resume"]; - readonly getPausedExecution?: ExecutionEngine["getPausedExecution"]; - } = {}, -): ExecutionEngine => ({ - execute: (code) => Effect.succeed({ result: `ran: ${code}` }), - executeWithPause: - overrides.executeWithPause ?? - ((code) => Effect.succeed({ status: "completed", result: { result: `ran: ${code}` } })), - resume: overrides.resume ?? (() => Effect.succeed(null)), - isExecutionSettled: () => Effect.succeed(false), - getPausedExecution: overrides.getPausedExecution ?? (() => Effect.succeed(null)), - pausedExecutionCount: () => Effect.succeed(0), - hasPausedExecutions: () => Effect.succeed(false), - getDescription: Effect.succeed("test executor"), -}); - -const withClient = async ( - config: TestServerConfig, - run: (client: Client) => Promise, - options?: { readonly manualInputRequired?: boolean }, -) => { - const requestBodies = new WeakMap(); - const handler = createMcpHandler( - (context) => - Effect.runPromise( - Effect.gen(function* () { - const requestStatePrincipal = config.requestStatePrincipal?.() ?? "principal-test"; - const requestStateResource = config.requestStateResource?.() ?? defaultMcpResource; - const requestStateBinding = yield* Effect.promise(() => - mcpRequestStateBindingFromBody({ - body: context.requestInfo ? requestBodies.get(context.requestInfo) : undefined, - principal: requestStatePrincipal, - resource: requestStateResource, - }), - ); - return yield* buildMcpServer({ - ...config, - requestStateSigningKey: REQUEST_STATE_KEY, - requestStatePrincipal, - ...(requestStateBinding === null ? {} : { requestStateBinding }), - }); - }), - ), - { legacy: "reject" }, - ); - const transport = new StreamableHTTPClientTransport(new URL("http://executor.test/mcp"), { - fetch: async (input, init) => { - const request = - input instanceof Request ? new Request(input, init) : new Request(input.toString(), init); - requestBodies.set(request, await request.clone().json()); - return handler.fetch(request, { parsedBody: requestBodies.get(request) }); - }, - }); - const client = new Client( - { name: "executor-protocol-test", version: "1.0.0" }, - { - capabilities: { elicitation: { form: {} } }, - versionNegotiation: { mode: { pin: "2026-07-28" } }, - ...(options?.manualInputRequired ? { inputRequired: { autoFulfill: false } } : {}), - }, - ); - await client.connect(transport); - // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: test helper owns the client transport and in-process HTTP handler - try { - await run(client); - } finally { - await client.close(); - await handler.close(); - } -}; - -const manualToolCall = ( - client: Client, - params: Record, -): Promise>> => { - const request: McpRequest = { method: "tools/call", params }; - return client.request(request, withInputRequired(CallToolResultSchema), { - allowInputRequired: true, - }); -}; - -describe("Executor MCP protocol assembly", () => { - it("lists Executor tools and executes code end to end over the modern HTTP entry", async () => { - await withClient({ engine: makeStubEngine(), appsEnabled: false }, async (client) => { - const names = (await client.listTools()).tools.map(({ name }) => name); - expect(names).toContain("execute"); - expect(names).toContain("skills"); - expect(names).toContain("resume"); - - const result = await client.callTool({ - name: "execute", - arguments: { code: "1 + 1" }, - }); - expect(result.content).toEqual([{ type: "text", text: "ran: 1 + 1" }]); - expect(result.isError).toBeFalsy(); - }); - }); - - it("registers app metadata and app-only tools only for apps-enabled requests", async () => { - const inspect = async (appsEnabled: boolean) => { - let observed: - | { - readonly names: readonly string[]; - readonly createMeta: Record | undefined; - readonly resourceCount: number; - } - | undefined; - await withClient( - { - engine: makeStubEngine(), - appsEnabled, - loadAppShellHtml: async () => "", - }, - async (client) => { - const tools = (await client.listTools()).tools; - observed = { - names: tools.map(({ name }) => name), - createMeta: tools.find(({ name }) => name === "create-artifact")?._meta, - resourceCount: (await client.listResources()).resources.length, - }; - }, - ); - return observed; - }; - - const enabled = await inspect(true); - expect(enabled?.names).toContain("execute-action"); - expect(enabled?.createMeta).toMatchObject({ - ui: { resourceUri: APP_URI, visibility: ["model"] }, - [RESOURCE_URI_META_KEY]: APP_URI, - }); - expect(enabled?.resourceCount).toBe(1); - - const disabled = await inspect(false); - expect(disabled?.names).not.toContain("execute-action"); - expect(disabled?.createMeta).toBeUndefined(); - expect(disabled?.resourceCount).toBe(0); - }); - - it("returns input_required and resumes native elicitation from signed requestState", async () => { - const request = FormElicitation.make({ - message: "Which value?", - requestedSchema: { - type: "object", - properties: { value: { type: "string" } }, - required: ["value"], - }, - }); - const paused: Extract = { - status: "paused", - execution: { - id: "execution-1", - elicitationContext: { address: TOOL_ADDRESS, args: {}, request }, - }, - }; - let resumedWith: ResumeResponse | undefined; - const engine = makeStubEngine({ - executeWithPause: () => Effect.succeed(paused), - getPausedExecution: () => Effect.succeed(paused.execution), - resume: (_executionId, response) => { - resumedWith = response; - return Effect.succeed({ - status: "completed", - result: { result: response.content?.value }, - }); - }, - }); - - await withClient( - { engine, appsEnabled: false, elicitationMode: { mode: "native" } }, - async (client) => { - const first = await manualToolCall(client, { - name: "execute", - arguments: { code: "await tools.test.echo()" }, - }); - expect(isInputRequiredResult(first)).toBe(true); - if (!isInputRequiredResult(first)) return; - expect(first.inputRequests?.elicitation).toMatchObject({ - method: "elicitation/create", - params: { message: "Which value?" }, - }); - expect(typeof first.requestState).toBe("string"); - - const completed = await manualToolCall(client, { - name: "execute", - arguments: { code: "await tools.test.echo()" }, - inputResponses: { - elicitation: { action: "accept", content: { value: "approved" } }, - }, - requestState: first.requestState, - }); - expect(isInputRequiredResult(completed)).toBe(false); - expect(completed.content).toEqual([{ type: "text", text: "approved" }]); - expect(resumedWith).toEqual({ action: "accept", content: { value: "approved" } }); - }, - { manualInputRequired: true }, - ); - }); - - it("rejects a tampered native-elicitation requestState before resuming", async () => { - const request = FormElicitation.make({ - message: "Confirm", - requestedSchema: {}, - }); - const paused: Extract = { - status: "paused", - execution: { - id: "execution-2", - elicitationContext: { address: TOOL_ADDRESS, args: {}, request }, - }, - }; - let resumeCalls = 0; - const engine = makeStubEngine({ - executeWithPause: () => Effect.succeed(paused), - getPausedExecution: () => Effect.succeed(paused.execution), - resume: () => { - resumeCalls += 1; - return Effect.succeed(null); - }, - }); - - await withClient( - { engine, appsEnabled: false, elicitationMode: { mode: "native" } }, - async (client) => { - const first = await manualToolCall(client, { - name: "execute", - arguments: { code: "await tools.test.echo()" }, - }); - expect(isInputRequiredResult(first)).toBe(true); - if (!isInputRequiredResult(first) || !first.requestState) return; - - // Corrupt an interior character: changing the final one can only touch - // discarded base64url padding bits, which lenient decoders (Bun) drop — - // the decoded bytes would be identical and the signature would verify. - const middle = Math.floor(first.requestState.length / 2); - const swapped = first.requestState[middle] === "A" ? "B" : "A"; - const tampered = `${first.requestState.slice(0, middle)}${swapped}${first.requestState.slice(middle + 1)}`; - await expect( - manualToolCall(client, { - name: "execute", - arguments: { code: "await tools.test.echo()" }, - inputResponses: { elicitation: { action: "accept", content: {} } }, - requestState: tampered, - }), - ).rejects.toMatchObject({ code: -32602 }); - expect(resumeCalls).toBe(0); - }, - { manualInputRequired: true }, - ); - }); - - it("rejects a requestState echoed with a different principal, resource, or code", async () => { - const request = FormElicitation.make({ - message: "Confirm", - requestedSchema: {}, - }); - const paused: Extract = { - status: "paused", - execution: { - id: "execution-3", - elicitationContext: { address: TOOL_ADDRESS, args: {}, request }, - }, - }; - let resumeCalls = 0; - const engine = makeStubEngine({ - executeWithPause: () => Effect.succeed(paused), - getPausedExecution: () => Effect.succeed(paused.execution), - resume: () => { - resumeCalls += 1; - return Effect.succeed(null); - }, - }); - - let principal = "user-a"; - let resource: McpResource = defaultMcpResource; - await withClient( - { - engine, - appsEnabled: false, - elicitationMode: { mode: "native" }, - requestStatePrincipal: () => principal, - requestStateResource: () => resource, - }, - async (client) => { - const first = await manualToolCall(client, { - name: "execute", - arguments: { code: "await tools.test.echo()" }, - }); - expect(isInputRequiredResult(first)).toBe(true); - if (!isInputRequiredResult(first) || !first.requestState) return; - - principal = "user-b"; - await expect( - manualToolCall(client, { - name: "execute", - arguments: { code: "await tools.test.echo()" }, - inputResponses: { elicitation: { action: "accept", content: {} } }, - requestState: first.requestState, - }), - ).rejects.toMatchObject({ code: -32602 }); - - principal = "user-a"; - resource = { kind: "toolkit", slug: "other" }; - await expect( - manualToolCall(client, { - name: "execute", - arguments: { code: "await tools.test.echo()" }, - inputResponses: { elicitation: { action: "accept", content: {} } }, - requestState: first.requestState, - }), - ).rejects.toMatchObject({ code: -32602 }); - - resource = defaultMcpResource; - await expect( - manualToolCall(client, { - name: "execute", - arguments: { code: "await tools.test.different()" }, - inputResponses: { elicitation: { action: "accept", content: {} } }, - requestState: first.requestState, - }), - ).rejects.toMatchObject({ code: -32602 }); - expect(resumeCalls).toBe(0); - }, - { manualInputRequired: true }, - ); - }); - - it("derives request-scoped app support from the exact MCP Apps MIME capability", () => { - expect( - appsEnabledForClientCapabilities({ - extensions: { - "io.modelcontextprotocol/ui": { mimeTypes: [RESOURCE_MIME_TYPE] }, - }, - }), - ).toBe(true); - expect( - appsEnabledForClientCapabilities({ - extensions: { - "io.modelcontextprotocol/ui": { mimeTypes: ["text/html"] }, - }, - }), - ).toBe(false); - }); -}); diff --git a/packages/hosts/mcp/src/tool-server.test.ts b/packages/hosts/mcp/src/tool-server.test.ts index 14b6bb4c3d..80118f37a3 100644 --- a/packages/hosts/mcp/src/tool-server.test.ts +++ b/packages/hosts/mcp/src/tool-server.test.ts @@ -1,8 +1,10 @@ import { describe, expect, it } from "@effect/vitest"; import { Data, Deferred, Effect } from "effect"; import type * as Tracer from "effect/Tracer"; -import { Client } from "@modelcontextprotocol/client"; -import { InMemoryTransport, type ClientCapabilities } from "@modelcontextprotocol/server"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { ElicitRequestSchema } from "@modelcontextprotocol/sdk/types.js"; +import type { ClientCapabilities } from "@modelcontextprotocol/sdk/types.js"; import type * as Cause from "effect/Cause"; import { @@ -16,11 +18,9 @@ import type { ToolFileValue } from "@executor-js/sdk"; import type { ExecutionEngine, ExecutionResult } from "@executor-js/execution"; import { - buildMcpServer, - clientInfoFromRequestBody, + createExecutorMcpServer, formatMcpExecutionOutcome, type ExecutorMcpServerConfig, - type McpClientInfo, } from "./tool-server"; // --------------------------------------------------------------------------- @@ -45,25 +45,18 @@ const makeStubEngine = (overrides: { resume?: ExecutionEngine["resume"]; isExecutionSettled?: ExecutionEngine["isExecutionSettled"]; description?: string; -}): ExecutionEngine => { - const execute: ExecutionEngine["execute"] = - overrides.execute ?? (() => Effect.succeed({ result: "default" })); - return { - execute, - executeWithPause: - overrides.executeWithPause ?? - ((code) => - execute(code, { - onElicitation: () => Effect.die("Unexpected elicitation in completed execution test"), - }).pipe(Effect.map((result) => ({ status: "completed" as const, result })))), - resume: overrides.resume ?? (() => Effect.succeed(null)), - isExecutionSettled: overrides.isExecutionSettled, - getPausedExecution: () => Effect.succeed(null), - pausedExecutionCount: () => Effect.succeed(0), - hasPausedExecutions: () => Effect.succeed(false), - getDescription: Effect.succeed(overrides.description ?? "test executor"), - }; -}; +}): ExecutionEngine => ({ + execute: overrides.execute ?? (() => Effect.succeed({ result: "default" })), + executeWithPause: + overrides.executeWithPause ?? + (() => Effect.succeed({ status: "completed", result: { result: "default" } })), + resume: overrides.resume ?? (() => Effect.succeed(null)), + isExecutionSettled: overrides.isExecutionSettled, + getPausedExecution: () => Effect.succeed(null), + pausedExecutionCount: () => Effect.succeed(0), + hasPausedExecutions: () => Effect.succeed(false), + getDescription: Effect.succeed(overrides.description ?? "test executor"), +}); type TestServerConfig = Pick< ExecutorMcpServerConfig, @@ -73,7 +66,6 @@ type TestServerConfig = Pick< | "pausedExecutionHooks" | "pausedExecutionLeaseMs" | "resumeFallback" - | "onClientInfoChange" >; /** Connect a real MCP Client to our executor MCP server over in-memory transports. */ @@ -84,14 +76,7 @@ const withClient = async ( config?: TestServerConfig & { readonly tracer?: Tracer.Tracer }, ) => { const { tracer, ...serverConfig } = config ?? {}; - const create = buildMcpServer({ - engine, - appsEnabled: false, - requestStateSigningKey: new Uint8Array(32).fill(13), - requestStatePrincipal: "tool-server-test-principal", - sessionful: true, - ...serverConfig, - }); + const create = createExecutorMcpServer({ engine, ...serverConfig }); const mcpServer = await Effect.runPromise(tracer ? Effect.withTracer(create, tracer) : create); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "test-client", version: "1.0.0" }, { capabilities }); @@ -169,6 +154,7 @@ const withTracedClient = async ( const ELICITATION_CAPS: ClientCapabilities = { elicitation: { form: {}, url: {} }, }; +const FORM_ONLY_CAPS: ClientCapabilities = { elicitation: { form: {} } }; const NO_CAPS: ClientCapabilities = {}; /** Extract the first text content from a callTool result. */ @@ -206,15 +192,33 @@ const toolFile = (input: { byteLength: input.byteLength, }); +/** Build an engine whose execute triggers one elicitation and returns the handler's result. */ +const makeElicitingEngine = ( + request: FormElicitation | UrlElicitation, + formatResult: (response: { action: string; content?: Record }) => unknown = ( + r, + ) => r.action, +): ExecutionEngine => + makeStubEngine({ + execute: (_code, { onElicitation }) => + Effect.gen(function* () { + const response = yield* onElicitation({ + address: STUB_TOOL_ADDRESS, + args: {}, + request, + }); + return { result: formatResult(response) }; + }), + }); + // --------------------------------------------------------------------------- // Explicit native elicitation mode // --------------------------------------------------------------------------- describe("MCP host server — native elicitation mode", () => { - it("execute tool calls engine.executeWithPause and returns result", async () => { + it("execute tool calls engine.execute and returns result", async () => { const engine = makeStubEngine({ - executeWithPause: (code) => - Effect.succeed({ status: "completed", result: { result: `ran: ${code}` } }), + execute: (code) => Effect.succeed({ result: `ran: ${code}` }), }); await withNativeClient(engine, ELICITATION_CAPS, async (client) => { @@ -765,6 +769,52 @@ describe("MCP host server — native elicitation mode", () => { }); }); + it("form elicitation is bridged from engine to MCP client and back", async () => { + const engine = makeElicitingEngine( + FormElicitation.make({ + message: "Approve this action?", + requestedSchema: { + type: "object", + properties: { approved: { type: "boolean" } }, + }, + }), + (r) => (r.action === "accept" && r.content?.approved ? "approved" : "denied"), + ); + + await withNativeClient(engine, ELICITATION_CAPS, async (client) => { + client.setRequestHandler(ElicitRequestSchema, async () => ({ + action: "accept" as const, + content: { approved: true }, + })); + + const result = await client.callTool({ + name: "execute", + arguments: { code: "do-it" }, + }); + expect(result.content).toEqual([{ type: "text", text: "approved" }]); + }); + }); + + it("form elicitation declined by client → engine sees decline", async () => { + const engine = makeElicitingEngine( + FormElicitation.make({ message: "Accept?", requestedSchema: {} }), + (r) => `action:${r.action}`, + ); + + await withNativeClient(engine, ELICITATION_CAPS, async (client) => { + client.setRequestHandler(ElicitRequestSchema, async () => ({ + action: "decline" as const, + content: {}, + })); + + const result = await client.callTool({ + name: "execute", + arguments: { code: "x" }, + }); + expect(result.content).toEqual([{ type: "text", text: "action:decline" }]); + }); + }); + it("browser approval mode does not auto-switch to native elicitation", async () => { let approvalUrlCalled = false; let executeCalled = false; @@ -787,6 +837,11 @@ describe("MCP host server — native elicitation mode", () => { engine, ELICITATION_CAPS, async (client) => { + client.setRequestHandler(ElicitRequestSchema, async () => ({ + action: "accept" as const, + content: {}, + })); + const { tools } = await client.listTools(); expect(tools.map((t) => t.name)).toContain("resume"); @@ -815,6 +870,56 @@ describe("MCP host server — native elicitation mode", () => { ); }); + it("empty form schema gets wrapped with minimal valid schema", async () => { + let receivedSchema: unknown; + const engine = makeElicitingEngine( + FormElicitation.make({ message: "Just approve", requestedSchema: {} }), + ); + + await withNativeClient(engine, ELICITATION_CAPS, async (client) => { + client.setRequestHandler(ElicitRequestSchema, async (request) => { + const params = request.params; + if ("requestedSchema" in params) { + receivedSchema = params.requestedSchema; + } + return { action: "accept" as const, content: {} }; + }); + + await client.callTool({ + name: "execute", + arguments: { code: "approve" }, + }); + expect(receivedSchema).toEqual({ type: "object", properties: {} }); + }); + }); + + it("UrlElicitation is sent as native mode:url elicitation", async () => { + let receivedParams: Record | undefined; + const engine = makeElicitingEngine( + UrlElicitation.make({ + message: "Please authenticate", + url: "https://example.com/oauth", + elicitationId: ElicitationId.make("elic-1"), + }), + ); + + await withNativeClient(engine, ELICITATION_CAPS, async (client) => { + client.setRequestHandler(ElicitRequestSchema, async (request) => { + receivedParams = request.params as Record; + return { action: "accept" as const, content: {} }; + }); + + await client.callTool({ + name: "execute", + arguments: { code: "oauth" }, + }); + expect(receivedParams?.mode).toBe("url"); + expect(receivedParams?.message).toBe("Please authenticate"); + expect(receivedParams?.url).toBe("https://example.com/oauth"); + expect(receivedParams?.elicitationId).toBe("elic-1"); + }); + }); + it("engine error is surfaced as isError result", async () => { const engine = makeStubEngine({ execute: () => @@ -872,6 +977,61 @@ describe("MCP host server — native elicitation mode", () => { }); }); +// --------------------------------------------------------------------------- +// Client with form-only elicitation in native mode +// --------------------------------------------------------------------------- + +describe("MCP host server — native form-only elicitation", () => { + it("resume tool is hidden in native mode", async () => { + await withNativeClient(makeStubEngine({}), FORM_ONLY_CAPS, async (client) => { + const { tools } = await client.listTools(); + expect(tools.map((t) => t.name)).toContain("execute"); + expect(tools.map((t) => t.name)).not.toContain("resume"); + }); + }); + + it("uses native elicitation path when client supports form", async () => { + const engine = makeStubEngine({ + execute: (code) => Effect.succeed({ result: `native: ${code}` }), + }); + + await withNativeClient(engine, FORM_ONLY_CAPS, async (client) => { + const result = await client.callTool({ + name: "execute", + arguments: { code: "test" }, + }); + expect(result.content).toEqual([{ type: "text", text: "native: test" }]); + }); + }); + + it("UrlElicitation falls back to form when client lacks url support", async () => { + let receivedMessage: string | undefined; + const engine = makeElicitingEngine( + UrlElicitation.make({ + message: "Please authenticate", + url: "https://auth.example.com/oauth", + elicitationId: ElicitationId.make("elic-1"), + }), + ); + + await withNativeClient(engine, FORM_ONLY_CAPS, async (client) => { + client.setRequestHandler(ElicitRequestSchema, async (request) => { + receivedMessage = + typeof request.params.message === "string" ? request.params.message : undefined; + return { action: "accept" as const, content: {} }; + }); + + const result = await client.callTool({ + name: "execute", + arguments: { code: "oauth" }, + }); + expect(result.content).toEqual([{ type: "text", text: "accept" }]); + expect(receivedMessage).toContain("https://auth.example.com/oauth"); + expect(receivedMessage).toContain("Please authenticate"); + }); + }); +}); + // --------------------------------------------------------------------------- // Client WITHOUT elicitation (pause/resume path) // --------------------------------------------------------------------------- @@ -1479,6 +1639,46 @@ describe("MCP host server — client without elicitation (pause/resume)", () => }); }); +// --------------------------------------------------------------------------- +// Elicitation error handling +// --------------------------------------------------------------------------- + +describe("MCP host server — elicitation error handling", () => { + it("elicitInput failure is not reported as user cancellation", async () => { + const engine = makeElicitingEngine( + FormElicitation.make({ + message: "will fail", + requestedSchema: { + type: "object", + properties: { x: { type: "string" } }, + }, + }), + (r) => `fallback:${r.action}`, + ); + + await withNativeClient(engine, ELICITATION_CAPS, async (client) => { + client.setRequestHandler(ElicitRequestSchema, async () => { + // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- boundary: MCP client request handler rejects to exercise server fallback + throw new Error("client cannot handle this"); + }); + + const result = await client.callTool({ + name: "execute", + arguments: { code: "fail" }, + }); + expect(result.isError).toBe(true); + expect(textOf(result)).toMatch( + /^Error: Native elicitation transport failed \[[0-9a-f]{8}\]\. Reconnect the MCP client and try again\.$/, + ); + expect(result.structuredContent).toMatchObject({ + status: "error", + errorCode: "native_elicitation_transport_failed", + }); + expect(textOf(result)).not.toContain("fallback:cancel"); + }); + }); +}); + // --------------------------------------------------------------------------- // Resume content parsing edge cases // --------------------------------------------------------------------------- @@ -1536,6 +1736,65 @@ describe("MCP host server — resume content parsing", () => { }); }); +// --------------------------------------------------------------------------- +// Multiple elicitations in a single execution +// --------------------------------------------------------------------------- + +describe("MCP host server — multiple elicitations", () => { + it("engine can elicit multiple times during a single execute call", async () => { + const engine = makeStubEngine({ + execute: (_code, { onElicitation }) => + Effect.gen(function* () { + const r1 = yield* onElicitation({ + address: STUB_TOOL_ADDRESS, + args: {}, + request: FormElicitation.make({ + message: "What is your name?", + requestedSchema: { + type: "object", + properties: { name: { type: "string" } }, + }, + }), + }); + + const r2 = yield* onElicitation({ + address: STUB_TOOL_ADDRESS, + args: {}, + request: FormElicitation.make({ + message: `Confirm: ${r1.content?.name}?`, + requestedSchema: { + type: "object", + properties: { confirmed: { type: "boolean" } }, + }, + }), + }); + + return { + result: `name=${r1.content?.name},confirmed=${r2.content?.confirmed}`, + }; + }), + }); + + await withNativeClient(engine, ELICITATION_CAPS, async (client) => { + let callCount = 0; + client.setRequestHandler(ElicitRequestSchema, async () => { + callCount++; + if (callCount === 1) { + return { action: "accept" as const, content: { name: "Alice" } }; + } + return { action: "accept" as const, content: { confirmed: true } }; + }); + + const result = await client.callTool({ + name: "execute", + arguments: { code: "multi" }, + }); + expect(result.content).toEqual([{ type: "text", text: "name=Alice,confirmed=true" }]); + expect(callCount).toBe(2); + }); + }); +}); + // --------------------------------------------------------------------------- // skills tool // --------------------------------------------------------------------------- @@ -1613,77 +1872,6 @@ describe("MCP host server — skills tool", () => { }); }); -describe("MCP host server — client attribution", () => { - it("stamps the initialize-reported client identity on execution spans", async () => { - await withTracedClient(makeStubEngine({}), async (client, spans) => { - await client.callTool({ name: "execute", arguments: { code: "1+1" } }); - - const execute = spans.find((span) => span.name === "mcp.host.tool.execute"); - expectDefined(execute); - expect(execute.attributes.get("mcp.client.name")).toBe("test-client"); - expect(execute.attributes.get("mcp.client.version")).toBe("1.0.0"); - }); - }); - - it("reports the initialize-reported identity to onClientInfoChange once", async () => { - const reported: McpClientInfo[] = []; - await withClient( - makeStubEngine({}), - NO_CAPS, - async (client) => { - await client.callTool({ name: "execute", arguments: { code: "1+1" } }); - expect(reported).toEqual([{ name: "test-client", version: "1.0.0" }]); - }, - { - onClientInfoChange: (clientInfo) => - Effect.sync(() => { - reported.push(clientInfo); - }), - }, - ); - }); -}); - -describe("clientInfoFromRequestBody", () => { - const META_KEY = "io.modelcontextprotocol/clientInfo"; - - it("prefers the per-request _meta identity", () => { - expect( - clientInfoFromRequestBody({ - method: "tools/call", - params: { _meta: { [META_KEY]: { name: "meta-client", version: "2.0.0" } } }, - }), - ).toEqual({ name: "meta-client", version: "2.0.0" }); - }); - - it("falls back to the initialize body's native clientInfo", () => { - expect( - clientInfoFromRequestBody({ - method: "initialize", - params: { clientInfo: { name: "init-client", version: "1.2.3", title: "Init Client" } }, - }), - ).toEqual({ name: "init-client", version: "1.2.3", title: "Init Client" }); - }); - - it("decodes a malformed or absent identity to null", () => { - expect(clientInfoFromRequestBody(null)).toBeNull(); - expect(clientInfoFromRequestBody({ method: "tools/call", params: {} })).toBeNull(); - expect( - clientInfoFromRequestBody({ - method: "tools/call", - params: { _meta: { [META_KEY]: { version: "no-name" } } }, - }), - ).toBeNull(); - // Native clientInfo is only trusted on `initialize`, where the spec puts it. - expect( - clientInfoFromRequestBody({ - method: "tools/call", - params: { clientInfo: { name: "misplaced" } }, - }), - ).toBeNull(); - }); -}); - describe("MCP host server — hang-visibility tracing", () => { it("execute emits a start marker and stamps the JSON-RPC id on execution spans", async () => { const engine = makeStubEngine({}); diff --git a/packages/hosts/mcp/src/tool-server.ts b/packages/hosts/mcp/src/tool-server.ts index 4d3469eec1..41c61bcd0a 100644 --- a/packages/hosts/mcp/src/tool-server.ts +++ b/packages/hosts/mcp/src/tool-server.ts @@ -1,598 +1,2259 @@ -/** - * MCP server assembly shared by stateless modern requests and sessionful - * connections. Stateless callers supply request-scoped capability policy; - * sessionful callers register the full surface once and read negotiated client - * capabilities from the live server. - */ -import { Data, Effect, Match, Option, Schema } from "effect"; +import { Data, Duration, Effect, Match, Option, Predicate, Result, Schema } from "effect"; import * as Cause from "effect/Cause"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { - acceptedContent, - CLIENT_CAPABILITIES_META_KEY, - CLIENT_INFO_META_KEY, - createRequestStateCodec, - fromJsonSchema, - inputRequired, - inputResponse, - McpServer, - type CallToolResult, - type Implementation, - type InputRequiredResult, - type ServerContext, -} from "@modelcontextprotocol/server"; -import * as z from "zod/v4"; - -import type { ElicitationRequest } from "@executor-js/sdk"; - -import { mcpResourceKey, type McpResource } from "./seams"; + ContentBlockSchema, + type ClientCapabilities, + type ContentBlock, +} from "@modelcontextprotocol/sdk/types.js"; import { getUiCapability, - EXTENSION_ID, registerAppResource, registerAppTool, RESOURCE_MIME_TYPE, - RESOURCE_URI_META_KEY, - type McpAppsClientCapabilities, - type McpAppToolMeta, -} from "./mcp-apps"; +} from "@modelcontextprotocol/ext-apps/server"; +import type { + jsonSchemaValidator, + JsonSchemaType, + JsonSchemaValidator, +} from "@modelcontextprotocol/sdk/validation/types.js"; +import { Validator } from "@cfworker/json-schema"; +import * as z from "zod/v4"; + +import { isToolFile, sanitizeArtifactPreviewMarkup } from "@executor-js/sdk"; +import type { + Artifact, + ArtifactBinding, + ArtifactSummary, + ElicitationResponse, + ElicitationHandler, + ElicitationContext, + ElicitationRequest, + SaveArtifactInput, + ToolFileValue, +} from "@executor-js/sdk"; +import type * as Tracer from "effect/Tracer"; import { - buildExecutorMcpTools, - type ExecutorMcpAssembly, - type ExecutorMcpToolConfig, - type McpClientInfo, - type McpHandlerResult, - type McpRequestJoinKeys, - type McpToolResult, - type NativeExecutionServices, -} from "./tool-server-core"; - -export { formatMcpExecutionOutcome, PAUSED_APPROVAL_TIMEOUT_MS } from "./tool-server-core"; -export type { - BrowserApprovalStore, - ExecutorMcpToolConfig, - McpArtifactsPort, - McpClientInfo, - McpConnectionsPort, - McpToolResult, - PausedExecutionHooks, - ResumeFallbackOutcome, - ResumeUnavailableStatus, -} from "./tool-server-core"; - -const NATIVE_ELICITATION_RESPONSE_KEY = "elicitation"; - -const NativeRequestStateSchema = Schema.Struct({ executionId: Schema.String }); -/** Verified payload carried by a modern native-elicitation continuation. */ -export type NativeRequestState = typeof NativeRequestStateSchema.Type; -const decodeNativeRequestState = Schema.decodeUnknownOption(NativeRequestStateSchema); - -const NativeRequestStateCallSchema = Schema.Struct({ - method: Schema.Literal("tools/call"), - params: Schema.Struct({ - name: Schema.String, - arguments: Schema.Struct({ code: Schema.String }), - }), -}); -const decodeNativeRequestStateCall = Schema.decodeUnknownOption(NativeRequestStateCallSchema); + createExecutionEngine, + formatExecuteResult, + formatPausedExecution, + formatTtlDuration, + findSkill, + renderSkillsIndex, + skillCatalogFor, + EXECUTE_SKILL, + INTEGRATION_INVENTORY_HEADER, + type Skill, + type ExecutionEngine, + type ExecutionEngineConfig, + type ResumeResponse, + type ExecutionResult, + type PausedExecution, + type PausedExecutionDeadline, +} from "@executor-js/execution"; +import { + MCP_APPS_SHELL_RESOURCE_URI, + applyArtifactEdits, + smokeRenderRejection, + validateArtifactCode, + type ArtifactEdit, + type ArtifactSmokeRenderResult, +} from "./create-artifact"; +import { TOOL_CALL_CONTRACT_MESSAGE } from "./tool-call-code"; +import { resolveArtifactAction } from "./artifact-action"; +import { + extractArtifactRoles, + resolveArtifactBindings, + type BindableConnection, +} from "./artifact-bindings"; + +// --------------------------------------------------------------------------- +// Workers-compatible JSON Schema validator (replaces Ajv which uses new Function()) +// --------------------------------------------------------------------------- + +class CfWorkerJsonSchemaValidator implements jsonSchemaValidator { + getValidator(schema: JsonSchemaType): JsonSchemaValidator { + const validator = new Validator(schema as Record, "2020-12", false); + return (input: unknown) => { + const result = validator.validate(input); + if (result.valid) { + return { valid: true, data: input as T, errorMessage: undefined }; + } + const errorMessage = result.errors.map((e) => `${e.instanceLocation}: ${e.error}`).join("; "); + return { valid: false, data: undefined, errorMessage }; + }; + } +} + +// --------------------------------------------------------------------------- +// Config +// --------------------------------------------------------------------------- -type McpServerRequestContext = McpRequestJoinKeys & { - readonly serverContext: ServerContext; +type SharedMcpServerConfig = { + /** + * Pre-built `execute` tool description. When provided, the factory skips + * its internal `engine.getDescription` yield. Useful when the caller + * wants to compute the description inside its own Effect tracer context + * so sub-spans (`executor.integrations.list`, `executor.tools.list`) nest as + * children of the caller's root span. + */ + readonly description?: string; + /** + * Parent span override for engine calls. The factory captures the + * caller's context at construction time, but `Effect.runPromiseWith` + * starts a fresh fiber per SDK callback — so the `currentSpan` + * FiberRef resets to root unless explicitly anchored. + * + * Accepts either a fixed span (per-request McpServer instances) or a + * getter (session-scoped instances that need to anchor each callback + * under whichever request triggered it; see the Cloud DO). + */ + readonly parentSpan?: Tracer.AnySpan | (() => Tracer.AnySpan | undefined); + /** + * Enable verbose MCP capability / elicitation debug logging. + */ + readonly debug?: boolean; + /** + * Controls how elicitation is handled for this MCP connection. The default + * is model-managed resume, where paused executions expose interaction + * metadata and the model can call `resume` with the user's response. + */ + readonly elicitationMode?: + | { + readonly mode: "browser"; + readonly approvalUrl: (executionId: string) => string; + } + | { + readonly mode: "model"; + } + | { + readonly mode: "native"; + }; + readonly browserApprovalStore?: BrowserApprovalStore; + /** + * Host-owned lifecycle for paused executions. The MCP server reports pause + * boundaries; the host decides whether that means a keepAlive lease, browser + * wait, durable record, or no-op. + */ + readonly pausedExecutionHooks?: PausedExecutionHooks; + /** + * Host-provided approval lease duration. When present, paused payloads carry + * an absolute deadline and hooks receive the same deadline. + */ + readonly pausedExecutionLeaseMs?: number; + /** + * Optional host-owned model resume fallback. Used by Cloudflare session + * Durable Objects to route a resume miss to the session that owns the pause. + */ + readonly resumeFallback?: ( + executionId: string, + response: ResumeResponse, + ) => Effect.Effect; + /** + * Loads the MCP-Apps shell HTML served as the `ui://executor/shell.html` + * resource. Injected rather than imported: the shell carries React, Recharts + * and Tailwind, and this package also runs on Workers. Hosts that can serve + * it pass `loadMcpAppsShellHtml` from `@executor-js/mcp-apps-shell`; hosts + * that leave it unset simply don't register the resource or the ui tools. + */ + readonly loadAppShellHtml?: () => Promise; + /** + * Per-connection artifacts opt-out. Defaults to true. A client that connects + * with `?artifacts=false` gets NO artifact surface at all: none of the five + * artifact tools, no `ui://` shell resource, and no artifact entries in the + * `skills` inventory — the same shape a host without `loadAppShellHtml` + * serves. `execute`, `skills` and `resume` are untouched. + */ + readonly artifactsEnabled?: boolean; + /** + * Renders an artifact once, server-side, before it is saved — so a component + * that throws on its first render is refused at create time with the real + * error instead of saving cleanly and dying on the user's page. + * + * Injected for the same reason `loadAppShellHtml` is: it needs React, + * react-dom/server and the whole component barrel, and this package must not + * drag any of that into the graph of a host that only ever calls `execute`. + * Hosts that can afford it pass `smokeRenderArtifact` from + * `@executor-js/mcp-apps-shell`, which loads it behind a dynamic import. + * + * Unset means no smoke check: creates are validated statically and saved, as + * they were before. That is also what happens when the check itself fails — + * see the fail-open path in `createArtifact`. + */ + readonly smokeRenderArtifact?: (code: string) => Promise; + /** + * The scoped executor's artifact operations, so `create-artifact` can persist what + * it renders and `list-artifacts` / `show-artifact` can read it back. Only + * the three operations the MCP surface needs, so hosts don't have to hand the + * whole `Executor` across this boundary. + */ + readonly artifacts?: McpArtifactsPort; + /** + * The caller's saved connections, for binding an artifact's integration roles + * at create time. Structurally satisfied by `executor.connections`; hosts pass + * the same scoped executor they pass `artifacts`. + * + * Absent means `create-artifact` cannot bind, so it refuses code that calls an + * integration rather than saving an artifact that could never run. + */ + readonly connections?: McpConnectionsPort; + /** + * Builds the web-app deep link for a saved artifact. Clients that can't + * render MCP Apps get this URL instead of an inline widget. Absent (stdio has + * no origin at all) means `create-artifact` still persists and reports the id, but + * has no URL to offer. + */ + readonly artifactUrl?: (artifactId: string) => string; + /** + * Notified when an agent-facing artifact tool completes a user-meaningful + * operation: `create-artifact` (created, or updated when it overwrote an + * existing id) and `show-artifact` (viewed). Internal artifact reads — + * binding resolution inside `execute-action` — deliberately do not notify. + * Best-effort observation: failures are swallowed and cannot affect the tool + * result. Hosts recording product analytics supply it; core stays agnostic. + */ + readonly onArtifactUsage?: (action: "created" | "viewed" | "updated") => Effect.Effect; + /** + * Whether the client this session belongs to can render MCP Apps, as + * negotiated at a previous `initialize`. + * + * Capabilities normally arrive from the client at `initialize` and live only + * in the server instance. A session whose host evicted and cold-restored it + * (deploy, idle) is rebuilt mid-conversation with no `initialize` to replay, + * so without this the rebuilt server assumes no apps support and silently + * downgrades every artifact to a deep link. Hosts that persist the + * negotiated value pass it back here; the next `initialize`, if one comes, + * overwrites it. + */ + readonly restoredAppsEnabled?: boolean; + /** + * Called when `initialize` negotiates the client's MCP-Apps support, so the + * host can persist it for {@link restoredAppsEnabled} on a later cold + * restore. Best-effort: failures are swallowed and never affect the session. + */ + readonly onAppsEnabledChange?: (appsEnabled: boolean) => Effect.Effect; +}; + +/** + * The narrow artifact surface the MCP tools need. Structurally satisfied by + * `Executor["artifacts"]`, so hosts holding a scoped executor can pass + * `executor.artifacts` directly. + */ +export type McpArtifactsPort = { + readonly list: () => Effect.Effect; + readonly get: (id: string) => Effect.Effect; + readonly save: (input: SaveArtifactInput) => Effect.Effect; +}; + +/** + * The connection surface binding needs: list what this caller can reach. The + * scoped executor has already narrowed it, so an inferred binding can never + * name a connection the caller couldn't call themselves. + */ +export type McpConnectionsPort = { + readonly list: () => Effect.Effect; }; -/** Configuration required to build an Executor MCP server. */ export type ExecutorMcpServerConfig = - ExecutorMcpToolConfig & { - /** Initial/static MCP Apps policy. Sessionful servers replace it after initialize. */ - readonly appsEnabled: boolean; - /** - * Register a connection-lifetime server whose capability-dependent behavior - * follows the live initialize-negotiated state. Omitted for stateless modern - * request factories, which keep using {@link appsEnabled} as fixed policy. - */ - readonly sessionful?: boolean; - /** HMAC key used to sign opaque native-elicitation continuation state. */ - readonly requestStateSigningKey: Uint8Array | string; - /** - * Stable identifier of the authenticated principal this server instance - * was built for (org/user/subject). Bound into the signed continuation - * state so a `requestState` minted for one principal is rejected when - * echoed by another — the spec's user-binding MUST for state that - * influences authorization. Single-user hosts pass a constant. - */ - readonly requestStatePrincipal: string; - /** Closed request binding derived before the modern server is constructed. */ - readonly requestStateBinding?: string; - /** Lifetime of signed continuation state in seconds; the SDK defaults to ten minutes. */ - readonly requestStateTtlSeconds?: number; - }; + | (ExecutionEngineConfig & SharedMcpServerConfig) + | ({ readonly engine: ExecutionEngine } & SharedMcpServerConfig) + | (ExecutionEngineConfig & SharedMcpServerConfig & { readonly stateless: true }) + | ({ readonly engine: ExecutionEngine; readonly stateless: true } & SharedMcpServerConfig); -/** Decide whether client capabilities advertise support for MCP Apps HTML. */ -export const appsEnabledForClientCapabilities = ( - clientCapabilities: McpAppsClientCapabilities | null | undefined, -): boolean => Boolean(getUiCapability(clientCapabilities)?.mimeTypes?.includes(RESOURCE_MIME_TYPE)); - -/** Bind modern continuation state to the ownership identity used by MCP hosts. */ -export const mcpRequestStatePrincipal = (principal: { - readonly accountId: string; - readonly organizationId: string; -}): string => `${principal.accountId}\u0000${principal.organizationId}`; - -/** Fields whose exact values bind one modern native-elicitation continuation. */ -export interface McpRequestStateBindingInput { - readonly principal: string; - readonly resource: McpResource; - readonly method: string; - readonly toolName: string; - readonly codeDigest: string; -} +export type BrowserApprovalStore = { + readonly takeResponse: (executionId: string) => Effect.Effect; + readonly waitForResponse?: (executionId: string) => Effect.Effect; +}; + +export const PAUSED_APPROVAL_TIMEOUT_MS = 4 * 60 * 1000; +const BROWSER_APPROVAL_WAIT_TIMEOUT_MS = PAUSED_APPROVAL_TIMEOUT_MS + 1000; -/** Build the canonical NUL-separated modern continuation binding. */ -export const mcpRequestStateBinding = (input: McpRequestStateBindingInput): string => - [ - input.principal, - mcpResourceKey(input.resource), - input.method, - input.toolName, - input.codeDigest, - ].join("\u0000"); - -/** Return the lowercase SHA-256 digest used to bind an execute code argument. */ -export const mcpCodeDigest = async (code: string): Promise => { - const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(code)); - return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join(""); +export type PausedExecutionHooks = { + readonly onExecutionPaused?: ( + executionId: string, + deadline: PausedExecutionDeadline | undefined, + ) => Effect.Effect; + readonly onResumeStarted?: (executionId: string) => Effect.Effect; + readonly onResumeSettled?: (executionId: string) => Effect.Effect; }; -/** Derive a continuation binding from an already-parsed modern tools/call body. */ -export const mcpRequestStateBindingFromBody = async (input: { - readonly body: unknown; - readonly principal: string; - readonly resource: McpResource; -}): Promise => { - const call = decodeNativeRequestStateCall(input.body); - if (Option.isNone(call)) return null; - return mcpRequestStateBinding({ - principal: input.principal, - resource: input.resource, - method: call.value.method, - toolName: call.value.params.name, - codeDigest: await mcpCodeDigest(call.value.params.arguments.code), - }); +export type ResumeUnavailableStatus = + | "execution_not_found" + | "execution_expired" + | "execution_forbidden" + | "execution_already_settled"; + +export type ResumeFallbackOutcome = + | { + readonly status: "result"; + readonly result: McpToolResult; + } + | { + readonly status: Exclude; + readonly ttlMs?: number; + } + | { + readonly status: "execution_not_found"; + }; + +// --------------------------------------------------------------------------- +// Elicitation bridge +// --------------------------------------------------------------------------- + +const getElicitationSupport = (server: McpServer): { form: boolean; url: boolean } => { + const capabilities = server.server.getClientCapabilities(); + if (capabilities === undefined || !capabilities.elicitation) return { form: false, url: false }; + const elicitation = capabilities.elicitation as Record; + return { form: Boolean(elicitation.form), url: Boolean(elicitation.url) }; }; -/** Route-level failure verifying untrusted modern continuation state. */ -export class McpRequestStateVerificationError extends Data.TaggedError( - "McpRequestStateVerificationError", -)<{ readonly cause: unknown }> {} - -class McpRequestStateBindingError extends Data.TaggedError("McpRequestStateBindingError")<{}> {} - -const requestStateBindingForContext = ( - binding: string | undefined, - principal: string, - context: ServerContext, -): Promise => { - if (binding !== undefined) return Promise.resolve(binding); - if (context.mcpReq.envelope === undefined) { - return Promise.resolve(`${context.mcpReq.method}\u0000${principal}`); - } - return Effect.runPromise(Effect.fail(new McpRequestStateBindingError())); +const readDebugDefault = (): boolean => { + if (typeof process === "undefined" || !process.env) return false; + const value = process.env.EXECUTOR_MCP_DEBUG; + return value === "1" || value === "true"; }; -/** - * Verify and parse a modern continuation before a stateless worker uses its - * execution id for Durable Object routing. - */ -export const verifyNativeRequestState = (input: { - readonly state: string; - readonly body: unknown; - readonly resource: McpResource; - readonly requestStateSigningKey: Uint8Array | string; - readonly requestStatePrincipal: string; -}): Effect.Effect => - Effect.gen(function* () { - const binding = yield* Effect.tryPromise({ - try: () => - mcpRequestStateBindingFromBody({ - body: input.body, - principal: input.requestStatePrincipal, - resource: input.resource, - }), - catch: (cause) => new McpRequestStateVerificationError({ cause }), - }); - if (binding === null) { - return yield* new McpRequestStateVerificationError({ - cause: "invalid request-state binding", - }); +const capabilitySnapshot = (server: McpServer) => ({ + clientCapabilities: server.server.getClientCapabilities() ?? null, + elicitationSupport: getElicitationSupport(server), +}); + +class McpNativeElicitationTransportError extends Data.TaggedError( + "McpNativeElicitationTransportError", +)<{ + readonly cause: unknown; +}> {} + +type ElicitInputParams = + | { + mode?: "form"; + message: string; + requestedSchema: { readonly [key: string]: unknown }; } - const codec = createRequestStateCodec({ - key: input.requestStateSigningKey, - bind: () => binding, - }); - const decoded = yield* Effect.tryPromise({ - // The route-level verifier has no handler context. Its codec binding is a - // closed value derived from the parsed call, resource, and principal, so - // the SDK callback never observes this inert placeholder. - try: () => Reflect.apply(codec.verify, codec, [input.state, null]) as Promise, - catch: (cause) => new McpRequestStateVerificationError({ cause }), - }); - return yield* Schema.decodeUnknownEffect(NativeRequestStateSchema)(decoded).pipe( - Effect.mapError((cause) => new McpRequestStateVerificationError({ cause })), + | { mode: "url"; message: string; url: string; elicitationId: string }; + +const elicitationRequestTag = (request: ElicitationRequest): ElicitationRequest["_tag"] => + Match.value(request).pipe( + Match.tag("UrlElicitation", () => "UrlElicitation" as const), + Match.tag("FormElicitation", () => "FormElicitation" as const), + Match.exhaustive, + ); + +const requestedSchemaIsNonEmpty = (request: ElicitationRequest): boolean => + Match.value(request).pipe( + Match.tag("FormElicitation", (req) => Object.keys(req.requestedSchema).length > 0), + Match.tag("UrlElicitation", () => false), + Match.exhaustive, + ); + +const elicitationRequestUrl = (request: ElicitationRequest): string | undefined => + Match.value(request).pipe( + Match.tag("UrlElicitation", (req): string | undefined => req.url), + Match.tag("FormElicitation", (): string | undefined => undefined), + Match.exhaustive, + ); + +const pausedInteractionKind = (request: ElicitationRequest): ElicitationRequest["_tag"] => + elicitationRequestTag(request); + +const elicitationRequestToParams: (request: ElicitationRequest) => ElicitInputParams = + Match.type().pipe( + Match.tag("UrlElicitation", (req) => ({ + mode: "url" as const, + message: req.message, + url: req.url, + elicitationId: req.elicitationId, + })), + Match.tag("FormElicitation", (req) => ({ + message: req.message, + // The MCP SDK validates requestedSchema as a JSON Schema with + // `type: "object"` and `properties`. For approval-only elicitations + // where no fields are needed, provide a minimal valid schema. + requestedSchema: + Object.keys(req.requestedSchema).length === 0 + ? { type: "object" as const, properties: {} } + : req.requestedSchema, + })), + Match.exhaustive, + ); + +const makeMcpElicitationHandler = + ( + server: McpServer, + relatedRequestId: string | number, + debugLog?: (event: string, data: Record) => void, + ): ElicitationHandler => + (ctx: ElicitationContext): Effect.Effect => { + const { url: supportsUrl } = getElicitationSupport(server); + + // If client doesn't support url mode, fall back to a form asking the user + // to visit the URL manually and confirm when done. + const params = Match.value(ctx.request).pipe( + Match.tag( + "UrlElicitation", + (req): ElicitInputParams => + !supportsUrl + ? { + message: `${req.message}\n\nPlease visit this URL:\n${req.url}\n\nClick accept once you have completed the flow.`, + requestedSchema: { type: "object" as const, properties: {} }, + } + : elicitationRequestToParams(req), + ), + Match.tag("FormElicitation", (req): ElicitInputParams => elicitationRequestToParams(req)), + Match.exhaustive, ); - }); + + return Effect.promise(async (): Promise => { + const requestTag = elicitationRequestTag(ctx.request); + debugLog?.("elicitation.request", { + requestTag, + supportsUrl, + message: ctx.request.message, + hasRequestedSchema: requestedSchemaIsNonEmpty(ctx.request), + url: elicitationRequestUrl(ctx.request), + clientCapabilities: server.server.getClientCapabilities() ?? null, + }); + + const response = await server.server.elicitInput( + params as Parameters[0], + { relatedRequestId }, + ); + + debugLog?.("elicitation.response", { + requestTag, + action: response.action, + hasContent: + typeof response.content === "object" && + response.content !== null && + Object.keys(response.content).length > 0, + }); + + return { + action: response.action as typeof ElicitationResponse.Type.action, + content: response.content, + }; + }).pipe( + Effect.tapDefect((defect) => + Effect.sync(() => { + debugLog?.("elicitation.error", { + requestTag: elicitationRequestTag(ctx.request), + error: formatBoundaryError(defect), + clientCapabilities: server.server.getClientCapabilities() ?? null, + }); + }), + ), + Effect.catchDefect((cause) => + // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: ElicitationHandler has no error channel, so retain a classified defect for the MCP result boundary. + Effect.die(new McpNativeElicitationTransportError({ cause })), + ), + ); + }; + +const formatBoundaryError = (err: unknown): { name?: string; message: string; stack?: string } => { + // oxlint-disable-next-line executor/no-instanceof-error, executor/no-unknown-error-message -- boundary: SDK Promise rejection supplies unknown JS errors for logging only + if (err instanceof Error) return { name: err.name, message: err.message, stack: err.stack }; + // oxlint-disable-next-line executor/no-unknown-error-message -- boundary: fallback log formatting for unknown SDK Promise rejection values + return { message: String(err) }; +}; + +// --------------------------------------------------------------------------- +// MCP result formatting +// --------------------------------------------------------------------------- + +export type McpToolResult = { + content: ContentBlock[]; + structuredContent?: Record; + isError?: boolean; +}; + +type FormattedExecuteInput = Parameters[0]; +type ExecuteOutputItem = NonNullable[number]; + +const TEXT_FILE_CONTENT_MAX_CHARS = 64_000; const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); -const appsClientCapabilitiesFromUnknown = ( - capabilities: unknown, -): McpAppsClientCapabilities | null => { - if (!isRecord(capabilities)) return null; - const extensions = capabilities.extensions; - if (!isRecord(extensions)) return null; - const ui = extensions[EXTENSION_ID]; - if (!isRecord(ui)) return null; - const mimeTypes = ui.mimeTypes; - if (mimeTypes === undefined) return { extensions: { [EXTENSION_ID]: {} } }; - if (!Array.isArray(mimeTypes) || !mimeTypes.every((value) => typeof value === "string")) { - return null; +const toolFileName = (file: ToolFileValue): string => file.name ?? "tool-output"; + +const fileResourceUri = (file: ToolFileValue): string => + `executor-file:///${encodeURIComponent(toolFileName(file))}`; + +const normalizedMimeType = (file: ToolFileValue): string => + file.mimeType.split(";")[0]?.trim().toLowerCase() ?? ""; + +const toolFileKind = (file: ToolFileValue): "image" | "audio" | "text" | "resource" => { + const mimeType = normalizedMimeType(file); + if (mimeType.startsWith("image/")) return "image"; + if (mimeType.startsWith("audio/")) return "audio"; + if ( + mimeType.startsWith("text/") || + mimeType === "application/json" || + mimeType.endsWith("+json") || + mimeType === "application/xml" || + mimeType.endsWith("+xml") || + mimeType === "application/javascript" || + mimeType === "application/x-javascript" || + mimeType === "application/yaml" || + mimeType === "application/x-yaml" + ) { + return "text"; + } + return "resource"; +}; + +const bytesFromBase64 = (base64: string): Uint8Array => { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index += 1) { + bytes[index] = binary.charCodeAt(index); } - return { extensions: { [EXTENSION_ID]: { mimeTypes } } }; + return bytes; +}; + +const decodeTextFile = (file: ToolFileValue): string => { + const text = new TextDecoder("utf-8", { fatal: false }).decode(bytesFromBase64(file.data)); + if (text.length <= TEXT_FILE_CONTENT_MAX_CHARS) return text; + return `${text.slice(0, TEXT_FILE_CONTENT_MAX_CHARS)}\n\n[truncated ${ + text.length - TEXT_FILE_CONTENT_MAX_CHARS + } characters]`; }; -const elicitationSupportFromUnknown = ( - capabilities: unknown, -): { readonly form: boolean; readonly url: boolean } => { - if (!isRecord(capabilities) || !isRecord(capabilities.elicitation)) { - return { form: false, url: false }; +const toolFileContent = (file: ToolFileValue): ContentBlock[] => { + const kind = toolFileKind(file); + if (kind === "image") { + return [{ type: "image", data: file.data, mimeType: file.mimeType }]; + } + if (kind === "audio") { + return [{ type: "audio", data: file.data, mimeType: file.mimeType }]; } - const elicitation = capabilities.elicitation; - const hasExplicitModes = "form" in elicitation || "url" in elicitation; + if (kind === "text") { + return [{ type: "text", text: decodeTextFile(file) }]; + } + return [ + { + type: "resource", + resource: { + uri: fileResourceUri(file), + mimeType: file.mimeType, + blob: file.data, + }, + }, + ]; +}; + +const toolFileSummaryLine = (file: ToolFileValue, index?: number): string => { + const prefix = index === undefined ? "" : `${index + 1}. `; + return `${prefix}${toolFileName(file)} (${file.mimeType}, ${file.byteLength} bytes)`; +}; + +const outputFileContent = (file: ToolFileValue): ContentBlock[] => [ + { + type: "text", + text: `File output: ${toolFileSummaryLine(file)}`, + }, + ...toolFileContent(file), +]; + +const isFileOutputItem = ( + item: ExecuteOutputItem, +): item is { readonly type: "file"; readonly file: ToolFileValue } => + isRecord(item) && item.type === "file" && isToolFile(item.file); + +const isMcpContentBlock = (value: unknown): value is ContentBlock => + ContentBlockSchema.safeParse(value).success; + +const isContentOutputItem = ( + item: ExecuteOutputItem, +): item is { readonly type: "content"; readonly content: ContentBlock } => + isRecord(item) && item.type === "content" && isMcpContentBlock(item.content); + +const outputItemContent = (item: ExecuteOutputItem): ContentBlock[] => { + if (isFileOutputItem(item)) { + return outputFileContent(item.file); + } + if (isContentOutputItem(item)) { + return [item.content]; + } + return [{ type: "text", text: "Invalid execution output item omitted." }]; +}; + +const toMcpOutputResult = ( + result: FormattedExecuteInput, + output: readonly ExecuteOutputItem[], +): McpToolResult => { + const formatted = formatExecuteResult(result); + const content = output.flatMap(outputItemContent); + const extraText: string[] = []; + if (result.error) { + extraText.push(formatted.text); + } else if (result.result != null) { + // A script may both emit() and return: keep the returned value in the + // content channel too, or clients that ignore structuredContent drop it. + // formatted.text already renders the return value plus any logs. + extraText.push(formatted.text); + } else if (result.logs && result.logs.length > 0) { + extraText.push(`Logs:\n${result.logs.join("\n")}`); + } + content.push(...extraText.map((text): ContentBlock => ({ type: "text", text }))); + + return { + content, + structuredContent: formatted.structured, + isError: formatted.isError || undefined, + }; +}; + +const toMcpResult = (result: FormattedExecuteInput): McpToolResult => { + if (result.output && result.output.length > 0) return toMcpOutputResult(result, result.output); + const formatted = formatExecuteResult(result); return { - form: hasExplicitModes ? Boolean(elicitation.form) : true, - url: Boolean(elicitation.url), + content: [{ type: "text", text: formatted.text }], + structuredContent: formatted.structured, + isError: formatted.isError || undefined, }; }; -const ClientInfoSchema = Schema.Struct({ - name: Schema.String, - version: Schema.optional(Schema.String), - title: Schema.optional(Schema.String), +const toMcpPausedResult = (formatted: ReturnType): McpToolResult => ({ + content: [{ type: "text", text: formatted.text }], + structuredContent: formatted.structured, }); -const decodeClientInfo = Schema.decodeUnknownOption(ClientInfoSchema); - -const toClientInfo = (value: unknown): McpClientInfo | null => - Option.getOrNull(decodeClientInfo(value)); - -const clientInfoFromImplementation = ( - implementation: Implementation | undefined, -): McpClientInfo | null => - implementation === undefined - ? null - : { - name: implementation.name, - version: implementation.version, - ...(implementation.title !== undefined ? { title: implementation.title } : {}), - }; -/** - * Parse the self-reported client identity from a modern request's `_meta` - * envelope (`io.modelcontextprotocol/clientInfo`, sent per request), falling - * back to the `initialize` body's native `params.clientInfo`. Malformed or - * absent identity decodes to null: it is display/telemetry data, never load-bearing. - */ -export const clientInfoFromRequestBody = (body: unknown): McpClientInfo | null => { - if (!isRecord(body)) return null; - const params = body.params; - if (!isRecord(params)) return null; - const metadata = params._meta; - const fromMeta = isRecord(metadata) ? toClientInfo(metadata[CLIENT_INFO_META_KEY]) : null; - if (fromMeta) return fromMeta; - return body.method === "initialize" ? toClientInfo(params.clientInfo) : null; -}; +export const formatMcpExecutionOutcome = ( + outcome: ExecutionResult, + options?: { readonly pausedDeadline?: PausedExecutionDeadline }, +): McpToolResult => + outcome.status === "completed" + ? toMcpResult(outcome.result) + : toMcpPausedResult( + formatPausedExecution(outcome.execution, { deadline: options?.pausedDeadline }), + ); -/** Parse the MCP Apps capability subset from an already-decoded modern body. */ -export const clientCapabilitiesFromRequestBody = ( - body: unknown, -): McpAppsClientCapabilities | null => { - if (!isRecord(body)) return null; - const params = body.params; - if (!isRecord(params)) return null; - const metadata = params._meta; - if (!isRecord(metadata)) return null; - const capabilities = metadata[CLIENT_CAPABILITIES_META_KEY]; - return appsClientCapabilitiesFromUnknown(capabilities); -}; +// `execute` failures reaching the MCP host are infra defects — domain +// failures from tools are now expressed as `ToolResult` values (success +// channel) and flow through `formatExecuteResult`. Emit an opaque +// generic plus a fresh correlation id and log the cause out-of-band so +// the model can't read internal context off `.message`. +const newCorrelationId = (): string => + Math.floor(Math.random() * 0x1_0000_0000) + .toString(16) + .padStart(8, "0"); -/** Parse a cloned HTTP request body without consuming the request itself. */ -export const requestBodyFromRequest = (request: Request): Effect.Effect => - Effect.tryPromise({ - try: () => request.clone().json(), - catch: () => null, - }).pipe( - Effect.match({ - onFailure: () => null, - onSuccess: (body) => body, - }), - ); +const defaultResumeApprovalUrl = (executionId: string): string => + `/resume/${encodeURIComponent(executionId)}`; -/** - * Parse the MCP Apps capability subset from a modern request's `_meta` - * envelope without consuming the request body used by the SDK handler. - */ -export const clientCapabilitiesFromRequest = ( - request: Request, -): Effect.Effect => - requestBodyFromRequest(request).pipe(Effect.map(clientCapabilitiesFromRequestBody)); - -const requestJoinKeys = (context: ServerContext): McpServerRequestContext => ({ - requestId: context.mcpReq.id, - ...(context.sessionId === undefined ? {} : { sessionId: context.sessionId }), - serverContext: context, +const browserApprovalReturnPrompt = + "Return text to the user telling them to approve the action at this approvalUrl. Only after you have prompted the user, call the `resume` tool with this executionId; `resume` will wait for the user's browser decision."; + +const formatResumeApprovalRequired = (input: { + readonly executionId: string; + readonly approvalUrl: string; +}): McpToolResult => ({ + content: [ + { + type: "text", + text: [ + "User approval required.", + "", + "Tell the user to open this URL while signed in and approve or decline the paused interaction:", + input.approvalUrl, + "", + "Required next steps for this agent:", + browserApprovalReturnPrompt, + ].join("\n"), + }, + ], + structuredContent: { + status: "user_approval_required", + executionId: input.executionId, + approvalUrl: input.approvalUrl, + resumePrompt: browserApprovalReturnPrompt, + }, }); -const appToolMeta = (metadata: Record): McpAppToolMeta | undefined => { - const ui = metadata.ui; - if (!isRecord(ui)) return undefined; - const resourceUri = typeof ui.resourceUri === "string" ? ui.resourceUri : undefined; - const visibility = Array.isArray(ui.visibility) - ? ui.visibility.filter( - (value): value is "model" | "app" => value === "model" || value === "app", - ) - : undefined; +const toMcpFailureResult = (cause: Cause.Cause): McpToolResult => { + const correlationId = newCorrelationId(); + const defect = Cause.findDefect(cause); + const nativeElicitationFailed = + Result.isSuccess(defect) && + Predicate.isTagged("McpNativeElicitationTransportError")(defect.success); + // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: best-effort defect logging must tolerate non-serializable causes + try { + console.error( + `[executor:mcp] execute defect correlation_id=${correlationId}`, + Cause.pretty(cause), + ); + } catch { + /* ignore logger failures */ + } + const text = nativeElicitationFailed + ? `Native elicitation transport failed [${correlationId}]. Reconnect the MCP client and try again.` + : `Internal tool error [${correlationId}]`; return { - ...(resourceUri === undefined ? {} : { resourceUri }), - ...(visibility === undefined ? {} : { visibility }), + content: [{ type: "text", text: `Error: ${text}` }], + structuredContent: { + status: "error", + error: text, + ...(nativeElicitationFailed ? { errorCode: "native_elicitation_transport_failed" } : {}), + }, + isError: true, }; }; -const normalizedAppMetadata = (metadata: Record) => { - const ui = appToolMeta(metadata); - const legacyResourceUri = metadata[RESOURCE_URI_META_KEY]; +const recoveryText = + "To recover, run the execute tool again with the original code; if it pauses, a fresh executionId will be issued."; + +const resumeUnavailableResult = (input: { + readonly status: ResumeUnavailableStatus; + readonly executionId: string; + readonly ttlMs?: number; +}): McpToolResult => { + const windowMs = input.ttlMs ?? PAUSED_APPROVAL_TIMEOUT_MS; + const approvalWindow = formatTtlDuration(windowMs); + const textByStatus: Record = { + execution_not_found: [ + `Paused execution is unknown: ${input.executionId}.`, + `Paused executions are only resumable for a limited window; this id may have expired or never existed.`, + recoveryText, + ], + execution_expired: [ + `Paused execution expired: ${input.executionId}.`, + `Approval windows last ${approvalWindow}; the owning session no longer has a live pause for this executionId.`, + recoveryText, + ], + execution_forbidden: [ + `Paused execution cannot be resumed by this authenticated identity: ${input.executionId}.`, + "Resume must be called by the same account and organization that owns the paused session.", + ], + execution_already_settled: [ + `Paused execution has already settled: ${input.executionId}.`, + "The resume result is no longer available for replay.", + "Run execute again only if the result is still needed.", + ], + }; return { - ...metadata, - ...(ui === undefined ? {} : { ui }), - ...(typeof legacyResourceUri === "string" - ? { [RESOURCE_URI_META_KEY]: legacyResourceUri } - : {}), + content: [ + { + type: "text" as const, + text: textByStatus[input.status].join(" "), + }, + ], + structuredContent: { + status: input.status, + executionId: input.executionId, + ...(input.status === "execution_expired" ? { ttlMs: windowMs } : {}), + ...(input.status === "execution_forbidden" ? {} : { recovery: "re_execute" }), + }, + isError: true, }; }; -const withoutAppMetadata = (metadata: Record): Record => { - const { ui: _ui, [RESOURCE_URI_META_KEY]: _resourceUri, ...rest } = metadata; - return rest; +const missingExecutionResult = (executionId: string): McpToolResult => + resumeUnavailableResult({ status: "execution_not_found", executionId }); + +const alreadySettledResult = (executionId: string): McpToolResult => + resumeUnavailableResult({ status: "execution_already_settled", executionId }); + +const fallbackOutcomeResult = ( + executionId: string, + outcome: ResumeFallbackOutcome, +): McpToolResult => { + if (outcome.status === "result") return outcome.result; + return resumeUnavailableResult({ + status: outcome.status, + executionId, + ttlMs: "ttlMs" in outcome ? outcome.ttlMs : undefined, + }); +}; + +// The `skills` tool serves named, static how-to docs (see the execution +// package's skills registry). No name -> the index; a known name -> that +// skill's body; an unknown name -> the index plus a not-found note so the model +// retries with a listed name instead of the same miss. +// +// The skill body IS the payload, returned as plain text content. We do NOT +// attach `structuredContent`: a client that prefers structured output (Claude +// Code does) will surface only that and drop the text, so the long-form guide +// silently fails to load. The not-found case keeps `isError` (a separate field +// clients honor) so a bad name still reads as a failure. +// +// The `execute` skill also gets the live integration inventory appended, the +// same block the execute tool description carries, so a model reading the guide +// sees what is connected without a second round trip. +// +// The catalog is per-session: a connection that opted out of artifacts never +// sees the artifact skills, so the index cannot advertise a how-to for tools it +// does not have, and fetching one by name misses like any unknown skill. +const skillsResult = ( + name: string | undefined, + executeInventory: string, + catalog: readonly Skill[], +): McpToolResult => { + const trimmed = name?.trim(); + if (!trimmed) { + return { content: [{ type: "text", text: renderSkillsIndex(catalog) }] }; + } + const skill = findSkill(trimmed, catalog); + if (!skill) { + return { + content: [ + { type: "text", text: `No skill named "${trimmed}".\n\n${renderSkillsIndex(catalog)}` }, + ], + isError: true, + }; + } + const text = + skill.name === EXECUTE_SKILL.name && executeInventory.length > 0 + ? `${skill.body}\n\n${executeInventory}` + : skill.body; + return { content: [{ type: "text", text }] }; }; -const visibilityIncludes = ( - metadata: Record, - visibility: "model" | "app", -): boolean => appToolMeta(metadata)?.visibility?.includes(visibility) ?? true; +/** Pull the live integration inventory block out of the built execute + * description (it runs from its header to the end), so the `skills` tool can + * re-use it without rebuilding the inventory from the executor. */ +const extractInventory = (description: string): string => { + const index = description.indexOf(INTEGRATION_INVENTORY_HEADER); + return index === -1 ? "" : description.slice(index).trimEnd(); +}; -const toolResult = (result: McpHandlerResult): CallToolResult | InputRequiredResult => result; +// --------------------------------------------------------------------------- +// Hang-visibility join keys +// --------------------------------------------------------------------------- +// A killed execution exports nothing: OTEL only ships a span when it ends, and +// a Cloudflare deploy/eviction cancels the request without an error, so a hung +// `execute` is invisible in the trace store. Two mitigations live here: +// 1. Every execution-path span carries the JSON-RPC id + transport session id +// (`mcp.rpc.id`, `mcp.request.session_id`), so a client's +// `notifications/cancelled` — which names the cancelled request id — can +// be joined to the exact call it gave up on. +// 2. A zero-duration start marker span (`.start`, a +// 1:1 pairing so "started without finishing" is a single unambiguous +// query) is emitted the moment execution begins. It ends immediately, so +// it becomes exportable while the execution is still running; whether it +// actually ships before a kill depends on the host's span processor +// draining first (cloud batches on a 1s timer, so markers for executions +// that survive >1s export, sub-second kills can still lose theirs). A +// start marker without a matching completion span is a true positive for +// an execution that died mid-flight. -const elicitationInputRequest = (request: ElicitationRequest) => - Match.value(request).pipe( - Match.tag("FormElicitation", (form) => - inputRequired.elicit({ - message: form.message, - requestedSchema: - Object.keys(form.requestedSchema).length === 0 - ? fromJsonSchema({ type: "object" as const, properties: {} }) - : fromJsonSchema(form.requestedSchema), - }), - ), - Match.tag("UrlElicitation", (url) => - inputRequired.elicitUrl({ message: url.message, url: url.url }), - ), - Match.exhaustive, - ); +type McpRequestJoinKeys = { + readonly requestId: string | number; + readonly sessionId?: string | undefined; +}; + +// `mcp.request.session_id` is emitted unconditionally (empty string when the +// transport carries none) to match the worker-side `annotateMcpRequest` +// producer: JSON-RPC ids are small per-session integers, so a row without the +// session key would make `mcp.rpc.id` globally ambiguous. +const joinKeyAttributes = (joinKeys: McpRequestJoinKeys): Record => ({ + "mcp.rpc.id": String(joinKeys.requestId), + "mcp.request.session_id": joinKeys.sessionId ?? "", +}); -const missingNativeExecution = (executionId: string): McpToolResult => ({ +const startMarker = (name: string, attributes: Record): Effect.Effect => + Effect.void.pipe(Effect.withSpan(name, { attributes })); + +// --------------------------------------------------------------------------- +// Artifacts / MCP Apps result formatting +// --------------------------------------------------------------------------- +// +// Delivery is negotiated, not branched on by the model: an artifact reaches the +// user as an inline widget when the client renders MCP Apps, and as a link into +// the web app when it doesn't. Both carry `artifactId`, because either way the +// artifact was saved and can be reopened later. + +const renderRejectedResult = (reason: string): McpToolResult => ({ + content: [{ type: "text", text: `create-artifact rejected: ${reason}` }], + structuredContent: { status: "error", error: reason }, + isError: true, +}); + +/** An edit batch that could not be applied. Carries the current stored source + * so the model can rebuild its edits without a `show-artifact` round trip. */ +const editRejectedResult = (reason: string, currentCode: string): McpToolResult => ({ + content: [ + { + type: "text", + text: [ + `edit-artifact rejected: ${reason}`, + "Nothing was changed. The artifact's current source is in structuredContent.code — build the retry against it.", + ].join("\n"), + }, + ], + structuredContent: { status: "error", error: reason, code: currentCode }, + isError: true, +}); + +/** `execute-action` was handed something other than a single proxy-shaped tool + * call. Names the contract rather than just refusing, since the reader is + * either a confused iframe or someone probing the app channel by hand. */ +const actionRejectedResult = (): McpToolResult => ({ + content: [{ type: "text", text: TOOL_CALL_CONTRACT_MESSAGE }], + structuredContent: { status: "error", error: "invalid_action_code" }, + isError: true, +}); + +/** + * The artifact whose bindings a call must be resolved through is missing or + * isn't this caller's. + * + * One result for both, deliberately: distinguishing "no such artifact" from + * "not yours" would let the app channel probe for ids that exist. + */ +const actionArtifactUnavailableResult = (): McpToolResult => ({ content: [ { type: "text", - text: `Paused execution is unknown: ${executionId}. Run execute again to start a fresh flow.`, + text: "This action refers to an artifact that isn't available on this account.", + }, + ], + structuredContent: { status: "error", error: "artifact_unavailable" }, + isError: true, +}); + +/** + * A role in the artifact's code has no connection behind it. + * + * Structured rather than prose-only because the binding UI that ships with + * sharing renders exactly this: which role failed, for which integration, and + * what the viewer could bind it to instead. The apps plugin's `BindingError` + * carries the same three facts for the same reason. + */ +const bindingUnresolvedResult = (input: { + readonly role: string; + readonly integration: string; + readonly message: string; + readonly candidates: readonly string[]; +}): McpToolResult => ({ + content: [ + { + type: "text", + text: + input.candidates.length > 0 + ? `${input.message} Choose one of ${input.candidates.join(", ")}.` + : input.message, }, ], structuredContent: { - status: "execution_not_found", - executionId, + status: "error", + error: "binding_unresolved", + role: input.role, + integration: input.integration, + candidates: input.candidates, }, isError: true, }); -const createMcpAssembly = ( - config: ExecutorMcpServerConfig, -): ExecutorMcpAssembly => { - const sessionful = config.sessionful ?? false; - const initialAppsEnabled = sessionful - ? (config.restoredAppsEnabled ?? config.appsEnabled) - : config.appsEnabled; - const requestStateCodec = (binding: string) => - createRequestStateCodec({ - key: config.requestStateSigningKey, - ...(config.requestStateTtlSeconds === undefined - ? {} - : { ttlSeconds: config.requestStateTtlSeconds }), - bind: () => binding, - }); - const verifyRequestState = async (state: string, context: ServerContext) => { - const binding = await requestStateBindingForContext( - config.requestStateBinding, - config.requestStatePrincipal, - context, - ); - const decoded = await requestStateCodec(binding).verify(state, context); - return Effect.runPromise(Schema.decodeUnknownEffect(NativeRequestStateSchema)(decoded)); - }; - const server = new McpServer( - { name: "executor", version: "1.0.0" }, +const renderedInAppResult = (input: { + readonly code: string; + readonly artifactId: string; + readonly title: string; + readonly url?: string | undefined; +}): McpToolResult => ({ + content: [ { - capabilities: { resources: {}, tools: {} }, - requestState: { verify: verifyRequestState }, + type: "text", + text: [ + `Rendered "${input.title}" as an interactive UI component. Saved as artifact ${input.artifactId}.`, + // The link rides along even though the widget rendered: clients lose + // rendered widgets in ways the server never sees (a transcript + // reopened without re-reading the ui:// resource shows raw JSON), and + // when that happens this URL in the conversation is the only path + // back to the artifact the model can offer. + ...(input.url ? [`It also stays available at ${input.url}`] : []), + ].join("\n"), }, - ); + ], + structuredContent: { + code: input.code, + artifactId: input.artifactId, + ...(input.url ? { url: input.url } : {}), + }, +}); - const registerTool: ExecutorMcpAssembly["registerTool"] = ( - name, - toolConfig, - callback, - ) => { - const inputSchema = z.object(toolConfig.inputSchema); - return server.registerTool, typeof inputSchema>( - name, - { ...toolConfig, inputSchema }, - async (args, context) => toolResult(await callback(args, requestJoinKeys(context))), - ); - }; +const renderedAsLinkResult = (input: { + readonly url: string; + readonly artifactId: string; + readonly title: string; +}): McpToolResult => ({ + content: [ + { + type: "text", + text: [ + `Saved "${input.title}" as artifact ${input.artifactId}.`, + "This MCP client cannot display MCP Apps, so give the user this URL to open it:", + input.url, + ].join("\n"), + }, + ], + structuredContent: { + status: "fallback_url", + url: input.url, + artifactId: input.artifactId, + }, +}); - const registerApp: ExecutorMcpAssembly["registerAppTool"] = ( - name, - toolConfig, - callback, - ) => { - const inputSchema = z.object(toolConfig.inputSchema); - const metadata = normalizedAppMetadata(toolConfig._meta); - if (!sessionful && !config.appsEnabled && visibilityIncludes(metadata, "model")) { - const plainMetadata = withoutAppMetadata(metadata); - return server.registerTool, typeof inputSchema>( - name, - { - ...toolConfig, - inputSchema, - ...(Object.keys(plainMetadata).length === 0 - ? { _meta: undefined } - : { _meta: plainMetadata }), - }, - async (args, context) => toolResult(await callback(args, requestJoinKeys(context))), +const renderedWithoutSurfaceResult = (input: { + readonly artifactId: string; + readonly title: string; +}): McpToolResult => ({ + content: [ + { + type: "text", + text: [ + `Saved "${input.title}" as artifact ${input.artifactId}.`, + "This MCP client cannot display MCP Apps and this deployment has no web UI configured, so there is nowhere to show it right now.", + "Tell the user the artifact was saved and can be opened from a client that supports MCP Apps.", + ].join("\n"), + }, + ], + structuredContent: { + status: "fallback_unavailable", + reason: "mcp_apps_unsupported", + artifactId: input.artifactId, + }, +}); + +const artifactsUnavailableResult = (): McpToolResult => ({ + content: [ + { + type: "text", + text: "Artifacts are not available on this connection.", + }, + ], + structuredContent: { status: "error", error: "artifacts_unavailable" }, + isError: true, +}); + +const artifactListResult = (artifacts: readonly ArtifactSummary[]): McpToolResult => { + const items = artifacts.map((artifact) => ({ + id: artifact.id, + title: artifact.title, + description: artifact.description, + updatedAt: artifact.updatedAt.toISOString(), + })); + const text = + items.length === 0 + ? "No saved artifacts yet. Use create-artifact to make one." + : [ + "Saved artifacts:", + ...items.map( + (item) => + `- ${item.id} — ${item.title}${item.description ? `: ${item.description}` : ""} (updated ${item.updatedAt})`, + ), + ].join("\n"); + return { content: [{ type: "text", text }], structuredContent: { artifacts: items } }; +}; + +const artifactNotFoundResult = (id: string): McpToolResult => ({ + content: [ + { + type: "text", + text: `No artifact with id "${id}". Call list-artifacts to see what is saved.`, + }, + ], + structuredContent: { status: "error", error: "artifact_not_found", id }, + isError: true, +}); + +const JsonObjectFromString = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)); +const decodeJsonObjectString = Schema.decodeUnknownOption(JsonObjectFromString); + +const parseJsonContent = (raw: string): Record | undefined => { + if (raw === "{}") return undefined; + const parsed = decodeJsonObjectString(raw); + return Option.isSome(parsed) ? parsed.value : undefined; +}; + +// --------------------------------------------------------------------------- +// Server factory +// --------------------------------------------------------------------------- + +export const createExecutorMcpServer = ( + config: ExecutorMcpServerConfig, +): Effect.Effect => + Effect.gen(function* () { + const engine = "engine" in config ? config.engine : createExecutionEngine(config); + const description = + config.description ?? + (yield* engine.getDescription.pipe(Effect.withSpan("mcp.host.get_description"))); + // The same live integration inventory the description carries, re-used by + // the `skills` tool so the `execute` guide lists what is connected too. + const executeInventory = extractInventory(description); + // Artifacts are on unless this connection opted out (`?artifacts=false`). + // One flag decides the whole surface: the tools, the shell resource, and + // the skills catalog below. + const artifactsEnabled = config.artifactsEnabled ?? true; + const skillCatalog: readonly Skill[] = skillCatalogFor({ artifacts: artifactsEnabled }); + + // Captured at construction time. SDK callbacks fire later (often + // deferred past the outer Effect's await), so we use the runtime to + // re-enter Effect-land at each callback edge. + const context = yield* Effect.context(); + const debugEnabled = config.debug ?? readDebugDefault(); + const debugLog = (event: string, data: Record) => { + if (!debugEnabled) return; + // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: debug logging must tolerate non-serializable SDK capability snapshots + try { + console.error(`[executor:mcp] ${event} ${JSON.stringify(data)}`); + } catch { + console.error(`[executor:mcp] ${event}`, data); + } + }; + const elicitationMode = + config.elicitationMode ?? + ({ + mode: "model", + } as const); + const pauseDeadline = (): PausedExecutionDeadline | undefined => { + const ttlMs = config.pausedExecutionLeaseMs; + return ttlMs === undefined || ttlMs <= 0 + ? undefined + : { ttlMs, expiresAt: new Date(Date.now() + ttlMs).toISOString() }; + }; + const onExecutionPaused = ( + executionId: string, + deadline: PausedExecutionDeadline | undefined, + ): Effect.Effect => + config.pausedExecutionHooks?.onExecutionPaused?.(executionId, deadline) ?? Effect.void; + const onResumeStarted = (executionId: string): Effect.Effect => + config.pausedExecutionHooks?.onResumeStarted?.(executionId) ?? Effect.void; + const onResumeSettled = (executionId: string): Effect.Effect => + config.pausedExecutionHooks?.onResumeSettled?.(executionId) ?? Effect.void; + const resumeWithLifecycle = (executionId: string, response: ResumeResponse) => + Effect.gen(function* () { + yield* onResumeStarted(executionId); + return yield* engine.resume(executionId, response); + }).pipe(Effect.ensuring(onResumeSettled(executionId))); + + const localExecutionAlreadySettled = (executionId: string): Effect.Effect => + engine.isExecutionSettled?.(executionId) ?? Effect.succeed(false); + + const resumeFallback = ( + executionId: string, + response: ResumeResponse, + ): Effect.Effect => + config + .resumeFallback?.(executionId, response) + .pipe(Effect.catchCause(() => Effect.succeed(null))) ?? Effect.succeed(null); + + const formatPausedModelResult = ( + execution: PausedExecution, + source: "execute" | "execute_action" | "resume" | "browser_resume", + ): Effect.Effect => + Effect.gen(function* () { + const deadline = pauseDeadline(); + yield* Effect.annotateCurrentSpan({ + "mcp.execute.paused": true, + "mcp.execute.paused_execution_id": execution.id, + "mcp.execute.pause_source": source, + }); + yield* onExecutionPaused(execution.id, deadline); + return toMcpPausedResult(formatPausedExecution(execution, { deadline })); + }); + + const resolveParentSpan = (): Tracer.AnySpan | undefined => { + const ps = config.parentSpan; + return typeof ps === "function" ? ps() : ps; + }; + const anchor = (effect: Effect.Effect): Effect.Effect => { + const parent = resolveParentSpan(); + return parent ? Effect.withParentSpan(effect, parent) : effect; + }; + const runToolEffect = (effect: Effect.Effect) => + Effect.runPromiseWith(context)( + anchor(effect).pipe( + Effect.catchCause((cause) => Effect.succeed(toMcpFailureResult(cause))), + ), ); - } - return registerAppTool>( - server, - name, - { ...toolConfig, inputSchema, _meta: metadata }, - async (args, context) => toolResult(await callback(args, requestJoinKeys(context))), + const server = yield* Effect.sync( + () => + new McpServer( + { name: "executor", version: "1.0.0" }, + { + // `resources` is required to serve the MCP-Apps shell at + // `ui://executor/shell.html`; it stays advertised even when no + // shell loader is configured so the capability set doesn't vary + // per host. + capabilities: { resources: {}, tools: {} }, + jsonSchemaValidator: new CfWorkerJsonSchemaValidator(), + }, + ), + ).pipe(Effect.withSpan("mcp.host.create_server")); + + const executeWithNativeElicitation = ( + code: string, + extra: McpRequestJoinKeys, + ): Effect.Effect => + engine + .execute(code, { + onElicitation: makeMcpElicitationHandler(server, extra.requestId, debugLog), + }) + .pipe(Effect.map(toMcpResult)); + + const executeCode = ( + code: string, + extra: McpRequestJoinKeys, + ): Effect.Effect => + Effect.gen(function* () { + yield* startMarker("mcp.host.tool.execute.start", { + "mcp.tool.name": "execute", + "mcp.execute.code_length": code.length, + }); + debugLog("execute.call", { + elicitationMode: elicitationMode.mode, + elicitationSupport: getElicitationSupport(server), + clientCapabilities: server.server.getClientCapabilities() ?? null, + codeLength: code.length, + }); + if (elicitationMode.mode === "native") { + return yield* executeWithNativeElicitation(code, extra); + } + const outcome = yield* engine.executeWithPause(code); + debugLog("execute.paused_flow_result", { + status: outcome.status, + executionId: outcome.status === "paused" ? outcome.execution.id : undefined, + interactionKind: + outcome.status === "paused" + ? pausedInteractionKind(outcome.execution.elicitationContext.request) + : undefined, + }); + if (outcome.status === "paused") { + const deadline = pauseDeadline(); + yield* Effect.annotateCurrentSpan({ + "mcp.execute.paused": true, + "mcp.execute.paused_execution_id": outcome.execution.id, + "mcp.execute.pause_source": "execute", + }); + yield* onExecutionPaused(outcome.execution.id, deadline); + return elicitationMode.mode === "browser" + ? yield* requireUserResumeApproval(outcome.execution.id) + : toMcpPausedResult(formatPausedExecution(outcome.execution, { deadline })); + } + return toMcpResult(outcome.result); + }).pipe( + Effect.withSpan("mcp.host.tool.execute", { + attributes: { + "mcp.tool.name": "execute", + "mcp.execute.code_length": code.length, + }, + }), + Effect.annotateSpans(joinKeyAttributes(extra)), + ); + + /** What the caller could bind an unresolved role to. Best effort: the + * connections port is optional, and a failure to enumerate must not + * replace the real error with a different one. */ + const bindingCandidates = (integration: string): Effect.Effect => + config.connections + ? config.connections.list().pipe( + Effect.map((all) => + all + .filter((connection) => connection.integration === integration) + .map( + (connection) => + `${connection.integration}.${connection.owner}.${connection.name}`, + ), + ), + Effect.catchCause(() => Effect.succeed([] as readonly string[])), + ) + : Effect.succeed([]); + + /** The artifact as THIS caller can read it. A miss and a row owned by + * someone else are the same answer, because they are the same query. */ + const loadArtifact = (id: string): Effect.Effect => + config.artifacts + ? config.artifacts.get(id).pipe(Effect.catchCause(() => Effect.succeed(null))) + : Effect.succeed(null); + + // `execute-action` is `execute` as called by the shell rather than by the + // model, and the difference is who owns approval. The shell renders the + // approval modal itself in its trusted outer frame, so a pause here must + // come back as the `waiting_for_interaction` payload the shell knows how to + // resolve — never as a browser approval URL, which the user would have no + // way to act on from inside a widget. That holds even when the session's + // elicitation mode is `browser`, which is why this doesn't just call + // `executeCode`. + // + // The other difference is WIDTH. `execute` takes arbitrary code because the + // model writes it; this channel takes exactly one proxy-shaped tool call, + // because that is all a declarative artifact can produce. See + // `tool-call-code.ts`. + // + // The third difference is that the incoming path is not yet an ADDRESS. + // Artifact code names an integration and, optionally, a role; the tier and + // connection are held on the artifact row. So this channel re-writes the + // call against those bindings before executing, and the executed code is + // built HERE, from a parsed path and a stored binding, never taken from the + // iframe verbatim. That is what makes the short form safe: an iframe that + // invented a five-segment address would only be naming a role the artifact + // has no binding for, and would be refused. + const executeCodeFromApp = ( + code: string, + artifactId: string | undefined, + extra: McpRequestJoinKeys, + ): Effect.Effect => + Effect.gen(function* () { + const resolution = yield* resolveArtifactAction({ code, artifactId, loadArtifact }); + debugLog("execute_action.call", { + elicitationMode: elicitationMode.mode, + elicitationSupport: getElicitationSupport(server), + codeLength: code.length, + status: resolution.status, + artifactId: artifactId ?? null, + }); + if (resolution.status === "invalid_action_code") { + yield* Effect.annotateCurrentSpan({ "mcp.execute_action.rejected": true }); + return actionRejectedResult(); + } + if (resolution.status === "artifact_unavailable") { + return actionArtifactUnavailableResult(); + } + if (resolution.status === "binding_unresolved") { + yield* Effect.annotateCurrentSpan({ + "mcp.execute_action.binding_unresolved": true, + "mcp.execute_action.role": resolution.role, + }); + return bindingUnresolvedResult({ + role: resolution.role, + integration: resolution.integration, + message: resolution.message, + candidates: yield* bindingCandidates(resolution.integration), + }); + } + const boundCode = resolution.code; + + if (elicitationMode.mode === "native") { + return yield* executeWithNativeElicitation(boundCode, extra); + } + const outcome = yield* engine.executeWithPause(boundCode); + debugLog("execute_action.paused_flow_result", { + status: outcome.status, + executionId: outcome.status === "paused" ? outcome.execution.id : undefined, + interactionKind: + outcome.status === "paused" + ? pausedInteractionKind(outcome.execution.elicitationContext.request) + : undefined, + }); + if (outcome.status === "paused") { + return yield* formatPausedModelResult(outcome.execution, "execute_action"); + } + return toMcpResult(outcome.result); + }).pipe( + Effect.withSpan("mcp.host.tool.execute_action", { + attributes: { + "mcp.tool.name": "execute-action", + "mcp.execute.code_length": code.length, + }, + }), + ); + + const resumeExecution = ( + executionId: string, + action: "accept" | "decline" | "cancel", + content: Record | undefined, + extra: McpRequestJoinKeys, + ): Effect.Effect => + Effect.gen(function* () { + yield* startMarker("mcp.host.tool.resume.start", { + "mcp.tool.name": "resume", + "mcp.execute.execution_id": executionId, + }); + debugLog("resume.call", { + executionId, + action, + hasContent: content !== undefined, + clientCapabilities: server.server.getClientCapabilities() ?? null, + }); + const outcome = yield* resumeWithLifecycle(executionId, { action, content }); + if (!outcome) { + debugLog("resume.missing_execution", { executionId }); + if (yield* localExecutionAlreadySettled(executionId)) { + return alreadySettledResult(executionId); + } + const fallback = yield* resumeFallback(executionId, { action, content }); + if (fallback) { + debugLog("resume.fallback_result", { executionId, status: fallback.status }); + return fallbackOutcomeResult(executionId, fallback); + } + return missingExecutionResult(executionId); + } + debugLog("resume.result", { + executionId, + status: outcome.status, + nextExecutionId: outcome.status === "paused" ? outcome.execution.id : undefined, + interactionKind: + outcome.status === "paused" + ? pausedInteractionKind(outcome.execution.elicitationContext.request) + : undefined, + }); + if (outcome.status === "paused") { + return yield* formatPausedModelResult(outcome.execution, "resume"); + } + return toMcpResult(outcome.result); + }).pipe( + Effect.withSpan("mcp.host.tool.resume", { + attributes: { + "mcp.tool.name": "resume", + "mcp.execute.resume.action": action, + "mcp.execute.execution_id": executionId, + }, + }), + Effect.annotateSpans(joinKeyAttributes(extra)), + ); + + const requireUserResumeApproval = (executionId: string): Effect.Effect => + Effect.sync(() => { + const approvalUrl = + elicitationMode.mode === "browser" + ? elicitationMode.approvalUrl(executionId) + : defaultResumeApprovalUrl(executionId); + debugLog("resume.user_approval_required", { + executionId, + approvalUrl, + clientCapabilities: server.server.getClientCapabilities() ?? null, + }); + return formatResumeApprovalRequired({ executionId, approvalUrl }); + }).pipe( + Effect.withSpan("mcp.host.tool.resume.user_approval_required", { + attributes: { + "mcp.tool.name": "resume", + "mcp.execute.execution_id": executionId, + }, + }), + ); + + const takeBrowserApprovalResponse = ( + executionId: string, + ): Effect.Effect => { + return config.browserApprovalStore?.takeResponse(executionId) ?? Effect.succeed(null); + }; + + const waitForBrowserApprovalResponse = ( + executionId: string, + ): Effect.Effect => { + const waitForResponse = config.browserApprovalStore?.waitForResponse; + if (!waitForResponse) return takeBrowserApprovalResponse(executionId); + + return waitForResponse(executionId).pipe( + Effect.timeoutOrElse({ + duration: Duration.millis(BROWSER_APPROVAL_WAIT_TIMEOUT_MS), + orElse: () => Effect.succeed(null), + }), + ); + }; + + const resumeAfterBrowserApproval = ( + executionId: string, + extra: McpRequestJoinKeys, + ): Effect.Effect => + Effect.gen(function* () { + yield* startMarker("mcp.host.tool.resume.browser_approval.start", { + "mcp.tool.name": "resume", + "mcp.execute.execution_id": executionId, + }); + const response = yield* waitForBrowserApprovalResponse(executionId); + if (!response) return yield* requireUserResumeApproval(executionId); + + const outcome = yield* resumeWithLifecycle(executionId, response); + if (!outcome) { + return missingExecutionResult(executionId); + } + if (outcome.status === "paused") { + const deadline = pauseDeadline(); + yield* Effect.annotateCurrentSpan({ + "mcp.execute.paused": true, + "mcp.execute.paused_execution_id": outcome.execution.id, + "mcp.execute.pause_source": "browser_resume", + }); + yield* onExecutionPaused(outcome.execution.id, deadline); + } + return outcome.status === "completed" + ? toMcpResult(outcome.result) + : yield* requireUserResumeApproval(outcome.execution.id); + }).pipe( + Effect.withSpan("mcp.host.tool.resume.browser_approval", { + attributes: { + "mcp.tool.name": "resume", + "mcp.execute.execution_id": executionId, + }, + }), + Effect.annotateSpans(joinKeyAttributes(extra)), + ); + + // --- tools --- + + yield* Effect.sync(() => + server.registerTool( + "execute", + { + description, + inputSchema: { code: z.string().trim().min(1) }, + }, + ({ code }, extra) => runToolEffect(executeCode(code, extra)), + ), + ).pipe( + Effect.withSpan("mcp.host.register_tool", { + attributes: { "mcp.tool.name": "execute" }, + }), ); - }; - const nativeInputRequired = async ( - services: NativeExecutionServices, - execution: Parameters< - NativeExecutionServices["executionPaused"] - >[0], - ): Promise => { - const binding = await requestStateBindingForContext( - config.requestStateBinding, - config.requestStatePrincipal, - services.requestContext.serverContext, + yield* Effect.sync(() => + server.registerTool( + "skills", + { + description: [ + "Fetch a named how-to skill. Skills hold the long-form guidance that would otherwise bloat another tool's always-loaded description.", + 'Call `skills({ name: "execute" })` for the full guide to writing code for the `execute` tool (search the catalog, call tools, emit results, resume paused runs).', + "Call with no name to list the available skills.", + ].join("\n"), + inputSchema: { + name: z + .string() + .optional() + .describe('The skill to fetch, e.g. "execute". Omit to list available skills.'), + }, + }, + ({ name }) => + runToolEffect(Effect.succeed(skillsResult(name, executeInventory, skillCatalog))), + ), + ).pipe( + Effect.withSpan("mcp.host.register_tool", { + attributes: { "mcp.tool.name": "skills" }, + }), ); - const requestState = await requestStateCodec(binding).mint( - { executionId: execution.id }, - services.requestContext.serverContext, + + yield* Effect.sync(() => { + if (elicitationMode.mode === "native") { + return undefined; + } + + if (elicitationMode.mode === "model") { + return server.registerTool( + "resume", + { + description: [ + "Resume a paused execution using the executionId returned by execute.", + "This connection explicitly allows model-side resume via elicitation_mode=model.", + ].join("\n"), + inputSchema: { + executionId: z.string().describe("The execution ID from the paused result"), + action: z + .enum(["accept", "decline", "cancel"]) + .describe("How to respond to the interaction"), + content: z + .string() + .describe("Optional JSON-encoded response content for form elicitations") + .default("{}"), + }, + }, + ({ executionId, action, content: rawContent }, extra) => + runToolEffect( + resumeExecution(executionId, action, parseJsonContent(rawContent), extra), + ), + ); + } + + return server.registerTool( + "resume", + { + description: [ + "Request user approval to resume a paused execution.", + "Call this with the executionId returned by execute. If the user has not approved in the browser yet, tell them to open the returned approval URL. If they have approved, this returns the resumed execution result.", + "This connection does not allow the model to choose accept, decline, cancel, or content.", + ].join("\n"), + inputSchema: { + executionId: z.string().describe("The execution ID from the paused result"), + }, + }, + ({ executionId }, extra) => runToolEffect(resumeAfterBrowserApproval(executionId, extra)), + ); + }).pipe( + Effect.withSpan("mcp.host.register_tool", { + attributes: { "mcp.tool.name": "resume" }, + }), ); - return inputRequired({ - inputRequests: { - [NATIVE_ELICITATION_RESPONSE_KEY]: elicitationInputRequest( - execution.elicitationContext.request, - ), - }, - requestState, - }); - }; - return { - server, - initialAppsEnabled, - getClientCapabilities: () => - sessionful ? (server.server.getClientCapabilities() ?? null) : null, - getClientInfo: () => - sessionful ? clientInfoFromImplementation(server.server.getClientVersion()) : null, - getElicitationSupport: () => - sessionful - ? elicitationSupportFromUnknown(server.server.getClientCapabilities()) - : { form: true, url: true }, - getUiCapability: () => - sessionful - ? getUiCapability(appsClientCapabilitiesFromUnknown(server.server.getClientCapabilities())) - : config.appsEnabled - ? { mimeTypes: [RESOURCE_MIME_TYPE] } - : undefined, - onInitialized: (callback) => { - if (sessionful) server.server.oninitialized = callback; - }, - registerTool, - registerAppTool: registerApp, - registerAppResource: (name, uri, resourceConfig, callback) => { - if (!sessionful && !config.appsEnabled) return; - registerAppResource(server, name, uri, resourceConfig, async () => { - const result = await callback(); - return { contents: [...result.contents] }; + // --- artifacts / MCP Apps --- + // + // These register unconditionally once a shell loader is configured. Whether + // the client can actually *render* an app is only known after `initialize`, + // so the app-only tools are toggled in `syncToolAvailability` below; the + // model-facing three stay enabled either way and fall back to a deep link. + + const artifacts = config.artifacts; + + // Set from the client's advertised capabilities at `initialize`. Read by + // the render handlers to choose inline widget vs. deep link. Seeded from + // the host's persisted value so a cold-restored session keeps rendering + // inline for a client that had already negotiated apps support. + // + // This is a cache, not the source of truth: `appsSupported()` below reads + // the live server on every render, because a cold restore re-establishes + // capabilities without ever running the hook that maintains this variable. + let appsEnabled = config.restoredAppsEnabled ?? false; + let executeActionTool: { enable: () => void; disable: () => void } | undefined; + let executeActionResumeTool: { enable: () => void; disable: () => void } | undefined; + + /** + * Move the cached flag and the app-only tools together. + * + * `execute-action` is only callable from inside a rendered app, so a client + * that can't render one should never see it. `create-artifact`, + * `list-artifacts` and `show-artifact` stay visible regardless: they still + * persist, and still return something useful (a deep link). + */ + const applyAppsEnabled = (next: boolean): void => { + appsEnabled = next; + if (next) { + executeActionTool?.enable(); + executeActionResumeTool?.enable(); + } else { + executeActionTool?.disable(); + executeActionResumeTool?.disable(); + } + }; + + // Best-effort usage observation; a failing observer never affects the tool. + const notifyArtifactUsage = (action: "created" | "viewed" | "updated"): Effect.Effect => + config.onArtifactUsage + ? config.onArtifactUsage(action).pipe(Effect.ignoreCause({ log: false })) + : Effect.void; + + const saveAndDeliverArtifact = (input: { + readonly code: string; + readonly title: string; + readonly description?: string; + readonly existingId?: string; + readonly bindings?: Readonly>; + /** Sanitized layout markup from the smoke render, when it produced any. */ + readonly preview?: string | null; + }): Effect.Effect => + Effect.gen(function* () { + if (!artifacts) return artifactsUnavailableResult(); + const saved = yield* artifacts.save({ + ...(input.existingId === undefined ? {} : { id: input.existingId }), + title: input.title, + description: input.description ?? null, + code: input.code, + ...(input.bindings === undefined ? {} : { bindings: input.bindings }), + preview: input.preview ?? null, + }); + yield* notifyArtifactUsage(input.existingId === undefined ? "created" : "updated"); + // Resolve once and report the value actually used, so the span can + // never disagree with what the client received. + const delivered = deliverArtifact({ + code: saved.code, + artifactId: saved.id, + title: saved.title, + }); + yield* Effect.annotateCurrentSpan({ + "mcp.artifact.id": saved.id, + "mcp.artifact.apps_enabled": appsEnabled, + }); + return delivered; }); - }, - executeNative: ( - services: NativeExecutionServices, - ) => + + /** + * Whether the client can render an app, resolved at render time. + * + * `appsEnabled` alone is not enough. On a cold restore the host replays the + * persisted `initialize` *request* — which does set the server's client + * capabilities — but never the `notifications/initialized` notification, + * and `oninitialized` (the only hook that re-runs `syncToolAvailability`) + * fires solely on that notification. So a restored session can hold full + * apps capabilities while `appsEnabled` still reads its seeded value, and + * the replay is dispatched un-awaited, so a tool call can land before it. + * + * Reading the live server here makes both orderings produce the same + * answer, and keeps the seeded value as the fallback for the window before + * any capabilities exist. + */ + const appsSupported = (): boolean => { + const live = server.server.getClientCapabilities(); + if (!live) return appsEnabled; + const uiCapability = getUiCapability( + live as ClientCapabilities & { extensions?: Record }, + ); + const supported = Boolean(uiCapability?.mimeTypes?.includes(RESOURCE_MIME_TYPE)); + // Reconcile the tools too: a restore that re-established capabilities + // without firing `oninitialized` would otherwise render inline while + // `execute-action` — the tool that rendered app calls back into — stayed + // hidden, leaving the widget unable to do anything. + if (supported !== appsEnabled) applyAppsEnabled(supported); + return supported; + }; + + const deliverArtifact = (input: { + readonly code: string; + readonly artifactId: string; + readonly title: string; + }): McpToolResult => { + const url = config.artifactUrl?.(input.artifactId); + if (appsSupported()) return renderedInAppResult({ ...input, url }); + return url + ? renderedAsLinkResult({ url, artifactId: input.artifactId, title: input.title }) + : renderedWithoutSurfaceResult({ artifactId: input.artifactId, title: input.title }); + }; + + /** + * The shared back half of `create-artifact` and `edit-artifact`: everything + * that happens once the full candidate source is in hand. Static checks, + * the smoke render, binding and the save are identical whether the code + * arrived whole or was assembled from stored source plus edits — sharing + * the pipeline is what guarantees an edit cannot save anything a create + * would have refused. + */ + const validateRenderAndSave = (input: { + readonly code: string; + readonly title: string; + readonly description?: string | undefined; + readonly connections?: Readonly> | undefined; + readonly existing: Artifact | null; + }): Effect.Effect => Effect.gen(function* () { - const decodedState = decodeNativeRequestState( - services.requestContext.serverContext.mcpReq.requestState(), - ); + const rejection = validateArtifactCode(input.code); + if (rejection) return renderRejectedResult(rejection); - if (Option.isSome(decodedState)) { - const paused = yield* services.engine.getPausedExecution(decodedState.value.executionId); - if (!paused) return missingNativeExecution(decodedState.value.executionId); - const response = inputResponse( - services.requestContext.serverContext.mcpReq.inputResponses, - NATIVE_ELICITATION_RESPONSE_KEY, + // Static checks first, then the real one: render it. See + // `smokeRenderRejection` for what the model is told. + // + // FAIL OPEN. The renderer is injected, runs on three different hosts, + // and is the newest thing in this path — if IT breaks (a missing + // module, an environment gap on some host), the right outcome is a + // saved artifact and a logged warning, never a refused create of code + // that is perfectly good. Only a definite `failed` blocks a save. + const smoke = config.smokeRenderArtifact; + // The render that validates the artifact is also the render that + // previews it: the same pass produces the loading-state markup the + // gallery draws, so a preview costs nothing beyond sanitizing it. + let preview: string | null = null; + if (smoke) { + const smokeResult: ArtifactSmokeRenderResult = yield* Effect.tryPromise(() => + smoke(input.code), + ).pipe( + Effect.catchCause((cause) => + Effect.as(Effect.logWarning("create-artifact smoke render was unavailable", cause), { + status: "ok", + } satisfies ArtifactSmokeRenderResult), + ), ); - if (response.kind === "elicit") { - const content = Match.value(paused.elicitationContext.request).pipe( - Match.tag("UrlElicitation", () => response.content), - Match.tag("FormElicitation", (form) => - response.action === "accept" - ? acceptedContent( - services.requestContext.serverContext.mcpReq.inputResponses, - NATIVE_ELICITATION_RESPONSE_KEY, - fromJsonSchema>( - Object.keys(form.requestedSchema).length === 0 - ? { type: "object", properties: {} } - : form.requestedSchema, - ), - ) - : response.content, - ), - Match.exhaustive, - ); - if (response.action === "accept" && content === undefined) { - return yield* Effect.promise(() => nativeInputRequired(services, paused)); - } - const outcome = yield* services.resume(decodedState.value.executionId, { - action: response.action, - content, - }); - if (!outcome) return missingNativeExecution(decodedState.value.executionId); - if (outcome.status === "completed") return services.complete(outcome.result); - yield* services.executionPaused(outcome.execution); - return yield* Effect.promise(() => nativeInputRequired(services, outcome.execution)); + const renderRejection = smokeRenderRejection(smokeResult); + if (renderRejection) { + yield* Effect.annotateCurrentSpan({ "mcp.artifact.smoke_render": "failed" }); + return renderRejectedResult(renderRejection); } + // Fail open, exactly as the verdict does: a preview that cannot be + // produced or cannot be sanitized is a card that falls back to its + // schematic, never a create that is refused. + preview = + smokeResult.status === "ok" && smokeResult.markup !== undefined + ? sanitizeArtifactPreviewMarkup(smokeResult.markup) + : null; + } - return yield* Effect.promise(() => nativeInputRequired(services, paused)); + const saveInput = { + code: input.code, + title: input.title, + preview, + ...(input.description === undefined ? {} : { description: input.description }), + ...(input.existing === null ? {} : { existingId: input.existing.id }), + }; + + const roles = extractArtifactRoles(input.code); + if (roles.length === 0 && input.connections === undefined) { + return yield* saveAndDeliverArtifact({ ...saveInput, bindings: {} }); } - const outcome = yield* services.engine.executeWithPause(services.code); - if (outcome.status === "completed") return services.complete(outcome.result); - yield* services.executionPaused(outcome.execution); - return yield* Effect.promise(() => nativeInputRequired(services, outcome.execution)); - }), - }; -}; + if (!config.connections) { + return renderRejectedResult( + "This connection cannot bind integrations, so an artifact that calls one cannot be saved here.", + ); + } -/** - * Build one Executor MCP server. - * - * Stateless hosts must reuse the signing key across every request that can - * participate in the same native-elicitation continuation flow. Sessionful - * hosts keep one instance connected and may use a connection-lifetime key. - */ -export const buildMcpServer = ( - config: ExecutorMcpServerConfig, -): Effect.Effect => buildExecutorMcpTools(config, () => createMcpAssembly(config)); + const available = yield* config.connections + .list() + .pipe(Effect.catchCause(() => Effect.succeed([] as readonly BindableConnection[]))); + const resolved = resolveArtifactBindings({ + roles, + connections: input.connections, + available, + }); + if (!resolved.ok) return renderRejectedResult(resolved.message); + + yield* Effect.annotateCurrentSpan({ + "mcp.artifact.role_count": roles.length, + }); + return yield* saveAndDeliverArtifact({ ...saveInput, bindings: resolved.bindings }); + }); + + /** + * Bind the integration roles an artifact's code uses, at create time. + * + * Binding happens HERE rather than at render time because this is the only + * moment the author, the code and their connections are all in hand — and + * because a create that can't bind is a create that would have saved a + * broken artifact. The model finds out now, with the candidate list, rather + * than the user finding out later through a query error inside the UI. + * + * `artifactId` turns the same call into an update in place — for a REWRITE, + * where the new source shares little with the old and edits would be longer + * than the code. A tweak belongs on `edit-artifact`, which patches the + * stored source instead of replacing it. Either way one row is kept: a copy + * per revision is the thing the model has to ask for, never the default. + * + * An update replaces the code outright — v1 keeps no version history — and + * re-extracts and re-resolves the bindings from the NEW source, because the + * roles the new code uses are not necessarily the ones the old code did. + * `title` and `description` are optional on an update and absent means keep + * what is stored, so a pure code tweak doesn't have to restate them. + */ + const createArtifact = (input: { + readonly code: string; + readonly title?: string; + readonly description?: string; + readonly connections?: Readonly>; + readonly artifactId?: string; + }): Effect.Effect => + Effect.gen(function* () { + // An update reads the existing row FIRST, both to carry its title and + // description forward and to refuse a foreign id before any work. The + // refusal is `artifact_unavailable` — the same answer `execute-action` + // gives — so create-artifact cannot be used to probe which ids exist. + const existing = + input.artifactId === undefined ? null : yield* loadArtifact(input.artifactId); + if (input.artifactId !== undefined && !existing) return actionArtifactUnavailableResult(); + + const title = input.title ?? existing?.title; + if (title === undefined) { + return renderRejectedResult( + "title is required when creating an artifact. Give it a short human-readable name.", + ); + } + // Only an update inherits; a create with no description stores none. + const description = input.description ?? existing?.description ?? undefined; + + return yield* validateRenderAndSave({ + code: input.code, + title, + description, + connections: input.connections, + existing, + }); + }).pipe( + Effect.withSpan("mcp.host.tool.create_artifact", { + attributes: { + "mcp.tool.name": "create-artifact", + "mcp.artifact.update": input.artifactId !== undefined, + "mcp.execute.code_length": input.code.length, + }, + }), + ); + + /** + * `edit-artifact`: the update path for tweaks, patching the stored source + * with exact find-and-replace edits so the call scales with the change + * rather than the component. The edited result runs the same + * validate → smoke-render → bind → save pipeline as a full create, so an + * edit cannot save anything a create would have refused. + * + * A failed edit hands the CURRENT source back in `structuredContent.code`. + * The model's usual recovery — `show-artifact`, re-read, retry — is a whole + * extra round trip to fetch a thing this call already loaded; giving it + * back here makes the retry immediate. + */ + const editArtifact = (input: { + readonly artifactId: string; + readonly edits: readonly ArtifactEdit[]; + readonly title?: string; + readonly description?: string; + readonly connections?: Readonly>; + }): Effect.Effect => + Effect.gen(function* () { + // Same probe-proof refusal as create-artifact's update arm. + const existing = yield* loadArtifact(input.artifactId); + if (!existing) return actionArtifactUnavailableResult(); + + const applied = applyArtifactEdits(existing.code, input.edits); + if (!applied.ok) return editRejectedResult(applied.message, existing.code); + + yield* Effect.annotateCurrentSpan({ + "mcp.artifact.edit_count": input.edits.length, + }); + return yield* validateRenderAndSave({ + code: applied.code, + title: input.title ?? existing.title, + description: input.description ?? existing.description ?? undefined, + connections: input.connections, + existing, + }); + }).pipe( + Effect.withSpan("mcp.host.tool.edit_artifact", { + attributes: { + "mcp.tool.name": "edit-artifact", + "mcp.artifact.id": input.artifactId, + }, + }), + ); + + const listArtifacts = (): Effect.Effect => + Effect.gen(function* () { + if (!artifacts) return artifactsUnavailableResult(); + return artifactListResult(yield* artifacts.list()); + }).pipe( + Effect.withSpan("mcp.host.tool.list_artifacts", { + attributes: { "mcp.tool.name": "list-artifacts" }, + }), + ); + + const showArtifact = (id: string): Effect.Effect => + Effect.gen(function* () { + if (!artifacts) return artifactsUnavailableResult(); + // A miss is the ordinary case (the model guessed an id, or the row was + // deleted), so it becomes an isError result rather than a defect. + const artifact: Artifact | null = yield* artifacts + .get(id) + .pipe(Effect.catchCause(() => Effect.succeed(null))); + if (!artifact) return artifactNotFoundResult(id); + yield* notifyArtifactUsage("viewed"); + return deliverArtifact({ + code: artifact.code, + artifactId: artifact.id, + title: artifact.title, + }); + }).pipe( + Effect.withSpan("mcp.host.tool.show_artifact", { + attributes: { "mcp.tool.name": "show-artifact", "mcp.artifact.id": id }, + }), + ); + + // Two independent reasons to serve no artifact surface: the host cannot + // (no shell loader), or this connection opted out (`?artifacts=false`). + // Either way nothing below registers, so a disabled session is byte-for-byte + // a session on a host that never had artifacts. + const loadAppShellHtml = artifactsEnabled ? config.loadAppShellHtml : undefined; + + if (loadAppShellHtml) { + yield* Effect.sync(() => { + registerAppResource( + server, + "Executor Shell", + MCP_APPS_SHELL_RESOURCE_URI, + { mimeType: RESOURCE_MIME_TYPE }, + async () => ({ + contents: [ + { + uri: MCP_APPS_SHELL_RESOURCE_URI, + mimeType: RESOURCE_MIME_TYPE, + text: await loadAppShellHtml(), + // Zero allowed domains: the shell may open no network + // connection of its own. Every read and write goes back over + // the MCP bridge through `execute-action`. + _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] } } }, + }, + ], + }), + ); + }).pipe( + Effect.withSpan("mcp.host.register_resource", { + attributes: { "mcp.resource.uri": MCP_APPS_SHELL_RESOURCE_URI }, + }), + ); + + yield* Effect.sync(() => + registerAppTool( + server, + "create-artifact", + { + description: [ + "Render an interactive React UI component as an MCP app, and save it as a reusable artifact.", + 'Call `skills({ name: "create-artifact" })` for the full guide: the discovery-then-render protocol, TanStack Query rules, and every component already in scope. Call `skills({ name: "artifact-style" })` for how it must look — artifacts render inside the Executor console and must match its design system.', + "Write a component named `App` in `code`. Do not import anything and do not paste fetched data into JSX — read it live with `useQuery(tools...queryOptions(args))`.", + "Lay it out as an app, not a document: an artifact may be given the whole viewport, so make the root `flex h-full flex-col`, keep headers and filters as ordinary children, and give the one long table or list `flex-1 min-h-0 overflow-auto` — its header then stays put while the rows scroll under it.", + "Artifact code addresses an INTEGRATION, never a connection: write `tools.vercel.domains.getDomains`, not the full `tools.vercel.user.personalVercel.domains.getDomains` address `execute` uses for discovery. The connection is bound when the artifact is saved, so it stays portable. Code containing a `.user.` or `.org.` segment is rejected.", + 'To use two accounts of the same integration, tag each call site with a role — `tools.linear("prod").issues.list` and `tools.linear("staging").issues.list` — and map every role in `connections`.', + "All data access is declarative `tools.*`: `.queryOptions()` to read, `.infiniteQueryOptions()` to page through a cursor, `.mutationOptions()` to write. There is no `run()` and no arbitrary code — never hand-roll `useQuery({ queryKey, queryFn })`, or invalidation breaks.", + "To read every page of a paginated tool, call `useInfiniteQuery(tools...infiniteQueryOptions(args, { cursorKey, getNextPageParam }))` once and render `data.pages`. Never call hooks inside a loop — a `useQuery` per page is rejected.", + "To CHANGE an artifact that already exists, use `edit-artifact` — it patches the stored source with find-and-replace edits, so a tweak costs only the changed lines. Only use create-artifact with `artifactId` for a full rewrite, sending the complete new component. Never create a second artifact for a revision of an existing one.", + "Clients that cannot display MCP apps receive a link to the saved artifact instead; pass it to the user.", + ].join("\n"), + inputSchema: { + code: z.string().trim().min(1).describe("The React component source. Export `App`."), + artifactId: z + .string() + .trim() + .min(1) + .optional() + .describe( + "The artifact to REWRITE in place, from `list-artifacts` or a previous create. Omit to create a new one. `code` fully replaces the stored source and the connection bindings are re-resolved from it, so send the complete component, not a fragment. For a tweak, use `edit-artifact` instead.", + ), + connections: z + .record(z.string(), z.string()) + .optional() + .describe( + 'Which connection each integration role in `code` uses, as `..` (the address `connections.list` reports, minus the leading `tools.`). Keys are roles: the integration slug for an untagged `tools.linear.…`, or the tag for `tools.linear("prod").…`. Optional when you have exactly one connection per integration used — that one binds automatically. Required when you have several, and the error lists them.', + ), + title: z + .string() + .trim() + .min(1) + .optional() + .describe( + 'Short human-readable name for the artifact, e.g. "Active users dashboard". The user sees this and you match against it later. Required when creating; on an update, omit it to keep the current title.', + ), + description: z + .string() + .optional() + .describe( + "What this UI shows, in a sentence. Used to find the artifact again on a later request. On an update, omit it to keep the current description.", + ), + }, + _meta: { + ui: { resourceUri: MCP_APPS_SHELL_RESOURCE_URI, visibility: ["model"] }, + }, + }, + ({ code, title, description, connections, artifactId }) => + runToolEffect(createArtifact({ code, title, description, connections, artifactId })), + ), + ).pipe( + Effect.withSpan("mcp.host.register_tool", { + attributes: { "mcp.tool.name": "create-artifact" }, + }), + ); + + yield* Effect.sync(() => + registerAppTool( + server, + "edit-artifact", + { + description: [ + "Change an existing artifact by patching its stored source with exact find-and-replace edits, and re-render it.", + "PREFER THIS over create-artifact for tweaks — a new column, a fixed label, a restyled section — because you send only the changed lines, not the whole component. Use create-artifact with `artifactId` only for a rewrite where most of the code changes.", + "Each edit's `oldText` must appear EXACTLY ONCE in the current source, verbatim (whitespace included); include enough surrounding lines to make it unique, or set `replaceAll: true` to change every occurrence. Edits apply in order, each seeing the previous one's result.", + "The batch is atomic: if any edit fails to match, nothing is saved and the error returns the current source in structuredContent.code — rebuild the edits from that instead of calling show-artifact again.", + "The edited component is validated and smoke-rendered exactly like a create, and connection bindings are re-resolved from the result; pass `connections` if an edit introduces an ambiguous integration.", + ].join("\n"), + inputSchema: { + artifactId: z + .string() + .trim() + .min(1) + .describe("The artifact to edit, from `list-artifacts` or a previous create."), + edits: z + .array( + z.object({ + oldText: z + .string() + .min(1) + .describe( + "Exact text to find in the current source, whitespace included. Must match exactly once unless replaceAll is true.", + ), + newText: z.string().describe("The replacement text."), + replaceAll: z + .boolean() + .optional() + .describe("Replace every occurrence instead of requiring a unique match."), + }), + ) + .min(1) + .describe("Find-and-replace edits, applied in order. All-or-nothing."), + connections: z + .record(z.string(), z.string()) + .optional() + .describe( + "Connection for each integration role the EDITED code uses, exactly as on create-artifact. Only needed when an edit introduces an integration with several connections.", + ), + title: z + .string() + .trim() + .min(1) + .optional() + .describe("New title. Omit to keep the current one."), + description: z + .string() + .optional() + .describe("New description. Omit to keep the current one."), + }, + _meta: { + ui: { resourceUri: MCP_APPS_SHELL_RESOURCE_URI, visibility: ["model"] }, + }, + }, + ({ artifactId, edits, connections, title, description }) => + runToolEffect(editArtifact({ artifactId, edits, connections, title, description })), + ), + ).pipe( + Effect.withSpan("mcp.host.register_tool", { + attributes: { "mcp.tool.name": "edit-artifact" }, + }), + ); + + yield* Effect.sync(() => + server.registerTool( + "list-artifacts", + { + description: [ + "List the saved UI artifacts for this account, newest first.", + "Match the user's phrasing against the returned titles and descriptions, then call `show-artifact` with that id.", + ].join("\n"), + inputSchema: {}, + }, + () => runToolEffect(listArtifacts()), + ), + ).pipe( + Effect.withSpan("mcp.host.register_tool", { + attributes: { "mcp.tool.name": "list-artifacts" }, + }), + ); + + yield* Effect.sync(() => + registerAppTool( + server, + "show-artifact", + { + description: [ + "Re-render a saved UI artifact by id.", + "Use `list-artifacts` first to find the id whose title or description matches what the user asked for.", + "Clients that cannot display MCP apps receive a link to the artifact instead.", + ].join("\n"), + inputSchema: { + id: z.string().trim().min(1).describe("The artifact id from `list-artifacts`."), + }, + _meta: { + ui: { resourceUri: MCP_APPS_SHELL_RESOURCE_URI, visibility: ["model"] }, + }, + }, + ({ id }) => runToolEffect(showArtifact(id)), + ), + ).pipe( + Effect.withSpan("mcp.host.register_tool", { + attributes: { "mcp.tool.name": "show-artifact" }, + }), + ); + + yield* Effect.sync(() => { + executeActionTool = registerAppTool( + server, + "execute-action", + { + description: + "Execute code from the UI shell. Used by interactive components to call tools and run mutations.", + inputSchema: { + code: z.string().trim().min(1), + artifactId: z + .string() + .trim() + .min(1) + .optional() + .describe( + "The artifact making the call. Its stored bindings resolve the integration role in `code` to a connection.", + ), + }, + _meta: { + ui: { resourceUri: MCP_APPS_SHELL_RESOURCE_URI, visibility: ["app"] }, + }, + }, + ({ code, artifactId }, extra) => + runToolEffect(executeCodeFromApp(code, artifactId, extra)), + ); + + executeActionResumeTool = registerAppTool( + server, + "execute-action-resume", + { + description: "Resume an interactive UI action after shell-owned user approval.", + inputSchema: { + executionId: z.string().describe("The execution ID from the paused UI action"), + action: z + .enum(["accept", "decline", "cancel"]) + .describe("How to respond to the interaction"), + content: z + .string() + .describe("Optional JSON-encoded response content for form elicitations") + .default("{}"), + }, + _meta: { + ui: { resourceUri: MCP_APPS_SHELL_RESOURCE_URI, visibility: ["app"] }, + }, + }, + ({ executionId, action, content: rawContent }, extra) => + runToolEffect( + resumeExecution(executionId, action, parseJsonContent(rawContent), extra), + ), + ); + }).pipe( + Effect.withSpan("mcp.host.register_tool", { + attributes: { "mcp.tool.name": "execute-action" }, + }), + ); + } + + // Client capabilities only exist after `initialize`, and `tools/list` is + // answered from whatever is registered at that moment — so app-only tool + // visibility has to be re-synced from the `oninitialized` hook rather than + // decided at construction. + // + // This hook covers live clients only. It does NOT run on a cold restore: + // the host replays the persisted `initialize` request, but `oninitialized` + // fires on the `notifications/initialized` notification, which is never + // persisted. `appsSupported()` is what makes the restored case correct. + const syncToolAvailability = () => { + const clientCapabilities = server.server.getClientCapabilities(); + const uiCapability = getUiCapability( + clientCapabilities as + | (ClientCapabilities & { extensions?: Record }) + | null, + ); + // Absent capabilities (the SDK returns `undefined`) mean `initialize` + // hasn't happened on THIS server instance — the construction-time call + // below, or a cold restore that resumed mid-conversation. Neither is + // evidence the client lost apps support, so the restored value stands + // until a real `initialize` replaces it. Reading `false` off an absent + // value here is exactly what made a cold-restored session fall back to + // deep links. + const negotiated = clientCapabilities + ? Boolean(uiCapability?.mimeTypes?.includes(RESOURCE_MIME_TYPE)) + : appsEnabled; + const changed = negotiated !== appsEnabled; + applyAppsEnabled(negotiated); + + // Persist only a real negotiation that moved the value, so the next cold + // restore seeds itself. Best-effort: the session must not fail on it. + // The `clientCapabilities` guard matters beyond skipping a no-op write: + // persisting an absent-capability reading would make a downgrade durable + // for every future restore of the session. + const onAppsEnabledChange = config.onAppsEnabledChange; + if (clientCapabilities && changed && onAppsEnabledChange) { + // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: `oninitialized` is a sync SDK hook; persistence is fire-and-forget and its failure must not fail the session + void Effect.runPromiseWith(context)( + onAppsEnabledChange(negotiated).pipe(Effect.ignoreCause({ log: false })), + ); + } + + console.error( + "[executor] MCP session mode", + JSON.stringify({ + ...capabilitySnapshot(server), + elicitationMode: elicitationMode.mode, + resumeEnabled: elicitationMode.mode !== "native", + }), + ); + debugLog("tool.visibility", { + clientCapabilities: clientCapabilities ?? null, + elicitationSupport: getElicitationSupport(server), + elicitationMode: elicitationMode.mode, + resumeEnabled: elicitationMode.mode !== "native", + appsSupport: uiCapability ?? null, + appsEnabled, + executeActionEnabled: appsEnabled, + }); + }; + + yield* Effect.sync(() => { + syncToolAvailability(); + server.server.oninitialized = syncToolAvailability; + }).pipe(Effect.withSpan("mcp.host.sync_tool_availability")); + + return server; + }).pipe(Effect.withSpan("mcp.host.create_executor_server")); diff --git a/packages/plugins/mcp/src/testing/server.ts b/packages/plugins/mcp/src/testing/server.ts index 6f9ccebbaa..0b6edf0f04 100644 --- a/packages/plugins/mcp/src/testing/server.ts +++ b/packages/plugins/mcp/src/testing/server.ts @@ -1,6 +1,5 @@ import { Context, Data, Effect, Layer, Ref, Scope } from "effect"; import * as http from "node:http"; -// Intentionally stays on the legacy SDK as a wire-interop fixture for MCP plugin clients. import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { OAuthTestServer } from "@executor-js/sdk/testing"; diff --git a/patches/agents@0.17.3.patch b/patches/agents@0.17.3.patch new file mode 100644 index 0000000000..df7396f95d --- /dev/null +++ b/patches/agents@0.17.3.patch @@ -0,0 +1,911 @@ +diff --git a/node_modules/agents/.bun-tag-c0c639aa2299e502 b/.bun-tag-c0c639aa2299e502 +new file mode 100644 +index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 +diff --git a/dist/agent-tool-types-CNyE1iz_.d.ts b/dist/agent-tool-types-CNyE1iz_.d.ts +index 571eececebd5a1eaf7f2fbf5278801c4d34728ba..317e526489fcd3fd477a50525da0df666253bf0b 100644 +--- a/dist/agent-tool-types-CNyE1iz_.d.ts ++++ b/dist/agent-tool-types-CNyE1iz_.d.ts +@@ -480,7 +480,10 @@ declare class DurableObjectEventStore implements EventStore { + private readonly seqByStream; + private readonly seqInit; + constructor(storage: DurableObjectStorage); +- storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise; ++ /** Resolves `undefined` for a message too large for DO storage's 128 KiB ++ * per-value cap: the event is delivered live without a replay id rather ++ * than failing the send. */ ++ storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise; + getStreamIdForEventId(eventId: EventId): Promise; + replayEventsAfter( + lastEventId: EventId, +diff --git a/dist/mcp/index.d.ts b/dist/mcp/index.d.ts +index c8fad448e8797b89690a99d93490d1363851b225..77f9fe3f6f2375eadc9f7a2974f0d202fe75b3bd 100644 +--- a/dist/mcp/index.d.ts ++++ b/dist/mcp/index.d.ts +@@ -29,6 +29,7 @@ import { + xt as MCPClientOAuthCallbackConfig, + zt as ElicitResult + } from "../agent-tool-types-CNyE1iz_.js"; ++declare const MAX_SSE_AGE_MS = 1800000; + export { + type ClearableEventStore, + type CreateMcpHandlerOptions, +@@ -41,6 +42,7 @@ export { + type MCPConnectionResult, + type MCPDiscoverResult, + type MCPServerOptions, ++ MAX_SSE_AGE_MS, + MCP_SERVER_ID_MAX_LENGTH, + McpAgent, + type McpAuthContext, +diff --git a/dist/mcp/index.js b/dist/mcp/index.js +index 1edcf0c8c9e67aa211ae515e7672cdf79912101e..444312ff41fbcff60e2ea681a9d5c756cd72faef 100644 +--- a/dist/mcp/index.js ++++ b/dist/mcp/index.js +@@ -28,13 +28,17 @@ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/ + const KEEPALIVE_INTERVAL_MS = 25e3; + /** SSE comment frame the parser drops before any event dispatch. */ + const KEEPALIVE_FRAME = ": keepalive\n\n"; ++// Max age is a stalled-client memory backstop, not session idleness. Keep it ++// well above Executor's 5 minute session idle timeout so active clients rarely ++// rotate. ++const MAX_SSE_AGE_MS = 30 * 60 * 1000; + /** + * Start an SSE keepalive on `writer`. Returns a `clearInterval` handle + * that the stream cleanup must invoke when the stream closes. + */ +-function startKeepalive(writer, encoder) { ++function startKeepalive(writeFrame, encoder) { + const handle = setInterval(() => { +- writer.write(encoder.encode(KEEPALIVE_FRAME)).catch(() => clearInterval(handle)); ++ writeFrame(encoder.encode(KEEPALIVE_FRAME)); + }, KEEPALIVE_INTERVAL_MS); + return handle; + } +@@ -180,10 +184,15 @@ const createStreamingHttpHandler = (basePath, namespace, options = {}) => { + }); + return new Response(body, { status: 404 }); + } +- const { readable, writable } = new TransformStream(); +- const writer = writable.getWriter(); +- const encoder = new TextEncoder(); +- const existingHeaders = {}; ++ const { readable, writable } = new TransformStream(); ++ const writer = writable.getWriter(); ++ const encoder = new TextEncoder(); ++ const MAX_PENDING_SSE_BYTES = 8 * 1024 * 1024; ++ let __pendingBytes = 0; ++ let __writeChain = Promise.resolve(); ++ let __sseClosed = false; ++ let keepAlive; ++ const existingHeaders = {}; + request.headers.forEach((value, key) => { + existingHeaders[key] = value; + }); +@@ -206,45 +215,99 @@ const createStreamingHttpHandler = (basePath, namespace, options = {}) => { + jsonrpc: "2.0" + }); + return new Response(body, { status: 500 }); +- } +- ws.accept(); +- if (messages.every((msg) => isJSONRPCNotification(msg) || isJSONRPCResultResponse(msg))) { +- ws.close(); +- return new Response(null, { ++ } ++ ws.accept(); ++ const __closeSse = () => { ++ if (__sseClosed) return; ++ __sseClosed = true; ++ try { ++ clearInterval(keepAlive); ++ } catch {} ++ try { ++ ws.close(1013, "SSE client not draining"); ++ } catch {} ++ writer.abort(new Error("SSE client not draining")).catch(() => {}); ++ }; ++ const __markSseClientClosed = () => { ++ if (__sseClosed) return; ++ __sseClosed = true; ++ try { ++ clearInterval(keepAlive); ++ } catch {} ++ writer.abort(new Error("SSE client disconnected")).catch(() => {}); ++ }; ++ writer.closed?.catch(() => { ++ __markSseClientClosed(); ++ }); ++ request.signal.addEventListener("abort", __closeSse, { once: true }); ++ const __forwardSse = (frame) => { ++ if (__sseClosed) return __writeChain; ++ if (__pendingBytes + frame.byteLength > MAX_PENDING_SSE_BYTES) { ++ __closeSse(); ++ return Promise.resolve(); ++ } ++ __pendingBytes += frame.byteLength; ++ __writeChain = __writeChain.then(() => writer.write(frame)).catch(() => { ++ __closeSse(); ++ }).finally(() => { ++ __pendingBytes -= frame.byteLength; ++ }); ++ return __writeChain; ++ }; ++ keepAlive = startKeepalive(__forwardSse, encoder); ++ if (messages.every((msg) => isJSONRPCNotification(msg) || isJSONRPCResultResponse(msg))) { ++ clearInterval(keepAlive); ++ ws.close(); ++ return new Response(null, { + headers: corsHeaders(request, options.corsOptions), + status: 202 +- }); +- } +- const keepAlive = startKeepalive(writer, encoder); +- ws.addEventListener("message", (event) => { ++ }); ++ } ++ ws.addEventListener("message", (event) => { + async function onMessage(event) { + try { +- const data = typeof event.data === "string" ? event.data : new TextDecoder().decode(event.data); +- const message = JSON.parse(data); +- if (message.type !== "cf_mcp_agent_event") return; +- await writer.write(encoder.encode(message.event)); +- if (message.close) { +- clearInterval(keepAlive); +- ws?.close(); +- await writer.close().catch(() => {}); +- } ++ const data = typeof event.data === "string" ? event.data : new TextDecoder().decode(event.data); ++ const message = JSON.parse(data); ++ if (message.type !== "cf_mcp_agent_event") return; ++ const writePromise = __forwardSse(encoder.encode(message.event)); ++ if (message.close) { ++ clearInterval(keepAlive); ++ await writePromise; ++ await writer.close(); ++ if (!__sseClosed && !request.signal.aborted) { ++ // workerd resolves writer.close() even when the client ++ // canceled the POST response body, and request.signal does ++ // not reliably fire for that cancellation, so a successful ++ // close is NOT proof of delivery. Never ack POST-stream ++ // deliveries: the DO keeps the response persisted and the ++ // client's own reconnect GET replays and acks it. A client ++ // that DID receive the result closes the POST body reader ++ // without a Last-Event-ID reconnect, and the SDK drops ++ // responses for request ids it no longer tracks, so the ++ // worst case of this at-least-once choice is a benign ++ // replay to a fresh GET, not a wedged tool call. ++ ws?.close(1000, "SSE response delivered"); ++ } ++ } + } catch (error) { + console.error("Error forwarding message to SSE:", error); + } + } + onMessage(event).catch(console.error); + }); +- ws.addEventListener("error", (error) => { +- async function onError(_error) { +- clearInterval(keepAlive); +- await writer.close().catch(() => {}); ++ ws.addEventListener("error", (error) => { ++ async function onError(_error) { ++ __sseClosed = true; ++ clearInterval(keepAlive); ++ await writer.close().catch(() => {}); + } + onError(error).catch(console.error); + }); +- ws.addEventListener("close", () => { +- async function onClose() { +- clearInterval(keepAlive); +- await writer.close().catch(() => {}); ++ ws.addEventListener("close", () => { ++ async function onClose() { ++ __sseClosed = true; ++ clearInterval(keepAlive); ++ await writer.close().catch(() => {}); + } + onClose().catch(console.error); + }); +@@ -279,10 +342,16 @@ const createStreamingHttpHandler = (basePath, namespace, options = {}) => { + id: null, + jsonrpc: "2.0" + }), { status: 400 }); +- const { readable, writable } = new TransformStream(); +- const writer = writable.getWriter(); +- const encoder = new TextEncoder(); +- const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { ++ const { readable, writable } = new TransformStream(); ++ const writer = writable.getWriter(); ++ const encoder = new TextEncoder(); ++ const __openedAt = Date.now(); ++ const MAX_PENDING_SSE_BYTES = 8 * 1024 * 1024; ++ let __pendingBytes = 0; ++ let __writeChain = Promise.resolve(); ++ let __sseClosed = false; ++ let keepAlive; ++ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { + props: ctx.props, + jurisdiction: options.jurisdiction + }); +@@ -306,27 +375,116 @@ const createStreamingHttpHandler = (basePath, namespace, options = {}) => { + if (!ws) { + await writer.close(); + return new Response("Failed to establish WS to DO", { status: 500 }); +- } +- ws.accept(); +- ws.addEventListener("message", (event) => { ++ } ++ ws.accept(); ++ const __abortSse = () => { ++ if (__sseClosed) return; ++ __sseClosed = true; ++ try { ++ clearInterval(keepAlive); ++ } catch {} ++ try { ++ ws.close(1013, "SSE client not draining"); ++ } catch {} ++ writer.abort(new Error("SSE client not draining")).catch(() => {}); ++ }; ++ writer.closed?.catch(() => { ++ __abortSse(); ++ }); ++ request.signal.addEventListener("abort", __abortSse, { once: true }); ++ const __closeSseGracefully = () => { ++ if (__sseClosed) return __writeChain; ++ __sseClosed = true; ++ try { ++ clearInterval(keepAlive); ++ } catch {} ++ try { ++ const finalFrame = encoder.encode(": max-age rotation, reconnect\n\n"); ++ __writeChain = __writeChain.then(() => writer.write(finalFrame)).catch(() => {}).then(() => writer.close()).catch(() => { ++ writer.abort().catch(() => {}); ++ }); ++ } catch { ++ __writeChain = writer.close().catch(() => { ++ writer.abort().catch(() => {}); ++ }); ++ } ++ try { ++ ws.close(1000, "sse_max_age_rotation"); ++ } catch {} ++ return __writeChain; ++ }; ++ const __forwardSse = (frame) => { ++ if (__sseClosed) return __writeChain; ++ const ageMs = Date.now() - __openedAt; ++ if (ageMs > MAX_SSE_AGE_MS) { ++ console.log(JSON.stringify({ ++ event: "sse_max_age_close", ++ sessionId, ++ variant: "streamable-get", ++ ageMs, ++ pendingBytes: __pendingBytes ++ })); ++ __closeSseGracefully(); ++ return Promise.resolve(); ++ } ++ if (__pendingBytes + frame.byteLength > MAX_PENDING_SSE_BYTES) { ++ __abortSse(); ++ return Promise.resolve(); ++ } ++ __pendingBytes += frame.byteLength; ++ __writeChain = __writeChain.then(() => writer.write(frame)).catch(() => { ++ __abortSse(); ++ }).finally(() => { ++ __pendingBytes -= frame.byteLength; ++ }); ++ return __writeChain; ++ }; ++ keepAlive = startKeepalive(__forwardSse, encoder); ++ ws.addEventListener("message", (event) => { + try { + async function onMessage(ev) { +- const data = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data); +- const message = JSON.parse(data); +- if (message.type !== "cf_mcp_agent_event") return; +- await writer.write(encoder.encode(message.event)); +- } ++ const data = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data); ++ const message = JSON.parse(data); ++ if (message.type !== "cf_mcp_agent_event") return; ++ const writePromise = __forwardSse(encoder.encode(message.event)); ++ if (message.close) { ++ clearInterval(keepAlive); ++ await writePromise; ++ await writer.close(); ++ if (!__sseClosed && !request.signal.aborted) { ++ // Storage is cleared only on this ack, which fires only ++ // after writer.close() resolved with the client still ++ // attached; a replayed response enqueued into a dead GET ++ // never acks and stays replayable. `ackStreamIds` lets a ++ // replay-complete frame confirm several replayed streams ++ // at once; a live final response carries its `streamId`. ++ const ackStreamIds = Array.isArray(message.ackStreamIds) ? message.ackStreamIds : message.streamId ? [message.streamId] : []; ++ for (const ackStreamId of ackStreamIds) try { ++ ws.send(JSON.stringify({ ++ type: "cf_mcp_delivery_ack", ++ eventId: message.eventId, ++ streamId: ackStreamId ++ })); ++ } catch {} ++ ws?.close(1000, "SSE response delivered"); ++ } ++ } ++ } + onMessage(event).catch(console.error); + } catch (e) { + console.error("Error forwarding message to SSE:", e); + } +- }); +- ws.addEventListener("error", () => { +- writer.close().catch(() => {}); +- }); +- ws.addEventListener("close", () => { +- writer.close().catch(() => {}); +- }); ++ }); ++ ws.addEventListener("error", () => { ++ __sseClosed = true; ++ clearInterval(keepAlive); ++ writer.close().catch(() => {}); ++ }); ++ ws.addEventListener("close", () => { ++ __sseClosed = true; ++ clearInterval(keepAlive); ++ writer.close().catch(() => {}); ++ }); + return new Response(readable, { + headers: { + "Cache-Control": "no-cache", +@@ -389,10 +547,16 @@ const createLegacySseHandler = (basePath, namespace, options = {}) => { + const url = new URL(request.url); + if (request.method === "GET" && basePattern.test(url)) { + const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString(); +- const { readable, writable } = new TransformStream(); +- const writer = writable.getWriter(); +- const encoder = new TextEncoder(); +- const endpointUrl = new URL(request.url); ++ const { readable, writable } = new TransformStream(); ++ const writer = writable.getWriter(); ++ const encoder = new TextEncoder(); ++ const __openedAt = Date.now(); ++ const MAX_PENDING_SSE_BYTES = 8 * 1024 * 1024; ++ let __pendingBytes = 0; ++ let __writeChain = Promise.resolve(); ++ let __sseClosed = false; ++ let keepAlive; ++ const endpointUrl = new URL(request.url); + endpointUrl.pathname = encodeURI(`${basePath}/message`); + endpointUrl.searchParams.set("sessionId", sessionId); + const endpointMessage = `event: endpoint\ndata: ${endpointUrl.pathname + endpointUrl.search + endpointUrl.hash}\n\n`; +@@ -414,35 +578,94 @@ const createLegacySseHandler = (basePath, namespace, options = {}) => { + console.error("Failed to establish WebSocket connection"); + await writer.close(); + return new Response("Failed to establish WebSocket connection", { status: 500 }); +- } +- ws.accept(); +- ws.addEventListener("message", (event) => { ++ } ++ ws.accept(); ++ const __abortSse = () => { ++ __sseClosed = true; ++ try { ++ clearInterval(keepAlive); ++ } catch {} ++ try { ++ ws.close(1013, "SSE client not draining"); ++ } catch {} ++ writer.abort(new Error("SSE client not draining")).catch(() => {}); ++ }; ++ const __closeSseGracefully = () => { ++ __sseClosed = true; ++ try { ++ clearInterval(keepAlive); ++ } catch {} ++ try { ++ const finalFrame = encoder.encode(": max-age rotation, reconnect\n\n"); ++ __writeChain = __writeChain.then(() => writer.write(finalFrame)).catch(() => {}).then(() => writer.close()).catch(() => { ++ writer.abort().catch(() => {}); ++ }); ++ } catch { ++ __writeChain = writer.close().catch(() => { ++ writer.abort().catch(() => {}); ++ }); ++ } ++ try { ++ ws.close(1000, "sse_max_age_rotation"); ++ } catch {} ++ return __writeChain; ++ }; ++ const __forwardSse = (frame) => { ++ if (__sseClosed) return __writeChain; ++ const ageMs = Date.now() - __openedAt; ++ if (ageMs > MAX_SSE_AGE_MS) { ++ console.log(JSON.stringify({ ++ event: "sse_max_age_close", ++ sessionId, ++ variant: "legacy-sse", ++ ageMs, ++ pendingBytes: __pendingBytes ++ })); ++ __closeSseGracefully(); ++ return Promise.resolve(); ++ } ++ if (__pendingBytes + frame.byteLength > MAX_PENDING_SSE_BYTES) { ++ __abortSse(); ++ return Promise.resolve(); ++ } ++ __pendingBytes += frame.byteLength; ++ __writeChain = __writeChain.then(() => writer.write(frame)).catch(() => {}).finally(() => { ++ __pendingBytes -= frame.byteLength; ++ }); ++ return __writeChain; ++ }; ++ keepAlive = startKeepalive(__forwardSse, encoder); ++ ws.addEventListener("message", (event) => { + async function onMessage(event) { + try { + const message = JSON.parse(event.data); +- const result = JSONRPCMessageSchema.safeParse(message); +- if (!result.success) return; +- const messageText = `event: message\ndata: ${JSON.stringify(result.data)}\n\n`; +- await writer.write(encoder.encode(messageText)); +- } catch (error) { ++ const result = JSONRPCMessageSchema.safeParse(message); ++ if (!result.success) return; ++ const messageText = `event: message\ndata: ${JSON.stringify(result.data)}\n\n`; ++ __forwardSse(encoder.encode(messageText)); ++ } catch (error) { + console.error("Error forwarding message to SSE:", error); + } + } + onMessage(event).catch(console.error); + }); +- ws.addEventListener("error", (error) => { +- async function onError(_error) { +- try { +- await writer.close(); +- } catch (_e) {} ++ ws.addEventListener("error", (error) => { ++ async function onError(_error) { ++ try { ++ __sseClosed = true; ++ clearInterval(keepAlive); ++ await writer.close(); ++ } catch (_e) {} + } + onError(error).catch(console.error); + }); +- ws.addEventListener("close", () => { +- async function onClose() { +- try { +- await writer.close(); +- } catch (error) { ++ ws.addEventListener("close", () => { ++ async function onClose() { ++ try { ++ __sseClosed = true; ++ clearInterval(keepAlive); ++ await writer.close(); ++ } catch (error) { + console.error("Error closing SSE connection:", error); + } + } +@@ -634,7 +857,23 @@ var StreamableHTTPServerTransport = class { + } + this.supersedePriorStreamConnections(agent, connection.id, resumedStreamId); + connection.setState(resumeState); +- await this.replayEvents(lastEventId); ++ const ackStreamIds = []; ++ const replayedResponse = await this.replayEvents(lastEventId); ++ if (resumedStreamId !== STANDALONE_STREAM_ID && replayedResponse) ackStreamIds.push(resumedStreamId); ++ // A reconnect can carry a Last-Event-ID for an already-delivered ++ // stream (e.g. the initialize response) while a tool result ++ // completed on a since-abandoned POST stream. Replay those other ++ // undelivered responses on this connection too, otherwise they are ++ // stranded until the session is torn down. ++ ackStreamIds.push(...await this.replayUndeliveredResponses(agent, connection, resumedStreamId)); ++ // Storage is NOT cleared here: replayed events are only enqueued ++ // on the WS bridge, and workerd cannot tell a dead client from a ++ // live one at write time. The close frame below makes the bridge ++ // drain the writes, close the HTTP response, and send one ++ // cf_mcp_delivery_ack per replayed stream only if the client was ++ // still attached; McpAgent.onMessage clears storage on that ack. ++ // A dead recovery GET therefore leaves everything replayable. ++ if (ackStreamIds.length > 0) this.sendReplayComplete(connection, ackStreamIds); + return; + } + } +@@ -644,6 +883,26 @@ var StreamableHTTPServerTransport = class { + _standaloneSse: true + }; + connection.setState(standaloneState); ++ const replayedStreamIds = await this.replayUndeliveredResponses(agent, connection); ++ // Same delivery-confirmed clearing as the resume branch above. When ++ // nothing was replayed no close frame is sent and this connection stays ++ // open as the session's long-lived standalone listener. ++ if (replayedStreamIds.length > 0) this.sendReplayComplete(connection, replayedStreamIds); ++ } ++ /** ++ * Ask the Worker bridge to flush everything queued on `connection`, ++ * close the client-facing SSE response, and, only if the writer close ++ * completed with the client still attached, echo one ++ * `cf_mcp_delivery_ack` per stream id in `ackStreamIds`. The event ++ * payload is an SSE comment so client parsers drop it. ++ */ ++ sendReplayComplete(connection, ackStreamIds) { ++ return connection.send(JSON.stringify({ ++ type: "cf_mcp_agent_event", ++ event: ": replay-complete\n\n", ++ ackStreamIds, ++ close: true ++ })); + } + /** + * Close any connection (other than `selfId`) currently bound to +@@ -664,12 +923,14 @@ var StreamableHTTPServerTransport = class { + * Only used when resumability is enabled + */ + async replayEvents(lastEventId) { +- if (!this._eventStore) return; ++ if (!this._eventStore) return false; + const { connection } = getCurrentAgent(); + if (!connection) throw new Error("Connection was not available in replayEvents"); ++ let replayedResponse = false; + try { + await this._eventStore?.replayEventsAfter(lastEventId, { send: async (eventId, message) => { + try { ++ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) replayedResponse = true; + this.writeSSEEvent(connection, message, eventId); + } catch (error) { + this.onerror?.(error); +@@ -678,6 +939,33 @@ var StreamableHTTPServerTransport = class { + } catch (error) { + this.onerror?.(error); + } ++ return replayedResponse; ++ } ++ /** ++ * Enqueue every undelivered stream's events on `connection` and return ++ * the stream ids whose replay included a response. Deliberately does ++ * NOT clear storage: the caller sends a replay-complete close frame and ++ * the bridge acks each stream only after the client-facing writer ++ * drained and closed with the client still attached. ++ */ ++ async replayUndeliveredResponses(agent, connection, skipStreamId) { ++ const replayedStreamIds = []; ++ if (!this._eventStore?.replayEventsForStream) return replayedStreamIds; ++ const streamIds = await agent.getUndeliveredStreamIds(); ++ for (const streamId of streamIds) { ++ if (skipStreamId !== void 0 && streamId === skipStreamId) continue; ++ let replayedResponse = false; ++ await this._eventStore.replayEventsForStream(streamId, { send: async (eventId, message) => { ++ try { ++ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) replayedResponse = true; ++ this.writeSSEEvent(connection, message, eventId); ++ } catch (error) { ++ this.onerror?.(error); ++ } ++ } }); ++ if (replayedResponse) replayedStreamIds.push(streamId); ++ } ++ return replayedStreamIds; + } + /** + * Writes an event to the SSE stream with proper formatting +@@ -689,10 +977,65 @@ var StreamableHTTPServerTransport = class { + return connection.send(JSON.stringify({ + type: "cf_mcp_agent_event", + event: eventData, ++ eventId, ++ streamId: eventId ? eventId.slice(0, eventId.lastIndexOf(":")) : void 0, + close + })); + } + /** ++ * Persist and write the priming SSE event for a freshly opened POST ++ * stream. The stored message is a benign JSON-RPC notification so that ++ * if a plain recovery GET ever replays this stream via ++ * {@link writeSSEEvent} (which forces `event: message`), a compliant ++ * client parses and ignores it rather than erroring. The live priming ++ * frame, however, uses a non-`message` SSE event type so the SDK ++ * records the id (setting hasPrimingEvent / lastEventId) WITHOUT ++ * dispatching it as a JSON-RPC message: its SSE loop skips any event ++ * whose type is not `message`. A data line is required because the ++ * SDK's SSE parser drops events with empty data before recording the ++ * id, so an id-only frame would not prime. ++ */ ++ async emitPrimingEvent(agent, connection, streamId) { ++ if (!this._eventStore) return; ++ const primingMessage = { ++ jsonrpc: "2.0", ++ method: "notifications/message", ++ params: { ++ level: "debug", ++ data: "mcp-stream-priming" ++ } ++ }; ++ let eventId; ++ try { ++ eventId = await this._eventStore.storeEvent(streamId, primingMessage); ++ } catch (error) { ++ this.onerror?.(error); ++ return; ++ } ++ if (!eventId) return; ++ try { ++ this.writePrimingSSEEvent(connection, primingMessage, eventId); ++ } catch (error) { ++ this.onerror?.(error); ++ } ++ } ++ /** ++ * Write a priming SSE frame: `event: mcp-priming`, an `id:` carrying a ++ * real replayable event-store id, and a data line the SDK ignores ++ * because the event type is not `message`. Never sets `close`. ++ */ ++ writePrimingSSEEvent(connection, message, eventId) { ++ let eventData = "event: mcp-priming\n"; ++ eventData += `id: ${eventId}\n`; ++ eventData += `data: ${JSON.stringify(message)}\n\n`; ++ return connection.send(JSON.stringify({ ++ type: "cf_mcp_agent_event", ++ event: eventData, ++ eventId, ++ streamId: eventId.slice(0, eventId.lastIndexOf(":")) ++ })); ++ } ++ /** + * Handles POST requests containing JSON-RPC messages + */ + async handlePostRequest(req, parsedBody) { +@@ -733,6 +1076,22 @@ var StreamableHTTPServerTransport = class { + }; + connection.setState(postState); + if (this._eventStore) await agent.setStreamRequestIds(streamId, requestIds); ++ // Emit a priming SSE event as the very first frame on this POST ++ // response stream, before dispatching the request(s). The MCP TS SDK ++ // only auto-reconnects a dropped POST SSE stream when it saw an event ++ // `id:` before the drop (hasPrimingEvent). Without this, a network ++ // blip or edge close mid-call leaves the SDK with hasPrimingEvent ++ // false, so it never issues the recovery GET that replays the ++ // persisted result, and callTool hangs forever. The priming event is ++ // a real event-store entry so its id sorts BEFORE the eventual ++ // response; a reconnect with `last-event-id: ` replays ++ // everything after it (i.e. the result). See patches/agents patch. ++ // Scoped to tools/call streams: reconnect-with-replay only matters ++ // where the result can outlive the connection (long-running tool ++ // calls). initialize/tools/list resolve in milliseconds and clients ++ // retry them; priming those streams adds a storage write and an ++ // extra SSE frame per request for nothing. ++ if (messages.some((message) => isJSONRPCRequest(message) && message.method === "tools/call")) await this.emitPrimingEvent(agent, connection, streamId); + for (const message of messages) { + if (this.messageInterceptor) { + if (await this.messageInterceptor(message, { +@@ -760,7 +1119,22 @@ var StreamableHTTPServerTransport = class { + * when the originating WS has dropped. + */ + async sendOnStream(agent, streamId, relatedIds, liveConnection, message, requestId) { +- const eventId = await this._eventStore?.storeEvent(streamId, message); ++ // Persistence is best-effort and must never block live delivery: a ++ // storeEvent failure (storage cap, storage outage) used to throw here, ++ // before writeSSEEvent, so the response was neither stored NOR sent and ++ // the client hung on keepalives. Deliver-live-first; a message without ++ // an eventId just isn't replayable after a drop. ++ let eventId; ++ try { ++ eventId = await this._eventStore?.storeEvent(streamId, message); ++ } catch (error) { ++ console.warn(JSON.stringify({ ++ event: "mcp_event_store_put_failed", ++ streamId, ++ error: String(error) ++ })); ++ this.onerror?.(error); ++ } + let shouldClose = false; + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + let responseIds = this._streamResponseIds.get(streamId); +@@ -777,9 +1151,11 @@ var StreamableHTTPServerTransport = class { + } catch (error) { + this.onerror?.(error); + } +- if (shouldClose) { ++ if (shouldClose && !this._eventStore) { ++ await agent.deleteStreamRequestIds(streamId); ++ } else if (shouldClose) { ++ await agent.markStreamUndelivered(streamId); + await agent.deleteStreamRequestIds(streamId); +- if (this._eventStore && isClearableEventStore(this._eventStore)) await this._eventStore.clearStream(streamId); + } + } + async send(message, options) { +@@ -861,12 +1237,10 @@ var StreamableHTTPServerTransport = class { + * + * ## Lifecycle + * +-* Each POST tool-call stream's events live only until the final +-* response is delivered. The transport calls {@link clearStream} +-* immediately after writing the close frame, so storage growth is +-* bounded by the in-flight POST streams plus the standalone GET +-* stream. There is no background sweep — quiescent agents do no work, +-* and the DO itself dies with the session. ++* Each POST tool-call stream's response events live until the Worker ++* bridge confirms the final SSE write or a reconnect GET replays them. ++* Per-stream storage is capped at 64 events or roughly 2 MB; oldest ++* entries are evicted first. + * + * Standalone GET stream events (`_GET_stream`) are *not* cleared + * automatically; they accumulate for the lifetime of the DO. Bounded +@@ -893,12 +1267,34 @@ var DurableObjectEventStore = class DurableObjectEventStore { + } + async storeEvent(streamId, message) { + if (streamId.includes(":")) throw new Error(`DurableObjectEventStore: streamId must not contain ':' (got ${JSON.stringify(streamId)})`); ++ // DO storage caps each value at 128 KiB; storage.put of a larger ++ // message throws, and before this guard that throw escaped through ++ // sendOnStream BEFORE the live SSE write, so an oversize response ++ // (e.g. the ~5MB ui:// shell document) was never delivered at all — ++ // the client saw only keepalives. Skip persistence instead: the ++ // event is delivered live without a replay id, which is strictly ++ // better than never delivering it. Undeliverable-if-dropped is the ++ // documented cost, logged so it is visible. ++ let messageBytes = 0; ++ try { ++ messageBytes = new TextEncoder().encode(JSON.stringify(message)).byteLength; ++ } catch {} ++ if (messageBytes > DurableObjectEventStore.MAX_STORABLE_EVENT_BYTES) { ++ console.warn(JSON.stringify({ ++ event: "mcp_event_store_skipped_oversize", ++ streamId, ++ messageBytes, ++ limit: DurableObjectEventStore.MAX_STORABLE_EVENT_BYTES ++ })); ++ return void 0; ++ } + await this.ensureSeqLoaded(streamId); + const seq = (this.seqByStream.get(streamId) ?? 0) + 1; + this.seqByStream.set(streamId, seq); + const eventId = `${streamId}:${seq.toString(16).padStart(DurableObjectEventStore.SEQ_PAD, "0")}`; + const eventKey = `${DurableObjectEventStore.EVENT_KEY_PREFIX}${eventId}`; + await this.storage.put(eventKey, message); ++ await this.trimStream(streamId); + return eventId; + } + async getStreamIdForEventId(eventId) { +@@ -915,9 +1311,59 @@ var DurableObjectEventStore = class DurableObjectEventStore { + start: startKey, + limit: DurableObjectEventStore.REPLAY_LIMIT + }); +- for (const [key, message] of rows) await send(key.slice(DurableObjectEventStore.EVENT_KEY_PREFIX.length), message); ++ for (const [key, message] of rows) try { ++ await send(key.slice(DurableObjectEventStore.EVENT_KEY_PREFIX.length), message); ++ } catch {} ++ return streamId; ++ } ++ async replayEventsForStream(streamId, { send }) { ++ const prefix = `${DurableObjectEventStore.EVENT_KEY_PREFIX}${streamId}:`; ++ const rows = await this.storage.list({ ++ prefix, ++ limit: DurableObjectEventStore.REPLAY_LIMIT ++ }); ++ for (const [key, message] of rows) try { ++ await send(key.slice(DurableObjectEventStore.EVENT_KEY_PREFIX.length), message); ++ } catch {} + return streamId; + } ++ async trimStream(streamId) { ++ const prefix = `${DurableObjectEventStore.EVENT_KEY_PREFIX}${streamId}:`; ++ const rows = await this.storage.list({ ++ prefix, ++ limit: DurableObjectEventStore.REPLAY_LIMIT ++ }); ++ let totalBytes = 0; ++ const entries = [...rows].map(([key, message]) => { ++ let bytes = DurableObjectEventStore.MAX_EVENT_BYTES; ++ try { ++ bytes = new TextEncoder().encode(JSON.stringify(message)).byteLength; ++ } catch {} ++ totalBytes += bytes; ++ return { key, bytes }; ++ }); ++ const deleteKeys = []; ++ // Never evict the newest entry: trimStream runs right after storeEvent ++ // put it, and for a final tool response it is the only copy a recovery ++ // GET can replay. An oversize final response is kept even past the byte ++ // cap; the cap then squeezes out older events instead. ++ while (entries.length > 1 && (entries.length > DurableObjectEventStore.MAX_EVENTS_PER_STREAM || totalBytes > DurableObjectEventStore.MAX_BYTES_PER_STREAM)) { ++ const evicted = entries.shift(); ++ if (!evicted) break; ++ deleteKeys.push(evicted.key); ++ totalBytes -= evicted.bytes; ++ } ++ if (deleteKeys.length > 0) { ++ console.warn(JSON.stringify({ ++ event: "mcp_event_store_evicted", ++ streamId, ++ evictedCount: deleteKeys.length, ++ remainingCount: entries.length, ++ remainingBytes: totalBytes ++ })); ++ for (let i = 0; i < deleteKeys.length; i += DurableObjectEventStore.DELETE_CHUNK) await this.storage.delete(deleteKeys.slice(i, i + DurableObjectEventStore.DELETE_CHUNK)); ++ } ++ } + /** + * Drop the event log for a single stream. Called by the transport + * immediately after a POST's final response has been written to the +@@ -973,6 +1419,13 @@ DurableObjectEventStore.EVENT_KEY_PREFIX = "__mcp_event__:"; + DurableObjectEventStore.SEQ_PAD = 16; + DurableObjectEventStore.DELETE_CHUNK = 128; + DurableObjectEventStore.REPLAY_LIMIT = 1e3; ++DurableObjectEventStore.MAX_EVENTS_PER_STREAM = 64; ++DurableObjectEventStore.MAX_BYTES_PER_STREAM = 2 * 1024 * 1024; ++DurableObjectEventStore.MAX_EVENT_BYTES = 2 * 1024 * 1024; ++// DO storage's per-value hard cap is 128 KiB. The JSON byte length measured in ++// storeEvent is a close proxy for the runtime's serialized size; the margin ++// below it absorbs the difference. Anything larger is delivered live only. ++DurableObjectEventStore.MAX_STORABLE_EVENT_BYTES = 120 * 1024; + //#endregion + //#region src/mcp/client-transports.ts + /** +@@ -1381,6 +1834,47 @@ var McpAgent = class McpAgent extends Agent { + async deleteStreamRequestIds(streamId) { + await this.ctx.storage.delete(`${McpAgent.STREAM_REQS_KEY_PREFIX}${streamId}`); + } ++ async markStreamUndelivered(streamId) { ++ await this.ctx.storage.put(`${McpAgent.UNDELIVERED_STREAM_KEY_PREFIX}${streamId}`, true); ++ } ++ async deleteUndeliveredStream(streamId) { ++ await this.ctx.storage.delete(`${McpAgent.UNDELIVERED_STREAM_KEY_PREFIX}${streamId}`); ++ } ++ async getUndeliveredStreamIds() { ++ const rows = await this.ctx.storage.list({ ++ prefix: McpAgent.UNDELIVERED_STREAM_KEY_PREFIX, ++ limit: 1e3 ++ }); ++ return [...rows.keys()].map((key) => key.slice(McpAgent.UNDELIVERED_STREAM_KEY_PREFIX.length)); ++ } ++ /** List persisted POST stream request ids for replay and idle accounting. @internal */ ++ async getOpenStreamRequestIds() { ++ const rows = await this.ctx.storage.list({ ++ prefix: McpAgent.STREAM_REQS_KEY_PREFIX, ++ limit: 1e3 ++ }); ++ return [...rows].flatMap(([key, requestIds]) => Array.isArray(requestIds) && requestIds.length > 0 ? [{ ++ streamId: key.slice(McpAgent.STREAM_REQS_KEY_PREFIX.length), ++ requestIds ++ }] : []); ++ } ++ async acknowledgeDeliveredStream(streamId) { ++ await this.deleteStreamRequestIds(streamId); ++ await this.deleteUndeliveredStream(streamId); ++ const eventStore = this._transport?.["_eventStore"]; ++ if (eventStore && isClearableEventStore(eventStore)) await eventStore.clearStream(streamId); ++ } ++ async onMessage(connection, message) { ++ if (typeof message !== "string") return super.onMessage(connection, message); ++ try { ++ const parsed = JSON.parse(message); ++ if (parsed?.type === "cf_mcp_delivery_ack" && typeof parsed.streamId === "string") { ++ await this.acknowledgeDeliveredStream(parsed.streamId); ++ return; ++ } ++ } catch {} ++ return super.onMessage(connection, message); ++ } + /** + * Reverse lookup: find which POST stream a given `requestId` belongs + * to, and return the stream's full `requestIds` list in the same +@@ -1697,7 +2191,8 @@ var McpAgent = class McpAgent extends Agent { + } + }; + McpAgent.STREAM_REQS_KEY_PREFIX = "__mcp_stream_reqs__:"; ++McpAgent.UNDELIVERED_STREAM_KEY_PREFIX = "__mcp_undelivered_stream__:"; + //#endregion +-export { DurableObjectEventStore, ElicitRequestSchema, MCP_SERVER_ID_MAX_LENGTH, McpAgent, RPCClientTransport, RPCServerTransport, RPC_DO_PREFIX, SSEEdgeClientTransport, StreamableHTTPEdgeClientTransport, WorkerTransport, createMcpHandler, experimental_createMcpHandler, getMcpAuthContext, normalizeServerId }; ++export { DurableObjectEventStore, ElicitRequestSchema, MAX_SSE_AGE_MS, MCP_SERVER_ID_MAX_LENGTH, McpAgent, RPCClientTransport, RPCServerTransport, RPC_DO_PREFIX, SSEEdgeClientTransport, StreamableHTTPEdgeClientTransport, WorkerTransport, createMcpHandler, experimental_createMcpHandler, getMcpAuthContext, normalizeServerId }; + + //# sourceMappingURL=index.js.map +\ No newline at end of file diff --git a/scripts/bootstrap.ts b/scripts/bootstrap.ts index 2527e5a3bb..a290803705 100644 --- a/scripts/bootstrap.ts +++ b/scripts/bootstrap.ts @@ -23,7 +23,11 @@ const run = (label: string, cmd: string, args: ReadonlyArray) => { // apps' vite dev servers fail without in a fresh worktree. run("dependencies (+ prepare builds)", "bun", ["install"]); -// Catch patched-dependency entries whose checked-in patch file was removed. +// Assert load-bearing patched dependencies actually installed in patched form. +// A bun cache edge case can leave a stale, unpatched dist in node_modules even +// though the lockfile records the patch (bun reports "no changes"). That would +// silently drop the agents MCP transport hang fix; fail here so a fresh +// checkout or worktree surfaces it immediately instead of at deploy time. run("verify patched deps", "bun", ["run", "scripts/check-patched-deps.ts"]); // e2e browser scenarios need Playwright's chromium; the cache is shared diff --git a/scripts/check-patched-deps.ts b/scripts/check-patched-deps.ts index 6e01649a19..7f982c0547 100644 --- a/scripts/check-patched-deps.ts +++ b/scripts/check-patched-deps.ts @@ -1,5 +1,35 @@ #!/usr/bin/env bun -/** Verify that every root patched-dependency entry still names a real file. */ +/** + * Asserts that patched dependencies are actually installed in patched form. + * + * We patch several npm packages via `bun patch` (see `patchedDependencies` in + * package.json and the `patches/*.patch` files). At least one of these patches + * is load-bearing at runtime, not just a build-time convenience: the + * `agents@0.17.3` patch carries the MCP transport persist/replay fix (the SSE + * "hang" fix that preserves tool results across dropped connections). If the + * installed `agents` dist is the STALE, unpatched upstream build, everything + * still compiles and tests mostly pass while the deployed transport silently + * lacks the fix, so prod ships the pre-fix transport with zero signal. + * + * This has actually happened: a bun cache edge case left a checkout with an + * unpatched `agents` dist in node_modules even though the lockfile and + * package.json recorded the patch. `bun install` reported no changes because + * the store entry it wanted was already present; it just wasn't the patched + * content. + * + * So we don't trust the lockfile — we read the installed dist off disk and + * assert the post-patch sentinel strings are present. The check is a couple of + * file reads plus greps, so it adds ~zero wall-clock time and is safe to run in + * CI before the test job and in `bootstrap` on every fresh checkout. + * + * Usage: + * bun run scripts/check-patched-deps.ts + * + * Env overrides (used by the self-test): + * CHECK_PATCHED_DEPS_AGENTS_MCP=/abs/path/to/agents/dist/mcp/index.js + * Force the agents MCP entry path instead of resolving it, so the self-test + * can point the check at a deliberately-corrupted copy. + */ import { existsSync, readFileSync } from "node:fs"; import { resolve } from "node:path"; @@ -8,26 +38,121 @@ const repoRoot = resolve(import.meta.dir, ".."); type Failure = { readonly package: string; readonly detail: string }; const failures: Failure[] = []; +/** + * Each patched package whose *runtime content* we assert against. Sentinels are + * identifiers that exist only in the patched dist (added by the patch), so + * their presence proves the installed file is the patched one, not a stale + * upstream build. Keep sentinels to a couple of stable, patch-unique symbols. + */ +type RuntimeCheck = { + readonly package: string; + /** Resolve the installed entry file we assert against. */ + readonly resolveEntry: () => string; + /** Strings that only appear post-patch. All must be present. */ + readonly sentinels: readonly string[]; + /** Human hint for what the patch does, shown on failure. */ + readonly purpose: string; +}; + +/** + * Resolve a subpath export of a dependency robustly, without hardcoding the + * bun store hash in `node_modules/.bun/@+/…`. We resolve + * from a workspace package that actually depends on it so the module graph is + * the real one; `require.resolve` then walks bun's store for us. + */ +const resolveFrom = (specifier: string, fromPackageDir: string): string => { + const fromDir = resolve(repoRoot, fromPackageDir); + return require.resolve(specifier, { paths: [fromDir] }); +}; + +const runtimeChecks: readonly RuntimeCheck[] = [ + { + package: "agents@0.17.3 (agents/mcp)", + purpose: + "MCP transport persist/replay fix (preserves tool results across dropped SSE connections)", + resolveEntry: () => { + const override = process.env.CHECK_PATCHED_DEPS_AGENTS_MCP; + if (override && override.length > 0) return resolve(override); + // `packages/hosts/cloudflare` is the workspace package that depends on + // `agents`, so resolve the `agents/mcp` export from there. + return resolveFrom("agents/mcp", "packages/hosts/cloudflare"); + }, + // These identifiers are introduced by patches/agents@0.17.3.patch and do + // not exist in the upstream 0.17.3 dist. + sentinels: ["markStreamUndelivered", "replayUndeliveredResponses"], + }, +]; + +for (const check of runtimeChecks) { + let entry: string; + try { + entry = check.resolveEntry(); + } catch (err) { + failures.push({ + package: check.package, + detail: `could not resolve installed entry: ${(err as Error).message.split("\n")[0]}`, + }); + continue; + } + + if (!existsSync(entry)) { + failures.push({ package: check.package, detail: `installed entry does not exist: ${entry}` }); + continue; + } + + const contents = readFileSync(entry, "utf8"); + const missing = check.sentinels.filter((s) => !contents.includes(s)); + if (missing.length > 0) { + failures.push({ + package: check.package, + detail: + `installed dist is missing post-patch sentinel(s): ${missing.join(", ")}\n` + + ` entry: ${entry}\n` + + ` patch purpose: ${check.purpose}`, + }); + } +} + +/** + * Lightweight generalized layer: every package listed in `patchedDependencies` + * must still have its referenced patch file on disk. This does not verify the + * installed *content* for packages without a dedicated runtime check above + * (that requires per-package sentinels), but it catches a patch entry pointing + * at a missing file, which would make `bun install` silently skip patching. + */ const rootPkg = JSON.parse(readFileSync(resolve(repoRoot, "package.json"), "utf8")) as { patchedDependencies?: Record; }; -for (const [dependency, patchPath] of Object.entries(rootPkg.patchedDependencies ?? {})) { - if (existsSync(resolve(repoRoot, patchPath))) continue; - failures.push({ - package: dependency, - detail: `patchedDependencies references a missing patch file: ${patchPath}`, - }); +for (const [dep, patchPath] of Object.entries(rootPkg.patchedDependencies ?? {})) { + const abs = resolve(repoRoot, patchPath); + if (!existsSync(abs)) { + failures.push({ + package: dep, + detail: `patchedDependencies references a missing patch file: ${patchPath}`, + }); + } } if (failures.length > 0) { - const lines = failures.map((failure) => ` - ${failure.package}: ${failure.detail}`).join("\n"); + const lines = failures.map((f) => ` - ${f.package}: ${f.detail}`).join("\n"); console.error( `\nPatched-dependency check FAILED (${failures.length} problem(s)):\n${lines}\n\n` + - "Every patchedDependencies entry must reference a checked-in patch file.\n", + "Cause: the installed dependency content does not match the patch we ship.\n" + + "This is usually a stale bun store entry: bun kept an unpatched build of the\n" + + "package in its cache and `bun install` reported no changes without applying\n" + + "the patch. The deployed/tested code then silently lacks the patched behavior\n" + + "(for `agents`, the MCP transport hang fix), with no other signal.\n\n" + + "Fix: force a clean reinstall of the affected package's store entry, e.g.\n" + + " rm -rf node_modules/.bun/agents@* node_modules/agents\n" + + " bun install\n" + + "If that does not take, clear bun's global cache for it:\n" + + " bun pm cache rm\n" + + " bun install\n", ); process.exit(1); } console.log( - `Patched-dependency check passed: ${Object.keys(rootPkg.patchedDependencies ?? {}).length} patch file(s) present.`, + `Patched-dependency check passed: ${runtimeChecks.length} runtime sentinel check(s), ` + + `${Object.keys(rootPkg.patchedDependencies ?? {}).length} patch file(s) present.`, );