Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add approval request and response policies (#1559)

Ben Pankow11908eb7a598
diff --git a/.changeset/approval-response-api.md b/.changeset/approval-response-api.md
new file mode 100644
index 000000000..af006a0bd
--- /dev/null
+++ b/.changeset/approval-response-api.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Tools and connections can now define optional `request` and `response` approval policies, while preserving the existing function shorthand. Response policies can authenticate the responder and return a tagged allow or rejection decision, and authorization token results can expose a stable provider subject.
diff --git a/packages/eve/extension-contracts/compatibility/connection/v4.ts b/packages/eve/extension-contracts/compatibility/connection/v4.ts
new file mode 100644
index 000000000..def585931
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/connection/v4.ts
@@ -0,0 +1,11 @@
+import { defineMcpClientConnection } from "#public/connections/index.js";
+
+export default defineMcpClientConnection({
+ description: "Tenant-aware MCP service",
+ toolCall: {
+ providedArguments: {
+ tenantId: ({ session, toolName }) => `${session.id}:${toolName}`,
+ },
+ },
+ url: "https://example.com/mcp",
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v13.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v13.ts
new file mode 100644
index 000000000..76b54cd92
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v13.ts
@@ -0,0 +1,14 @@
+import { z as z3 } from "zod/v3";
+
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": (_event, ctx) =>
+ defineTool({
+ description: "Return the active session identifier.",
+ inputSchema: z3.object({ prefix: z3.string() }),
+ execute: ({ prefix }) => ({ sessionId: `${prefix}:${ctx.session.id}` }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v11.ts b/packages/eve/extension-contracts/compatibility/tool/v11.ts
new file mode 100644
index 000000000..eae0f5b7e
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v11.ts
@@ -0,0 +1,11 @@
+import { z as z3 } from "zod/v3";
+
+import { defineTool } from "#public/tools/index.js";
+
+export default defineTool({
+ description: "Look up a report.",
+ inputSchema: z3.object({ reportId: z3.string() }),
+ execute(input, ctx) {
+ return { callId: ctx.callId, reportId: input.reportId };
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/connection/v5.json b/packages/eve/extension-contracts/reports/connection/v5.json
new file mode 100644
index 000000000..e93c07161
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v5.json
@@ -0,0 +1,15 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 5,
+ "sha256": "e33d7dc289b2b1d8f99bc732dc35c3cf5014561681cd70775660a124345ffa9c",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v14.json b/packages/eve/extension-contracts/reports/dynamicTool/v14.json
new file mode 100644
index 000000000..bdaceb2a2
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v14.json
@@ -0,0 +1,13 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 14,
+ "sha256": "bc3b0e6ddcb68aa697227805e8235a23bcf40edfdb3ffbcecd648978919da8d0",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v12.json b/packages/eve/extension-contracts/reports/tool/v12.json
new file mode 100644
index 000000000..e6173620d
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v12.json
@@ -0,0 +1,22 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 12,
+ "sha256": "c6902b95df593e9441755720920f1844aec149186d49f356a5a99d6d7bee19ef",
+ "exports": [
+ "defineBashTool",
+ "defineGlobTool",
+ "defineGrepTool",
+ "defineReadFileTool",
+ "defineTool",
+ "defineWriteFileTool",
+ "disableTool",
+ "experimental_workflow",
+ "isDisabledToolSentinel",
+ "isExperimentalWorkflowToolDefinition",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch"
+ ]
+}
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index b0921cc3d..a44ac0f89 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -21,13 +21,13 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
- tool: { current: 11, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dropped: {} },
+ tool: { current: 12, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dropped: {} },
dynamicTool: {
- current: 13,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
+ current: 14,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
dropped: {},
},
- connection: { current: 4, supported: [1, 2, 3, 4], dropped: {} },
+ connection: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },
hook: {
current: 10,
supported: [10],
diff --git a/packages/eve/src/context/build-dynamic-tools.ts b/packages/eve/src/context/build-dynamic-tools.ts
index 4df436eac..a94ef004f 100644
--- a/packages/eve/src/context/build-dynamic-tools.ts
+++ b/packages/eve/src/context/build-dynamic-tools.ts
@@ -8,7 +8,12 @@ import {
import type { DurableDynamicToolMetadata } from "#context/keys.js";
import { createToolExecuteWithAuth } from "#execution/tool-auth.js";
import { createLogger } from "#internal/logging.js";
-import type { ApprovalContext, ApprovalStatus } from "#public/definitions/approval.js";
+import type {
+ ApprovalContext,
+ ApprovalResponseDecision,
+ ApprovalResponseContext,
+ ApprovalStatus,
+} from "#public/definitions/approval.js";
import { toInputSchema, toOutputSchema } from "#shared/tool-schema.js";
const log = createLogger("dynamic-tools");
@@ -79,8 +84,30 @@ function buildReplayedApproval(
return () => "user-approval";
}
- return async (approvalCtx: ApprovalContext) =>
+ const policy = async (approvalCtx: ApprovalContext) =>
(await approvalStepFn(metadata.closureVars ?? {}, approvalCtx)) as ApprovalStatus;
+ if (metadata.approvalResponseStepFnName === undefined) return policy;
+
+ const responseStepFn = lookupStepFunction(metadata.approvalResponseStepFnName);
+ if (responseStepFn === null) {
+ log.warn(
+ `Dynamic tool "${metadata.name}" references response authorizer ` +
+ `"${metadata.approvalResponseStepFnName}" which is not registered — rejecting responses.`,
+ );
+ return {
+ request: policy,
+ response: async () => ({
+ reason: "Approval response authorization is temporarily unavailable.",
+ status: "rejected" as const,
+ }),
+ };
+ }
+
+ return {
+ request: policy,
+ response: async (responseCtx: ApprovalResponseContext) =>
+ (await responseStepFn(metadata.closureVars ?? {}, responseCtx)) as ApprovalResponseDecision,
+ };
}
/**
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
index a1eeac1d7..1ffec4dbe 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import type { DynamicToolEntry } from "#shared/dynamic-tool-definition.js";
import type { DurableDynamicToolMetadata } from "#context/keys.js";
-import type { ApprovalContext } from "#public/definitions/approval.js";
+import { resolveApprovalPolicy, type ApprovalContext } from "#public/definitions/approval.js";
import { defineTool, type ToolContext } from "#public/definitions/tool.js";
import type { JsonObject } from "#shared/json.js";
import { serializeOutputSchema, type ToolSchema } from "#shared/tool-schema.js";
@@ -1165,7 +1165,7 @@ describe("framework dynamic tools (no bundler transform)", () => {
expect(tools[0]!.name).toBe("risky");
expect(tools[0]!.approval).toBe(approvalFn);
const approvalCtx = createApprovalContext({ toolName: "risky" });
- expect(tools[0]!.approval!(approvalCtx)).toBe("user-approval");
+ expect(resolveApprovalPolicy(tools[0]!.approval!)(approvalCtx)).toBe("user-approval");
expect(testRegistry.has("eve:framework-dynamic:connection:risky")).toBe(false);
expect(testRegistry.has("eve:dynamic-tool-approval:connection:risky")).toBe(false);
});
@@ -1199,10 +1199,97 @@ describe("framework dynamic tools (no bundler transform)", () => {
toolInput: { draftId: "draft_123" },
toolName: "guarded",
});
- await expect(tools[0]!.approval!(approvalCtx)).resolves.toBe("user-approval");
+ await expect(resolveApprovalPolicy(tools[0]!.approval!)(approvalCtx)).resolves.toBe(
+ "user-approval",
+ );
expect(approvalFn).toHaveBeenCalledExactlyOnceWith(approvalCtx);
});
+ it("replays turn metadata written before request/response policy naming", async () => {
+ const ctx = createCtx();
+ const approval = vi.fn(() => "user-approval" as const);
+ testRegistry.set("legacy-turn-execute", () => ({ ok: true }));
+ testRegistry.set("legacy-turn-approval", approval);
+ ctx.set(TurnDynamicToolMetadataKey, [
+ {
+ approvalStepFnName: "legacy-turn-approval",
+ closureVars: {},
+ description: "legacy guarded tool",
+ entryKey: "legacy:guarded",
+ executeStepFnName: "legacy-turn-execute",
+ inputSchema: { type: "object" },
+ name: "guarded",
+ resolverSlug: "legacy",
+ },
+ ]);
+
+ const tool = buildDynamicTools(ctx)[0];
+ if (tool?.approval === undefined) throw new Error("Expected replayed approval.");
+
+ await expect(
+ resolveApprovalPolicy(tool.approval)(createApprovalContext({ toolName: "guarded" })),
+ ).resolves.toBe("user-approval");
+ });
+
+ it("replays response authorization from session-scoped dynamic tools", async () => {
+ const ctx = createCtx();
+ const response = vi.fn(async () => ({ status: "allowed" }) as const);
+ const entry: DynamicToolEntry = defineTool({
+ approval: {
+ request: async () => "user-approval" as const,
+ response,
+ },
+ description: "destructive op",
+ execute: async (): Promise<unknown> => ({ ok: true }),
+ inputSchema: { type: "object" },
+ });
+ const resolver = createResolver("session_guard", ["session.started"], () => ({
+ guarded: entry,
+ }));
+
+ await dispatchDynamicToolEvent({
+ ctx,
+ event: makeEvent("session.started"),
+ messages: [],
+ resolvers: [resolver],
+ });
+ ctx.clearVirtualContext();
+
+ const approval = buildDynamicTools(ctx)[0]!.approval;
+ if (approval === undefined || typeof approval === "function") {
+ throw new Error("Expected replayed approval configuration.");
+ }
+ const responseCtx = {
+ auth: {
+ getToken: vi.fn(),
+ requireAuth: () => {
+ throw new Error("not implemented");
+ },
+ },
+ request: {
+ callId: "call_1",
+ requestId: "approval_1",
+ toolInput: { owner: "vercel", repo: "eve" },
+ toolName: "guarded",
+ },
+ response: { decision: "approve" as const },
+ responder: {
+ attributes: {},
+ authenticator: "slack",
+ principalId: "U123",
+ principalType: "user",
+ },
+ session: {
+ id: "test-session",
+ initiator: null,
+ turn: { id: "test-turn", sequence: 0 },
+ },
+ };
+
+ await expect(approval.response!(responseCtx)).resolves.toEqual({ status: "allowed" });
+ expect(response).toHaveBeenCalledExactlyOnceWith(responseCtx);
+ });
+
it("propagates outputSchema from dynamic entries into harness tools and metadata", async () => {
const ctx = createCtx();
const outputSchema = {
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.ts b/packages/eve/src/context/dynamic-tool-lifecycle.ts
index 8a6cc147b..eb53c2466 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.ts
@@ -1,7 +1,11 @@
import type { ModelMessage } from "ai";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import type { ApprovalContext } from "#public/definitions/approval.js";
+import {
+ resolveApprovalPolicy,
+ type ApprovalContext,
+ type ApprovalResponseContext,
+} from "#public/definitions/approval.js";
import type { DynamicToolEntry } from "#shared/dynamic-tool-definition.js";
import type { UnstampedMessageStreamEvent, SessionStartedStreamEvent } from "#protocol/message.js";
import {
@@ -309,12 +313,24 @@ async function resolveToolsFromEvent(
}
let approvalStepFnName: string | undefined;
+ let approvalResponseStepFnName: string | undefined;
if (entry.approval !== undefined) {
approvalStepFnName = `eve:dynamic-tool-approval:${resolver.slug}:${entryKey}`;
- const originalApproval = entry.approval.bind(entry);
+ const originalApproval = resolveApprovalPolicy(entry.approval).bind(entry);
registerStepFunction(approvalStepFnName, (_closureVars: unknown, approvalCtx: unknown) =>
originalApproval(approvalCtx as ApprovalContext),
);
+
+ const responsePolicy =
+ typeof entry.approval === "function" ? undefined : entry.approval.response;
+ if (responsePolicy !== undefined) {
+ approvalResponseStepFnName = `eve:dynamic-tool-approval-response:${resolver.slug}:${entryKey}`;
+ registerStepFunction(
+ approvalResponseStepFnName,
+ (_closureVars: unknown, responseCtx: unknown) =>
+ responsePolicy(responseCtx as ApprovalResponseContext),
+ );
+ }
}
metadata.push({
@@ -326,6 +342,7 @@ async function resolveToolsFromEvent(
entryKey,
executeStepFnName,
approvalStepFnName,
+ approvalResponseStepFnName,
closureVars: serializedClosureVars,
});
}
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 27199c22f..ef1c9d35a 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -145,6 +145,7 @@ export interface DurableDynamicToolMetadata {
readonly entryKey: string;
readonly executeStepFnName?: string;
readonly approvalStepFnName?: string;
+ readonly approvalResponseStepFnName?: string;
readonly closureVars?: Record<string, unknown>;
}
diff --git a/packages/eve/src/execution/tool-auth.integration.test.ts b/packages/eve/src/execution/tool-auth.integration.test.ts
index 2ffa32270..8c9f05c89 100644
--- a/packages/eve/src/execution/tool-auth.integration.test.ts
+++ b/packages/eve/src/execution/tool-auth.integration.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { createToolExecuteWithAuth } from "#execution/tool-auth.js";
+import { buildApprovalResponseAuth, createToolExecuteWithAuth } from "#execution/tool-auth.js";
import { evictScopedToken, resolveScopedToken } from "#runtime/connections/scoped-authorization.js";
import { loadContext } from "#context/container.js";
import { AuthKey, SessionIdKey } from "#context/keys.js";
@@ -77,6 +77,83 @@ function authoredTool(input: {
};
}
+describe("approval response authorization", () => {
+ it("keeps distinct connector tokens separate within one response policy", async () => {
+ const github: AuthorizationDefinition = {
+ principalType: "user",
+ vercelConnect: { connector: "github/approver" },
+ async getToken(): Promise<TokenResult> {
+ return { token: "github-token" };
+ },
+ };
+ const linear: AuthorizationDefinition = {
+ principalType: "user",
+ vercelConnect: { connector: "linear/approver" },
+ async getToken(): Promise<TokenResult> {
+ return { token: "linear-token" };
+ },
+ };
+ const runtime = createTestRuntime({ tools: [] });
+
+ const tokens = await runtime.runAsSession(undefined, async () => {
+ const auth = buildApprovalResponseAuth({
+ responder: {
+ attributes: {},
+ authenticator: "test-idp",
+ principalId: "bound-U1",
+ principalType: "user",
+ },
+ scope: "candidate-1",
+ });
+ return {
+ github: (await auth.getToken(github)).token,
+ linear: (await auth.getToken(linear)).token,
+ };
+ });
+
+ expect(tokens).toEqual({ github: "github-token", linear: "linear-token" });
+ });
+
+ it("resolves user tokens for the explicitly bound responder instead of ambient auth", async () => {
+ let resolvedPrincipal: ConnectionPrincipal | undefined;
+ const provider: AuthorizationDefinition = {
+ principalType: "user",
+ async getToken({ principal }): Promise<TokenResult> {
+ resolvedPrincipal = principal;
+ return { token: "bound-responder-token" };
+ },
+ };
+ const runtime = createTestRuntime({ tools: [] });
+
+ await runtime.runAsSession(undefined, async () => {
+ loadContext().set(AuthKey, {
+ attributes: {},
+ authenticator: "test-idp",
+ principalId: "ambient-U2",
+ principalType: "user",
+ });
+ return await buildApprovalResponseAuth({
+ responder: {
+ attributes: { role: ["approver"] },
+ authenticator: "test-idp",
+ issuer: "test-idp",
+ principalId: "bound-U1",
+ principalType: "user",
+ subject: "bound-subject-U1",
+ },
+ scope: "candidate-1",
+ }).getToken(provider);
+ });
+
+ expect(resolvedPrincipal).toMatchObject({
+ attributes: { role: ["approver"] },
+ id: "bound-U1",
+ issuer: "test-idp",
+ type: "user",
+ });
+ });
+});
+
describe("tool-hosted authorization", () => {
it("resolves and caches the bearer through ctx.getToken(provider)", async () => {
let calls = 0;
diff --git a/packages/eve/src/execution/tool-auth.ts b/packages/eve/src/execution/tool-auth.ts
index c6b6640b1..52428fa14 100644
--- a/packages/eve/src/execution/tool-auth.ts
+++ b/packages/eve/src/execution/tool-auth.ts
@@ -14,11 +14,13 @@
*/
import { buildBaseToolContext } from "#context/build-base-tool-context.js";
+import type { SessionAuthContext } from "#channel/types.js";
import {
ConnectionAuthorizationFailedError,
ConnectionAuthorizationRequiredError,
isConnectionAuthorizationRequiredError,
} from "#public/connections/errors.js";
+import type { ApprovalResponseAuth } from "#public/definitions/approval.js";
import type { ToolAuthOptions, ToolAuthProvider, ToolContext } from "#public/definitions/tool.js";
import { type AuthorizationChallenge, requestAuthorization } from "#harness/authorization.js";
import {
@@ -103,6 +105,56 @@ export function createToolExecuteWithAuth(input: {
};
}
+/** Builds the narrow token capability used by approval response authorizers. */
+export function buildApprovalResponseAuth(input: {
+ readonly responder: SessionAuthContext;
+ readonly scope: string;
+}): ApprovalResponseAuth {
+ const inlineAuthState: InlineAuthState = {};
+ const justAuthorizedScopes = new Set<string>();
+ return {
+ async getToken(provider?: ToolAuthProvider, options?: ToolAuthOptions): Promise<TokenResult> {
+ if (provider === undefined) throw missingProviderError("ctx.getToken");
+ return await resolveInlineToken({
+ boundResponder: input.responder,
+ inlineAuthState,
+ justAuthorizedScopes,
+ options: namespaceApprovalAuthOptions(input.scope, options),
+ provider,
+ toolScope: input.scope,
+ });
+ },
+ requireAuth(provider?: ToolAuthProvider, options?: ToolAuthOptions): never {
+ if (provider === undefined) throw missingProviderError("ctx.requireAuth");
+ const scoped = buildInlineScopedAuthorization({
+ boundResponder: input.responder,
+ inlineAuthState,
+ options: namespaceApprovalAuthOptions(input.scope, options),
+ provider,
+ toolScope: input.scope,
+ });
+ throw new ToolAuthorizationRequiredError([
+ { justAuthorized: justAuthorizedScopes.has(scoped.scope), scoped },
+ ]);
+ },
+ };
+}
+
+function namespaceApprovalAuthOptions(
+ scope: string,
+ options: ToolAuthOptions | undefined,
+): ToolAuthOptions | undefined {
+ return options?.authKey === undefined
+ ? options
+ : { ...options, authKey: `${scope}:${options.authKey}` };
+}
+
+/** Starts authorization requested by an approval response authorizer. */
+export async function handleApprovalResponsePolicyError(error: unknown): Promise<unknown> {
+ if (!isToolAuthorizationRequiredError(error)) throw error;
+ return await handleAuthorizationRequests(error.requests);
+}
+
function buildToolContext(input: {
readonly options: ToolExecuteOptions;
readonly scope: string;
@@ -142,6 +194,7 @@ function buildToolContext(input: {
}
async function resolveInlineToken(input: {
+ readonly boundResponder?: SessionAuthContext;
readonly toolScope: string;
readonly provider: ToolAuthProvider;
readonly options?: ToolAuthOptions;
@@ -234,6 +287,7 @@ async function handleAuthorizationRequests(
}
function buildInlineScopedAuthorization(input: {
+ readonly boundResponder?: SessionAuthContext;
readonly toolScope: string;
readonly provider: ToolAuthProvider;
readonly options?: ToolAuthOptions;
@@ -242,6 +296,7 @@ function buildInlineScopedAuthorization(input: {
const authorization = normalizeInlineProvider(input.provider, input.options);
return {
authorization,
+ boundResponder: input.boundResponder,
connection: input.options?.connection ?? { url: "" },
scope:
input.options?.authKey === undefined
diff --git a/packages/eve/src/harness/tools.test.ts b/packages/eve/src/harness/tools.test.ts
index 8f1a19ee5..2804d1da6 100644
--- a/packages/eve/src/harness/tools.test.ts
+++ b/packages/eve/src/harness/tools.test.ts
@@ -20,6 +20,7 @@ import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import { buildToolApproval, buildToolSet, buildToolSetWithProviderTools } from "#harness/tools.js";
import type { HarnessToolMap } from "#harness/types.js";
import { createToolExecuteWithAuth } from "#execution/tool-auth.js";
+import type { ApprovalContext } from "#public/definitions/approval.js";
import type { ToolContext } from "#public/definitions/tool.js";
import type { ToolExecuteOptions } from "#shared/tool-definition.js";
@@ -991,7 +992,7 @@ describe("buildToolSet", () => {
});
it("passes the active caller and session context into approval", async () => {
- let capturedCtx: Parameters<NonNullable<HarnessToolDefinition["approval"]>>[0] | undefined;
+ let capturedCtx: ApprovalContext | undefined;
const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
[
"delete_project",
diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.ts
index 4ed80c259..8611f7557 100644
--- a/packages/eve/src/harness/tools.ts
+++ b/packages/eve/src/harness/tools.ts
@@ -7,7 +7,7 @@ import { ASK_QUESTION_TOOL_NAME } from "#runtime/framework-tools/ask-question.js
import { WEB_SEARCH_TOOL_DEFINITION } from "#runtime/framework-tools/web-search.js";
import { isObject } from "#shared/guards.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import type { ApprovalStatus } from "#public/definitions/approval.js";
+import { resolveApprovalPolicy, type ApprovalStatus } from "#public/definitions/approval.js";
import { resolveWebSearchBackend, resolveWebSearchProviderTool } from "#harness/provider-tools.js";
import type { HarnessToolMap } from "#harness/types.js";
import { buildCallbackContext } from "#context/build-callback-context.js";
@@ -277,7 +277,7 @@ function buildApprovalFn(
const toolInputRecord = isObject(toolInput) ? toolInput : undefined;
- const status = await definition.approval({
+ const status = await resolveApprovalPolicy(definition.approval)({
...buildCallbackContext(),
approvedTools: input.approvedTools ?? new Set(),
callId,
diff --git a/packages/eve/src/internal/authored-definition/approval.ts b/packages/eve/src/internal/authored-definition/approval.ts
new file mode 100644
index 000000000..45321b281
--- /dev/null
+++ b/packages/eve/src/internal/authored-definition/approval.ts
@@ -0,0 +1,22 @@
+import {
+ expectFunction,
+ expectObjectRecord,
+ expectOnlyKnownKeys,
+} from "#internal/authored-module.js";
+import type {
+ Approval,
+ ApprovalPolicy,
+ ApprovalResponsePolicy,
+} from "#public/definitions/approval.js";
+
+/** Validates the function shorthand or explicit request/response approval shape. */
+export function normalizeApproval(value: unknown, message: string): Approval {
+ if (typeof value === "function") return value as Approval;
+
+ const approval = expectObjectRecord(value, message);
+ expectOnlyKnownKeys(approval, ["request", "response"], message);
+ const request = expectFunction<ApprovalPolicy>(approval.request, message);
+ if (approval.response === undefined) return { request };
+ const response = expectFunction<ApprovalResponsePolicy>(approval.response, message);
+ return { request, response };
+}
diff --git a/packages/eve/src/internal/authored-definition/connection.test.ts b/packages/eve/src/internal/authored-definition/connection.test.ts
index 9b9d65f38..064ec40a8 100644
--- a/packages/eve/src/internal/authored-definition/connection.test.ts
+++ b/packages/eve/src/internal/authored-definition/connection.test.ts
@@ -325,16 +325,25 @@ describe("normalizeMcpClientConnectionDefinition", () => {
expect(result.approval).toBe(fn);
});
+ it("accepts request and response approval policies", () => {
+ const approval = {
+ request: () => "user-approval" as const,
+ response: () => ({ status: "allowed" as const }),
+ };
+ const result = normalizeMcpClientConnectionDefinition(validInput({ approval }), MSG);
+ expect(result.approval).toEqual(approval);
+ });
+
it("rejects a non-function approval", () => {
expect(() =>
normalizeMcpClientConnectionDefinition(validInput({ approval: "never" }), MSG),
- ).toThrow(/must be a function/);
+ ).toThrow();
});
it("rejects a boolean approval", () => {
expect(() =>
normalizeMcpClientConnectionDefinition(validInput({ approval: true }), MSG),
- ).toThrow(/must be a function/);
+ ).toThrow();
});
});
diff --git a/packages/eve/src/internal/authored-definition/connection.ts b/packages/eve/src/internal/authored-definition/connection.ts
index 96f6aae8f..7d63ce7f2 100644
--- a/packages/eve/src/internal/authored-definition/connection.ts
+++ b/packages/eve/src/internal/authored-definition/connection.ts
@@ -1,3 +1,4 @@
+import { normalizeApproval } from "#internal/authored-definition/approval.js";
import type { McpClientConnectionDefinition } from "#public/definitions/connections/mcp.js";
import type { OpenAPIConnectionDefinition } from "#public/definitions/connections/openapi.js";
import type {
@@ -101,10 +102,7 @@ export function normalizeMcpClientConnectionDefinition(
}
if (record.approval !== undefined) {
- if (typeof record.approval !== "function") {
- throw new Error(`${message} The "approval" field must be a function when provided.`);
- }
- result.approval = record.approval as McpClientConnectionDefinition["approval"];
+ result.approval = normalizeApproval(record.approval, message);
}
return result;
@@ -213,10 +211,7 @@ export function normalizeOpenApiConnectionDefinition(
}
if (record.approval !== undefined) {
- if (typeof record.approval !== "function") {
- throw new Error(`${message} The "approval" field must be a function when provided.`);
- }
- result.approval = record.approval as OpenAPIConnectionDefinition["approval"];
+ result.approval = normalizeApproval(record.approval, message);
}
return result;
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.test.ts b/packages/eve/src/internal/authored-definition/schema-backed.test.ts
index 2d816edbe..4b6db15f7 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.test.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.test.ts
@@ -180,6 +180,20 @@ describe("normalizeToolDefinition", () => {
expect(normalizeToolDefinition(tool, FAILURE_MESSAGE).kind).toBe("tool");
});
+ it("accepts explicit request and response approval policies", () => {
+ const tool = defineTool({
+ approval: {
+ request: () => "user-approval",
+ response: () => ({ status: "allowed" }),
+ },
+ description: "Uses response authorization.",
+ execute: () => null,
+ inputSchema: z.object({ city: z.string() }),
+ });
+
+ expect(normalizeToolDefinition(tool, FAILURE_MESSAGE).kind).toBe("tool");
+ });
+
it("accepts generic approval helpers on schema-typed tools", () => {
const tool = defineTool({
description: "Uses a reusable approval helper.",
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.ts
index 417d8feee..dab814cec 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts
@@ -16,6 +16,7 @@ import {
serializeOutputSchema,
type ToolSchemaSource,
} from "#shared/tool-schema.js";
+import { normalizeApproval } from "#internal/authored-definition/approval.js";
import {
assertResolverOnlyDynamicSentinel,
isDynamicSentinel,
@@ -116,7 +117,7 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal
* the module export and attaches them to the ResolvedToolDefinition.
*/
if (record.approval !== undefined) {
- expectFunction(record.approval, message);
+ normalizeApproval(record.approval, message);
}
if (record.toModelOutput !== undefined) {
diff --git a/packages/eve/src/public/definitions/approval.test.ts b/packages/eve/src/public/definitions/approval.test.ts
new file mode 100644
index 000000000..e249d0a04
--- /dev/null
+++ b/packages/eve/src/public/definitions/approval.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, expectTypeOf, it, vi } from "vitest";
+
+import {
+ resolveApprovalPolicy,
+ type Approval,
+ type ApprovalResponseContext,
+} from "#public/definitions/approval.js";
+
+describe("approval definitions", () => {
+ it("preserves request-time function shorthand", async () => {
+ const policy: Approval = () => "user-approval";
+
+ expect(await resolveApprovalPolicy(policy)({} as never)).toBe("user-approval");
+ });
+
+ it("resolves request policy from the object form", async () => {
+ const policy = vi.fn(() => "not-applicable" as const);
+ const approval: Approval = {
+ request: policy,
+ response: () => ({ status: "allowed" }),
+ };
+
+ expect(await resolveApprovalPolicy(approval)({} as never)).toBe("not-applicable");
+ expect(policy).toHaveBeenCalledOnce();
+ });
+
+ it("keeps response authorization context capability narrow", () => {
+ expectTypeOf<ApprovalResponseContext>().toMatchTypeOf<{
+ auth: {
+ getToken: (...args: any[]) => Promise<unknown>;
+ requireAuth: (...args: any[]) => never;
+ };
+ request: { callId: string; requestId: string; toolName: string };
+ response: { decision: "approve" };
+ responder: { principalId: string };
+ session: { id: string; initiator: unknown; turn: unknown };
+ }>();
+ expectTypeOf<ApprovalResponseContext["auth"]>().not.toHaveProperty("getSandbox");
+ expectTypeOf<ApprovalResponseContext["auth"]>().not.toHaveProperty("getSkill");
+ });
+});
diff --git a/packages/eve/src/public/definitions/approval.ts b/packages/eve/src/public/definitions/approval.ts
index b008eee5d..3c1c4a828 100644
--- a/packages/eve/src/public/definitions/approval.ts
+++ b/packages/eve/src/public/definitions/approval.ts
@@ -1,19 +1,16 @@
+import type { SessionAuthContext } from "#channel/types.js";
+import type { SessionParent, SessionTurn } from "#context/keys.js";
+import type { ToolAuthOptions, ToolAuthProvider } from "#public/definitions/tool.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
+import type { TokenResult } from "#runtime/connections/types.js";
type ApprovalToolInput<TInput> = TInput extends object ? Readonly<TInput> : TInput;
/**
- * Context passed to an {@link Approval} function.
+ * Context passed to an {@link ApprovalPolicy} function.
*
* Extends {@link SessionContext} so approval policies can make decisions from
* the active session, current caller, and turn.
- *
- * `approvedTools` is the set of tool names (or compound approval keys)
- * already approved at least once in the current session. `toolName` is the
- * runtime name of the tool being evaluated. `toolInput` is the raw input the
- * model passed, available for input-aware decisions. `callId` is the id of
- * the call being evaluated — the same `callId` carried by the call's stream
- * events and its `execute` context.
*/
export interface ApprovalContext<TInput = Record<string, unknown>> extends SessionContext {
readonly approvedTools: ReadonlySet<string>;
@@ -22,12 +19,7 @@ export interface ApprovalContext<TInput = Record<string, unknown>> extends Sessi
readonly toolName: string;
}
-/**
- * Approval decision returned by an {@link Approval} function.
- *
- * AI SDK 7 statuses are accepted directly. For compatibility, `true` maps to
- * `"user-approval"` and `false` maps to `"not-applicable"`.
- */
+/** Request-time approval decision returned by an {@link ApprovalPolicy}. */
export type ApprovalStatus =
| undefined
| boolean
@@ -40,7 +32,69 @@ export type ApprovalStatus =
| { readonly type: "denied"; readonly reason?: string }
| { readonly type: "user-approval"; readonly reason?: never };
-/** Shared approval policy used by authored tools and connections. */
-export type Approval<TInput = Record<string, unknown>> = (
+/** Request-time approval policy shared by authored tools and connections. */
+export type ApprovalPolicy<TInput = Record<string, unknown>> = (
ctx: ApprovalContext<TInput>,
) => ApprovalStatus | Promise<ApprovalStatus>;
+
+/** Stable tool request passed to a response authorizer. */
+export interface ApprovalRequest<TInput = Record<string, unknown>> {
+ readonly callId: string;
+ readonly requestId: string;
+ readonly toolInput?: ApprovalToolInput<TInput>;
+ readonly toolName: string;
+}
+
+/** Read-only session identity and lineage available to a response authorizer. */
+export interface ApprovalResponseSession {
+ readonly id: string;
+ readonly initiator: SessionAuthContext | null;
+ readonly parent?: SessionParent;
+ readonly turn: SessionTurn;
+}
+
+/** Narrow authorization capability available while validating a responder. */
+export interface ApprovalResponseAuth {
+ getToken(provider: ToolAuthProvider, options?: ToolAuthOptions): Promise<TokenResult>;
+ requireAuth(provider: ToolAuthProvider, options?: ToolAuthOptions): never;
+}
+
+/** Submitted decision passed to an approval response policy. */
+export interface ApprovalResponse {
+ readonly decision: "approve";
+}
+
+/** Context passed to an approval response policy. */
+export interface ApprovalResponseContext<TInput = Record<string, unknown>> {
+ readonly auth: ApprovalResponseAuth;
+ readonly request: ApprovalRequest<TInput>;
+ readonly response: ApprovalResponse;
+ readonly responder: SessionAuthContext;
+ readonly session: ApprovalResponseSession;
+}
+
+/** Response policy decision. Rejection keeps the shared request pending. */
+export type ApprovalResponseDecision =
+ | { readonly status: "allowed" }
+ | { readonly reason: string; readonly status: "rejected" };
+
+/** Decides whether an authenticated responder may approve one request. */
+export type ApprovalResponsePolicy<TInput = Record<string, unknown>> = (
+ ctx: ApprovalResponseContext<TInput>,
+) => ApprovalResponseDecision | Promise<ApprovalResponseDecision>;
+
+/** Approval definition with request- and response-time policy. */
+export interface ApprovalConfiguration<TInput = Record<string, unknown>> {
+ readonly request: ApprovalPolicy<TInput>;
+ readonly response?: ApprovalResponsePolicy<TInput>;
+}
+
+/** Shared approval definition used by authored tools and connections. */
+export type Approval<TInput = Record<string, unknown>> =
+ | ApprovalPolicy<TInput>
+ | ApprovalConfiguration<TInput>;
+
+/** Returns the request-time policy from either approval authoring shape. */
+export function resolveApprovalPolicy<TInput>(approval: Approval<TInput>): ApprovalPolicy<TInput> {
+ return typeof approval === "function" ? approval : approval.request;
+}
diff --git a/packages/eve/src/public/tools/approval/approval-helpers.ts b/packages/eve/src/public/tools/approval/approval-helpers.ts
index 1d2906654..200a40455 100644
--- a/packages/eve/src/public/tools/approval/approval-helpers.ts
+++ b/packages/eve/src/public/tools/approval/approval-helpers.ts
@@ -1,10 +1,10 @@
-import type { Approval } from "#public/definitions/approval.js";
+import type { ApprovalPolicy } from "#public/definitions/approval.js";
/**
* Returns an `approval` callback that always requires user approval before
* the tool executes.
*/
-export function always<TInput = unknown>(): Approval<TInput> {
+export function always<TInput = unknown>(): ApprovalPolicy<TInput> {
return () => "user-approval";
}
@@ -12,7 +12,7 @@ export function always<TInput = unknown>(): Approval<TInput> {
* Returns an `approval` callback that never requires user approval before
* the tool executes.
*/
-export function never<TInput = unknown>(): Approval<TInput> {
+export function never<TInput = unknown>(): ApprovalPolicy<TInput> {
return () => "not-applicable";
}
@@ -23,7 +23,7 @@ export function never<TInput = unknown>(): Approval<TInput> {
* responding) leaves it unrecorded, so the next call prompts again. Keys off
* the bare tool name, so it ignores compound approval keys.
*/
-export function once<TInput = unknown>(): Approval<TInput> {
+export function once<TInput = unknown>(): ApprovalPolicy<TInput> {
return ({ approvedTools, toolName }) =>
approvedTools.has(toolName) ? "not-applicable" : "user-approval";
}
diff --git a/packages/eve/src/public/tools/index.ts b/packages/eve/src/public/tools/index.ts
index 27fb84c69..55834961e 100644
--- a/packages/eve/src/public/tools/index.ts
+++ b/packages/eve/src/public/tools/index.ts
@@ -20,7 +20,20 @@ export {
type ToolModelOutputPart,
} from "#public/definitions/tool.js";
export { toolOutput, toolOutputPart } from "#public/tools/output-builders.js";
-export type { Approval, ApprovalContext, ApprovalStatus } from "#public/definitions/approval.js";
+export type {
+ Approval,
+ ApprovalConfiguration,
+ ApprovalContext,
+ ApprovalPolicy,
+ ApprovalRequest,
+ ApprovalResponse,
+ ApprovalResponseAuth,
+ ApprovalResponseContext,
+ ApprovalResponseDecision,
+ ApprovalResponsePolicy,
+ ApprovalResponseSession,
+ ApprovalStatus,
+} from "#public/definitions/approval.js";
export type {
DynamicToolEntry,
DynamicEvents,
diff --git a/packages/eve/src/runtime/connections/principal.ts b/packages/eve/src/runtime/connections/principal.ts
index 13cbef558..c63bc9d45 100644
--- a/packages/eve/src/runtime/connections/principal.ts
+++ b/packages/eve/src/runtime/connections/principal.ts
@@ -82,12 +82,21 @@ export function resolveConnectionPrincipal(
connectionName: string,
authorization: AuthorizationDefinition,
ctx: AlsContext | undefined = contextStorage.getStore(),
+): ConnectionPrincipal {
+ return resolveConnectionPrincipalFromAuth(connectionName, authorization, ctx?.get(AuthKey), ctx);
+}
+
+/** Resolves a connection principal from an explicitly bound session identity. */
+export function resolveConnectionPrincipalFromAuth(
+ connectionName: string,
+ authorization: AuthorizationDefinition,
+ current: SessionAuthContext | null | undefined,
+ ctx?: AlsContext,
): ConnectionPrincipal {
if (authorization.principalType === "app") {
return { type: "app" };
}
- const current = ctx?.get(AuthKey);
if (current === null || current === undefined || current.principalType !== "user") {
throw new ConnectionAuthorizationFailedError(connectionName, {
message: buildUserPrincipalRequiredMessage(connectionName, authorization, ctx, current),
diff --git a/packages/eve/src/runtime/connections/scoped-authorization.ts b/packages/eve/src/runtime/connections/scoped-authorization.ts
index a4b816043..c8dad53e0 100644
--- a/packages/eve/src/runtime/connections/scoped-authorization.ts
+++ b/packages/eve/src/runtime/connections/scoped-authorization.ts
@@ -24,7 +24,12 @@ import {
readCachedToken,
writeCachedToken,
} from "#runtime/connections/authorization-tokens.js";
-import { principalKey, resolveConnectionPrincipal } from "#runtime/connections/principal.js";
+import {
+ principalKey,
+ resolveConnectionPrincipal,
+ resolveConnectionPrincipalFromAuth,
+} from "#runtime/connections/principal.js";
+import type { SessionAuthContext } from "#context/keys.js";
import {
type AuthorizationDefinition,
type ConnectionAuthorizationContext,
@@ -42,6 +47,7 @@ const LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES: ReadonlySet<string> = new Set(["127.0
* {@link ConnectionAuthorizationContext} handed to every callback.
*/
export interface ScopedAuthorization {
+ readonly boundResponder?: SessionAuthContext;
readonly scope: string;
readonly authorization: Readonly<AuthorizationDefinition>;
readonly connection: ConnectionAuthorizationContext;
@@ -68,7 +74,7 @@ export async function resolveScopedToken(input: ScopedAuthorization): Promise<To
// place that tolerates a missing context; authored code uses
// `loadContext()` so misuse fails loudly.
const ctx = contextStorage.getStore();
- const principal = resolveConnectionPrincipal(scope, authorization, ctx);
+ const principal = resolveScopedPrincipal(input, ctx);
if (ctx === undefined) {
return await authorization.getToken({ connection, principal });
@@ -106,7 +112,7 @@ export async function evictScopedToken(input: ScopedAuthorization): Promise<void
if (ctx === undefined) return;
let principal;
try {
- principal = resolveConnectionPrincipal(scope, authorization, ctx);
+ principal = resolveScopedPrincipal(input, ctx);
evictCachedToken(ctx, scope, principalKey(principal));
} catch {
// Eviction is best-effort; without a principal we can drop neither
@@ -141,7 +147,7 @@ export async function completeScopedAuthorization(input: ScopedAuthorization): P
const interactive = authorization as InteractiveAuthorizationDefinition<JsonValue>;
const ctx: AlsContext = loadContext();
- const principal = result.principal ?? resolveConnectionPrincipal(scope, interactive, ctx);
+ const principal = result.principal ?? resolveScopedPrincipal(input, ctx);
const token = await interactive.completeAuthorization({
callbackUrl: result.hookUrl,
connection,
@@ -171,7 +177,7 @@ export async function startScopedAuthorization(
if (attempt === undefined) return undefined;
const interactive = authorization as InteractiveAuthorizationDefinition<JsonValue>;
- const principal = resolveConnectionPrincipal(scope, interactive);
+ const principal = resolveScopedPrincipal(input);
const callbackUrl = resolveAuthorizationCallbackUrl({
authorization,
callbackUrl: attempt.hookUrl,
@@ -193,11 +199,18 @@ export async function startScopedAuthorization(
]);
}
-/**
- * Vercel Connect accepts local HTTP callback URLs only when their hostname is
- * literally `localhost`. Other authorization providers keep the framework's
- * original callback URL so their registered redirect URI remains unchanged.
- */
+function resolveScopedPrincipal(input: ScopedAuthorization, ctx?: AlsContext) {
+ return input.boundResponder === undefined
+ ? resolveConnectionPrincipal(input.scope, input.authorization, ctx)
+ : resolveConnectionPrincipalFromAuth(
+ input.scope,
+ input.authorization,
+ input.boundResponder,
+ ctx,
+ );
+}
+
+/** Normalizes callback URLs for providers with localhost requirements. */
export function resolveAuthorizationCallbackUrl(input: {
readonly authorization: Readonly<AuthorizationDefinition>;
readonly callbackUrl: string;
diff --git a/packages/eve/src/runtime/connections/types.ts b/packages/eve/src/runtime/connections/types.ts
index 33c1b40d2..535f19a1c 100644
--- a/packages/eve/src/runtime/connections/types.ts
+++ b/packages/eve/src/runtime/connections/types.ts
@@ -23,10 +23,15 @@ import type { ResolvedConnectionDefinition } from "#runtime/types.js";
* `expiresAt` is an optional absolute expiration in **milliseconds since
* the Unix epoch** ({@link Date.now}). Advisory: the runtime may refresh a
* cached token before the next call based on it, but is not required to.
+ *
+ * `providerSubject` is the stable subject of the provider account represented
+ * by this credential. It is scoped to the provider and must not be compared
+ * across providers without provider context.
*/
export interface TokenResult {
readonly token: string;
readonly expiresAt?: number;
+ readonly providerSubject?: string;
}
/**
diff --git a/packages/eve/src/runtime/resolve-tool.ts b/packages/eve/src/runtime/resolve-tool.ts
index 138bd5df3..cd5775299 100644
--- a/packages/eve/src/runtime/resolve-tool.ts
+++ b/packages/eve/src/runtime/resolve-tool.ts
@@ -1,6 +1,7 @@
import type { CompiledToolDefinition } from "#compiler/manifest.js";
import type { CompiledModuleMap } from "#compiler/module-map.js";
import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";
+import { normalizeApproval } from "#internal/authored-definition/approval.js";
import { registerDefinitionSource, stampDefinitionKey } from "#public/tool-result-narrowing.js";
import { isToolSchema, toInputSchema, toOutputSchema } from "#shared/tool-schema.js";
import { toErrorMessage } from "#shared/errors.js";
@@ -103,10 +104,10 @@ function extractOptionalHooks(
const optional: OptionalResolvedFields = {};
if (record.approval !== undefined) {
- optional.approval = expectFunction(
+ optional.approval = normalizeApproval(
record.approval,
- describe(definition, "to provide an approval function"),
- ) as ResolvedToolDefinition["approval"];
+ describe(definition, "to provide a valid approval definition"),
+ );
}
if (record.toModelOutput !== undefined) {