Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat: define experimental managed connection event callbacks (#4484)

Allen Zhou6d67e9a52c60
diff --git a/.changeset/experimental-connection-event-config.md b/.changeset/experimental-connection-event-config.md
new file mode 100644
index 000000000..546c579d4
--- /dev/null
+++ b/.changeset/experimental-connection-event-config.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Add experimental MCP connection event callback definitions and preserve the Connect runtime events bridge while keeping compiler metadata serializable.
diff --git a/.changeset/stable-session-replay-deadline.md b/.changeset/stable-session-replay-deadline.md
new file mode 100644
index 000000000..2eee0e6f4
--- /dev/null
+++ b/.changeset/stable-session-replay-deadline.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Keep a session's deadline stable across workflow replay and compaction handoffs.
diff --git a/docs/connections/mcp.mdx b/docs/connections/mcp.mdx
index 428849a35..0a99c75b6 100644
--- a/docs/connections/mcp.mdx
+++ b/docs/connections/mcp.mdx
@@ -220,3 +220,50 @@ When a remote tool returns more data than the model needs, narrow the result at
- [OpenAPI connections](./openapi): generate tools from OpenAPI operations.
- [Authentication](../guides/auth-and-route-protection): establish the caller identity required by user-scoped auth.
- [Security model](../concepts/security-model): how connection credentials stay out of the model's reach.
+
+## Events (experimental)
+
+The experimental connection event contract accepts separate callbacks:
+
+```ts
+import { defineMcpClientConnection } from "eve/connections";
+import { connect } from "@vercel/connect/eve";
+
+export default defineMcpClientConnection({
+ url: "https://issues.example/mcp",
+ description: "Search and watch issues",
+ auth: connect("oauth/issues"),
+ experimental_events: {
+ async onEvent({ event, origin, auth, attachSession }) {
+ await attachSession(origin.sessionId).send(
+ `Review this issue event: ${JSON.stringify(event.data)}`,
+ { auth, turnPolicy: "queue" },
+ );
+ },
+ async onGap({ origin, cursor }) {
+ // Reconcile the source before assuming a contiguous event stream.
+ },
+ async onTerminated({ origin, error }) {
+ // Decide whether to notify the session or request another subscription.
+ },
+ },
+});
+```
+
+This contract is experimental and requires the matching managed-events runtime
+and Connect SDK releases. Defining callbacks does not create a subscription or
+start a model turn. `onEvent` is required; lifecycle callbacks are optional.
+`experimental_events` opts this connection into event handling. The `connect()`
+auth provider supplies the backend that manages subscriptions and verifies
+deliveries using the same authorized account. Using `connect()` alone does not
+enable event handling or create subscriptions.
+Use a statically authored MCP connection and a static `connect()` auth provider
+that exposes the events bridge. Dynamic connections and auth resolvers are not
+supported by this first version because the receiver must be mounted at build
+time. The provider still resolves the current authorized user or app for each
+subscription operation.
+
+`origin` and `auth` come from eve's saved subscription binding. Provider event
+payloads never select the execution principal. Callback code chooses whether
+to send input to an existing session. A session attachment never creates a
+replacement session.
diff --git a/packages/eve/extension-contracts/compatibility/connection/v49.ts b/packages/eve/extension-contracts/compatibility/connection/v49.ts
new file mode 100644
index 000000000..5b13ca53b
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/connection/v49.ts
@@ -0,0 +1,12 @@
+import { defineMcpClientConnection } from "#public/connections/index.js";
+
+// Epoch 49 Connect providers carry connector metadata without an events bridge.
+export default defineMcpClientConnection({
+ description: "Read issues from the tracker.",
+ url: "https://tracker.example.com/mcp",
+ auth: {
+ principalType: "app",
+ getToken: async () => ({ token: "service-credential" }),
+ vercelConnect: { connector: "oauth/issues" },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v85.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v85.ts
new file mode 100644
index 000000000..489faa8b2
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v85.ts
@@ -0,0 +1,21 @@
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+// Epoch 85 dynamic tools can use Connect auth without opting into event handling.
+export default defineDynamic({
+ events: {
+ "session.started": () => ({
+ authorization: defineTool({
+ description: "Check that the issue service is authorized.",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ async execute(_input, ctx) {
+ const { token } = await ctx.getToken({
+ principalType: "app",
+ getToken: async () => ({ token: "service-credential" }),
+ vercelConnect: { connector: "oauth/issues" },
+ });
+ return { authorized: token.length > 0 };
+ },
+ }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v91.ts b/packages/eve/extension-contracts/compatibility/tool/v91.ts
new file mode 100644
index 000000000..97bbb16f1
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v91.ts
@@ -0,0 +1,15 @@
+import { defineTool } from "#public/tools/index.js";
+
+// Existing Connect auth providers still work without event support.
+export default defineTool({
+ description: "Check that the issue service is authorized.",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ async execute(_input, ctx) {
+ const { token } = await ctx.getToken({
+ principalType: "app",
+ getToken: async () => ({ token: "service-credential" }),
+ vercelConnect: { connector: "oauth/issues" },
+ });
+ return { authorized: token.length > 0 };
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/connection/v50.json b/packages/eve/extension-contracts/reports/connection/v50.json
new file mode 100644
index 000000000..577af7cf5
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v50.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 50,
+ "sha256": "81fa5ad1c041ca6e156f502c5740a804bd48bc5434eaa92d19005ba4d60dd901",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineDynamic",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v86.json b/packages/eve/extension-contracts/reports/dynamicTool/v86.json
new file mode 100644
index 000000000..2ed939cb6
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v86.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 86,
+ "sha256": "8c403d23eed21dd4e06fe15cba9a5c2cae846662a7d453bec459584a2254103a",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "auto",
+ "defineDurableCallback",
+ "defineDurableSchema",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v92.json b/packages/eve/extension-contracts/reports/tool/v92.json
new file mode 100644
index 000000000..3e51a11c5
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v92.json
@@ -0,0 +1,29 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 92,
+ "sha256": "3e7dccca7e440ac2f146df824d8a95b4aba6b5f1e96d47d099b42f057da61477",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolDefinition",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "decide",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "serializeModelInputSchema",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/src/compiler/connection-events.test.ts b/packages/eve/src/compiler/connection-events.test.ts
new file mode 100644
index 000000000..361b4f003
--- /dev/null
+++ b/packages/eve/src/compiler/connection-events.test.ts
@@ -0,0 +1,71 @@
+import { expect, it, vi } from "vitest";
+import { normalizeMcpClientConnectionDefinition } from "#internal/authored-definition/connection.js";
+import { normalizeAuthorizationSpec } from "#shared/validate-authorization.js";
+import { extractVercelConnectMetadata } from "#shared/vercel-connect-metadata.js";
+import { resolveDynamicConnectionValue } from "#runtime/resolve-connection.js";
+import { defineMcpClientConnection } from "#public/definitions/connections/mcp.js";
+
+const backend = { createAdapter: vi.fn(), verify: vi.fn() };
+const auth = {
+ getToken: async () => ({ token: "credential" }),
+ vercelConnect: {
+ connector: "oauth/issues",
+ experimental_events: backend,
+ },
+};
+const definition = { auth, description: "Issue events", url: "https://issues.example/mcp" };
+
+it("preserves the runtime bridge through repeated auth normalization but excludes it from build metadata", () => {
+ const normalized = normalizeAuthorizationSpec(normalizeAuthorizationSpec(auth, "test"), "test");
+ expect(normalized.vercelConnect?.experimental_events).toBe(backend);
+ expect(extractVercelConnectMetadata(normalized.vercelConnect)).toEqual({
+ connector: "oauth/issues",
+ });
+ expect(backend.createAdapter).not.toHaveBeenCalled();
+});
+
+it.each([
+ { experimental_events: true },
+ { experimental_events: {} },
+ { experimental_events: { onEvent() {}, onGap: true } },
+ { auth: { getToken: auth.getToken }, experimental_events: { onEvent() {} } },
+ { auth: () => auth, experimental_events: { onEvent() {} } },
+])(
+ "rejects event configurations without callbacks and a static events-capable provider: %j",
+ (override) => {
+ expect(() =>
+ normalizeMcpClientConnectionDefinition({ ...definition, ...override }, "issues"),
+ ).toThrow();
+ },
+);
+
+it("accepts separate event/lifecycle callbacks without invoking them or allocating a subscription", () => {
+ const onEvent = vi.fn();
+ const callbacks = { onEvent, onGap: vi.fn(), onTerminated: vi.fn() };
+ const normalized = normalizeMcpClientConnectionDefinition(
+ { ...definition, experimental_events: callbacks },
+ "issues",
+ );
+ expect(normalized.experimental_events).toEqual(callbacks);
+ expect(onEvent).not.toHaveBeenCalled();
+ expect(backend.createAdapter).not.toHaveBeenCalled();
+ expect(
+ normalizeMcpClientConnectionDefinition(definition, "issues").experimental_events,
+ ).toBeUndefined();
+});
+
+it("rejects events on dynamic connections whose receiver cannot be mounted at build time", () => {
+ const value = defineMcpClientConnection({
+ ...definition,
+ instanceKey: "issues",
+ experimental_events: { onEvent() {} },
+ });
+ expect(() =>
+ resolveDynamicConnectionValue(value, {
+ connectionName: "issues",
+ sourceId: "issues",
+ sourceKind: "module",
+ logicalPath: "connections/issues.ts",
+ }),
+ ).toThrow("statically authored");
+});
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 0b6ea5c1b..90c33bcaa 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,10 +22,10 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 91,
+ current: 92,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77, 78, 80, 81, 82, 84,
- 85, 86, 87, 88, 89, 90, 91,
+ 85, 86, 87, 88, 89, 90, 91, 92,
],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
@@ -89,11 +89,11 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
dynamicTool: {
- current: 85,
+ current: 86,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 31, 32, 33, 52, 54,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
- 85,
+ 85, 86,
],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -189,10 +189,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
connection: {
- current: 49,
+ current: 50,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 32, 33, 34,
- 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49,
+ 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50,
],
dropped: {
9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index d901e818a..021336b0d 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -804,6 +804,7 @@ const compiledWorkspaceResourceRootSchema = z
const compiledConnectionDefinitionSchema = z
.object({
+ experimental_events: z.literal(true).optional(),
connectionName: z.string(),
description: z.string(),
exportName: z.string().optional(),
diff --git a/packages/eve/src/compiler/normalize-connection.ts b/packages/eve/src/compiler/normalize-connection.ts
index 2dfe4fc49..a8e3663ef 100644
--- a/packages/eve/src/compiler/normalize-connection.ts
+++ b/packages/eve/src/compiler/normalize-connection.ts
@@ -119,6 +119,9 @@ export async function compileConnectionDefinition(
...shared,
description: normalized.description,
protocol: "mcp",
+ ...(normalized.experimental_events === undefined
+ ? {}
+ : { experimental_events: true as const }),
url: normalized.url,
};
auth = normalized.auth;
diff --git a/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts b/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts
index a9f36d62b..af9349786 100644
--- a/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts
+++ b/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts
@@ -1,6 +1,6 @@
import { startSessionOwner } from "#internal/testing/workflow-test-helpers.js";
import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session/timeout.js";
-import { assert, describe, expect, it, vi } from "vitest";
+import { afterEach, assert, describe, expect, it, vi } from "vitest";
import { getWorld, resumeHook } from "#internal/workflow/runtime.js";
import { hydrateStepReturnValue, hydrateWorkflowArguments } from "@workflow/core/serialization";
import { captureTurnEvents } from "#internal/testing/events.js";
@@ -217,11 +217,25 @@ describe("workflowEntry integration", () => {
});
describe("compaction handoff", () => {
+ afterEach(() => vi.restoreAllMocks());
+
it("moves each compacted session to a fresh run on its deployment and keeps its deadline", async () => {
const output = captureConsoleOutput();
const runtime = await createTestRuntime({ agent: { name: "workflow-entry-compaction" } });
await runtime.run(async () => {
+ const world = await getWorld();
+ const createEvent = world.events.create.bind(world.events);
+ let delayFirstStart = true;
+ vi.spyOn(world.events, "create").mockImplementation(async (...args) => {
+ if (delayFirstStart && args[1].eventType === "run_started") {
+ delayFirstStart = false;
+ // Make the optimistic run's start time differ from the persisted
+ // timestamp used on replay, without changing the workflow clock.
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ return createEvent(...args);
+ });
const anchor = await startSessionOwner(workflowEntry, [
{
kind: "initial",
@@ -235,7 +249,6 @@ describe("workflowEntry integration", () => {
},
]);
const stream = captureTurnEvents(anchor);
- const world = await getWorld();
const workflowRuntime = createWorkflowRuntime({
compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
});
diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.ts
index b8959e5a0..cc0e1bd66 100644
--- a/packages/eve/src/execution/session/entry.ts
+++ b/packages/eve/src/execution/session/entry.ts
@@ -157,9 +157,9 @@ export async function bootInitialOwner(
const serializedContext = stampSessionIdentity(input.serializedContext, sessionId);
const sessionWritable = getWritable<Uint8Array>();
const inbox = createSessionInbox(sessionId);
- const { workflowStartedAt } = getWorkflowMetadata();
const sessionTimeoutMs = input.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;
- const deadline = sessionTimeoutDeadline(sessionTimeoutMs, workflowStartedAt.getTime());
+ // Workflow's clock is replay-stable; its optimistic startedAt metadata is not.
+ const deadline = sessionTimeoutDeadline(sessionTimeoutMs, Date.now());
const continuationToken = (serializedContext["eve.continuationToken"] as string) || "";
const serializedBundle = serializedContext["eve.bundle"] as {
source: DurableCompiledArtifactsSource;
diff --git a/packages/eve/src/internal/authored-definition/connection.ts b/packages/eve/src/internal/authored-definition/connection.ts
index 8d3e96836..a3e302aae 100644
--- a/packages/eve/src/internal/authored-definition/connection.ts
+++ b/packages/eve/src/internal/authored-definition/connection.ts
@@ -19,6 +19,7 @@ const KNOWN_TOP_LEVEL_KEYS = [
"auth",
"description",
"forwardPrincipal",
+ "experimental_events",
"headers",
"instanceKey",
"protocolVersionDiscovery",
@@ -96,6 +97,38 @@ export function normalizeMcpClientConnectionDefinition(
url: record.url as string,
};
+ if (record.experimental_events !== undefined) {
+ const events = expectObjectRecord(
+ record.experimental_events,
+ `${message} experimental_events must be an object.`,
+ );
+ expectOnlyKnownKeys(events, ["onEvent", "onGap", "onTerminated"], message);
+ if (
+ typeof events.onEvent !== "function" ||
+ (events.onGap !== undefined && typeof events.onGap !== "function") ||
+ (events.onTerminated !== undefined && typeof events.onTerminated !== "function")
+ ) {
+ throw new Error(
+ `${message} experimental_events requires onEvent; onGap and onTerminated must be functions when provided.`,
+ );
+ }
+ if (
+ authorization === undefined ||
+ typeof authorization === "function" ||
+ authorization.vercelConnect?.experimental_events === undefined
+ ) {
+ throw new Error(
+ `${message} experimental_events requires a static Connect auth provider with the events bridge.`,
+ );
+ }
+ type Events = NonNullable<McpClientConnectionDefinition["experimental_events"]>;
+ result.experimental_events = {
+ onEvent: events.onEvent as Events["onEvent"],
+ onGap: events.onGap as Events["onGap"],
+ onTerminated: events.onTerminated as Events["onTerminated"],
+ };
+ }
+
if (record.protocolVersionDiscovery !== undefined) {
if (typeof record.protocolVersionDiscovery !== "boolean") {
throw new Error(`${message} "protocolVersionDiscovery" must be a boolean.`);
diff --git a/packages/eve/src/public/connections/index.ts b/packages/eve/src/public/connections/index.ts
index d62d0bb4f..1694c378a 100644
--- a/packages/eve/src/public/connections/index.ts
+++ b/packages/eve/src/public/connections/index.ts
@@ -51,3 +51,10 @@ export {
isConnectionAuthorizationFailedError,
isConnectionAuthorizationRequiredError,
} from "#public/connections/errors.js";
+
+export type {
+ Experimental_ConnectionEvents,
+ Experimental_ConnectionEvent,
+ Experimental_ConnectionEventOrigin,
+ Experimental_ConnectionEventContext,
+} from "#public/definitions/connections/events.js";
diff --git a/packages/eve/src/public/definitions/connections/events.ts b/packages/eve/src/public/definitions/connections/events.ts
new file mode 100644
index 000000000..601d96a10
--- /dev/null
+++ b/packages/eve/src/public/definitions/connections/events.ts
@@ -0,0 +1,49 @@
+import type { Session } from "#channel/session.js";
+import type { SessionAuthContext } from "#channel/types.js";
+
+/** Framework-owned origin captured when the authorized caller subscribes. */
+export interface Experimental_ConnectionEventOrigin {
+ readonly sessionId: string;
+ readonly connectionName: string;
+ readonly subscriptionId: string;
+}
+
+export interface Experimental_ConnectionEventContext {
+ readonly origin: Experimental_ConnectionEventOrigin;
+ readonly deliveryId: string;
+ /** The subscription creator's authenticated session identity. */
+ readonly auth: SessionAuthContext | null;
+ /** Attaches to an existing session; never creates a replacement session. */
+ readonly attachSession: (sessionId: string) => Session;
+}
+
+export interface Experimental_ConnectionEvent {
+ readonly eventId: string;
+ readonly name: string;
+ readonly timestamp: string;
+ readonly data: Readonly<Record<string, unknown>>;
+ readonly cursor: string | null;
+}
+
+/** Opts a static Connect-backed MCP connection into managed webhook events. */
+export interface Experimental_ConnectionEvents {
+ /** Called durably after verification and subscription binding checks. */
+ readonly onEvent: (
+ input: Experimental_ConnectionEventContext & {
+ readonly event: Experimental_ConnectionEvent;
+ },
+ ) => void | PromiseLike<void>;
+ /** The upstream server could not deliver a contiguous event stream. */
+ readonly onGap?: (
+ input: Experimental_ConnectionEventContext & {
+ readonly cursor: string | null;
+ readonly truncated?: true;
+ },
+ ) => void | PromiseLike<void>;
+ /** The upstream subscription ended; no model turn starts automatically. */
+ readonly onTerminated?: (
+ input: Experimental_ConnectionEventContext & {
+ readonly error: { readonly code: number; readonly message: string; readonly data?: unknown };
+ },
+ ) => void | PromiseLike<void>;
+}
diff --git a/packages/eve/src/public/definitions/connections/mcp.ts b/packages/eve/src/public/definitions/connections/mcp.ts
index dce49bc90..e01d03aeb 100644
--- a/packages/eve/src/public/definitions/connections/mcp.ts
+++ b/packages/eve/src/public/definitions/connections/mcp.ts
@@ -1,3 +1,4 @@
+import type { Experimental_ConnectionEvents } from "#public/definitions/connections/events.js";
import type {
ConnectionAuthDefinition,
HeadersDefinition,
@@ -25,6 +26,8 @@ import {
* servers that require no authentication (e.g. localhost).
*/
export interface McpClientConnectionDefinition {
+ /** Opt-in Connect webhook callbacks. Enabling this does not subscribe. */
+ readonly experimental_events?: Experimental_ConnectionEvents;
/**
* The MCP server's HTTP endpoint URL.
*
diff --git a/packages/eve/src/runtime/resolve-connection.ts b/packages/eve/src/runtime/resolve-connection.ts
index eea2b87a9..40ccf992f 100644
--- a/packages/eve/src/runtime/resolve-connection.ts
+++ b/packages/eve/src/runtime/resolve-connection.ts
@@ -65,6 +65,7 @@ export async function resolveConnectionDefinition(
definition.protocol === "openapi" ? resolvedRecord.operations : resolvedRecord.tools;
const result: {
+ experimental_events?: ResolvedConnectionDefinition["experimental_events"];
approval?: ResolvedConnectionDefinition["approval"];
authorization?: ResolvedConnectionDefinition["authorization"];
connectionName: string;
@@ -133,6 +134,13 @@ export async function resolveConnectionDefinition(
result.forwardPrincipal = resolvedRecord.forwardPrincipal;
}
+ if (definition.experimental_events === true) {
+ result.experimental_events = normalizeMcpClientConnectionDefinition(
+ resolvedRecord,
+ `Connection "${definition.connectionName}":`,
+ ).experimental_events;
+ }
+
if (hasHeaders) {
result.headers = resolvedRecord.headers as Readonly<HeadersDefinition>;
}
@@ -216,6 +224,11 @@ export function resolveDynamicConnectionValue(
}
const normalized = normalizeMcpClientConnectionDefinition(value, message);
+ if (normalized.experimental_events !== undefined) {
+ throw new Error(
+ `${message} experimental_events requires a statically authored connection so eve can mount its receiver at build time.`,
+ );
+ }
assertAuthenticatedDynamicInstanceKey(normalized.auth, normalized.instanceKey, message);
return omitUndefined({
approval: normalized.approval,
diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.ts
index 816529e67..d9ffc80e8 100644
--- a/packages/eve/src/runtime/types.ts
+++ b/packages/eve/src/runtime/types.ts
@@ -1,3 +1,4 @@
+import type { Experimental_ConnectionEvents } from "#public/definitions/connections/events.js";
import type { ChannelAdapter } from "#channel/adapter.js";
import type { CompiledChannel } from "#channel/compiled-channel.js";
import type { NormalizedChannelCorsOptions } from "#channel/cors.js";
@@ -100,6 +101,7 @@ export type ResolvedScheduleDefinition = Readonly<
* server that requires no authentication (e.g. localhost) may omit both.
*/
export interface ResolvedConnectionDefinition extends ResolvedModuleSourceRef {
+ readonly experimental_events?: Experimental_ConnectionEvents;
readonly protocolVersionDiscovery?: boolean;
/** MCP only: send the turn's principals in `eve-forwarded-principal`. */
readonly forwardPrincipal?: boolean;
diff --git a/packages/eve/src/shared/connection-events.ts b/packages/eve/src/shared/connection-events.ts
new file mode 100644
index 000000000..06797d8ae
--- /dev/null
+++ b/packages/eve/src/shared/connection-events.ts
@@ -0,0 +1,75 @@
+import type { ConnectionPrincipal } from "#shared/connection-types.js";
+import type { Experimental_ConnectionEvent } from "#public/definitions/connections/events.js";
+
+// The bridge is structural so auth helpers do not need a runtime dependency on eve.
+export type EventJson = string | number | boolean | null | readonly EventJson[] | EventJsonObject;
+export type EventJsonObject = { [key: string]: EventJson | undefined };
+export interface ManagedEventSubscription {
+ id: string;
+ name: string;
+ arguments: EventJsonObject;
+ status: "pending" | "active" | "needs_auth" | "stopped" | "expired" | "failed";
+ expiresAt: string | null;
+ cleanupStatus?: "pending" | "complete" | "exhausted";
+}
+export type ManagedEventSubscribeInput = {
+ name: string;
+ arguments: EventJsonObject;
+ context?: EventJsonObject;
+ idempotencyKey: string;
+ /** Application lifetime in milliseconds, or null until explicitly stopped. */
+ ttlMs: number | null;
+ options?: { signal?: AbortSignal; timeout?: number; maxTotalTimeout?: number };
+};
+export interface ConnectionEventsAdapter {
+ subscribe(input: ManagedEventSubscribeInput): Promise<ManagedEventSubscription>;
+ getSubscription(input: {
+ id: string;
+ options?: { timeout?: number };
+ }): Promise<ManagedEventSubscription>;
+ listSubscriptions(input?: {
+ cursor?: string;
+ limit?: number;
+ status?: ManagedEventSubscription["status"];
+ }): Promise<{ subscriptions: ManagedEventSubscription[]; nextCursor?: string }>;
+ unsubscribe(input: {
+ id: string;
+ options?: { timeout?: number };
+ }): Promise<ManagedEventSubscription>;
+}
+export type ConnectionEventDelivery = {
+ version: 1;
+ deliveryId: string;
+ subscriptionId: string;
+ source: { type: "mcp"; connectorId: string };
+ context: Record<string, unknown>;
+} & (
+ | { event: Experimental_ConnectionEvent }
+ | { control: { type: "gap"; cursor: string | null; truncated?: true } }
+ | { control: { type: "terminated"; error: { code: number; message: string; data?: unknown } } }
+);
+export interface ConnectionEventsBackend {
+ createAdapter(input: {
+ principal: ConnectionPrincipal;
+ connection: { url: string };
+ destination: { path: string };
+ }): Promise<ConnectionEventsAdapter>;
+ verify(request: Request, options: { path: string }): Promise<ConnectionEventDelivery>;
+}
+
+export function readConnectionEventsBackend(value: unknown): ConnectionEventsBackend | undefined {
+ if (value === undefined) return undefined;
+ if (
+ value === null ||
+ typeof value !== "object" ||
+ !("createAdapter" in value) ||
+ typeof value.createAdapter !== "function" ||
+ !("verify" in value) ||
+ typeof value.verify !== "function"
+ ) {
+ throw new TypeError(
+ "Connect experimental_events must provide createAdapter and verify methods.",
+ );
+ }
+ return value as ConnectionEventsBackend;
+}
diff --git a/packages/eve/src/shared/connection-types.ts b/packages/eve/src/shared/connection-types.ts
index c4ecff74f..e4cdc0b00 100644
--- a/packages/eve/src/shared/connection-types.ts
+++ b/packages/eve/src/shared/connection-types.ts
@@ -1,3 +1,4 @@
+import type { ConnectionEventsBackend } from "#shared/connection-events.js";
/**
* Protocol-agnostic interfaces for the connection system.
*
@@ -255,6 +256,7 @@ interface AuthorizationDefinitionBase {
* Connect side.
*/
readonly vercelConnect?: {
+ readonly experimental_events?: ConnectionEventsBackend;
readonly connector: string;
};
@@ -458,6 +460,8 @@ export interface ConnectionToolExecuteOptions {
/** A live client for a single connection. */
export interface ConnectionClient {
+ /** eve-owned event actions, separate from remote protocol tools and their filters. */
+ readonly eventActions?: ConnectionEventActionHandler;
close(): Promise<void>;
connect(): Promise<unknown>;
executeTool(
@@ -467,3 +471,10 @@ export interface ConnectionClient {
): Promise<unknown>;
getToolMetadata(): Promise<readonly ConnectionToolMetadata[]>;
}
+
+export interface ConnectionEventActionHandler {
+ ownsName(name: string): boolean;
+ metadata(): Promise<readonly ConnectionToolMetadata[]>;
+ recoveryMetadata(): readonly ConnectionToolMetadata[];
+ execute(name: string, args: unknown, options: ConnectionToolExecuteOptions): Promise<unknown>;
+}
diff --git a/packages/eve/src/shared/validate-authorization.ts b/packages/eve/src/shared/validate-authorization.ts
index 92c98734e..dea75c62d 100644
--- a/packages/eve/src/shared/validate-authorization.ts
+++ b/packages/eve/src/shared/validate-authorization.ts
@@ -1,3 +1,4 @@
+import { readConnectionEventsBackend } from "#shared/connection-events.js";
/**
* Structural validation for authored connection auth definitions. Returns
* `undefined` on success or a context-free error fragment for the caller to
@@ -95,6 +96,13 @@ export function normalizeAuthorizationSpec(
const auth = authorization as Record<string, unknown>;
const vercelConnect = extractVercelConnectMetadata(auth.vercelConnect);
+ const backend = readConnectionEventsBackend(
+ (auth.vercelConnect as { experimental_events?: unknown } | undefined)?.experimental_events,
+ );
+ let runtimeConnect: AuthorizationDefinition["vercelConnect"] = vercelConnect;
+ if (backend !== undefined && vercelConnect !== undefined) {
+ runtimeConnect = { ...vercelConnect, experimental_events: backend };
+ }
const displayName = auth.displayName as string | undefined;
const evict =
typeof auth.evict === "function" ? (auth.evict as AuthorizationDefinition["evict"]) : undefined;
@@ -107,7 +115,8 @@ export function normalizeAuthorizationSpec(
startAuthorization:
auth.startAuthorization as InteractiveAuthorizationDefinition["startAuthorization"],
};
- if (vercelConnect !== undefined) interactive = { ...interactive, vercelConnect };
+ if (runtimeConnect !== undefined)
+ interactive = { ...interactive, vercelConnect: runtimeConnect };
if (displayName !== undefined) interactive = { ...interactive, displayName };
if (evict !== undefined) interactive = { ...interactive, evict };
return interactive;
@@ -119,7 +128,8 @@ export function normalizeAuthorizationSpec(
auth.principalType ??
"app") as NonInteractiveAuthorizationDefinition["principalType"],
};
- if (vercelConnect !== undefined) nonInteractive = { ...nonInteractive, vercelConnect };
+ if (runtimeConnect !== undefined)
+ nonInteractive = { ...nonInteractive, vercelConnect: runtimeConnect };
if (displayName !== undefined) nonInteractive = { ...nonInteractive, displayName };
if (evict !== undefined) nonInteractive = { ...nonInteractive, evict };
return nonInteractive;