The Open Framework for Building Agents
feat(eve): add durable MCP agent channel (#2049)
Allen Zhou5ba9749643ae
diff --git a/.changeset/tidy-mice-invoke.md b/.changeset/tidy-mice-invoke.mdnew file mode 100644index 000000000..58a7fa782--- /dev/null+++ b/.changeset/tidy-mice-invoke.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add a secure MCP channel that reuses eve route auth and lets clients start, inspect, update, authorize, and cancel principal-bound durable agent invocations over MCP 2026-07-28 with a stateless 2025 compatibility path.diff --git a/packages/eve/package.json b/packages/eve/package.jsonindex 6d9183645..11a1a2701 100644--- a/packages/eve/package.json+++ b/packages/eve/package.json@@ -231,6 +231,11 @@"import": "./dist/src/public/channels/auth.js","default": "./dist/src/public/channels/auth.js"},+ "./channels/mcp": {+ "types": "./dist/src/public/channels/mcp.d.ts",+ "import": "./dist/src/public/channels/mcp.js",+ "default": "./dist/src/public/channels/mcp.js"+ },"./channels/slack": {"types": "./dist/src/public/channels/slack/index.d.ts","import": "./dist/src/public/channels/slack/index.js",@@ -331,6 +336,7 @@"@chat-adapter/twilio": "4.34.0","@clack/core": "1.3.1","@eve/catalog": "workspace:*",+ "@modelcontextprotocol/server": "2.0.0","@nuxt/kit": "^4.0.0","@opentelemetry/context-async-hooks": "catalog:","@opentelemetry/core": "catalog:",diff --git a/packages/eve/scripts/vendor-compiled/@modelcontextprotocol/server.mjs b/packages/eve/scripts/vendor-compiled/@modelcontextprotocol/server.mjsnew file mode 100644index 000000000..ecaea6b9f--- /dev/null+++ b/packages/eve/scripts/vendor-compiled/@modelcontextprotocol/server.mjs@@ -0,0 +1,111 @@+export default {+ packageName: "@modelcontextprotocol/server",+ compiledPath: "@modelcontextprotocol/server",+ chunkGroup: "workflow",+ entries: [+ {+ entry: "dist/index.mjs",+ outputPath: "index",+ declaration: `+export interface CallToolRequest {+ readonly params: {+ readonly arguments?: Readonly<Record<string, unknown>>;+ readonly name: string;+ };+}++export interface McpRequestHandlerExtra {+ readonly mcpReq: {+ readonly signal: AbortSignal;+ };+}++export interface McpToolAnnotations {+ readonly destructiveHint?: boolean;+ readonly idempotentHint?: boolean;+ readonly openWorldHint?: boolean;+ readonly readOnlyHint?: boolean;+}++export interface StandardSchemaWithJSON<TInput = unknown, TOutput = TInput> {+ readonly "~standard": {+ readonly types?: { readonly input: TInput; readonly output: TOutput };+ };+}++export declare class Server {+ constructor(info: { readonly name: string; readonly version: string }, options?: {+ readonly capabilities?: Readonly<Record<string, unknown>>;+ });+ setRequestHandler<Result>(+ method: "tools/list",+ handler: (+ request: { readonly params: Readonly<Record<string, unknown>> },+ context: McpRequestHandlerExtra,+ ) => Result | Promise<Result>,+ ): void;+ setRequestHandler<Result>(+ method: "tools/call",+ handler: (+ request: CallToolRequest,+ context: McpRequestHandlerExtra,+ ) => Result | Promise<Result>,+ ): void;+}++export declare class McpServer {+ constructor(info: { readonly name: string; readonly version: string }, options?: {+ readonly capabilities?: Readonly<Record<string, unknown>>;+ });+ registerTool<TInput = unknown, TOutput = TInput>(+ name: string,+ config: {+ readonly annotations?: McpToolAnnotations;+ readonly description?: string;+ readonly inputSchema: StandardSchemaWithJSON<TInput, TOutput>;+ readonly outputSchema?: StandardSchemaWithJSON;+ },+ callback: (+ input: TOutput,+ context: McpRequestHandlerExtra,+ ) => unknown | Promise<unknown>,+ ): void;+}++export interface McpRequestContext {+ readonly era: "legacy" | "modern";+ readonly requestInfo: Request;+}++export interface McpHandler {+ close(): Promise<void>;+ fetch(request: Request, options?: { readonly parsedBody?: unknown }): Promise<Response>;+}++export declare function fromJsonSchema<T = unknown>(+ schema: Readonly<Record<string, unknown>>,+): StandardSchemaWithJSON<T, T>;++export declare function hostHeaderValidationResponse(+ request: Request,+ allowedHostnames: readonly string[],+): Response | undefined;++export declare function originValidationResponse(+ request: Request,+ allowedOriginHostnames: readonly string[],+): Response | undefined;++export declare function createMcpHandler(+ factory: (context: McpRequestContext) => McpServer | Server | Promise<McpServer | Server>,+ options?: {+ readonly legacy?: "reject" | "stateless";+ readonly onerror?: (error: Error) => void;+ readonly responseMode?: "auto" | "json" | "stream";+ },+): McpHandler;+`,+ },+ ],+ platform: "neutral",+};diff --git a/packages/eve/scripts/vendor-compiled/index.mjs b/packages/eve/scripts/vendor-compiled/index.mjsindex 3bae2d10e..82b2dec03 100644--- a/packages/eve/scripts/vendor-compiled/index.mjs+++ b/packages/eve/scripts/vendor-compiled/index.mjs@@ -17,6 +17,7 @@ import chatAdapterStateMemory from "./@chat-adapter/state-memory.mjs";import chatAdapterTwilio from "./@chat-adapter/twilio.mjs";import photonChatAdapterIMessage from "./@photon-ai/chat-adapter-imessage.mjs";+import modelContextProtocolServer from "./@modelcontextprotocol/server.mjs";import opentelemetryApi from "./@opentelemetry/api.mjs";import opentelemetryOtlpTransformer from "./@opentelemetry/otlp-transformer.mjs";import standardSchemaSpec from "./@standard-schema/spec.mjs";@@ -69,6 +70,7 @@ export const MODULES = [jsonSchema,marked,mcp,+ modelContextProtocolServer,openai,opentelemetryApi,opentelemetryOtlpTransformer,diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.tsindex 3423da280..76b07e657 100644--- a/packages/eve/src/channel/routes.ts+++ b/packages/eve/src/channel/routes.ts@@ -168,9 +168,9 @@ export interface WebSocketRouteDefinition<TState = undefined> {/*** A single channel route: either an {@link HttpRouteDefinition} or a- * {@link WebSocketRouteDefinition}. Produced by the {@link GET}, {@link POST},- * {@link PUT}, {@link PATCH}, {@link DELETE}, and {@link WS} helpers and listed- * in a channel's `routes` array.+ * {@link WebSocketRouteDefinition}. Produced by the {@link GET}, {@link HEAD},+ * {@link POST}, {@link PUT}, {@link PATCH}, {@link DELETE}, {@link OPTIONS},+ * and {@link WS} helpers and listed in a channel's `routes` array.*/export type RouteDefinition<TState = undefined> =| HttpRouteDefinition<TState>@@ -187,6 +187,17 @@ export function GET<TState = undefined>(return { transport: "http", method: "GET", path, handler };}+/**+ * Declares an HTTP `HEAD` route at `path`. See {@link GET} for the handler+ * contract.+ */+export function HEAD<TState = undefined>(+ path: string,+ handler: RouteHandler<TState>,+): HttpRouteDefinition<TState> {+ return { transport: "http", method: "HEAD", path, handler };+}+/*** Declares an HTTP `POST` route at `path`. See {@link GET} for the handler* contract.@@ -231,6 +242,17 @@ export function DELETE<TState = undefined>(return { transport: "http", method: "DELETE", path, handler };}+/**+ * Declares an HTTP `OPTIONS` route at `path`. See {@link GET} for the handler+ * contract.+ */+export function OPTIONS<TState = undefined>(+ path: string,+ handler: RouteHandler<TState>,+): HttpRouteDefinition<TState> {+ return { transport: "http", method: "OPTIONS", path, handler };+}+/*** Declares a WebSocket channel route.*diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex fa49abd6e..129bda700 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -461,6 +461,11 @@ export interface RunInput {* parent depth + 1.*/readonly subagentDepth?: number;+ /** Framework-owned metadata for a protocol-neutral external invocation. */+ readonly externalInvocation?: {+ readonly continuationToken: string;+ readonly ownerKey: string;+ };}export interface DeliverInput {diff --git a/packages/eve/src/compiler/manifest.test.ts b/packages/eve/src/compiler/manifest.test.tsindex 9e63883c7..5ad6394a4 100644--- a/packages/eve/src/compiler/manifest.test.ts+++ b/packages/eve/src/compiler/manifest.test.ts@@ -9,6 +9,35 @@ import {import { classifyModelRouting } from "#internal/classify-model-routing.js";describe("compiledAgentManifestSchema", () => {+ it("accepts authored HEAD and OPTIONS channel routes", () => {+ const channel = {+ adapterKind: "mcp",+ kind: "channel" as const,+ logicalPath: "channels/mcp.ts",+ name: "mcp",+ sourceId: "channel-mcp",+ sourceKind: "module" as const,+ urlPath: "/.well-known/oauth-protected-resource",+ };+ const manifest = createCompiledAgentManifest({+ agentRoot: "/app/agent",+ appRoot: "/app",+ channels: [+ { ...channel, method: "HEAD" },+ { ...channel, method: "OPTIONS" },+ ],+ config: {+ model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },+ name: "app",+ },+ });++ const parsed = compiledAgentManifestSchema.parse(manifest);+ expect(+ parsed.channels.map((entry) => (entry.kind === "channel" ? entry.method : null)),+ ).toEqual(["HEAD", "OPTIONS"]);+ });+it("requires exactly one static description or dynamic resolver for each subagent", () => {const manifest = createCompiledAgentManifest({agentRoot: "/app/agent",diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex 2d224ca9c..e86aaf598 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -316,10 +316,12 @@ const compiledDynamicModelDefinitionSchema: z.ZodType<CompiledDynamicModelDefiniconst channelMethodSchema = z.union([z.literal("GET"),+ z.literal("HEAD"),z.literal("POST"),z.literal("PUT"),z.literal("PATCH"),z.literal("DELETE"),+ z.literal("OPTIONS"),z.literal("WEBSOCKET"),]);diff --git a/packages/eve/src/execution/eve-workflow-attributes.ts b/packages/eve/src/execution/eve-workflow-attributes.tsindex 4e76b0e13..826719c9c 100644--- a/packages/eve/src/execution/eve-workflow-attributes.ts+++ b/packages/eve/src/execution/eve-workflow-attributes.ts@@ -23,6 +23,8 @@* - `$eve.trigger` — channel adapter kind (session/subagent rows)* - `$eve.title` — truncated session title from the first user message* - `$eve.channel_request_id` — inbound channel request id+ * - `$eve.invocation_token` — channel-local continuation token for an external invocation+ * - `$eve.invocation_owner` — SHA-256 fingerprint of the invocation's initiating principal*/import { ChannelRequestIdKey } from "#context/keys.js";diff --git a/packages/eve/src/execution/session-command-inbox.ts b/packages/eve/src/execution/session-command-inbox.tsindex 997442d31..ae29c093e 100644--- a/packages/eve/src/execution/session-command-inbox.ts+++ b/packages/eve/src/execution/session-command-inbox.ts@@ -95,7 +95,6 @@ export function createSessionCommandInbox(): SessionCommandInboxHandle {let offered: Promise<IteratorResult<SessionInboxPayload>> | null = null;let offeredRead: HookRead | undefined;let wake: (() => void) | undefined;-const enqueue = (read: HookRead): void => {ready.push(read);ready.sort((left, right) => left.order - right.order);diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex c229f7524..3d8dbd1d9 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -48,6 +48,7 @@ import { parseNdjsonStream } from "#execution/ndjson-stream.js";import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";import type { WorkflowEntryInput } from "#execution/workflow-entry.js";import { walkCauseChain } from "#shared/errors.js";+import { buildInvocationAttributes } from "#internal/invocation/metadata.js";import { sessionCommandHookToken } from "#execution/session-command-token.js";import { sendCommandToDelivery } from "#execution/session-command-wire.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";@@ -145,8 +146,7 @@ export function createWorkflowRuntime(config: {if (sessionTimeoutMs !== undefined) {workflowInput.sessionTimeoutMs = sessionTimeoutMs;}-- const attributes =+ const sessionAttributes =parentLineage.sessionId === undefined? buildSessionAttributes({inputMessage: input.title ?? input.input.message,@@ -160,6 +160,12 @@ export function createWorkflowRuntime(config: {rootSessionId: parentLineage.rootSessionId ?? parentLineage.sessionId,serializedContext,});+ const attributes = {+ ...sessionAttributes,+ ...(input.externalInvocation === undefined+ ? {}+ : buildInvocationAttributes(input.externalInvocation)),+ };let run: Awaited<ReturnType<typeof startWorkflowPreferLatest>>;try {diff --git a/packages/eve/src/internal/invocation/agent-invocation.ts b/packages/eve/src/internal/invocation/agent-invocation.tsnew file mode 100644index 000000000..ef201852a--- /dev/null+++ b/packages/eve/src/internal/invocation/agent-invocation.ts@@ -0,0 +1,54 @@+import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";+import type { InputRequest } from "#runtime/input/types.js";+import type { JsonValue } from "#shared/json.js";++export interface AgentInvocationAuthorizationRequest {+ readonly authorization?: ConnectionAuthorizationChallenge;+ readonly description: string;+ readonly name: string;+ readonly webhookUrl?: string;+}++interface AgentInvocationBase {+ readonly invocationId: string;+ readonly createdAt: string;+ readonly expiresAt?: string;+}++export type AgentInvocation =+ | (AgentInvocationBase & {+ readonly status: "working";+ readonly pollAfterMs: number;+ readonly result?: JsonValue;+ })+ | (AgentInvocationBase & {+ readonly status: "input_required";+ readonly inputRequests: Readonly<Record<string, InputRequest>>;+ readonly result?: JsonValue;+ })+ | (AgentInvocationBase & {+ readonly status: "authorization_required";+ readonly authorizations: readonly [+ AgentInvocationAuthorizationRequest,+ ...AgentInvocationAuthorizationRequest[],+ ];+ readonly pollAfterMs: number;+ readonly result?: JsonValue;+ })+ | (AgentInvocationBase & { readonly status: "completed"; readonly result?: JsonValue })+ | (AgentInvocationBase & {+ readonly status: "failed";+ readonly error: {+ readonly code: number;+ readonly message: string;+ readonly data?: JsonValue;+ };+ })+ | (AgentInvocationBase & { readonly status: "cancelled" });++export type AgentInvocationStatus = AgentInvocation["status"];++export type AgentInvocationMutationResult =+ | { readonly type: "success"; readonly invocation: AgentInvocation }+ | { readonly type: "conflict"; readonly message: string }+ | { readonly type: "not_found" };diff --git a/packages/eve/src/internal/invocation/attributes.ts b/packages/eve/src/internal/invocation/attributes.tsnew file mode 100644index 000000000..665f51c9c--- /dev/null+++ b/packages/eve/src/internal/invocation/attributes.ts@@ -0,0 +1,2 @@+export const INVOCATION_TOKEN_ATTRIBUTE = "$eve.invocation_token";+export const INVOCATION_OWNER_ATTRIBUTE = "$eve.invocation_owner";diff --git a/packages/eve/src/internal/invocation/mcp-agent-channel.scenario.test.ts b/packages/eve/src/internal/invocation/mcp-agent-channel.scenario.test.tsnew file mode 100644index 000000000..f713c2b0f--- /dev/null+++ b/packages/eve/src/internal/invocation/mcp-agent-channel.scenario.test.ts@@ -0,0 +1,335 @@+import { spawn, type ChildProcessByStdio } from "node:child_process";+import { join } from "node:path";+import type { Readable } from "node:stream";++import { describe, expect, it } from "vitest";++import { type ScenarioAppDescriptor, useScenarioApp } from "#internal/testing/scenario-app.js";++const scenarioApp = useScenarioApp();+const SCENARIO_TIMEOUT_MS = 360_000;+const OPERATION_TIMEOUT_MS = 30_000;+const MCP_PROTOCOL_VERSION = "2026-07-28";++const MCP_AGENT_DESCRIPTOR: ScenarioAppDescriptor = {+ files: {+ "agent/agent.ts": `import { defineAgent } from "eve";+import { mockModel } from "eve/evals";++const model = mockModel((request) => {+ const answered = request.toolResults.some((result) => result.name === "ask_question");+ if (!answered) {+ return {+ toolCalls: [{+ id: "question-1",+ input: {+ options: [{ id: "yes", label: "Yes" }, { id: "no", label: "No" }],+ prompt: "Proceed with the delegated work?",+ },+ name: "ask_question",+ }],+ };+ }+ return "MCP-LIFECYCLE-COMPLETE";+});++export default defineAgent({+ description: "Exercises the durable MCP invocation lifecycle.",+ model,+ modelContextWindowTokens: 32_000,+});+`,+ "agent/channels/mcp.ts": `import { mcpChannel } from "eve/channels/mcp";++export default mcpChannel({+ auth: (request) => {+ const principalId = request.headers.get("x-test-principal");+ return principalId === null+ ? null+ : { attributes: {}, authenticator: "scenario", principalId, principalType: "user" };+ },+});+`,+ "agent/instructions.md": "Follow the deterministic mock-model lifecycle.\n",+ },+ installDependencies: true,+ name: "mcp-agent-channel",+};++describe("MCP agent channel", () => {+ it(+ "runs a durable input lifecycle through modern and legacy Nitro requests",+ async () => {+ const app = await scenarioApp(MCP_AGENT_DESCRIPTOR);+ const server = await startEveDev(app.appRoot);++ try {+ const started = await callTool(server.url, "alice", "modern", "agent_start", {+ message: "Run the lifecycle.",+ });+ const invocationId = requiredString(started.invocationId, "invocationId");+ const pending = await pollInvocation(server.url, "alice", "modern", invocationId, [+ "input_required",+ ]);+ const requestId = requiredString(+ Object.keys(requiredRecord(pending.inputRequests, "inputRequests"))[0],+ "requestId",+ );++ const hidden = await callToolResult(server.url, "bob", "modern", "agent_get", {+ invocationId,+ });+ expect(hidden.isError).toBe(true);++ const responses = [{ optionId: "yes", requestId }];+ await expect(+ callTool(server.url, "alice", "modern", "agent_update", {+ invocationId,+ responses,+ }),+ ).resolves.toMatchObject({ invocationId });++ const completed = await pollInvocation(server.url, "alice", "modern", invocationId, [+ "completed",+ ]);+ expect(completed).toMatchObject({ result: "MCP-LIFECYCLE-COMPLETE" });+ await initializeLegacy(server.url, "alice");+ const legacyStarted = await callTool(server.url, "alice", "legacy", "agent_start", {+ message: "Cancel this lifecycle.",+ });+ const legacyInvocationId = requiredString(legacyStarted.invocationId, "invocationId");+ await pollInvocation(server.url, "alice", "legacy", legacyInvocationId, ["input_required"]);+ await expect(+ callTool(server.url, "alice", "legacy", "agent_cancel", {+ invocationId: legacyInvocationId,+ }),+ ).resolves.toMatchObject({ invocationId: legacyInvocationId });+ await expect(+ pollInvocation(server.url, "alice", "legacy", legacyInvocationId, ["cancelled"]),+ ).resolves.toMatchObject({ status: "cancelled" });+ } catch (error) {+ throw new Error(+ [`stdout:\n${server.stdout()}`, `stderr:\n${server.stderr()}`].join("\n\n"),+ { cause: error },+ );+ } finally {+ await server.stop();+ }+ },+ SCENARIO_TIMEOUT_MS,+ );+});++type McpEra = "legacy" | "modern";++async function callTool(+ serverUrl: string,+ principal: string,+ era: McpEra,+ name: string,+ args: Readonly<Record<string, unknown>>,+): Promise<Record<string, unknown>> {+ const result = await callToolResult(serverUrl, principal, era, name, args);+ if (result.isError === true) {+ throw new Error(`MCP tool ${name} failed: ${JSON.stringify(result.content)}`);+ }+ return requiredRecord(result.structuredContent, `${name}.structuredContent`);+}++async function callToolResult(+ serverUrl: string,+ principal: string,+ era: McpEra,+ name: string,+ args: Readonly<Record<string, unknown>>,+): Promise<Record<string, unknown>> {+ const response = await mcpRequest(serverUrl, principal, era, "tools/call", {+ arguments: args,+ name,+ });+ const envelope = requiredRecord(await readJsonRpcResponse(response), "JSON-RPC envelope");+ return requiredRecord(requiredRecord(envelope.result, "result"), "tool result");+}++async function initializeLegacy(serverUrl: string, principal: string): Promise<void> {+ const response = await mcpRequest(serverUrl, principal, "legacy", "initialize", {+ capabilities: {},+ clientInfo: { name: "eve-scenario", version: "0.0.0" },+ protocolVersion: "2025-11-25",+ });+ expect(response.ok).toBe(true);+}++async function pollInvocation(+ serverUrl: string,+ principal: string,+ era: McpEra,+ invocationId: string,+ statuses: readonly string[],+): Promise<Record<string, unknown>> {+ const deadline = Date.now() + OPERATION_TIMEOUT_MS;+ while (Date.now() < deadline) {+ const invocation = await callTool(serverUrl, principal, era, "agent_get", { invocationId });+ if (typeof invocation.status === "string" && statuses.includes(invocation.status)) {+ return invocation;+ }+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ throw new Error(`Timed out waiting for ${statuses.join(" or ")} on ${invocationId}.`);+}++async function mcpRequest(+ serverUrl: string,+ principal: string,+ era: McpEra,+ method: string,+ params: Readonly<Record<string, unknown>>,+): Promise<Response> {+ const modernMeta =+ era === "modern"+ ? {+ _meta: {+ "io.modelcontextprotocol/clientCapabilities": {},+ "io.modelcontextprotocol/clientInfo": { name: "eve-scenario", version: "0.0.0" },+ "io.modelcontextprotocol/protocolVersion": MCP_PROTOCOL_VERSION,+ },+ }+ : {};+ const headers: Record<string, string> = {+ accept: "application/json, text/event-stream",+ "content-type": "application/json",+ "x-test-principal": principal,+ };+ if (era === "modern") {+ headers["mcp-method"] = method;+ headers["mcp-protocol-version"] = MCP_PROTOCOL_VERSION;+ if (typeof params.name === "string") headers["mcp-name"] = params.name;+ }+ return await fetch(new URL("/mcp", serverUrl), {+ body: JSON.stringify({+ id: crypto.randomUUID(),+ jsonrpc: "2.0",+ method,+ params: { ...params, ...modernMeta },+ }),+ headers,+ method: "POST",+ });+}++async function readJsonRpcResponse(response: Response): Promise<unknown> {+ const body = await response.text();+ if (!response.ok) throw new Error(`MCP HTTP ${response.status}: ${body}`);+ if (!response.headers.get("content-type")?.includes("text/event-stream")) {+ return JSON.parse(body);+ }+ const data = body.split("\n").find((line) => line.startsWith("data: "));+ if (data === undefined) throw new Error("MCP response did not contain an SSE data event.");+ return JSON.parse(data.slice("data: ".length));+}++function requiredRecord(value: unknown, name: string): Record<string, unknown> {+ if (typeof value !== "object" || value === null || Array.isArray(value)) {+ throw new Error(`${name} was not an object.`);+ }+ return value as Record<string, unknown>;+}++function requiredString(value: unknown, name: string): string {+ if (typeof value !== "string" || value.length === 0) {+ throw new Error(`${name} was not a non-empty string.`);+ }+ return value;+}++interface RunningEveDev {+ readonly stderr: () => string;+ readonly stdout: () => string;+ readonly url: string;+ stop(): Promise<void>;+}++async function startEveDev(appRoot: string): Promise<RunningEveDev> {+ const eveBinPath = join(appRoot, "node_modules", "eve", "bin", "eve.js");+ const child = spawn(+ process.execPath,+ [eveBinPath, "dev", "--no-ui", "--host", "127.0.0.1", "--port", "0"],+ {+ cwd: appRoot,+ env: { ...process.env, EVE_MOCK_AUTHORED_MODELS: "", NODE_ENV: "production" },+ stdio: ["ignore", "pipe", "pipe"],+ },+ );+ let stderr = "";+ let stdout = "";+ child.stdout.setEncoding("utf8");+ child.stderr.setEncoding("utf8");+ child.stdout.on("data", (chunk: string) => {+ stdout += chunk;+ });+ child.stderr.on("data", (chunk: string) => {+ stderr += chunk;+ });++ let url: string;+ try {+ url = await waitForServerUrl(child, () => ({ stderr, stdout }));+ } catch (error) {+ await stopChild(child);+ throw error;+ }+ return {+ stderr: () => stderr,+ stdout: () => stdout,+ async stop() {+ await stopChild(child);+ },+ url,+ };+}++async function waitForServerUrl(+ child: ChildProcessByStdio<null, Readable, Readable>,+ output: () => { readonly stderr: string; readonly stdout: string },+): Promise<string> {+ return await new Promise((resolve, reject) => {+ const timeout = setTimeout(() => {+ cleanup();+ const current = output();+ reject(new Error(`Timed out waiting for eve dev.\n${current.stdout}\n${current.stderr}`));+ }, OPERATION_TIMEOUT_MS);+ function inspect() {+ const url = /\[DEV\] server listening at (http:\/\/[^\s]+)/u.exec(output().stdout)?.[1];+ if (url !== undefined) {+ cleanup();+ resolve(url);+ }+ }+ function exited(code: number | null, signal: NodeJS.Signals | null) {+ cleanup();+ reject(new Error(`eve dev exited before startup (code ${String(code)}, ${String(signal)}).`));+ }+ function cleanup() {+ clearTimeout(timeout);+ child.stdout.off("data", inspect);+ child.stderr.off("data", inspect);+ child.off("exit", exited);+ }+ child.stdout.on("data", inspect);+ child.stderr.on("data", inspect);+ child.once("exit", exited);+ inspect();+ });+}++async function stopChild(child: ChildProcessByStdio<null, Readable, Readable>): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) return;+ await new Promise<void>((resolve) => {+ const force = setTimeout(() => child.kill("SIGKILL"), 10_000);+ child.once("exit", () => {+ clearTimeout(force);+ resolve();+ });+ child.kill("SIGTERM");+ });+}diff --git a/packages/eve/src/internal/invocation/metadata.ts b/packages/eve/src/internal/invocation/metadata.tsnew file mode 100644index 000000000..a128d9b0e--- /dev/null+++ b/packages/eve/src/internal/invocation/metadata.ts@@ -0,0 +1,42 @@+import { createHash } from "node:crypto";++import type { RunInput, SessionAuthContext } from "#channel/types.js";+import {+ INVOCATION_OWNER_ATTRIBUTE,+ INVOCATION_TOKEN_ATTRIBUTE,+} from "#internal/invocation/attributes.js";++export { INVOCATION_OWNER_ATTRIBUTE, INVOCATION_TOKEN_ATTRIBUTE };++export type ExternalInvocationMetadata = NonNullable<RunInput["externalInvocation"]>;++/** Batch-scoped request id exposed to MCP clients for one durable pending-input event. */+export function invocationInputRequestId(pendingBatchId: string, requestId: string): string {+ return createHash("sha256")+ .update(JSON.stringify([pendingBatchId, requestId]), "utf8")+ .digest("hex");+}++/** Fixed-width fingerprint used to bind an invocation to its initiating principal. */+export function invocationOwnerKey(auth: SessionAuthContext | null): string {+ const identity =+ auth === null+ ? ["anonymous"]+ : [+ auth.authenticator,+ auth.issuer ?? "",+ auth.principalType,+ auth.principalId,+ auth.subject ?? "",+ ];+ return createHash("sha256").update(JSON.stringify(identity), "utf8").digest("hex");+}++export function buildInvocationAttributes(+ metadata: ExternalInvocationMetadata,+): Readonly<Record<string, string>> {+ return {+ [INVOCATION_OWNER_ATTRIBUTE]: metadata.ownerKey,+ [INVOCATION_TOKEN_ATTRIBUTE]: metadata.continuationToken,+ };+}diff --git a/packages/eve/src/internal/invocation/workflow-execution.test.ts b/packages/eve/src/internal/invocation/workflow-execution.test.tsnew file mode 100644index 000000000..7df19ea14--- /dev/null+++ b/packages/eve/src/internal/invocation/workflow-execution.test.ts@@ -0,0 +1,490 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { RunHandle, SessionAuthContext } from "#channel/types.js";+import { INTERNAL_CHANNEL_DELIVER } from "#channel/channel-operations.js";+import {+ buildInvocationAttributes,+ INVOCATION_OWNER_ATTRIBUTE,+ invocationInputRequestId,+ invocationOwnerKey,+} from "#internal/invocation/metadata.js";+import { WorkflowAgentInvocationExecution } from "#internal/invocation/workflow-execution.js";+import type { HandleMessageStreamEvent } from "#protocol/message.js";+import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";++const runsGet = vi.fn();+const cancel = vi.fn();+const returnValue = vi.fn();+const getReadable = vi.fn();++vi.mock("#internal/workflow/runtime.js", () => ({+ getWorld: async () => ({ runs: { get: runsGet } }),+ getRun: () => ({+ cancel,+ get returnValue() {+ return returnValue();+ },+ getReadable,+ }),+}));++const auth: SessionAuthContext = {+ attributes: {},+ authenticator: "test",+ principalId: "alice",+ principalType: "user",+};++const createSession = vi.fn<() => Promise<RunHandle>>();+const deliver = vi.fn();+const from = vi.fn(() => ({ [INTERNAL_CHANNEL_DELIVER]: deliver }) as never);++describe("WorkflowAgentInvocationExecution", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getReadable.mockReturnValue(eventStream([]));+ });++ it("seeds invocation metadata when starting a task run", async () => {+ runsGet.mockResolvedValue(run({ status: "running" }));+ createSession.mockResolvedValue({+ events: new ReadableStream(),+ sessionId: "wrun_invocation",+ });+ const invocation = await execution().create({+ auth,+ message: "work",+ });++ expect(createSession).toHaveBeenCalledWith(+ expect.objectContaining({+ capabilities: { requestInput: true },+ externalInvocation: expect.objectContaining({ continuationToken: expect.any(String) }),+ mode: "task",+ }),+ );+ expect(invocation).toMatchObject({+ createdAt: "2026-07-20T00:00:00.000Z",+ invocationId: "wrun_invocation",+ status: "working",+ });+ });++ it("requires the same authenticated principal for invocation access", async () => {+ runsGet.mockResolvedValue(run({ status: "running" }));++ await expect(+ execution().read({+ auth: { ...auth, principalId: "other" },+ invocationId: "wrun_invocation",+ }),+ ).resolves.toBeUndefined();+ });++ it("preserves principal ownership through workflow attribute normalization", async () => {+ const longAuth: SessionAuthContext = {+ attributes: {},+ authenticator: "jwt-ecdsa",+ issuer: `https://login.example/${"tenant".repeat(64)}`,+ principalId: "principal".repeat(64),+ principalType: "user",+ subject: "subject".repeat(64),+ };+ const ownerKey = invocationOwnerKey(longAuth);+ const attributes = normalizeEveAttributes(+ buildInvocationAttributes({ continuationToken: "invocation:token", ownerKey }),+ );+ expect(ownerKey).toHaveLength(64);+ expect(attributes[INVOCATION_OWNER_ATTRIBUTE]).toBe(ownerKey);+ runsGet.mockResolvedValue(run({ ownerKey, status: "running" }));++ await expect(+ execution().read({ auth: longAuth, invocationId: "wrun_invocation" }),+ ).resolves.toMatchObject({ status: "working" });+ await expect(+ execution().read({+ auth: { ...longAuth, subject: `${longAuth.subject}-other` },+ invocationId: "wrun_invocation",+ }),+ ).resolves.toBeUndefined();+ });++ it("rejects a workflow run without invocation metadata", async () => {+ const otherRun = run({ status: "running" });+ runsGet.mockResolvedValue({ ...otherRun, attributes: {} });++ await expect(+ execution().read({ auth, invocationId: "wrun_invocation" }),+ ).resolves.toBeUndefined();+ });++ it("replays the existing event stream to reconstruct pending input", async () => {+ runsGet.mockResolvedValue(run({ status: "running" }));+ getReadable.mockReturnValue(+ eventStream([+ {+ type: "turn.started",+ data: { turnId: "turn_1" },+ meta: { at: "2026-07-20T00:00:00.000Z", id: "event_1" },+ } as HandleMessageStreamEvent,+ {+ type: "input.requested",+ data: {+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ requests: [+ {+ action: {+ callId: "call_1",+ input: {},+ kind: "tool-call",+ toolName: "ask_question",+ },+ kind: "question",+ options: [{ id: "yes", label: "Yes" }],+ prompt: "Proceed?",+ requestId: "question",+ },+ ],+ },+ meta: { at: "2026-07-20T00:00:01.000Z", id: "event_2" },+ } as HandleMessageStreamEvent,+ ]),+ );++ const requestId = invocationInputRequestId("event_2", "question");+ await expect(+ execution().read({ auth, invocationId: "wrun_invocation" }),+ ).resolves.toMatchObject({+ inputRequests: { [requestId]: { prompt: "Proceed?", requestId } },+ status: "input_required",+ });+ expect(getReadable).toHaveBeenCalledWith({ startIndex: -64 });+ });++ it("returns working immediately after accepting pending input", async () => {+ const requestId = invocationInputRequestId("event_1", "question");+ const responses = [{ optionId: "yes", requestId }] as const;+ runsGet.mockResolvedValue(run({ status: "running" }));+ let events: HandleMessageStreamEvent[] = [+ {+ type: "input.requested",+ data: {+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ requests: [+ {+ action: {+ callId: "call_1",+ input: {},+ kind: "tool-call",+ toolName: "ask_question",+ },+ kind: "question",+ options: [{ id: "yes", label: "Yes" }],+ prompt: "Proceed?",+ requestId: "question",+ },+ ],+ },+ meta: { at: "2026-07-20T00:00:00.000Z", id: "event_1" },+ } as HandleMessageStreamEvent,+ ];+ getReadable.mockImplementation(() => eventStream(events));+ deliver.mockResolvedValue({ sessionId: "wrun_invocation" });++ await expect(+ execution().update({+ auth,+ invocationId: "wrun_invocation",+ responses,+ }),+ ).resolves.toMatchObject({+ invocation: { pollAfterMs: 1_000, status: "working" },+ type: "success",+ });+ expect(from).toHaveBeenCalledWith("invocation:token");+ expect(deliver).toHaveBeenCalledWith(+ { inputResponses: [{ optionId: "yes", requestId: "question" }] },+ { auth },+ );+ expect(getReadable).toHaveBeenCalledWith({ startIndex: -64 });+ });++ it("requires one update to answer the complete pending input batch", async () => {+ const pendingRun = run({ status: "running" });+ runsGet.mockResolvedValue(pendingRun);+ getReadable.mockImplementation(() =>+ eventStream([inputRequestedEvent("event_split", ["one", "two"])]),+ );+ deliver.mockResolvedValue({ sessionId: "wrun_invocation" });++ const one = invocationInputRequestId("event_split", "one");+ const two = invocationInputRequestId("event_split", "two");+ await expect(+ execution().update({+ auth,+ invocationId: "wrun_invocation",+ responses: [{ optionId: "yes", requestId: one }],+ }),+ ).resolves.toEqual({+ message: "Responses must answer the complete pending input batch exactly once.",+ type: "conflict",+ });+ await expect(+ execution().update({+ auth,+ invocationId: "wrun_invocation",+ responses: [+ { optionId: "yes", requestId: one },+ { optionId: "yes", requestId: two },+ ],+ }),+ ).resolves.toMatchObject({ type: "success" });+ expect(deliver).toHaveBeenCalledExactlyOnceWith(+ {+ inputResponses: [+ { optionId: "yes", requestId: "one" },+ { optionId: "yes", requestId: "two" },+ ],+ },+ expect.objectContaining({ auth }),+ );+ });++ it("rejects delayed retries when a later batch reuses an internal request id", async () => {+ const pendingRun = run({ status: "running" });+ runsGet.mockResolvedValue(pendingRun);+ let events: HandleMessageStreamEvent[] = [inputRequestedEvent("event_first", ["question"])];+ getReadable.mockImplementation(() => eventStream(events));+ deliver.mockResolvedValue({ sessionId: "wrun_invocation" });++ const firstRequestId = invocationInputRequestId("event_first", "question");+ await execution().update({+ auth,+ invocationId: "wrun_invocation",+ responses: [{ optionId: "yes", requestId: firstRequestId }],+ });+ events = [+ {+ data: { sequence: 1, turnId: "turn_2" },+ meta: { at: "2026-07-20T00:00:01.000Z", id: "event_turn" },+ type: "turn.started",+ },+ inputRequestedEvent("event_second", ["question"]),+ ];+ await expect(+ execution().update({+ auth,+ invocationId: "wrun_invocation",+ responses: [{ optionId: "yes", requestId: firstRequestId }],+ }),+ ).resolves.toEqual({+ message: `Unknown input request: ${firstRequestId}`,+ type: "conflict",+ });++ const secondRequestId = invocationInputRequestId("event_second", "question");+ await expect(+ execution().update({+ auth,+ invocationId: "wrun_invocation",+ responses: [{ optionId: "no", requestId: secondRequestId }],+ }),+ ).resolves.toMatchObject({ type: "success" });++ expect(deliver).toHaveBeenCalledTimes(2);+ });++ it("projects and clears pending connection authorization", async () => {+ runsGet.mockResolvedValue(run({ status: "running" }));+ const required = {+ type: "authorization.required",+ data: {+ authorization: {+ displayName: "Linear",+ url: "https://linear.example/authorize",+ },+ description: "Sign in to Linear",+ name: "linear",+ sequence: 0,+ stepIndex: 1,+ turnId: "turn_1",+ webhookUrl: "https://agent.example/connections/linear/callback/token",+ },+ meta: { at: "2026-07-20T00:00:00.000Z", id: "event_1" },+ } as HandleMessageStreamEvent;+ getReadable.mockReturnValue(eventStream([required]));++ await expect(+ execution().read({ auth, invocationId: "wrun_invocation" }),+ ).resolves.toMatchObject({+ authorizations: [+ {+ authorization: {+ displayName: "Linear",+ url: "https://linear.example/authorize",+ },+ description: "Sign in to Linear",+ name: "linear",+ },+ ],+ pollAfterMs: 1_000,+ status: "authorization_required",+ });++ getReadable.mockReturnValue(+ eventStream([+ required,+ {+ type: "authorization.completed",+ data: {+ name: "linear",+ outcome: "authorized",+ sequence: 0,+ stepIndex: 2,+ turnId: "turn_1",+ },+ meta: { at: "2026-07-20T00:00:01.000Z", id: "event_2" },+ } as HandleMessageStreamEvent,+ ]),+ );+ await expect(+ execution().read({ auth, invocationId: "wrun_invocation" }),+ ).resolves.toMatchObject({ status: "working" });+ });++ it("does not project intermediate tool-call narration as a result", async () => {+ runsGet.mockResolvedValue(run({ status: "running" }));+ getReadable.mockReturnValue(+ eventStream([+ {+ type: "message.completed",+ data: {+ finishReason: "tool-calls",+ message: "I'll search for that.",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ },+ meta: { at: "2026-07-20T00:00:00.000Z", id: "event_1" },+ } as HandleMessageStreamEvent,+ ]),+ );++ const invocation = await execution().read({ auth, invocationId: "wrun_invocation" });++ expect(invocation).toMatchObject({ status: "working" });+ expect(invocation?.status === "working" ? invocation.result : undefined).toBeUndefined();+ });++ it("decodes a final persisted event without a trailing newline", async () => {+ runsGet.mockResolvedValue(run({ status: "running" }));+ getReadable.mockReturnValue(+ eventStream(+ [+ {+ type: "message.completed",+ data: {+ finishReason: "stop",+ message: "Done.",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ },+ meta: { at: "2026-07-20T00:00:00.000Z", id: "event_1" },+ } as HandleMessageStreamEvent,+ ],+ { trailingNewline: false },+ ),+ );++ await expect(+ execution().read({ auth, invocationId: "wrun_invocation" }),+ ).resolves.toMatchObject({ result: "Done.", status: "working" });+ });++ it("uses workflow return value as terminal result", async () => {+ runsGet.mockResolvedValue(run({ status: "completed" }));+ getReadable.mockReturnValue(eventStream([{ type: "session.completed" }]));+ returnValue.mockResolvedValue({ output: { answer: 42 } });++ await expect(+ execution().read({ auth, invocationId: "wrun_invocation" }),+ ).resolves.toMatchObject({ result: { answer: 42 }, status: "completed" });+ expect(getReadable).not.toHaveBeenCalled();+ });++ it("terminally cancels the workflow run", async () => {+ runsGet+ .mockResolvedValueOnce(run({ status: "running" }))+ .mockResolvedValueOnce(run({ status: "cancelled" }));+ cancel.mockResolvedValue(undefined);++ await expect(+ execution().cancel({ auth, invocationId: "wrun_invocation" }),+ ).resolves.toMatchObject({ status: "cancelled" });+ expect(cancel).toHaveBeenCalledWith();+ });+});++function execution(): WorkflowAgentInvocationExecution {+ return new WorkflowAgentInvocationExecution({ channelName: "mcp", createSession, from });+}++function run(input: { ownerKey?: string; status: string }) {+ const attributes: Record<string, string> = {+ "$eve.invocation_owner": input.ownerKey ?? invocationOwnerKey(auth),+ "$eve.invocation_token": "invocation:token",+ };+ return {+ attributes,+ createdAt: new Date("2026-07-20T00:00:00.000Z"),+ input: [{ serializedContext: { "eve.initiatorAuth": auth } }],+ runId: "wrun_invocation",+ status: input.status,+ };+}++function inputRequestedEvent(id: string, requestIds: readonly string[]): HandleMessageStreamEvent {+ return {+ data: {+ requests: requestIds.map((requestId) => ({+ action: {+ callId: requestId,+ input: {},+ kind: "tool-call" as const,+ toolName: "ask_question",+ },+ kind: "question" as const,+ prompt: `Answer ${requestId}`,+ requestId,+ })),+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ },+ meta: { at: "2026-07-20T00:00:00.000Z", id },+ type: "input.requested",+ };+}++function eventStream(+ events: readonly unknown[],+ options: { readonly trailingNewline?: boolean } = {},+): ReadableStream<Uint8Array> {+ const encoder = new TextEncoder();+ const chunks = events.map((event, index) => {+ const newline = options.trailingNewline === false && index === events.length - 1 ? "" : "\n";+ return encoder.encode(`${JSON.stringify(event)}${newline}`);+ });+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ for (const chunk of chunks) controller.enqueue(chunk);+ controller.close();+ },+ });+ return Object.assign(stream, { getTailIndex: async () => events.length - 1 });+}diff --git a/packages/eve/src/internal/invocation/workflow-execution.ts b/packages/eve/src/internal/invocation/workflow-execution.tsnew file mode 100644index 000000000..80ae687d2--- /dev/null+++ b/packages/eve/src/internal/invocation/workflow-execution.ts@@ -0,0 +1,352 @@+import type { UserContent } from "ai";+import { RunExpiredError, WorkflowRunNotFoundError } from "#compiled/@workflow/errors/index.js";++import type { SessionAuthContext } from "#channel/types.js";+import {+ INTERNAL_CHANNEL_DELIVER,+ type ChannelFrom,+ type InternalChannelSource,+} from "#channel/channel-operations.js";+import { parseNdjsonStream } from "#execution/ndjson-stream.js";+import type {+ AgentInvocation,+ AgentInvocationAuthorizationRequest,+ AgentInvocationMutationResult,+ AgentInvocationStatus,+} from "#internal/invocation/agent-invocation.js";+import {+ INVOCATION_OWNER_ATTRIBUTE,+ INVOCATION_TOKEN_ATTRIBUTE,+ invocationInputRequestId,+ invocationOwnerKey,+} from "#internal/invocation/metadata.js";+import type { RouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";+import { getRun, getWorld } from "#internal/workflow/runtime.js";+import type { HandleMessageStreamEvent } from "#protocol/message.js";+import type { InputRequest, InputResponse } from "#runtime/input/types.js";+import type { JsonObject, JsonValue } from "#shared/json.js";+import { parseJsonValue } from "#shared/json.js";++export class WorkflowAgentInvocationExecution {+ readonly #channelName: string;+ readonly #createSession: RouteSessionCreator;+ readonly #from: ChannelFrom;++ constructor(input: {+ readonly channelName: string;+ readonly createSession: RouteSessionCreator;+ readonly from: ChannelFrom;+ }) {+ this.#channelName = input.channelName;+ this.#createSession = input.createSession;+ this.#from = input.from;+ }++ async create(input: {+ readonly auth: SessionAuthContext | null;+ readonly message: string | UserContent;+ readonly outputSchema?: JsonObject;+ }): Promise<AgentInvocation> {+ const continuationToken = `invocation:${crypto.randomUUID()}`;+ const handle = await this.#createSession({+ auth: input.auth,+ capabilities: { requestInput: true },+ continuationToken: `${this.#channelName}:${continuationToken}`,+ externalInvocation: {+ continuationToken,+ ownerKey: invocationOwnerKey(input.auth),+ },+ input: { message: input.message, outputSchema: input.outputSchema },+ mode: "task",+ });++ const run = await this.#readInvocationRun(handle.sessionId, input.auth);+ if (run === undefined) {+ throw new Error("Invocation run was unavailable after durable creation.");+ }+ return workingInvocation(+ handle.sessionId,+ run.createdAt.toISOString(),+ run.expiredAt?.toISOString(),+ );+ }++ async read(input: {+ readonly auth: SessionAuthContext | null;+ readonly invocationId: string;+ }): Promise<AgentInvocation | undefined> {+ const run = await this.#readInvocationRun(input.invocationId, input.auth);+ if (run === undefined) return undefined;++ if (isTerminalRunStatus(run.status)) {+ return await terminalInvocation(run);+ }+ const events = await readRecentPersistedEvents(input.invocationId);+ return projectNonterminal(+ run.runId,+ run.createdAt.toISOString(),+ run.expiredAt?.toISOString(),+ events,+ );+ }++ async update(input: {+ readonly auth: SessionAuthContext | null;+ readonly invocationId: string;+ readonly responses: readonly InputResponse[];+ }): Promise<AgentInvocationMutationResult> {+ const current = await this.read(input);+ if (current === undefined) return { type: "not_found" };+ if (current.status !== "input_required") {+ return conflict("Invocation is not waiting for input.");+ }+ const run = await this.#readInvocationRun(input.invocationId, input.auth);+ if (run === undefined) return { type: "not_found" };+ const pendingBatch = latestPendingInputBatch(+ await readRecentPersistedEvents(input.invocationId),+ );+ if (pendingBatch === undefined) {+ return conflict("Invocation input changed before the update could be applied.");+ }+ const responseIds = new Set<string>();+ const deliveredResponses: InputResponse[] = [];+ for (const response of input.responses) {+ const rawRequestId = pendingBatch.rawRequestIds[response.requestId];+ if (rawRequestId === undefined) {+ return conflict(`Unknown input request: ${response.requestId}`);+ }+ responseIds.add(response.requestId);+ deliveredResponses.push({ ...response, requestId: rawRequestId });+ }+ if (+ responseIds.size !== input.responses.length ||+ responseIds.size !== Object.keys(pendingBatch.requests).length+ ) {+ return conflict("Responses must answer the complete pending input batch exactly once.");+ }+ const token = run.attributes[INVOCATION_TOKEN_ATTRIBUTE];+ if (token === undefined) return { type: "not_found" };+ try {+ const source = this.#from(token) as InternalChannelSource;+ await source[INTERNAL_CHANNEL_DELIVER](+ { inputResponses: deliveredResponses },+ { auth: input.auth },+ );+ } catch (error) {+ if (RunExpiredError.is(error)) return { type: "not_found" };+ throw error;+ }++ return {+ invocation: workingInvocation(input.invocationId, current.createdAt, current.expiresAt),+ type: "success",+ };+ }++ async cancel(input: {+ readonly auth: SessionAuthContext | null;+ readonly invocationId: string;+ }): Promise<AgentInvocation | undefined> {+ const current = await this.read(input);+ if (current === undefined || isTerminal(current.status)) return current;+ try {+ await getRun(input.invocationId).cancel();+ } catch (error) {+ if (WorkflowRunNotFoundError.is(error) || RunExpiredError.is(error)) return undefined;+ throw error;+ }+ return await this.read(input);+ }++ async #readInvocationRun(invocationId: string, auth: SessionAuthContext | null) {+ const world = await getWorld();+ try {+ const run = await world.runs.get(invocationId);+ if (run.attributes[INVOCATION_TOKEN_ATTRIBUTE] === undefined) return undefined;+ return run.attributes[INVOCATION_OWNER_ATTRIBUTE] === invocationOwnerKey(auth)+ ? run+ : undefined;+ } catch (error) {+ if (WorkflowRunNotFoundError.is(error) || RunExpiredError.is(error)) return undefined;+ throw error;+ }+ }+}++const INVOCATION_EVENT_WINDOW_SIZE = 64;++async function readRecentPersistedEvents(+ invocationId: string,+): Promise<HandleMessageStreamEvent[]> {+ const readable = getRun(invocationId).getReadable<Uint8Array>({+ startIndex: -INVOCATION_EVENT_WINDOW_SIZE,+ });+ const tailIndex = await readable.getTailIndex();+ if (tailIndex < 0) {+ await readable.cancel("invocation event stream is empty").catch(() => {});+ return [];+ }+ const expectedEvents = Math.min(tailIndex + 1, INVOCATION_EVENT_WINDOW_SIZE);++ const reader = parseNdjsonStream<HandleMessageStreamEvent>(() => readable).getReader();+ const events: HandleMessageStreamEvent[] = [];+ try {+ while (events.length < expectedEvents) {+ const { done, value } = await reader.read();+ if (done) break;+ events.push(value);+ }+ } finally {+ await reader.cancel("invocation event window read complete").catch(() => {});+ reader.releaseLock();+ }+ return events;+}++interface PendingInputBatch {+ readonly id: string;+ readonly rawRequestIds: Readonly<Record<string, string>>;+ readonly requests: Readonly<Record<string, InputRequest>>;+}++function pendingInputBatch(+ event: Extract<HandleMessageStreamEvent, { type: "input.requested" }>,+): PendingInputBatch {+ const rawRequestIds: Record<string, string> = {};+ const requests: Record<string, InputRequest> = {};+ for (const request of event.data.requests) {+ const requestId = invocationInputRequestId(event.meta.id, request.requestId);+ rawRequestIds[requestId] = request.requestId;+ requests[requestId] = { ...request, requestId };+ }+ return { id: event.meta.id, rawRequestIds, requests };+}++function latestPendingInputBatch(+ events: readonly HandleMessageStreamEvent[],+): PendingInputBatch | undefined {+ let batch: PendingInputBatch | undefined;+ for (const event of events) {+ if (event.type === "input.requested") batch = pendingInputBatch(event);+ else if (event.type === "turn.started") batch = undefined;+ }+ return batch;+}++function projectNonterminal(+ invocationId: string,+ createdAt: string,+ expiresAt: string | undefined,+ events: readonly HandleMessageStreamEvent[],+): AgentInvocation {+ const authorizations = new Map<string, AgentInvocationAuthorizationRequest>();+ let inputBatch: PendingInputBatch | undefined;+ let result: JsonValue | undefined;+ for (const event of events) {+ if (event.type === "input.requested") {+ inputBatch = pendingInputBatch(event);+ } else if (event.type === "turn.started") {+ authorizations.clear();+ inputBatch = undefined;+ result = undefined;+ } else if (event.type === "authorization.required") {+ const authorization: {+ authorization?: AgentInvocationAuthorizationRequest["authorization"];+ description: string;+ name: string;+ webhookUrl?: string;+ } = {+ description: event.data.description,+ name: event.data.name,+ };+ if (event.data.authorization !== undefined) {+ authorization.authorization = event.data.authorization;+ }+ if (event.data.webhookUrl !== undefined) {+ authorization.webhookUrl = event.data.webhookUrl;+ }+ authorizations.set(event.data.name, authorization);+ } else if (event.type === "authorization.completed") {+ authorizations.delete(event.data.name);+ } else if (+ event.type === "message.completed" &&+ event.data.finishReason !== "tool-calls" &&+ event.data.message !== null+ ) {+ result = safeJson(event.data.message);+ }+ }+ const pendingAuthorizations = [...authorizations.values()];+ const base = { createdAt, expiresAt, invocationId, result };+ if (pendingAuthorizations.length > 0) {+ return {+ ...base,+ authorizations: pendingAuthorizations as [+ AgentInvocationAuthorizationRequest,+ ...AgentInvocationAuthorizationRequest[],+ ],+ pollAfterMs: 1_000,+ status: "authorization_required",+ };+ }+ if (inputBatch !== undefined) {+ return { ...base, inputRequests: inputBatch.requests, status: "input_required" };+ }+ return { ...base, pollAfterMs: 1_000, status: "working" };+}++async function terminalInvocation(run: {+ readonly createdAt: Date;+ readonly error?: unknown;+ readonly expiredAt?: Date;+ readonly runId: string;+ readonly status: string;+}): Promise<AgentInvocation> {+ const base = {+ createdAt: run.createdAt.toISOString(),+ expiresAt: run.expiredAt?.toISOString(),+ invocationId: run.runId,+ };+ if (run.status === "cancelled") return { ...base, status: "cancelled" };+ if (run.status === "failed") {+ return {+ ...base,+ error: { code: -32603, data: safeJson(run.error), message: errorMessage(run.error) },+ status: "failed",+ };+ }+ const returned = await getRun<{ readonly output: unknown }>(run.runId).returnValue;+ return { ...base, result: safeJson(returned.output), status: "completed" };+}++function workingInvocation(+ invocationId: string,+ createdAt: string,+ expiresAt: string | undefined,+): AgentInvocation {+ return { createdAt, expiresAt, invocationId, pollAfterMs: 1_000, status: "working" };+}++function safeJson(value: unknown): JsonValue {+ try {+ return parseJsonValue(value);+ } catch {+ return String(value);+ }+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : "Session failed.";+}++function conflict(message: string): AgentInvocationMutationResult {+ return { message, type: "conflict" };+}++function isTerminal(status: AgentInvocationStatus): boolean {+ return status === "completed" || status === "failed" || status === "cancelled";+}++function isTerminalRunStatus(status: string): boolean {+ return status === "completed" || status === "failed" || status === "cancelled";+}diff --git a/packages/eve/src/internal/mcp/http-security.test.ts b/packages/eve/src/internal/mcp/http-security.test.tsnew file mode 100644index 000000000..b238b64bb--- /dev/null+++ b/packages/eve/src/internal/mcp/http-security.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it } from "vitest";++import { validateMcpHttpRequest, validateMcpMetadataRequest } from "#internal/mcp/http-security.js";++describe("MCP HTTP security", () => {+ it("accepts secure non-browser requests and exact same-origin browser requests", () => {+ expect(validateMcpHttpRequest(request("https://agent.example/mcp"))).toBeUndefined();+ expect(+ validateMcpHttpRequest(+ request("https://agent.example/mcp", { origin: "https://agent.example" }),+ ),+ ).toBeUndefined();+ });++ it("rejects missing or mismatched Host headers", async () => {+ const missing = validateMcpHttpRequest(+ new Request("https://agent.example/mcp", { method: "POST" }),+ );+ expect(missing?.status).toBe(403);+ await expect(missing?.json()).resolves.toMatchObject({+ error: { message: "Missing Host header" },+ });++ const mismatched = validateMcpHttpRequest(+ request("https://agent.example/mcp", { host: "attacker.example" }),+ );+ expect(mismatched?.status).toBe(403);++ const mismatchedPort = validateMcpHttpRequest(+ request("https://agent.example/mcp", { host: "agent.example:444" }),+ );+ expect(mismatchedPort?.status).toBe(403);+ expect(+ validateMcpHttpRequest(+ request("https://agent.example/mcp", { host: "[email protected]" }),+ )?.status,+ ).toBe(403);++ expect(validateMcpHttpRequest(request("https://agent.example:444/mcp"))).toBeUndefined();+ });++ it("rejects cross-origin browser requests including port changes", () => {+ expect(+ validateMcpHttpRequest(+ request("https://agent.example/mcp", { origin: "https://attacker.example" }),+ )?.status,+ ).toBe(403);+ expect(+ validateMcpHttpRequest(+ request("https://agent.example/mcp", { origin: "https://agent.example:444" }),+ )?.status,+ ).toBe(403);+ });++ it("allows cross-origin OAuth metadata discovery while retaining base guards", () => {+ expect(+ validateMcpMetadataRequest(+ request("https://agent.example/.well-known/oauth-protected-resource", {+ origin: "https://client.example",+ }),+ ),+ ).toBeUndefined();+ expect(+ validateMcpMetadataRequest(+ request("https://agent.example/.well-known/oauth-protected-resource", {+ host: "attacker.example",+ origin: "https://client.example",+ }),+ )?.status,+ ).toBe(403);+ });++ it("allows plain HTTP only on loopback", () => {+ expect(validateMcpHttpRequest(request("http://localhost:2117/mcp"))).toBeUndefined();+ expect(validateMcpHttpRequest(request("http://127.0.0.7:2117/mcp"))).toBeUndefined();+ expect(validateMcpHttpRequest(request("http://127.attacker.example:2117/mcp"))?.status).toBe(+ 403,+ );+ expect(validateMcpHttpRequest(request("http://agent.example/mcp"))?.status).toBe(403);+ });+});++function request(url: string, headers: Record<string, string> = {}): Request {+ const target = new URL(url);+ return new Request(url, {+ headers: { host: target.host, ...headers },+ method: "POST",+ });+}diff --git a/packages/eve/src/internal/mcp/http-security.ts b/packages/eve/src/internal/mcp/http-security.tsnew file mode 100644index 000000000..d248725ea--- /dev/null+++ b/packages/eve/src/internal/mcp/http-security.ts@@ -0,0 +1,92 @@+import { isLoopbackHostname } from "#shared/network-address.js";++/**+ * Applies the fetch-native HTTP guards required in front of the MCP SDK.+ *+ * Non-browser clients normally omit `Origin`; browser requests are restricted+ * to the endpoint's exact origin. Plain HTTP is accepted only on loopback.+ */+export function validateMcpHttpRequest(request: Request): Response | undefined {+ const baseFailure = validateMcpHttpRequestBase(request);+ if (baseFailure !== undefined) return baseFailure;++ const target = new URL(request.url);+ const originHeader = request.headers.get("origin");+ if (originHeader === null || originHeader.length === 0) return undefined;++ let origin: URL;+ try {+ origin = new URL(originHeader);+ } catch {+ return securityError("Invalid Origin header.");+ }+ if (origin.origin !== target.origin) {+ return securityError(`Invalid Origin: ${origin.origin}`);+ }++ return undefined;+}++/**+ * Applies transport and Host validation to the public OAuth discovery route+ * without restricting its Origin. The route itself supplies permissive CORS.+ */+export function validateMcpMetadataRequest(request: Request): Response | undefined {+ return validateMcpHttpRequestBase(request);+}++function validateMcpHttpRequestBase(request: Request): Response | undefined {+ let target: URL;+ try {+ target = new URL(request.url);+ } catch {+ return securityError("Invalid MCP request URL.", 400);+ }++ if (+ target.protocol !== "https:" &&+ !(target.protocol === "http:" && isLoopbackHostname(target.hostname))+ ) {+ return securityError("MCP endpoints require HTTPS except on loopback.");+ }++ const hostFailure = validateHostHeader(request, target);+ if (hostFailure !== undefined) return hostFailure;+ return undefined;+}++function validateHostHeader(request: Request, target: URL): Response | undefined {+ const hostHeader = request.headers.get("host");+ if (hostHeader === null || hostHeader.length === 0) {+ return securityError("Missing Host header");+ }++ let authority: URL;+ try {+ authority = new URL(`${target.protocol}//${hostHeader}`);+ } catch {+ return securityError("Invalid Host header");+ }+ if (+ authority.username !== "" ||+ authority.password !== "" ||+ authority.pathname !== "/" ||+ authority.search !== "" ||+ authority.hash !== "" ||+ authority.host !== target.host+ ) {+ return securityError(`Invalid Host header: ${hostHeader}`);+ }+ return undefined;+}++function securityError(message: string, status = 403): Response {+ return Response.json(+ {+ error: { code: -32_000, message },+ id: null,+ jsonrpc: "2.0",+ },+ { headers: { "content-type": "application/json" }, status },+ );+}diff --git a/packages/eve/src/internal/mcp/protected-resource.test.ts b/packages/eve/src/internal/mcp/protected-resource.test.tsnew file mode 100644index 000000000..da29c538d--- /dev/null+++ b/packages/eve/src/internal/mcp/protected-resource.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from "vitest";++import {+ createMcpProtectedResourceMetadata,+ createMcpResourceChallenge,+} from "#internal/mcp/protected-resource.js";++describe("MCP protected-resource authentication", () => {+ it("builds RFC 9728 metadata", () => {+ expect(+ createMcpProtectedResourceMetadata({+ authorizationServers: ["https://issuer.example"],+ resource: "https://agent.example/mcp",+ scopesSupported: ["agent:invoke"],+ }),+ ).toEqual({+ authorization_servers: ["https://issuer.example"],+ resource: "https://agent.example/mcp",+ scopes_supported: ["agent:invoke"],+ });+ });++ it("challenges with the metadata URL", () => {+ expect(+ createMcpResourceChallenge("https://agent.example/.well-known/oauth-protected-resource", [+ "agent:invoke",+ ]),+ ).toBe(+ 'Bearer resource_metadata="https://agent.example/.well-known/oauth-protected-resource", scope="agent:invoke"',+ );+ });+});diff --git a/packages/eve/src/internal/mcp/protected-resource.ts b/packages/eve/src/internal/mcp/protected-resource.tsnew file mode 100644index 000000000..e7219ff90--- /dev/null+++ b/packages/eve/src/internal/mcp/protected-resource.ts@@ -0,0 +1,33 @@+import { escapeAuthChallengeParameter } from "#public/channels/auth.js";++export interface McpProtectedResourceMetadataOptions {+ readonly authorizationServers: readonly string[];+ readonly resource: string;+ readonly scopesSupported?: readonly string[];+}++/** Creates RFC 9728 protected-resource metadata for an MCP endpoint. */+export function createMcpProtectedResourceMetadata(+ options: McpProtectedResourceMetadataOptions,+): Readonly<Record<string, unknown>> {+ const metadata: Record<string, unknown> = {+ authorization_servers: options.authorizationServers,+ resource: options.resource,+ };+ if (options.scopesSupported !== undefined) {+ metadata.scopes_supported = options.scopesSupported;+ }+ return metadata;+}++/** Creates the RFC 9728 bearer discovery challenge for an MCP resource. */+export function createMcpResourceChallenge(+ resourceMetadataUrl: string,+ scopes?: readonly string[],+): string {+ const parameters = [`resource_metadata="${escapeAuthChallengeParameter(resourceMetadataUrl)}"`];+ if (scopes?.length) {+ parameters.push(`scope="${escapeAuthChallengeParameter(scopes.join(" "))}"`);+ }+ return `Bearer ${parameters.join(", ")}`;+}diff --git a/packages/eve/src/internal/mcp/streamable-http-server.test.ts b/packages/eve/src/internal/mcp/streamable-http-server.test.tsnew file mode 100644index 000000000..1cbc20e7f--- /dev/null+++ b/packages/eve/src/internal/mcp/streamable-http-server.test.ts@@ -0,0 +1,381 @@+import { describe, expect, it, vi } from "vitest";++import type { SessionAuthContext } from "#channel/types.js";+import { z } from "#compiled/zod/index.js";+import {+ createMcpStreamableHttpServer,+ defineMcpTool,+ MCP_LEGACY_PROTOCOL_VERSION,+ MCP_PROTOCOL_VERSION,+} from "#internal/mcp/streamable-http-server.js";++const MCP_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion";+const MCP_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";+const MCP_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities";++const auth: SessionAuthContext = {+ attributes: {},+ authenticator: "test",+ principalId: "alice",+ principalType: "user",+};++function request(body: unknown, headers: Record<string, string> = {}): Request {+ return new Request("https://agent.example/mcp", {+ body: JSON.stringify(body),+ headers: {+ accept: "application/json, text/event-stream",+ "content-type": "application/json",+ ...headers,+ },+ method: "POST",+ });+}++function modernRequest(+ body: {+ readonly method: string;+ readonly params?: Readonly<Record<string, unknown>>;+ readonly [key: string]: unknown;+ },+ headers: Record<string, string> = {},+): Request {+ const standardHeaders: Record<string, string> = {+ "mcp-method": body.method,+ "mcp-protocol-version": MCP_PROTOCOL_VERSION,+ };+ if (typeof body.params?.name === "string") standardHeaders["mcp-name"] = body.params.name;++ return request(+ {+ ...body,+ params: {+ ...body.params,+ _meta: {+ [MCP_CLIENT_CAPABILITIES_META_KEY]: {},+ [MCP_CLIENT_INFO_META_KEY]: { name: "eve-test-client", version: "0.0.0" },+ [MCP_PROTOCOL_VERSION_META_KEY]: MCP_PROTOCOL_VERSION,+ },+ },+ },+ { ...standardHeaders, ...headers },+ );+}++async function jsonRpcResponse(response: Response): Promise<unknown> {+ if (!response.headers.get("content-type")?.includes("text/event-stream")) {+ return await response.json();+ }+ const data = (await response.text()).split("\n").find((line) => line.startsWith("data: "));+ if (data === undefined) throw new Error("MCP SSE response did not contain a data event.");+ return JSON.parse(data.slice("data: ".length));+}++function server() {+ const call = vi.fn(async (input: unknown) => ({+ content: [{ text: JSON.stringify(input), type: "text" as const }],+ }));+ return {+ call,+ handle: createMcpStreamableHttpServer({+ authenticate: async () => auth,+ name: "eve-test",+ tools: [+ defineMcpTool({+ call,+ definition: {+ description: "Echoes input.",+ inputSchema: z.strictObject({ value: z.number() }),+ name: "echo",+ },+ }),+ ],+ version: "0.0.0",+ }),+ };+}++function initialize(handle: (request: Request) => Promise<Response>): Promise<Response> {+ return handle(+ request({+ id: 1,+ jsonrpc: "2.0",+ method: "initialize",+ params: {+ capabilities: {},+ clientInfo: { name: "eve-test-client", version: "0.0.0" },+ protocolVersion: MCP_LEGACY_PROTOCOL_VERSION,+ },+ }),+ );+}++describe("stateless MCP Streamable HTTP server", () => {+ it("serves MCP 2026-07-28 discovery and tools without initialize", async () => {+ const { handle } = server();+ const discovered = await handle(+ modernRequest({+ id: 1,+ jsonrpc: "2.0",+ method: "server/discover",+ }),+ );+ expect(await jsonRpcResponse(discovered)).toMatchObject({+ id: 1,+ result: {+ supportedVersions: [MCP_PROTOCOL_VERSION],+ },+ });++ const listed = await handle(modernRequest({ id: 2, jsonrpc: "2.0", method: "tools/list" }));+ expect(await jsonRpcResponse(listed)).toMatchObject({+ result: { tools: [{ name: "echo" }] },+ });+ });++ it("rejects a modern POST without MCP-Protocol-Version as HeaderMismatch", async () => {+ const { handle } = server();+ const response = await handle(+ request(+ {+ id: "missing-version",+ jsonrpc: "2.0",+ method: "server/discover",+ params: {+ _meta: {+ [MCP_CLIENT_CAPABILITIES_META_KEY]: {},+ [MCP_CLIENT_INFO_META_KEY]: { name: "eve-test-client", version: "0.0.0" },+ [MCP_PROTOCOL_VERSION_META_KEY]: MCP_PROTOCOL_VERSION,+ },+ },+ },+ { "mcp-method": "server/discover" },+ ),+ );++ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toMatchObject({+ error: {+ code: -32_020,+ message: expect.stringContaining("MCP-Protocol-Version header is absent"),+ },+ id: "missing-version",+ jsonrpc: "2.0",+ });+ });++ it("leaves malformed and unsupported modern envelopes to earlier SDK validation rungs", async () => {+ const { handle } = server();+ const malformed = await handle(+ request(+ {+ id: "malformed-envelope",+ jsonrpc: "2.0",+ method: "server/discover",+ params: {+ _meta: {+ [MCP_PROTOCOL_VERSION_META_KEY]: MCP_PROTOCOL_VERSION,+ },+ },+ },+ { "mcp-method": "server/discover" },+ ),+ );+ expect(malformed.status).toBe(400);+ await expect(malformed.json()).resolves.toMatchObject({+ error: { code: -32_602 },+ id: "malformed-envelope",+ });++ const unsupported = await handle(+ request(+ {+ id: "unsupported-version",+ jsonrpc: "2.0",+ method: "server/discover",+ params: {+ _meta: {+ [MCP_CLIENT_CAPABILITIES_META_KEY]: {},+ [MCP_CLIENT_INFO_META_KEY]: { name: "eve-test-client", version: "0.0.0" },+ [MCP_PROTOCOL_VERSION_META_KEY]: "2027-01-01",+ },+ },+ },+ { "mcp-method": "server/discover" },+ ),+ );+ expect(unsupported.status).toBe(400);+ await expect(unsupported.json()).resolves.toMatchObject({+ error: { code: -32_022 },+ id: "unsupported-version",+ });+ });++ it("keeps stateless compatibility with 2025 clients", async () => {+ const { handle } = server();+ const initialized = await initialize(handle);+ expect(await jsonRpcResponse(initialized)).toMatchObject({+ id: 1,+ result: {+ capabilities: { tools: { listChanged: false } },+ protocolVersion: MCP_LEGACY_PROTOCOL_VERSION,+ serverInfo: { name: "eve-test", version: "0.0.0" },+ },+ });+ expect(initialized.headers.get("mcp-session-id")).toBeNull();++ const listed = await handle(request({ id: 2, jsonrpc: "2.0", method: "tools/list" }));+ expect(await jsonRpcResponse(listed)).toMatchObject({+ result: { tools: [{ name: "echo" }] },+ });+ });++ it("calls modern tools with authenticated context and SDK cancellation", async () => {+ const { call, handle } = server();+ const response = await handle(+ modernRequest({+ id: "call-1",+ jsonrpc: "2.0",+ method: "tools/call",+ params: { arguments: { value: 42 }, name: "echo" },+ }),+ );+ expect(await jsonRpcResponse(response)).toMatchObject({+ id: "call-1",+ result: { content: [{ text: '{"value":42}', type: "text" }] },+ });+ expect(call).toHaveBeenCalledWith(+ { value: 42 },+ expect.objectContaining({ auth, signal: expect.any(AbortSignal) }),+ );+ });++ it("enforces the advertised tool input schema before dispatch", async () => {+ const { call, handle } = server();+ const response = await handle(+ modernRequest({+ id: "invalid-call",+ jsonrpc: "2.0",+ method: "tools/call",+ params: { arguments: { extra: true, value: "not-a-number" }, name: "echo" },+ }),+ );++ expect(await jsonRpcResponse(response)).toMatchObject({+ id: "invalid-call",+ result: {+ content: [{ text: expect.stringContaining("Input validation error"), type: "text" }],+ isError: true,+ },+ });+ expect(call).not.toHaveBeenCalled();+ });++ it("returns JSON-RPC errors and acknowledges notifications", async () => {+ const { handle } = server();+ const unknown = await handle(modernRequest({ id: 3, jsonrpc: "2.0", method: "unknown" }));+ expect(await jsonRpcResponse(unknown)).toMatchObject({+ error: { code: -32601, message: "Method not found" },+ id: 3,+ jsonrpc: "2.0",+ });++ const notification = await handle(+ request(+ { jsonrpc: "2.0", method: "notifications/initialized" },+ {+ "mcp-method": "notifications/initialized",+ "mcp-protocol-version": MCP_PROTOCOL_VERSION,+ },+ ),+ );+ expect(notification.status).toBe(202);+ expect(await notification.text()).toBe("");+ });++ it("authenticates before transport handling", async () => {+ const challenge = new Response(null, {+ headers: {+ "www-authenticate":+ 'Bearer resource_metadata="https://agent.example/.well-known/oauth-protected-resource"',+ },+ status: 401,+ });+ const handle = createMcpStreamableHttpServer({+ authenticate: async () => challenge,+ name: "test",+ tools: [],+ version: "0",+ });++ const unauthorized = await handle(request("not relevant"));+ expect(unauthorized.status).toBe(401);+ expect(unauthorized.headers.get("www-authenticate")).toContain("resource_metadata=");++ const streamed = await handle(new Request("https://agent.example/mcp"));+ expect(streamed.status).toBe(401);++ const deleted = await handle(new Request("https://agent.example/mcp", { method: "DELETE" }));+ expect(deleted.status).toBe(401);+ });++ it("does not open a process-local session for authenticated GET", async () => {+ const response = await server().handle(+ new Request("https://agent.example/mcp", {+ headers: { accept: "text/event-stream" },+ }),+ );++ expect(response.status).toBe(405);+ });++ it("enforces Streamable HTTP media types", async () => {+ const response = await server().handle(+ request(+ {+ id: 1,+ jsonrpc: "2.0",+ method: "initialize",+ params: {+ capabilities: {},+ clientInfo: { name: "eve-test-client", version: "0.0.0" },+ protocolVersion: MCP_LEGACY_PROTOCOL_VERSION,+ },+ },+ { accept: "application/json" },+ ),+ );++ expect(response.status).toBe(406);+ expect(await jsonRpcResponse(response)).toMatchObject({ error: { code: -32000 } });+ });++ it("bounds compatibility preflight parsing before the transport reads the body", async () => {+ const { handle } = server();+ const response = await handle(+ request({ padding: "x".repeat(4 * 1024 * 1024), method: "tools/list" }),+ );++ expect(response.status).toBe(413);+ await expect(response.json()).resolves.toMatchObject({+ error: { code: -32_000, message: "Request body too large" },+ id: null,+ jsonrpc: "2.0",+ });+ });++ it("rejects duplicate tool names at construction", () => {+ const tool = defineMcpTool({+ call: async () => ({ content: [] }),+ definition: { inputSchema: z.strictObject({}), name: "duplicate" },+ });+ expect(() =>+ createMcpStreamableHttpServer({+ authenticate: async () => auth,+ name: "test",+ tools: [tool, tool],+ version: "0",+ }),+ ).toThrow("MCP tool names must be unique");+ });+});diff --git a/packages/eve/src/internal/mcp/streamable-http-server.ts b/packages/eve/src/internal/mcp/streamable-http-server.tsnew file mode 100644index 000000000..ed043c8ed--- /dev/null+++ b/packages/eve/src/internal/mcp/streamable-http-server.ts@@ -0,0 +1,338 @@+import {+ createMcpHandler,+ McpServer,+ type McpToolAnnotations,+ type StandardSchemaWithJSON,+} from "#compiled/@modelcontextprotocol/server/index.js";++import type { SessionAuthContext } from "#channel/types.js";++export const MCP_PROTOCOL_VERSION = "2026-07-28";+export const MCP_LEGACY_PROTOCOL_VERSION = "2025-11-25";+const MCP_COMPATIBILITY_INSPECTION_MAX_BYTES = 4 * 1024 * 1024;++export interface McpToolDefinition<+ TInputSchema extends StandardSchemaWithJSON = StandardSchemaWithJSON,+> {+ readonly name: string;+ readonly description?: string;+ readonly annotations?: McpToolAnnotations;+ readonly inputSchema: TInputSchema;+ readonly outputSchema?: StandardSchemaWithJSON;+}++export interface McpCallToolResult<+ TStructured extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,+> {+ readonly content: readonly McpContent[];+ readonly isError?: boolean;+ readonly structuredContent?: TStructured;+}++export type McpContent =+ | { readonly type: "text"; readonly text: string }+ | { readonly type: "resource_link"; readonly name: string; readonly uri: string };++export interface McpServerTool {+ readonly name: string;+ register(server: McpServer, auth: SessionAuthContext | null): void;+}++type InferSchemaOutput<TSchema> =+ TSchema extends StandardSchemaWithJSON<unknown, infer TOutput> ? TOutput : never;++/** Keeps a schema and its inferred handler input coupled while erasing heterogeneous storage. */+export function defineMcpTool<+ const TInputSchema extends StandardSchemaWithJSON<unknown, unknown>,+ TStructured extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,+>(input: {+ readonly definition: McpToolDefinition<TInputSchema>;+ call(+ value: InferSchemaOutput<TInputSchema>,+ context: { readonly auth: SessionAuthContext | null; readonly signal: AbortSignal },+ ): Promise<McpCallToolResult<TStructured>>;+}): McpServerTool {+ return {+ name: input.definition.name,+ register(server, auth) {+ server.registerTool(+ input.definition.name,+ {+ ...(input.definition.annotations === undefined+ ? {}+ : { annotations: input.definition.annotations }),+ ...(input.definition.description === undefined+ ? {}+ : { description: input.definition.description }),+ inputSchema: input.definition.inputSchema,+ ...(input.definition.outputSchema === undefined+ ? {}+ : { outputSchema: input.definition.outputSchema }),+ },+ async (value, context) =>+ await callTool(+ input.call,+ value as InferSchemaOutput<TInputSchema>,+ context.mcpReq.signal,+ auth,+ ),+ );+ },+ };+}++export interface McpStreamableHttpServerOptions {+ readonly name: string;+ readonly version: string;+ readonly tools: readonly McpServerTool[];+ authenticate(request: Request): Promise<SessionAuthContext | null | Response>;+}++/**+ * Creates a dual-era, stateless MCP HTTP request handler.+ *+ * Current clients use MCP 2026-07-28's per-request envelope. Older clients+ * fall back to the SDK's stateless 2025 Streamable HTTP implementation.+ */+export function createMcpStreamableHttpServer(+ options: McpStreamableHttpServerOptions,+): (request: Request) => Promise<Response> {+ const tools = new Map(options.tools.map((tool) => [tool.name, tool]));+ if (tools.size !== options.tools.length) throw new Error("MCP tool names must be unique.");++ return async (request) => {+ const auth = await options.authenticate(request);+ if (auth instanceof Response) return auth;++ const preflight = await preflightModernRequest(request);+ if (preflight.response !== undefined) return preflight.response;++ const handler = createMcpHandler(() => createServer(options, tools, auth), {+ legacy: "stateless",+ });+ return await handler.fetch(+ request,+ preflight.parsedBody === undefined ? undefined : { parsedBody: preflight.parsedBody },+ );+ };+}++interface ModernRequestPreflight {+ readonly parsedBody?: unknown;+ readonly response?: Response;+}++/**+ * The SDK currently checks MCP-Protocol-Version only when the header is+ * present. MCP 2026-07-28 requires it on every modern POST, so reject the+ * missing-header case here until the upstream handler does:+ * modelcontextprotocol/typescript-sdk#2589.+ */+async function preflightModernRequest(request: Request): Promise<ModernRequestPreflight> {+ if (request.method.toUpperCase() !== "POST" || request.headers.has("mcp-protocol-version")) {+ return {};+ }++ const inspected = await inspectRequestBody(request);+ if (inspected.tooLarge) return { response: requestBodyTooLargeResponse() };+ if (inspected.invalidJson) return { response: invalidJsonResponse() };+ const parsedBody = inspected.value;+ if (parsedBody === undefined) return {};++ if (!claimsCurrentProtocolVersion(parsedBody)) {+ return { parsedBody };+ }++ const earlierFailure = await probeEarlierValidationFailure(request, parsedBody);+ if (earlierFailure !== undefined) {+ return { parsedBody, response: earlierFailure };+ }++ return {+ parsedBody,+ response: headerMismatchResponse(parsedBody),+ };+}++async function inspectRequestBody(request: Request): Promise<{+ readonly invalidJson?: boolean;+ readonly tooLarge: boolean;+ readonly value?: unknown;+}> {+ const body = request.body;+ if (body === null) return { tooLarge: false };++ const reader = body.getReader();+ const chunks: Uint8Array[] = [];+ let size = 0;+ try {+ while (true) {+ const chunk = await reader.read();+ if (chunk.done) break;+ size += chunk.value.byteLength;+ if (size > MCP_COMPATIBILITY_INSPECTION_MAX_BYTES) {+ await reader.cancel();+ return { tooLarge: true };+ }+ chunks.push(chunk.value);+ }++ const bytes = new Uint8Array(size);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }+ return { tooLarge: false, value: JSON.parse(new TextDecoder().decode(bytes)) };+ } catch {+ return { invalidJson: true, tooLarge: false };+ }+}++function invalidJsonResponse(): Response {+ return Response.json(+ {+ error: { code: -32_700, message: "Parse error" },+ id: null,+ jsonrpc: "2.0",+ },+ { status: 400 },+ );+}++function requestBodyTooLargeResponse(): Response {+ return Response.json(+ {+ error: { code: -32_000, message: "Request body too large" },+ id: null,+ jsonrpc: "2.0",+ },+ { status: 413, statusText: "Request Entity Too Large" },+ );+}++function claimsCurrentProtocolVersion(body: unknown): boolean {+ return (+ isPlainRecord(body) &&+ isPlainRecord(body.params) &&+ isPlainRecord(body.params._meta) &&+ body.params._meta["io.modelcontextprotocol/protocolVersion"] === MCP_PROTOCOL_VERSION+ );+}++function isPlainRecord(value: unknown): value is Readonly<Record<string, unknown>> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/**+ * Ask a side-effect-free SDK handler to apply the validation rungs that+ * precede required standard-header presence. Preserve those errors; otherwise+ * the valid current-revision envelope is ready for the missing-header error.+ */+async function probeEarlierValidationFailure(+ request: Request,+ parsedBody: unknown,+): Promise<Response | undefined> {+ const headers = new Headers(request.headers);+ headers.set("mcp-protocol-version", MCP_PROTOCOL_VERSION);+ const probeRequest = new Request(request.url, {+ body: JSON.stringify(parsedBody),+ headers,+ method: request.method,+ });+ const probe = createMcpHandler(() => new McpServer({ name: "eve-mcp-preflight", version: "0" }), {+ legacy: "reject",+ });+ try {+ const response = await probe.fetch(probeRequest, { parsedBody });+ if (response.status === 406 || response.status === 415) {+ return response;+ }+ if (response.status === 400) {+ const body = (await response+ .clone()+ .json()+ .catch(() => undefined)) as { readonly error?: { readonly code?: unknown } } | undefined;+ if (+ body?.error?.code === -32_700 ||+ body?.error?.code === -32_600 ||+ body?.error?.code === -32_602 ||+ body?.error?.code === -32_022+ ) {+ return response;+ }+ }+ await response.body?.cancel();+ return undefined;+ } finally {+ await probe.close().catch(() => {});+ }+}++function headerMismatchResponse(body: unknown): Response {+ const mismatchBody =+ "the body carries a modern MCP envelope but the required MCP-Protocol-Version header is absent";+ return Response.json(+ {+ error: {+ code: -32_020,+ data: {+ mismatch: {+ body: mismatchBody,+ header: "(missing)",+ },+ },+ message: `Bad Request: the request headers and body disagree: ${mismatchBody}`,+ },+ id: readJsonRpcRequestId(body),+ jsonrpc: "2.0",+ },+ { status: 400 },+ );+}++function readJsonRpcRequestId(body: unknown): string | number | null {+ if (typeof body !== "object" || body === null || Array.isArray(body)) return null;+ const id = Reflect.get(body, "id");+ return typeof id === "string" || typeof id === "number" ? id : null;+}++function createServer(+ options: Pick<McpStreamableHttpServerOptions, "name" | "version">,+ tools: ReadonlyMap<string, McpServerTool>,+ auth: SessionAuthContext | null,+): McpServer {+ const server = new McpServer(+ { name: options.name, version: options.version },+ { capabilities: { tools: { listChanged: false } } },+ );++ for (const tool of tools.values()) tool.register(server, auth);++ return server;+}++async function callTool<TInput, TStructured extends Readonly<Record<string, unknown>>>(+ call: (+ input: TInput,+ context: { readonly auth: SessionAuthContext | null; readonly signal: AbortSignal },+ ) => Promise<McpCallToolResult<TStructured>>,+ input: TInput,+ signal: AbortSignal,+ auth: SessionAuthContext | null,+): Promise<McpCallToolResult<TStructured>> {+ try {+ return await call(input, { auth, signal });+ } catch (error) {+ return toolError(error instanceof Error ? error.message : "Tool call failed.");+ }+}++function toolError<TStructured extends Readonly<Record<string, unknown>>>(+ message: string,+): McpCallToolResult<TStructured> {+ return {+ content: [{ type: "text", text: message }],+ isError: true,+ };+}diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex 3708d1914..05acbd2e9 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -12,6 +12,7 @@ import { readTrustedDevelopmentClientAddress } from "#internal/nitro/dev-client-import { DEVELOPMENT_WORKFLOW_SECRET_ENV } from "#internal/workflow/development-world-protocol.js";import {attachAgentInfoRouteResponse,+ attachRouteChannelName,attachRouteSessionCreator,} from "#internal/nitro/routes/channel-route-context.js";import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";@@ -248,19 +249,22 @@ function buildRouteArgs(const to = createCrossChannelToFn(bundle.runtime, toCrossChannelTargets(bundle.channels));const args = attachRouteSessionCreator(- attachAgentInfoRouteResponse(- {- attachSession,- ...channelOperations,- params,- requestIp,- to,- waitUntil,- },- async () => {- const { handleAgentInfoRequest } = await import("#internal/nitro/routes/info.js");- return await handleAgentInfoRequest(config);- },+ attachRouteChannelName(+ attachAgentInfoRouteResponse(+ {+ attachSession,+ ...channelOperations,+ params,+ requestIp,+ to,+ waitUntil,+ },+ async () => {+ const { handleAgentInfoRequest } = await import("#internal/nitro/routes/info.js");+ return await handleAgentInfoRequest(config);+ },+ ),+ channelName,),async (input) =>await bundle.runtime.createSession({diff --git a/packages/eve/src/internal/nitro/routes/channel-route-context.ts b/packages/eve/src/internal/nitro/routes/channel-route-context.tsindex d0c8673ab..d018e3064 100644--- a/packages/eve/src/internal/nitro/routes/channel-route-context.ts+++ b/packages/eve/src/internal/nitro/routes/channel-route-context.ts@@ -7,13 +7,29 @@ export type RouteSessionCreator = () => Promise<RunHandle>;const agentInfoRouteResponseKey = "__eveAgentInfoRouteResponse";+const routeChannelNameKey = "__eveRouteChannelName";const routeSessionCreatorKey = "__eveRouteSessionCreator";type InternalRouteArgs = RouteHandlerArgs & {[agentInfoRouteResponseKey]?: AgentInfoRouteResponse;+ [routeChannelNameKey]?: string;[routeSessionCreatorKey]?: RouteSessionCreator;};+export function attachRouteChannelName<TArgs extends RouteHandlerArgs>(+ args: TArgs,+ channelName: string,+): TArgs {+ const routeArgs: InternalRouteArgs = args;+ routeArgs[routeChannelNameKey] = channelName;+ return args;+}++export function readRouteChannelName(args: RouteHandlerArgs): string | undefined {+ const routeArgs: InternalRouteArgs = args;+ return routeArgs[routeChannelNameKey];+}+export function attachAgentInfoRouteResponse<TArgs extends RouteHandlerArgs>(args: TArgs,respond: AgentInfoRouteResponse,diff --git a/packages/eve/src/internal/vercel-agent-summary.ts b/packages/eve/src/internal/vercel-agent-summary.tsindex fa280a49d..1958003c1 100644--- a/packages/eve/src/internal/vercel-agent-summary.ts+++ b/packages/eve/src/internal/vercel-agent-summary.ts@@ -148,7 +148,7 @@ export interface VercelEveConnectionEntry {export interface VercelEveChannelEntry {readonly name: string;- readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "WEBSOCKET";+ readonly method: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" | "WEBSOCKET";readonly urlPath: string;readonly type: VercelEveChannelType;/**diff --git a/packages/eve/src/public/channels/auth.test.ts b/packages/eve/src/public/channels/auth.test.tsindex e2d2459da..20192a33e 100644--- a/packages/eve/src/public/channels/auth.test.ts+++ b/packages/eve/src/public/channels/auth.test.ts@@ -262,12 +262,12 @@ describe("createUnauthorizedResponse", () => {const response = createUnauthorizedResponse({challenges: [{ scheme: "Basic", parameters: { realm: "weather" } },- { scheme: "Bearer", parameters: { error: 'need "token"' } },+ { scheme: "Bearer", parameters: { error: 'need \\"token"' } },],});expect(response.headers.get("www-authenticate")).toContain('Basic realm="weather"');- expect(response.headers.get("www-authenticate")).toMatch(/Bearer error="need \\"token\\""/);+ expect(response.headers.get("www-authenticate")).toMatch(/Bearer error="need \\\\\\"token\\""/);});});@@ -570,6 +570,60 @@ describe("routeAuth", () => {}});+ it("marks a supplied Bearer token as invalid after all Bearer strategies decline it", async () => {+ const first = vi.fn(() => null);+ const second = vi.fn(() => null);+ const request = new Request(TEST_ROUTE_URL, {+ headers: { authorization: "Bearer expired-or-malformed" },+ method: "POST",+ });+ const result = await routeAuth(request, [+ withAuthChallenges(first, [{ scheme: "Bearer" }]),+ withAuthChallenges(second, [{ scheme: "Bearer" }]),+ ]);++ expect(first).toHaveBeenCalledOnce();+ expect(second).toHaveBeenCalledOnce();+ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ expect(result.status).toBe(401);+ expect(result.headers.get("www-authenticate")).toBe('Bearer error="invalid_token"');+ }+ });++ it("keeps a missing Bearer credential as a bare challenge", async () => {+ const result = await routeAuth(+ makeRequest(),+ withAuthChallenges(() => null, [{ scheme: "Bearer" }]),+ );++ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ expect(result.headers.get("www-authenticate")).toBe("Bearer");+ }+ });++ it("does not label a rejected Basic credential as an invalid Bearer token", async () => {+ const result = await routeAuth(+ new Request(TEST_ROUTE_URL, {+ headers: { authorization: `Basic ${Buffer.from("ops:wrong").toString("base64")}` },+ method: "POST",+ }),+ [+ httpBasic({ password: "top-secret", username: "ops" }),+ withAuthChallenges(() => null, [{ scheme: "Bearer" }]),+ ],+ );++ expect(result).toBeInstanceOf(Response);+ if (result instanceof Response) {+ const challenge = result.headers.get("www-authenticate");+ expect(challenge).toContain('Basic realm="eve"');+ expect(challenge).toContain("Bearer");+ expect(challenge).not.toContain("invalid_token");+ }+ });+it("advertises both Basic and Bearer for a mixed httpBasic + jwtHmac route", async () => {const request = makeRequest();const result = await routeAuth(request, [diff --git a/packages/eve/src/public/channels/auth.ts b/packages/eve/src/public/channels/auth.tsindex dac65a40c..b0a15a9f4 100644--- a/packages/eve/src/public/channels/auth.ts+++ b/packages/eve/src/public/channels/auth.ts@@ -29,6 +29,7 @@ import {isRuntimeIpAllowed,type RuntimeIpAllowList,} from "#runtime/governance/network/ip-allow-list.js";+import { isLoopbackHostname } from "#shared/network-address.js";// ---------------------------------------------------------------------------// Result types@@ -438,15 +439,39 @@ function formatChallenge(challenge: UnauthorizedChallenge): string {return challenge.scheme;}const renderedParameters = Object.entries(challenge.parameters)- .map(([key, value]) => `${key}="${escapeChallengeValue(value)}"`)+ .map(([key, value]) => `${key}="${escapeAuthChallengeParameter(value)}"`).join(", ");return `${challenge.scheme} ${renderedParameters}`;}-function escapeChallengeValue(value: string): string {+/** @internal Escapes a value for an HTTP auth challenge quoted string. */+export function escapeAuthChallengeParameter(value: string): string {return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');}+function isValidOAuthIdentifierUrl(value: string): boolean {+ try {+ const url = new URL(value);+ const secureTransport =+ url.protocol === "https:" || (url.protocol === "http:" && isLoopbackHostname(url.hostname));+ return (+ secureTransport &&+ url.username.length === 0 &&+ url.password.length === 0 &&+ url.search.length === 0 &&+ url.hash.length === 0+ );+ } catch {+ return false;+ }+}++function isValidMetadataPath(value: string): boolean {+ if (!value.startsWith("/") || value.startsWith("//")) return false;+ const url = new URL(value, "https://eve.invalid");+ return url.origin === "https://eve.invalid" && url.search.length === 0 && url.hash.length === 0;+}+/*** Options accepted by auth error classes. The class chooses the HTTP status.*/@@ -497,6 +522,97 @@ export type AuthFn<TEvent = Request> = (event: TEvent,) => SessionAuthContext | null | undefined | Promise<SessionAuthContext | null | undefined>;+/**+ * OAuth protected-resource metadata attached to an inbound auth policy.+ * `issuer` is shorthand for a single authorization server.+ */+export type OAuthResourceOptions = {+ readonly metadataPath?: string;+ readonly resource?: string;+ readonly scopes?: readonly string[];+} & (+ | {+ readonly authorizationServers?: never;+ readonly issuer: string;+ }+ | {+ readonly authorizationServers: readonly string[];+ readonly issuer?: never;+ }+);++const OAUTH_RESOURCE_SYMBOL = Symbol.for("eve.channels.auth.oauthResource");++/**+ * An ordinary route authenticator decorated with OAuth protected-resource+ * discovery metadata.+ */+export type OAuthResourceAuth = AuthFn<Request> & {+ readonly [OAUTH_RESOURCE_SYMBOL]: OAuthResourceOptions;+};++/**+ * Adds OAuth protected-resource metadata to an existing inbound auth policy.+ *+ * The returned value remains an {@link AuthFn}: it preserves the ordered auth+ * walk and can be used by any channel. A protocol-aware channel such as+ * `mcpChannel` may additionally publish the metadata and discovery challenge.+ */+export function oauthResource(+ auth: AuthFn<Request> | readonly AuthFn<Request>[],+ options: OAuthResourceOptions,+): OAuthResourceAuth {+ const authorizationServers =+ options.issuer !== undefined ? [options.issuer] : options.authorizationServers;+ if (+ authorizationServers.length === 0 ||+ authorizationServers.some((value) => !isValidOAuthIdentifierUrl(value))+ ) {+ throw new Error(+ "oauthResource requires at least one HTTPS authorization server URL (HTTP is allowed only on loopback).",+ );+ }+ if (options.resource !== undefined && !isValidOAuthIdentifierUrl(options.resource)) {+ throw new Error(+ "oauthResource resource must be an HTTPS URL without credentials, query, or fragment (HTTP is allowed only on loopback).",+ );+ }+ if (options.metadataPath !== undefined && !isValidMetadataPath(options.metadataPath)) {+ throw new Error(+ "oauthResource metadataPath must be an absolute path without a host, query, or fragment.",+ );+ }++ const list: readonly AuthFn<Request>[] = Array.isArray(auth)+ ? (auth as readonly AuthFn<Request>[])+ : [auth as AuthFn<Request>];+ const composed: AuthFn<Request> = async (request) => {+ for (const fn of list) {+ const result = await fn(request);+ if (result) return result;+ }+ return null;+ };+ const declaredChallenges = collectDeclaredChallenges(list);+ const wrapped = withAuthChallenges(+ composed,+ declaredChallenges.length > 0 ? declaredChallenges : [{ scheme: "Bearer" }],+ ) as OAuthResourceAuth;+ Object.defineProperty(wrapped, OAUTH_RESOURCE_SYMBOL, {+ enumerable: false,+ value: options,+ });+ return wrapped;+}++/** @internal Reads OAuth resource metadata without widening `AuthFn`. */+export function readOAuthResourceOptions(+ auth: AuthFn<Request> | readonly AuthFn<Request>[],+): OAuthResourceOptions | undefined {+ if (Array.isArray(auth)) return undefined;+ return (auth as Partial<OAuthResourceAuth>)[OAUTH_RESOURCE_SYMBOL];+}+/*** Symbol-keyed property carrying the `www-authenticate` challenges an* {@link AuthFn} would satisfy, attached via {@link withAuthChallenges}.@@ -608,11 +724,45 @@ export async function routeAuth(}const declaredChallenges = collectDeclaredChallenges(list);+ const challenges =+ declaredChallenges.length > 0+ ? addInvalidBearerTokenError(request, declaredChallenges)+ : [{ scheme: "Bearer" } satisfies UnauthorizedChallenge];return createUnauthorizedResponse({- challenges: declaredChallenges.length > 0 ? declaredChallenges : [{ scheme: "Bearer" }],+ challenges,});}+/**+ * A supplied Bearer credential that every declared Bearer strategy declined+ * is invalid, rather than absent. Add the RFC 6750 error only after the whole+ * auth walk has exhausted so another Bearer strategy or a fallback such as+ * localDev() still has a chance to accept the request.+ */+function addInvalidBearerTokenError(+ request: Request,+ challenges: readonly UnauthorizedChallenge[],+): readonly UnauthorizedChallenge[] {+ const authorization = request.headers.get("authorization");+ if (authorization === null || !/^Bearer(?:\s|$)/i.test(authorization.trim())) {+ return challenges;+ }+ if (!challenges.some((challenge) => challenge.scheme === "Bearer")) {+ return challenges;+ }+ return challenges.map((challenge) =>+ challenge.scheme !== "Bearer" || challenge.parameters?.error !== undefined+ ? challenge+ : {+ ...challenge,+ parameters: {+ ...challenge.parameters,+ error: "invalid_token",+ },+ },+ );+}+/*** Returns an {@link AuthFn} for scaffolded apps that makes unfinished* production auth fail as an intentional 401 rather than an internal routediff --git a/packages/eve/src/public/channels/mcp.test.ts b/packages/eve/src/public/channels/mcp.test.tsnew file mode 100644index 000000000..c2a27284d--- /dev/null+++ b/packages/eve/src/public/channels/mcp.test.ts@@ -0,0 +1,478 @@+import { describe, expect, it, vi } from "vitest";++import type { SessionAuthContext } from "#channel/types.js";+import type { RouteHandlerArgs } from "#channel/routes.js";+import {+ attachAgentInfoRouteResponse,+ attachRouteChannelName,+ attachRouteSessionCreator,+} from "#internal/nitro/routes/channel-route-context.js";+import { MCP_LEGACY_PROTOCOL_VERSION } from "#internal/mcp/streamable-http-server.js";+import { ForbiddenError, none, oauthResource, withAuthChallenges } from "#public/channels/auth.js";+import { mcpChannel } from "#public/channels/mcp.js";++const principal: SessionAuthContext = {+ attributes: {},+ authenticator: "test",+ principalId: "user-1",+ principalType: "user",+};++describe("mcpChannel", () => {+ it("fails closed when auth is omitted", () => {+ expect(() => mcpChannel({} as never)).toThrow(+ "mcpChannel requires auth. Use none() for explicit public access.",+ );+ });++ it("publishes task-mode durable invocation compatibility tools", async () => {+ const channel = mcpChannel({ auth: none() });+ expect(channel.routes.map((route) => `${route.method} ${route.path}`)).toEqual([+ "GET /mcp",+ "POST /mcp",+ "DELETE /mcp",+ ]);+ const postRoute = channel.routes[1]!;+ if (postRoute.transport === "websocket") throw new Error("expected HTTP route");++ const initialize = await postRoute.handler(+ mcpRequest({+ id: 1,+ jsonrpc: "2.0",+ method: "initialize",+ params: {+ capabilities: {},+ clientInfo: { name: "test-client", version: "0.0.0" },+ protocolVersion: MCP_LEGACY_PROTOCOL_VERSION,+ },+ }),+ routeArgs(),+ );+ await expect(jsonRpcResponse(initialize)).resolves.toMatchObject({+ result: { serverInfo: { name: "compiled-agent" } },+ });++ const tools = await postRoute.handler(+ mcpRequest({ id: 2, jsonrpc: "2.0", method: "tools/list" }),+ routeArgs(),+ );+ const body = (await jsonRpcResponse(tools)) as {+ result: {+ tools: Array<{+ description?: string;+ inputSchema: Record<string, unknown>;+ name: string;+ outputSchema?: Record<string, unknown>;+ }>;+ };+ };+ expect(body.result.tools.map((tool) => tool.name)).toEqual([+ "agent_start",+ "agent_get",+ "agent_update",+ "agent_cancel",+ ]);+ expect(body.result.tools[0]).toMatchObject({+ annotations: {+ destructiveHint: true,+ openWorldHint: true,+ },+ description: expect.stringContaining("Investigates tasks."),+ outputSchema: { type: "object" },+ });+ expect(body.result.tools[1]).toMatchObject({+ annotations: {+ idempotentHint: true,+ openWorldHint: false,+ readOnlyHint: true,+ },+ });+ expect(body.result.tools[2]).toMatchObject({+ annotations: {+ idempotentHint: false,+ },+ inputSchema: {+ properties: {+ responses: {+ items: {+ properties: {+ optionId: { type: "string" },+ requestId: { type: "string" },+ text: { type: "string" },+ },+ required: ["requestId"],+ },+ },+ },+ },+ outputSchema: {+ oneOf: expect.arrayContaining([+ expect.objectContaining({+ properties: expect.objectContaining({+ inputRequests: expect.any(Object),+ status: { const: "input_required", type: "string" },+ }),+ required: expect.arrayContaining(["inputRequests"]),+ }),+ expect.objectContaining({+ properties: expect.objectContaining({+ authorizations: expect.objectContaining({ minItems: 1 }),+ status: { const: "authorization_required", type: "string" },+ }),+ required: expect.arrayContaining(["authorizations"]),+ }),+ expect.objectContaining({+ properties: expect.objectContaining({+ error: expect.any(Object),+ status: { const: "failed", type: "string" },+ }),+ required: expect.arrayContaining(["error"]),+ }),+ ]),+ },+ });+ });++ it("uses existing eve auth strategies directly", async () => {+ const channel = mcpChannel({ auth: () => principal });+ const route = channel.routes[1]!;+ if (route.transport === "websocket") throw new Error("expected HTTP route");++ const response = await route.handler(+ mcpRequest({+ id: 1,+ jsonrpc: "2.0",+ method: "initialize",+ params: {+ capabilities: {},+ clientInfo: { name: "test-client", version: "0.0.0" },+ protocolVersion: MCP_LEGACY_PROTOCOL_VERSION,+ },+ }),+ routeArgs(),+ );+ expect(response.status).toBe(200);+ });++ it("rejects cross-origin requests before running auth", async () => {+ const authenticate = vi.fn(() => principal);+ const channel = mcpChannel({ auth: authenticate });+ const route = channel.routes[1]!;+ if (route.transport === "websocket") throw new Error("expected HTTP route");++ const response = await route.handler(+ mcpRequest(+ {+ id: 1,+ jsonrpc: "2.0",+ method: "tools/list",+ },+ { origin: "https://attacker.example" },+ ),+ routeArgs(),+ );++ expect(response.status).toBe(403);+ expect(authenticate).not.toHaveBeenCalled();+ });++ it("bounds and rejects external output schemas before starting work", async () => {+ const createSession = vi.fn();+ const channel = mcpChannel({ auth: none() });+ const route = channel.routes[1]!;+ if (route.transport === "websocket") throw new Error("expected HTTP route");++ const response = await route.handler(+ mcpRequest({+ id: 1,+ jsonrpc: "2.0",+ method: "tools/call",+ params: {+ arguments: {+ message: "work",+ outputSchema: { $ref: "https://attacker.example/schema.json" },+ },+ name: "agent_start",+ },+ }),+ routeArgs(createSession),+ );++ await expect(jsonRpcResponse(response)).resolves.toMatchObject({+ result: {+ content: [+ {+ text: "outputSchema external $ref values are not supported.",+ type: "text",+ },+ ],+ isError: true,+ },+ });+ expect(createSession).not.toHaveBeenCalled();+ });++ it("mounts OAuth resource metadata and augments auth failures", async () => {+ const channel = mcpChannel({+ auth: oauthResource(+ withAuthChallenges(+ () => null,+ [{ parameters: { realm: "eve" }, scheme: "Basic" }, { scheme: "Bearer" }],+ ),+ {+ issuer: "https://issuer.example",+ resource: "https://agent.example/delegate",+ scopes: ["agent:invoke"],+ },+ ),+ path: "/delegate",+ });+ expect(channel.routes.map((route) => `${route.method} ${route.path}`)).toEqual([+ "GET /.well-known/oauth-protected-resource",+ "HEAD /.well-known/oauth-protected-resource",+ "OPTIONS /.well-known/oauth-protected-resource",+ "GET /delegate",+ "POST /delegate",+ "DELETE /delegate",+ ]);++ const metadataRoute = channel.routes[0]!;+ if (metadataRoute.transport === "websocket") throw new Error("expected HTTP route");+ const metadata = await metadataRoute.handler(+ requestWithHost("https://private.example/.well-known/oauth-protected-resource"),+ {} as never,+ );+ await expect(metadata.json()).resolves.toEqual({+ authorization_servers: ["https://issuer.example"],+ resource: "https://agent.example/delegate",+ scopes_supported: ["agent:invoke"],+ });+ expect(metadata.headers.get("access-control-allow-origin")).toBe("*");++ const route = channel.routes[4]!;+ if (route.transport === "websocket") throw new Error("expected HTTP route");+ const response = await route.handler(+ requestWithHost("https://private.example/delegate", { method: "POST" }),+ {} as never,+ );+ expect(response.status).toBe(401);+ const challenge = response.headers.get("www-authenticate");+ expect(challenge).toContain(+ 'resource_metadata="https://agent.example/.well-known/oauth-protected-resource"',+ );+ expect(challenge).toContain('Basic realm="eve"');+ expect(challenge).toContain('scope="agent:invoke"');+ expect(challenge?.match(/\bBearer\b/g)).toHaveLength(1);+ });++ it("adds resource metadata only to explicit insufficient-scope responses", async () => {+ const genericChannel = mcpChannel({+ auth: oauthResource(+ () => {+ throw new ForbiddenError();+ },+ { issuer: "https://issuer.example", scopes: ["agent:invoke"] },+ ),+ });+ const genericRoute = genericChannel.routes[4]!;+ if (genericRoute.transport === "websocket") throw new Error("expected HTTP route");+ const generic = await genericRoute.handler(+ requestWithHost("https://agent.example/mcp", { method: "POST" }),+ {} as never,+ );+ expect(generic.status).toBe(403);+ expect(generic.headers.get("www-authenticate")).toBeNull();++ const scopedChannel = mcpChannel({+ auth: oauthResource(+ () => {+ throw new ForbiddenError({+ challenges: [+ {+ parameters: { error: "insufficient_scope", scope: "agent:admin" },+ scheme: "Bearer",+ },+ ],+ });+ },+ { issuer: "https://issuer.example", scopes: ["agent:invoke"] },+ ),+ });+ const scopedRoute = scopedChannel.routes[4]!;+ if (scopedRoute.transport === "websocket") throw new Error("expected HTTP route");+ const scoped = await scopedRoute.handler(+ requestWithHost("https://agent.example/mcp", { method: "POST" }),+ {} as never,+ );+ const scopedChallenge = scoped.headers.get("www-authenticate");+ expect(scoped.status).toBe(403);+ expect(scopedChallenge).toContain('error="insufficient_scope"');+ expect(scopedChallenge).toContain('scope="agent:admin"');+ expect(scopedChallenge).not.toContain('scope="agent:invoke"');+ expect(scopedChallenge).toContain(+ 'resource_metadata="https://agent.example/.well-known/oauth-protected-resource"',+ );+ expect(scopedChallenge?.match(/\bBearer\b/g)).toHaveLength(1);+ });++ it("preserves invalid_token in the OAuth resource challenge", async () => {+ const channel = mcpChannel({+ auth: oauthResource(+ withAuthChallenges(() => null, [{ scheme: "Bearer" }]),+ {+ issuer: "https://issuer.example",+ scopes: ["agent:invoke"],+ },+ ),+ });+ const route = channel.routes[4]!;+ if (route.transport === "websocket") throw new Error("expected HTTP route");+ const response = await route.handler(+ requestWithHost("https://agent.example/mcp", {+ headers: { authorization: "Bearer expired-token" },+ method: "POST",+ }),+ {} as never,+ );++ expect(response.status).toBe(401);+ const challenge = response.headers.get("www-authenticate");+ expect(challenge).toContain('error="invalid_token"');+ expect(challenge).toContain('scope="agent:invoke"');+ expect(challenge).toContain(+ 'resource_metadata="https://agent.example/.well-known/oauth-protected-resource"',+ );+ expect(challenge?.match(/\bBearer\b/g)).toHaveLength(1);+ });++ it("derives the protected resource from the public request origin", async () => {+ const channel = mcpChannel({+ auth: oauthResource(() => null, { issuer: "https://issuer.example" }),+ path: "/delegate",+ });+ const route = channel.routes[0]!;+ if (route.transport === "websocket") throw new Error("expected HTTP route");+ const response = await route.handler(+ requestWithHost("https://agent.example/.well-known/oauth-protected-resource"),+ {} as never,+ );+ await expect(response.json()).resolves.toEqual({+ authorization_servers: ["https://issuer.example"],+ resource: "https://agent.example/delegate",+ });+ });++ it("serves protected-resource metadata to cross-origin browser clients", async () => {+ const channel = mcpChannel({+ auth: oauthResource(() => null, { issuer: "https://issuer.example" }),+ });+ const [getRoute, headRoute, optionsRoute] = channel.routes;+ if (+ getRoute?.transport === "websocket" ||+ headRoute?.transport === "websocket" ||+ optionsRoute?.transport === "websocket" ||+ getRoute === undefined ||+ headRoute === undefined ||+ optionsRoute === undefined+ ) {+ throw new Error("expected HTTP metadata routes");+ }++ const origin = "https://client.example";+ const get = await getRoute.handler(+ requestWithHost("https://agent.example/.well-known/oauth-protected-resource", {+ headers: { origin },+ }),+ {} as never,+ );+ expect(get.status).toBe(200);+ expect(get.headers.get("access-control-allow-origin")).toBe("*");++ const head = await headRoute.handler(+ requestWithHost("https://agent.example/.well-known/oauth-protected-resource", {+ headers: { origin },+ method: "HEAD",+ }),+ {} as never,+ );+ expect(head.status).toBe(200);+ expect(head.headers.get("access-control-allow-origin")).toBe("*");+ expect(head.headers.get("content-type")).toContain("application/json");+ expect(await head.text()).toBe("");++ const options = await optionsRoute.handler(+ requestWithHost("https://agent.example/.well-known/oauth-protected-resource", {+ headers: {+ "access-control-request-headers": "authorization, mcp-protocol-version",+ "access-control-request-method": "GET",+ origin,+ },+ method: "OPTIONS",+ }),+ {} as never,+ );+ expect(options.status).toBe(204);+ expect(options.headers.get("access-control-allow-origin")).toBe("*");+ expect(options.headers.get("access-control-allow-methods")).toBe("GET, HEAD, OPTIONS");+ expect(options.headers.get("access-control-allow-headers")).toBe(+ "authorization, mcp-protocol-version",+ );+ expect(options.headers.get("vary")).toBe("Access-Control-Request-Headers");+ });+});++function routeArgs(createSession: () => Promise<never> = vi.fn()): RouteHandlerArgs {+ const unavailable = () => {+ throw new Error("Route operation is unavailable in this test.");+ };+ const args: RouteHandlerArgs = {+ attachSession: unavailable,+ from: unavailable,+ params: {},+ requestIp: "127.0.0.1",+ resolveSession: vi.fn(),+ to: unavailable,+ waitUntil: vi.fn(),+ };+ return attachRouteChannelName(+ attachAgentInfoRouteResponse(attachRouteSessionCreator(args, createSession), async () =>+ Response.json({+ agent: {+ description: "Investigates tasks.",+ name: "compiled-agent",+ },+ }),+ ),+ "mcp",+ );+}++function mcpRequest(body: unknown, headers: Record<string, string> = {}): Request {+ return new Request("https://agent.example/mcp", {+ body: JSON.stringify(body),+ headers: {+ accept: "application/json, text/event-stream",+ "content-type": "application/json",+ host: "agent.example",+ ...headers,+ },+ method: "POST",+ });+}++function requestWithHost(url: string, init: RequestInit = {}): Request {+ const target = new URL(url);+ return new Request(url, {+ ...init,+ headers: { host: target.host, ...Object.fromEntries(new Headers(init.headers)) },+ });+}++async function jsonRpcResponse(response: Response): Promise<unknown> {+ if (!response.headers.get("content-type")?.includes("text/event-stream")) {+ return await response.json();+ }+ const data = (await response.text()).split("\n").find((line) => line.startsWith("data: "));+ if (data === undefined) throw new Error("MCP SSE response did not contain a data event.");+ return JSON.parse(data.slice("data: ".length));+}diff --git a/packages/eve/src/public/channels/mcp.ts b/packages/eve/src/public/channels/mcp.tsnew file mode 100644index 000000000..72b7e4410--- /dev/null+++ b/packages/eve/src/public/channels/mcp.ts@@ -0,0 +1,617 @@+import { parseJsonObject, type JsonObject } from "#shared/json.js";+import { z } from "#compiled/zod/index.js";+import {+ defineChannel,+ DELETE,+ GET,+ HEAD,+ OPTIONS,+ POST,+ type Channel,+} from "#public/definitions/channel.js";+import type { RouteHandlerArgs } from "#channel/routes.js";+import type {+ AgentInvocation,+ AgentInvocationMutationResult,+} from "#internal/invocation/agent-invocation.js";+import { WorkflowAgentInvocationExecution } from "#internal/invocation/workflow-execution.js";+import { resolveInstalledPackageInfo } from "#internal/application/package.js";+import { validateMcpHttpRequest, validateMcpMetadataRequest } from "#internal/mcp/http-security.js";+import {+ createMcpStreamableHttpServer,+ defineMcpTool,+ type McpCallToolResult,+ type McpServerTool,+} from "#internal/mcp/streamable-http-server.js";+import {+ createMcpProtectedResourceMetadata,+ createMcpResourceChallenge,+} from "#internal/mcp/protected-resource.js";+import { inputRequestSchema, inputResponseSchema } from "#runtime/input/types.js";+import {+ escapeAuthChallengeParameter,+ readOAuthResourceOptions,+ routeAuth,+ type AuthFn,+ type OAuthResourceOptions,+} from "#public/channels/auth.js";+import {+ readAgentInfoRouteResponse,+ readRouteChannelName,+ readRouteSessionCreator,+} from "#internal/nitro/routes/channel-route-context.js";+export interface McpChannelInput {+ /** Existing eve route-auth policy. Use `none()` for explicit public access. */+ readonly auth: AuthFn<Request> | readonly AuthFn<Request>[];+ /** Streamable HTTP endpoint path. Defaults to `/mcp`. */+ readonly path?: string;+}++/** Public MCP channel exposing durable agent invocation compatibility tools. */+export type McpChannel = Channel;++/**+ * Publishes this agent as a stateless Streamable HTTP MCP server.+ *+ * This channel owns only MCP transport and durable eve invocation. It reuses+ * eve's inbound auth strategies and recognizes `oauthResource(...)` metadata+ * when OAuth discovery is needed.+ * The file containing this channel must be `agent/channels/mcp.ts`.+ */+export function mcpChannel(input: McpChannelInput): McpChannel {+ if (input?.auth === undefined) {+ throw new Error("mcpChannel requires auth. Use none() for explicit public access.");+ }+ const path = input.path ?? "/mcp";+ const oauth = readOAuthResourceOptions(input.auth);+ const routes = [+ GET(+ path,+ async (request, args) => await authenticateMcpRequest(request, args, input.auth, oauth),+ ),+ POST(+ path,+ async (request, args) => await authenticateMcpRequest(request, args, input.auth, oauth),+ ),+ DELETE(+ path,+ async (request, args) => await authenticateMcpRequest(request, args, input.auth, oauth),+ ),+ ];+ if (oauth !== undefined) {+ routes.unshift(...protectedResourceMetadataRoutes(oauth, path));+ }+ return defineChannel({ routes });+}++function protectedResourceMetadataRoutes(options: OAuthResourceOptions, resourcePath: string) {+ const metadataPath = options.metadataPath ?? "/.well-known/oauth-protected-resource";+ return [+ GET(metadataPath, async (request) =>+ protectedResourceMetadataResponse(request, options, resourcePath, false),+ ),+ HEAD(metadataPath, async (request) =>+ protectedResourceMetadataResponse(request, options, resourcePath, true),+ ),+ OPTIONS(metadataPath, async (request) => protectedResourceMetadataOptionsResponse(request)),+ ] as const;+}++function protectedResourceMetadataResponse(+ request: Request,+ options: OAuthResourceOptions,+ resourcePath: string,+ head: boolean,+): Response {+ const securityFailure = validateMcpMetadataRequest(request);+ if (securityFailure !== undefined) return securityFailure;+ const resource =+ options.resource ?? new URL(resourcePath, new URL(request.url).origin).toString();+ const authorizationServers =+ options.issuer !== undefined ? [options.issuer] : options.authorizationServers;+ const response = Response.json(+ createMcpProtectedResourceMetadata({+ authorizationServers,+ resource,+ scopesSupported: options.scopes,+ }),+ {+ headers: {+ "access-control-allow-origin": "*",+ "cache-control": "no-store",+ },+ },+ );+ return head+ ? new Response(null, { headers: response.headers, status: response.status })+ : response;+}++function protectedResourceMetadataOptionsResponse(request: Request): Response {+ const securityFailure = validateMcpMetadataRequest(request);+ if (securityFailure !== undefined) return securityFailure;+ const headers = new Headers({+ "access-control-allow-methods": "GET, HEAD, OPTIONS",+ "access-control-allow-origin": "*",+ "cache-control": "no-store",+ });+ const requestedHeaders = request.headers.get("access-control-request-headers");+ if (requestedHeaders !== null) {+ headers.set("access-control-allow-headers", requestedHeaders);+ headers.set("vary", "Access-Control-Request-Headers");+ }+ return new Response(null, { headers, status: 204 });+}++function addResourceChallenge(+ response: Response,+ request: Request,+ options: OAuthResourceOptions,+): Response {+ if (response.status !== 401 && response.status !== 403) return response;+ const metadataPath = options.metadataPath ?? "/.well-known/oauth-protected-resource";+ const publicBase = options.resource ?? new URL(request.url).origin;+ const metadataUrl = new URL(metadataPath, publicBase).toString();+ const headers = new Headers(response.headers);+ const existing = headers.get("www-authenticate");+ if (response.status === 401) {+ headers.set("www-authenticate", mergeMcpBearerChallenge(existing, metadataUrl, options.scopes));+ } else {+ const challenge = augmentInsufficientScopeChallenge(existing, metadataUrl);+ if (challenge === undefined) return response;+ headers.set("www-authenticate", challenge);+ }+ return new Response(response.body, {+ headers,+ status: response.status,+ statusText: response.statusText,+ });+}++interface ParsedAuthChallenge {+ readonly scheme: string;+ readonly value: string;+}++function mergeMcpBearerChallenge(+ header: string | null,+ metadataUrl: string,+ scopes: readonly string[] | undefined,+): string {+ const challenges = parseAuthChallenges(header);+ const bearer =+ challenges.find(+ (challenge) =>+ challenge.scheme.toLowerCase() === "bearer" && hasAuthParameter(challenge.value, "error"),+ ) ?? challenges.find((challenge) => challenge.scheme.toLowerCase() === "bearer");+ const canonical =+ bearer === undefined+ ? createMcpResourceChallenge(metadataUrl, scopes)+ : augmentBearerChallenge(bearer.value, metadataUrl, scopes);+ return replaceBearerChallenges(challenges, bearer, canonical);+}++function augmentInsufficientScopeChallenge(+ header: string | null,+ metadataUrl: string,+): string | undefined {+ const challenges = parseAuthChallenges(header);+ const bearer = challenges.find(+ (challenge) =>+ challenge.scheme.toLowerCase() === "bearer" &&+ hasAuthParameter(challenge.value, "error", "insufficient_scope"),+ );+ if (bearer === undefined) return undefined;+ return replaceBearerChallenges(+ challenges,+ bearer,+ augmentBearerChallenge(bearer.value, metadataUrl),+ );+}++function replaceBearerChallenges(+ challenges: readonly ParsedAuthChallenge[],+ selected: ParsedAuthChallenge | undefined,+ replacement: string,+): string {+ const result: string[] = [];+ let inserted = false;+ for (const challenge of challenges) {+ if (challenge.scheme.toLowerCase() !== "bearer") {+ result.push(challenge.value);+ continue;+ }+ if (!inserted && challenge === selected) {+ result.push(replacement);+ inserted = true;+ }+ }+ if (!inserted) result.push(replacement);+ return result.join(", ");+}++function augmentBearerChallenge(+ challenge: string,+ metadataUrl: string,+ scopes?: readonly string[],+): string {+ let result = challenge;+ if (!hasAuthParameter(result, "resource_metadata")) {+ result = appendAuthParameter(result, "resource_metadata", metadataUrl);+ }+ if (scopes?.length && !hasAuthParameter(result, "scope")) {+ result = appendAuthParameter(result, "scope", scopes.join(" "));+ }+ return result;+}++function appendAuthParameter(challenge: string, name: string, value: string): string {+ const separator = challenge.trim().toLowerCase() === "bearer" ? " " : ", ";+ return `${challenge}${separator}${name}="${escapeAuthChallengeParameter(value)}"`;+}++function hasAuthParameter(challenge: string, name: string, value?: string): boolean {+ const escapedName = name.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");+ if (value === undefined) {+ return new RegExp(`(?:^|[\\s,])${escapedName}\\s*=`, "i").test(challenge);+ }+ const escapedValue = value.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");+ return new RegExp(+ `(?:^|[\\s,])${escapedName}\\s*=\\s*(?:"${escapedValue}"|${escapedValue})(?=$|[\\s,])`,+ "i",+ ).test(challenge);+}++function parseAuthChallenges(header: string | null): readonly ParsedAuthChallenge[] {+ if (header === null) return [];+ const challenges: Array<{ scheme: string; value: string }> = [];+ for (const part of splitQuotedHeaderList(header)) {+ const scheme = readChallengeScheme(part);+ if (scheme !== undefined) {+ challenges.push({ scheme, value: part });+ continue;+ }+ const current = challenges.at(-1);+ if (current !== undefined) current.value += `, ${part}`;+ }+ return challenges;+}++function splitQuotedHeaderList(header: string): readonly string[] {+ const parts: string[] = [];+ let escaped = false;+ let quoted = false;+ let start = 0;+ for (let index = 0; index < header.length; index++) {+ const character = header[index];+ if (escaped) {+ escaped = false;+ } else if (character === "\\") {+ escaped = true;+ } else if (character === '"') {+ quoted = !quoted;+ } else if (character === "," && !quoted) {+ const part = header.slice(start, index).trim();+ if (part.length > 0) parts.push(part);+ start = index + 1;+ }+ }+ const last = header.slice(start).trim();+ if (last.length > 0) parts.push(last);+ return parts;+}++function readChallengeScheme(value: string): string | undefined {+ const match = /^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?:\s+|$)/.exec(value);+ if (match === null) return undefined;+ const scheme = match[1];+ if (scheme === undefined) return undefined;+ return value.slice(scheme.length).trimStart().startsWith("=") ? undefined : scheme;+}++async function authenticateMcpRequest(+ request: Request,+ args: RouteHandlerArgs,+ policy: AuthFn<Request> | readonly AuthFn<Request>[],+ oauth: OAuthResourceOptions | undefined,+): Promise<Response> {+ const securityFailure = validateMcpHttpRequest(request);+ if (securityFailure !== undefined) return securityFailure;+ const auth = await routeAuth(request, policy);+ if (auth instanceof Response) {+ return oauth === undefined ? auth : addResourceChallenge(auth, request, oauth);+ }+ return await handleMcpRequest(request, args, auth);+}++async function handleMcpRequest(+ request: Request,+ args: RouteHandlerArgs,+ auth: import("#channel/types.js").SessionAuthContext,+): Promise<Response> {+ const createSession = readRouteSessionCreator(args);+ const channelName = readRouteChannelName(args);+ const respondWithAgentInfo = readAgentInfoRouteResponse(args);+ if (+ channelName === undefined ||+ createSession === undefined ||+ respondWithAgentInfo === undefined+ ) {+ return Response.json({ error: "MCP requires agent route context." }, { status: 500 });+ }+ const agentInfoResponse = await respondWithAgentInfo();+ if (!agentInfoResponse.ok) return agentInfoResponse;+ const agentInfo = (await agentInfoResponse.json()) as {+ readonly agent?: { readonly description?: unknown; readonly name?: unknown };+ };+ if (typeof agentInfo.agent?.name !== "string") {+ return Response.json({ error: "MCP requires compiled agent metadata." }, { status: 500 });+ }+ const description =+ typeof agentInfo.agent.description === "string" ? agentInfo.agent.description : undefined;+ const execution = new WorkflowAgentInvocationExecution({+ channelName,+ createSession,+ from: args.from,+ });+ return await createMcpStreamableHttpServer({+ authenticate: async () => auth,+ name: agentInfo.agent.name,+ tools: createInvocationTools(+ execution,+ description,+ auth.authenticator === "none" && auth.principalType === "anonymous",+ ),+ version: resolveInstalledPackageInfo().version,+ })(request);+}++function createInvocationTools(+ execution: WorkflowAgentInvocationExecution,+ agentDescription: string | undefined,+ publicAccess: boolean,+): readonly McpServerTool[] {+ const publicHandleDescription = publicAccess+ ? " On this public channel, the invocation ID is a bearer capability until workflow retention expires."+ : "";+ const startDescription = `Starts durable work and returns an invocation handle immediately.${publicHandleDescription}`;+ const tools: McpServerTool[] = [+ defineMcpTool({+ definition: {+ annotations: {+ destructiveHint: true,+ idempotentHint: false,+ openWorldHint: true,+ readOnlyHint: false,+ },+ description:+ agentDescription === undefined+ ? startDescription+ : `${agentDescription} ${startDescription}`,+ inputSchema: z.strictObject({+ message: z.string().min(1),+ outputSchema: z.looseObject({}).optional(),+ }),+ name: "agent_start",+ outputSchema: AGENT_INVOCATION_OUTPUT_SCHEMA,+ },+ async call(body, context) {+ const invocation = await execution.create({+ auth: context.auth,+ message: body.message,+ outputSchema: asJsonObject(body.outputSchema),+ });+ return invocationResult(invocation);+ },+ }),+ defineMcpTool({+ definition: {+ annotations: {+ destructiveHint: false,+ idempotentHint: true,+ openWorldHint: false,+ readOnlyHint: true,+ },+ description: `Reads complete durable invocation state.${publicHandleDescription}`,+ inputSchema: z.strictObject({ invocationId: z.string().min(1) }),+ name: "agent_get",+ outputSchema: AGENT_INVOCATION_OUTPUT_SCHEMA,+ },+ async call(body, context) {+ return invocationResult(+ requiredInvocation(+ await execution.read({+ auth: context.auth,+ invocationId: body.invocationId,+ }),+ ),+ );+ },+ }),+ defineMcpTool({+ definition: {+ annotations: {+ destructiveHint: true,+ idempotentHint: false,+ openWorldHint: true,+ readOnlyHint: false,+ },+ description: "Answers a pending input request on a durable invocation.",+ inputSchema: z.strictObject({+ invocationId: z.string().min(1),+ responses: z.array(inputResponseSchema).min(1),+ }),+ name: "agent_update",+ outputSchema: AGENT_INVOCATION_OUTPUT_SCHEMA,+ },+ async call(body, context) {+ return invocationResult(+ requiredMutation(+ await execution.update({+ auth: context.auth,+ invocationId: body.invocationId,+ responses: body.responses,+ }),+ ),+ );+ },+ }),+ defineMcpTool({+ definition: {+ annotations: {+ destructiveHint: true,+ idempotentHint: true,+ openWorldHint: false,+ readOnlyHint: false,+ },+ description:+ "Requests cancellation of a durable invocation. Read it again to observe acknowledgement.",+ inputSchema: z.strictObject({ invocationId: z.string().min(1) }),+ name: "agent_cancel",+ outputSchema: AGENT_INVOCATION_OUTPUT_SCHEMA,+ },+ async call(body, context) {+ return invocationResult(+ requiredInvocation(+ await execution.cancel({+ auth: context.auth,+ invocationId: body.invocationId,+ }),+ ),+ );+ },+ }),+ ];+ return tools;+}++function requiredInvocation(invocation: AgentInvocation | undefined): AgentInvocation {+ if (invocation === undefined) throw new Error("Invocation not found.");+ return invocation;+}++function requiredMutation(result: AgentInvocationMutationResult): AgentInvocation {+ switch (result.type) {+ case "success":+ return result.invocation;+ case "conflict":+ throw new Error(result.message);+ case "not_found":+ throw new Error("Invocation not found.");+ }+}++function invocationResult(invocation: AgentInvocation): McpCallToolResult {+ const structuredContent = parseJsonObject(invocation);+ return {+ content: [{ text: JSON.stringify(structuredContent), type: "text" }],+ structuredContent,+ };+}++function asJsonObject(value: unknown): JsonObject | undefined {+ if (value === undefined) return undefined;+ const schema = parseJsonObject(value);+ validateOutputSchemaComplexity(schema);+ return schema;+}++const AUTHORIZATION_CHALLENGE_SCHEMA = z.strictObject({+ displayName: z.string().optional(),+ expiresAt: z.iso.datetime().optional(),+ instructions: z.string().optional(),+ url: z.url().optional(),+ userCode: z.string().optional(),+});++const AUTHORIZATION_REQUEST_SCHEMA = z.strictObject({+ authorization: AUTHORIZATION_CHALLENGE_SCHEMA.optional(),+ description: z.string(),+ name: z.string(),+ webhookUrl: z.url().optional(),+});++const MCP_INPUT_REQUEST_SCHEMA = inputRequestSchema.safeExtend({+ action: z.strictObject({+ callId: z.string(),+ input: z.record(z.string(), z.json()),+ kind: z.literal("tool-call"),+ toolName: z.string(),+ }),+});++const AGENT_INVOCATION_BASE_SCHEMA = z.strictObject({+ createdAt: z.iso.datetime(),+ expiresAt: z.iso.datetime().optional(),+ invocationId: z.string(),+});++const AGENT_INVOCATION_OUTPUT_SCHEMA = z.discriminatedUnion("status", [+ AGENT_INVOCATION_BASE_SCHEMA.extend({+ pollAfterMs: z.number().int().nonnegative(),+ result: z.json().optional(),+ status: z.literal("working"),+ }),+ AGENT_INVOCATION_BASE_SCHEMA.extend({+ inputRequests: z.record(z.string(), MCP_INPUT_REQUEST_SCHEMA),+ result: z.json().optional(),+ status: z.literal("input_required"),+ }),+ AGENT_INVOCATION_BASE_SCHEMA.extend({+ authorizations: z.array(AUTHORIZATION_REQUEST_SCHEMA).min(1),+ pollAfterMs: z.number().int().nonnegative(),+ result: z.json().optional(),+ status: z.literal("authorization_required"),+ }),+ AGENT_INVOCATION_BASE_SCHEMA.extend({+ result: z.json().optional(),+ status: z.literal("completed"),+ }),+ AGENT_INVOCATION_BASE_SCHEMA.extend({+ error: z.strictObject({+ code: z.number().int(),+ data: z.json().optional(),+ message: z.string(),+ }),+ status: z.literal("failed"),+ }),+ AGENT_INVOCATION_BASE_SCHEMA.extend({ status: z.literal("cancelled") }),+]);++const MAX_OUTPUT_SCHEMA_BYTES = 64 * 1_024;+const MAX_OUTPUT_SCHEMA_DEPTH = 32;+const MAX_OUTPUT_SCHEMA_NODES = 2_048;++function validateOutputSchemaComplexity(schema: JsonObject): void {+ if (new TextEncoder().encode(JSON.stringify(schema)).byteLength > MAX_OUTPUT_SCHEMA_BYTES) {+ throw new Error(`outputSchema must be at most ${String(MAX_OUTPUT_SCHEMA_BYTES)} bytes.`);+ }++ let nodes = 0;+ const visit = (value: import("#shared/json.js").JsonValue, depth: number): void => {+ nodes++;+ if (nodes > MAX_OUTPUT_SCHEMA_NODES) {+ throw new Error(+ `outputSchema must contain at most ${String(MAX_OUTPUT_SCHEMA_NODES)} nodes.`,+ );+ }+ if (depth > MAX_OUTPUT_SCHEMA_DEPTH) {+ throw new Error(+ `outputSchema must be at most ${String(MAX_OUTPUT_SCHEMA_DEPTH)} levels deep.`,+ );+ }+ if (Array.isArray(value)) {+ for (const item of value) visit(item, depth + 1);+ return;+ }+ if (value === null || typeof value !== "object") return;+ for (const [key, entry] of Object.entries(value)) {+ if (key === "$ref" && typeof entry === "string" && !entry.startsWith("#")) {+ throw new Error("outputSchema external $ref values are not supported.");+ }+ visit(entry, depth + 1);+ }+ };++ visit(schema, 0);+}diff --git a/packages/eve/src/public/channels/oauth-resource.test.ts b/packages/eve/src/public/channels/oauth-resource.test.tsnew file mode 100644index 000000000..83d825373--- /dev/null+++ b/packages/eve/src/public/channels/oauth-resource.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it, vi } from "vitest";++import type { SessionAuthContext } from "#channel/types.js";+import {+ oauthResource,+ readOAuthResourceOptions,+ routeAuth,+ type AuthFn,+} from "#public/channels/auth.js";++const principal: SessionAuthContext = {+ attributes: {},+ authenticator: "test",+ principalId: "user-1",+ principalType: "user",+};++describe("oauthResource", () => {+ it("preserves the ordered auth walk and attaches non-enumerable metadata", async () => {+ const skip = vi.fn<AuthFn<Request>>(() => null);+ const accept = vi.fn<AuthFn<Request>>(() => principal);+ const auth = oauthResource([skip, accept], {+ issuer: "https://auth.example",+ scopes: ["agent:invoke"],+ });++ await expect(routeAuth(new Request("https://agent.example/mcp"), auth)).resolves.toBe(+ principal,+ );+ expect(skip).toHaveBeenCalledOnce();+ expect(accept).toHaveBeenCalledOnce();+ expect(Object.keys(auth)).toEqual([]);+ expect(readOAuthResourceOptions(auth)).toEqual({+ issuer: "https://auth.example",+ scopes: ["agent:invoke"],+ });+ });++ it("rejects invalid resource metadata at authoring time", () => {+ expect(() =>+ oauthResource(() => principal, {+ authorizationServers: [],+ }),+ ).toThrow("at least one HTTPS authorization server URL");+ expect(() =>+ oauthResource(() => principal, {+ issuer: "https://auth.example",+ metadataPath: "oauth-protected-resource",+ }),+ ).toThrow("metadataPath must be an absolute path");+ });++ it("requires secure OAuth identifiers and a same-origin metadata path", () => {+ for (const issuer of [+ "ftp://auth.example",+ "http://auth.example",+ "http://127.attacker.example",+ "https://user:[email protected]",+ "https://auth.example?tenant=one",+ "https://auth.example#fragment",+ ]) {+ expect(() => oauthResource(() => principal, { issuer })).toThrow(+ "HTTPS authorization server URL",+ );+ }++ expect(() =>+ oauthResource(() => principal, {+ issuer: "https://auth.example",+ resource: "http://agent.example/mcp",+ }),+ ).toThrow("resource must be an HTTPS URL");+ expect(() =>+ oauthResource(() => principal, {+ issuer: "https://auth.example",+ metadataPath: "//attacker.example/metadata",+ }),+ ).toThrow("metadataPath must be an absolute path");++ expect(() =>+ oauthResource(() => principal, {+ issuer: "http://localhost:3000",+ resource: "http://127.0.0.1:2117/mcp",+ }),+ ).not.toThrow();+ });+});diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex ca7c998ad..5c96917a3 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -45,7 +45,7 @@ export type {ChannelSource,};export type { ChannelCors, ChannelCorsOptions } from "#channel/cors.js";-export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";+export { DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, WS } from "#channel/routes.js";export type {AttachSessionFn,HttpRouteDefinition,@@ -65,7 +65,7 @@ export type {* is a webhook. Override only when authoring a non-webhook route such as a* long-poll endpoint or an event-stream reader.*/-export type ChannelMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";+export type ChannelMethod = "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS";/*** Method-like discriminator used by compiled channel route entries.diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b20cf16af..b3ace3e4e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1109,6 +1109,9 @@ importers:'@eve/catalog':specifier: workspace:*version: link:../eve-catalog+ '@modelcontextprotocol/server':+ specifier: 2.0.0+ version: 2.0.0'@nuxt/kit':specifier: ^4.0.0version: 4.4.6([email protected])@@ -3104,6 +3107,10 @@ packages:'@mixmark-io/[email protected]':resolution: {integrity: sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==}+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==}+ engines: {node: '>=20'}+'@modelcontextprotocol/[email protected]':resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==}engines: {node: '>=18'}@@ -3114,6 +3121,10 @@ packages:'@cfworker/json-schema':optional: true+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==}+ engines: {node: '>=20'}+'@mux/[email protected]':resolution: {integrity: sha512-4wpH6dYybyZhqLn9qGn/+67Z8MZnQRAdqTFEEZw2bx61M9q01uPYYHxd8qwOnYtUGEeafsdTwVHVxKHGD3oc1A==}@@ -17134,6 +17145,10 @@ snapshots:'@mixmark-io/[email protected]': {}+ '@modelcontextprotocol/[email protected]':+ dependencies:+ zod: 4.4.3+'@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])([email protected])':dependencies:'@hono/node-server': 1.19.14([email protected])@@ -17182,6 +17197,11 @@ snapshots:transitivePeerDependencies:- supports-color+ '@modelcontextprotocol/[email protected]':+ dependencies:+ '@modelcontextprotocol/core': 2.0.0+ zod: 4.4.3+'@mux/[email protected]':dependencies:mux-embed: 5.18.1