Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): connections - resolve auth and headers per caller (#299)

Andrew Barba7c532fe6974f
diff --git a/.changeset/tidy-pandas-connect.md b/.changeset/tidy-pandas-connect.md
new file mode 100644
index 000000000..db639739a
--- /dev/null
+++ b/.changeset/tidy-pandas-connect.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+MCP and OpenAPI connections can now resolve `auth` providers and headers from the active session context, enabling per-caller and per-tenant credentials.
diff --git a/docs/connections/mcp.mdx b/docs/connections/mcp.mdx
index f8a2d7a40..5b4624c32 100644
--- a/docs/connections/mcp.mdx
+++ b/docs/connections/mcp.mdx
@@ -48,8 +48,8 @@ Use `allow` for the smallest safe surface, especially on MCP servers that expose
MCP connections support the shared connection options:
-- `auth` for static tokens, Vercel Connect, or self-hosted interactive OAuth.
-- `headers` for API-key schemes or extra server configuration.
+- `auth` for static tokens, Vercel Connect, self-hosted interactive OAuth, or a per-caller provider resolver.
+- `headers` for static or per-caller API-key schemes and extra server configuration.
- `approval` for human-in-the-loop gates before connection tools run.
See [Connections](/docs/connections) for the shared auth, headers, and approval shapes.
diff --git a/docs/connections/openapi.mdx b/docs/connections/openapi.mdx
index 8516b15c7..2fbc3abed 100644
--- a/docs/connections/openapi.mdx
+++ b/docs/connections/openapi.mdx
@@ -55,8 +55,8 @@ Filters match `operationId`. If an operation does not declare one, use the deter
OpenAPI connections support the shared connection options:
-- `auth` for static tokens, Vercel Connect, or self-hosted interactive OAuth.
-- `headers` for API-key schemes or extra server configuration.
+- `auth` for static tokens, Vercel Connect, self-hosted interactive OAuth, or a per-caller provider resolver.
+- `headers` for static or per-caller API-key schemes and extra server configuration.
- `approval` for human-in-the-loop gates before generated operation tools run.
See [Connections](/docs/connections) for the shared auth, headers, and approval shapes.
diff --git a/docs/connections/overview.mdx b/docs/connections/overview.mdx
index 6fe6d1337..7552c06cc 100644
--- a/docs/connections/overview.mdx
+++ b/docs/connections/overview.mdx
@@ -57,6 +57,38 @@ export default defineMcpClientConnection({
});
```
+## Per-caller auth and headers
+
+When credentials or routing depend on the caller, make `auth` or `headers` a function. eve calls it inside the active turn and passes the same session context exposed to tools and hooks:
+
+```ts title="agent/connections/warehouse.ts"
+import { defineOpenAPIConnection } from "eve/connections";
+
+export default defineOpenAPIConnection({
+ spec: "https://warehouse.example.com/openapi.json",
+ description: "The caller's tenant-scoped warehouse.",
+ auth: (ctx) => ({
+ principalType: "user",
+ getToken: async () => ({
+ token: await tenantToken(ctx.session.auth.current),
+ }),
+ }),
+ headers: (ctx) => ({
+ "X-Tenant-Id": tenantId(ctx.session.auth.current),
+ }),
+});
+```
+
+An `auth` resolver returns the same provider object accepted by static `auth`, including a `connect(...)` provider for interactive OAuth. The resolver itself can be async. Header callbacks can return the whole map, as above, or resolve individual values:
+
+```ts
+headers: {
+ "X-Tenant-Id": (ctx) => tenantId(ctx.session.auth.current),
+}
+```
+
+Use `principalType: "user"` for per-user tokens so eve rejects unauthenticated callers and keys its step-local token cache by user. The resolver supplements route auth; it does not authenticate the inbound request. Static auth objects and header maps remain available when every caller shares the same configuration.
+
## Per-connection approval
To put every tool a connection serves behind a human, use the helpers from `eve/tools/approval`:
diff --git a/docs/guides/session-context.md b/docs/guides/session-context.md
index c3bad69ea..044c820d7 100644
--- a/docs/guides/session-context.md
+++ b/docs/guides/session-context.md
@@ -3,7 +3,7 @@ title: "Session Context"
description: "Runtime helpers: ctx.session, ctx.getSandbox, ctx.getSkill, and defineState."
---
-eve exposes runtime state through the `ctx` parameter passed to tool `execute`, hook handlers, and channel event handlers:
+eve exposes runtime state through the `ctx` parameter passed to tool `execute`, hook handlers, channel event handlers, and connection auth/header resolvers:
- `ctx.session`: session metadata, turn, auth, and parent lineage
- `ctx.getSandbox()`: live sandbox handle for the current agent
@@ -119,6 +119,7 @@ export const budget = defineState<BudgetState>("myapp.budget", () => ({
Safe places:
- inside `defineTool(...).execute(input, ctx)`
+- inside connection `auth: (ctx) => provider` and `headers: (ctx) => values` resolvers
- inside authored callbacks eve runs inside the runtime
- after asynchronous boundaries inside the same authored execution chain
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index e52853b75..b2e4cbff3 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -55,7 +55,7 @@ A few non-`define*` helpers round out the set: `disableTool` and `ExperimentalWo
## Runtime context (`ctx`)
-`ctx` is passed to your tool `execute`, hook handlers, and channel event handlers. It is live only while authored code is running, so reaching for it at module top level throws. See [Session context](../guides/session-context) for the full model.
+`ctx` is passed to your tool `execute`, hook handlers, channel event handlers, and connection auth/header resolvers. It is live only while authored code is running, so reaching for it at module top level throws. See [Session context](../guides/session-context) for the full model.
| Member | Use |
| --------------------------- | ---------------------------------------------------------------------------- |
diff --git a/packages/eve/src/internal/authored-definition/connection.test.ts b/packages/eve/src/internal/authored-definition/connection.test.ts
index 802edd1b3..b6e078543 100644
--- a/packages/eve/src/internal/authored-definition/connection.test.ts
+++ b/packages/eve/src/internal/authored-definition/connection.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vitest";
import { normalizeMcpClientConnectionDefinition } from "#internal/authored-definition/connection.js";
+import type {
+ ConnectionAuthDefinition,
+ ConnectionAuthProvider,
+} from "#runtime/connections/types.js";
const MSG = "Expected the connection export to match the public eve shape.";
@@ -16,6 +20,13 @@ function validInput(overrides: Record<string, unknown> = {}) {
};
}
+function authProvider(auth: ConnectionAuthDefinition | undefined): ConnectionAuthProvider {
+ if (auth === undefined || typeof auth === "function") {
+ throw new Error("Expected a static auth provider.");
+ }
+ return auth;
+}
+
describe("normalizeMcpClientConnectionDefinition", () => {
describe("happy path", () => {
it("accepts a valid definition with a getToken function", () => {
@@ -23,7 +34,7 @@ describe("normalizeMcpClientConnectionDefinition", () => {
expect(result.url).toBe("https://mcp.example.com/sse");
expect(result.description).toBe("A test connection.");
- expect(typeof result.auth?.getToken).toBe("function");
+ expect(typeof authProvider(result.auth).getToken).toBe("function");
});
it("preserves the author's getToken reference", () => {
@@ -33,7 +44,7 @@ describe("normalizeMcpClientConnectionDefinition", () => {
MSG,
);
- expect(result.auth?.getToken).toBe(getToken);
+ expect(authProvider(result.auth).getToken).toBe(getToken);
});
it('defaults getToken-only auth to principalType "app"', () => {
@@ -46,6 +57,18 @@ describe("normalizeMcpClientConnectionDefinition", () => {
expect(result.auth).toMatchObject({ getToken, principalType: "app" });
});
+ it("preserves a context-aware auth resolver without invoking it at build time", () => {
+ let calls = 0;
+ const auth = () => {
+ calls += 1;
+ return { getToken: async () => ({ token: "x" }) };
+ };
+ const result = normalizeMcpClientConnectionDefinition(validInput({ auth }), MSG);
+
+ expect(result.auth).toBe(auth);
+ expect(calls).toBe(0);
+ });
+
it("accepts the full three-method interactive-OAuth shape", () => {
const getToken = async () => ({ token: "cached" });
const startAuthorization = async () => ({
@@ -65,9 +88,9 @@ describe("normalizeMcpClientConnectionDefinition", () => {
MSG,
);
- expect(result.auth?.getToken).toBe(getToken);
- expect(result.auth?.startAuthorization).toBe(startAuthorization);
- expect(result.auth?.completeAuthorization).toBe(completeAuthorization);
+ expect(authProvider(result.auth).getToken).toBe(getToken);
+ expect(authProvider(result.auth).startAuthorization).toBe(startAuthorization);
+ expect(authProvider(result.auth).completeAuthorization).toBe(completeAuthorization);
});
it("accepts an http URL", () => {
diff --git a/packages/eve/src/internal/authored-definition/connection.ts b/packages/eve/src/internal/authored-definition/connection.ts
index 1c41c622c..059fe41f6 100644
--- a/packages/eve/src/internal/authored-definition/connection.ts
+++ b/packages/eve/src/internal/authored-definition/connection.ts
@@ -1,7 +1,7 @@
import type { McpClientConnectionDefinition } from "#public/definitions/connections/mcp.js";
import type { OpenAPIConnectionDefinition } from "#public/definitions/connections/openapi.js";
import type {
- AuthorizationDefinition,
+ ConnectionAuthDefinition,
HeadersDefinition,
ToolFilterDefinition,
} from "#runtime/connections/types.js";
@@ -219,14 +219,18 @@ function validateDescription(record: Record<string, unknown>, message: string):
function normalizeAuthorization(
record: Record<string, unknown>,
message: string,
-): AuthorizationDefinition | undefined {
+): ConnectionAuthDefinition | undefined {
if (record.auth === undefined) {
return undefined;
}
+ if (typeof record.auth === "function") {
+ return record.auth as ConnectionAuthDefinition;
+ }
+
const auth = expectObjectRecord(
record.auth,
- `${message} The "auth" field must be an object with a "getToken" method.`,
+ `${message} The "auth" field must be an object with a "getToken" method or a function.`,
);
expectOnlyKnownKeys(auth, KNOWN_AUTHORIZATION_KEYS, `${message} The "auth" field`);
@@ -242,7 +246,7 @@ function normalizeHeaders(
}
if (typeof record.headers === "function") {
- return record.headers as () => Record<string, string> | Promise<Record<string, string>>;
+ return record.headers as HeadersDefinition;
}
if (
diff --git a/packages/eve/src/internal/authored-definition/openapi-connection.test.ts b/packages/eve/src/internal/authored-definition/openapi-connection.test.ts
index ac2cc694a..b5ab29b42 100644
--- a/packages/eve/src/internal/authored-definition/openapi-connection.test.ts
+++ b/packages/eve/src/internal/authored-definition/openapi-connection.test.ts
@@ -45,6 +45,18 @@ describe("normalizeOpenApiConnectionDefinition", () => {
expect(result.auth).toMatchObject({ principalType: "app" });
});
+
+ it("preserves a context-aware auth resolver without invoking it at build time", () => {
+ let calls = 0;
+ const auth = () => {
+ calls += 1;
+ return { getToken: async () => ({ token: "x" }) };
+ };
+ const result = normalizeOpenApiConnectionDefinition(validInput({ auth }), MSG);
+
+ expect(result.auth).toBe(auth);
+ expect(calls).toBe(0);
+ });
});
describe("validation", () => {
diff --git a/packages/eve/src/public/connections/index.ts b/packages/eve/src/public/connections/index.ts
index 2d602d40a..9d02db0e8 100644
--- a/packages/eve/src/public/connections/index.ts
+++ b/packages/eve/src/public/connections/index.ts
@@ -6,6 +6,8 @@ export type {
AuthorizationCallback,
AuthorizationDefinition,
ConnectionAuthDefinition,
+ ConnectionAuthProvider,
+ ConnectionAuthResolver,
ConnectionPrincipal,
HeadersDefinition,
InteractiveAuthorizationDefinition,
diff --git a/packages/eve/src/public/definitions/connections/mcp.test.ts b/packages/eve/src/public/definitions/connections/mcp.test.ts
index f06a49cc3..a2f0f7a46 100644
--- a/packages/eve/src/public/definitions/connections/mcp.test.ts
+++ b/packages/eve/src/public/definitions/connections/mcp.test.ts
@@ -13,4 +13,17 @@ describe("defineMcpClientConnection", () => {
expect(definition.auth).toMatchObject({ getToken, principalType: "app" });
});
+
+ it("preserves context-aware auth resolvers for runtime resolution", () => {
+ const definition = defineMcpClientConnection({
+ auth: (ctx) => ({
+ getToken: async () => ({ token: ctx.session.id }),
+ }),
+ description: "test connection",
+ headers: (ctx) => ({ "X-Session": ctx.session.id }),
+ url: "https://mcp.example.com",
+ });
+
+ expect(typeof definition.auth).toBe("function");
+ });
});
diff --git a/packages/eve/src/public/definitions/connections/mcp.ts b/packages/eve/src/public/definitions/connections/mcp.ts
index db964bee2..78c701a54 100644
--- a/packages/eve/src/public/definitions/connections/mcp.ts
+++ b/packages/eve/src/public/definitions/connections/mcp.ts
@@ -45,6 +45,8 @@ export interface McpClientConnectionDefinition {
* - Three-method form: provide `startAuthorization` and
* `completeAuthorization` together to opt into
* interactive OAuth authorization.
+ * - Resolver form: pass `(ctx) => provider` to select either shape
+ * from the active caller's session context.
*
* Optional when `headers` is provided for non-Bearer auth schemes.
*/
@@ -65,7 +67,9 @@ export interface McpClientConnectionDefinition {
* Arbitrary HTTP headers sent with every request to the MCP server.
*
* Use for non-Bearer auth (e.g. API key headers) or server-level
- * configuration headers. Can be combined with `auth`.
+ * configuration headers. Can be combined with `auth`. The whole map
+ * or individual values may be callbacks that receive the active
+ * session context.
*/
headers?: HeadersDefinition;
/**
@@ -81,17 +85,15 @@ export interface McpClientConnectionDefinition {
/**
* Defines an MCP client connection.
*
- * Validates the {@link ConnectionAuthDefinition} shape at
- * definition time, in particular the "both-or-neither" constraint
- * for `startAuthorization` and `completeAuthorization`: providing
- * exactly one is a definition error. `getToken` alone is valid and
- * selects the non-interactive flow; providing both opts into
- * interactive OAuth authorization.
+ * Validates static auth providers at definition time, in particular the
+ * "both-or-neither" constraint for `startAuthorization` and
+ * `completeAuthorization`. Context-aware auth resolvers are validated when
+ * eve invokes them inside an active turn.
*/
export function defineMcpClientConnection(
definition: McpClientConnectionDefinition,
): McpClientConnectionDefinition {
- if (definition.auth !== undefined) {
+ if (definition.auth !== undefined && typeof definition.auth !== "function") {
definition.auth = normalizeAuthorizationSpec(definition.auth, "defineMcpClientConnection:");
}
stampDefinitionKey(definition, `connection:${definition.url}`);
diff --git a/packages/eve/src/public/definitions/connections/openapi.test.ts b/packages/eve/src/public/definitions/connections/openapi.test.ts
index 0d4ed54ca..a580ceadd 100644
--- a/packages/eve/src/public/definitions/connections/openapi.test.ts
+++ b/packages/eve/src/public/definitions/connections/openapi.test.ts
@@ -26,6 +26,20 @@ describe("defineOpenAPIConnection", () => {
expect(definition.auth).toMatchObject({ getToken, principalType: "app" });
});
+ it("preserves context-aware auth resolvers for runtime resolution", () => {
+ const definition = defineOpenAPIConnection({
+ auth: (ctx) => ({
+ getToken: async () => ({ token: ctx.session.id }),
+ }),
+ baseUrl: "https://api.example.com",
+ description: "test connection",
+ headers: { "X-User": (ctx) => ctx.session.auth.current?.principalId ?? "anonymous" },
+ spec: "https://api.example.com/openapi.json",
+ });
+
+ expect(typeof definition.auth).toBe("function");
+ });
+
it("accepts an inline spec object", () => {
const spec = { openapi: "3.0.0", paths: {} };
const definition = defineOpenAPIConnection({
diff --git a/packages/eve/src/public/definitions/connections/openapi.ts b/packages/eve/src/public/definitions/connections/openapi.ts
index 36f59faf9..4850429ca 100644
--- a/packages/eve/src/public/definitions/connections/openapi.ts
+++ b/packages/eve/src/public/definitions/connections/openapi.ts
@@ -68,6 +68,8 @@ export interface OpenAPIConnectionDefinition {
* omitted.
* - Three-method form: provide `startAuthorization` and
* `completeAuthorization` together to opt into interactive OAuth.
+ * - Resolver form: pass `(ctx) => provider` to select either shape
+ * from the active caller's session context.
*
* Optional when `headers` is provided for non-Bearer auth schemes.
*/
@@ -85,7 +87,8 @@ export interface OpenAPIConnectionDefinition {
* Arbitrary HTTP headers sent with every request to the API.
*
* Use for non-Bearer auth (e.g. API key headers) or configuration
- * headers. Can be combined with `auth`.
+ * headers. Can be combined with `auth`. The whole map or individual
+ * values may be callbacks that receive the active session context.
*/
headers?: HeadersDefinition;
/**
@@ -102,16 +105,15 @@ export interface OpenAPIConnectionDefinition {
/**
* Defines an OpenAPI connection.
*
- * Validates the auth shape at definition time, in particular the
+ * Validates static auth providers at definition time, in particular the
* "both-or-neither" constraint for `startAuthorization` and
- * `completeAuthorization`: providing exactly one is a definition error.
- * `getToken` alone is valid and selects the non-interactive flow;
- * providing both opts into interactive OAuth.
+ * `completeAuthorization`. Context-aware auth resolvers are validated when
+ * eve invokes them inside an active turn.
*/
export function defineOpenAPIConnection(
definition: OpenAPIConnectionDefinition,
): OpenAPIConnectionDefinition {
- if (definition.auth !== undefined) {
+ if (definition.auth !== undefined && typeof definition.auth !== "function") {
definition.auth = normalizeAuthorizationSpec(definition.auth, "defineOpenAPIConnection:");
}
const definitionKey =
diff --git a/packages/eve/src/runtime/connections/mcp-client.test.ts b/packages/eve/src/runtime/connections/mcp-client.test.ts
index ff3f17e67..0df8352f6 100644
--- a/packages/eve/src/runtime/connections/mcp-client.test.ts
+++ b/packages/eve/src/runtime/connections/mcp-client.test.ts
@@ -1,11 +1,12 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { contextStorage, ContextContainer } from "#context/container.js";
-import { AuthKey, type SessionAuthContext } from "#context/keys.js";
+import { AuthKey, SessionKey, type SessionAuthContext } from "#context/keys.js";
import {
isConnectionAuthorizationFailedError,
isConnectionAuthorizationRequiredError,
} from "#public/connections/errors.js";
+import type { SessionContext } from "#public/definitions/callback-context.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
import { ConnectionAuthorizationTokensKey } from "#runtime/connections/authorization-tokens.js";
import {
@@ -26,6 +27,11 @@ vi.mock("#compiled/@ai-sdk/mcp/index.js", () => ({
function ctxWithAuth(current: SessionAuthContext | null): ContextContainer {
const ctx = new ContextContainer();
ctx.set(AuthKey, current);
+ ctx.set(SessionKey, {
+ auth: { current, initiator: current },
+ sessionId: "session-1",
+ turn: { id: "turn-1", sequence: 0 },
+ });
return ctx;
}
@@ -457,22 +463,26 @@ describe("resolveHeaders", () => {
});
it("resolves function-valued headers", async () => {
- const headers = await resolveHeaders(
- makeConnection({
- authorization: undefined,
- headers: { "X-Key": () => "from-fn" },
- }),
+ const headers = await contextStorage.run(ctxWithAuth(userAuth("alice")), () =>
+ resolveHeaders(
+ makeConnection({
+ authorization: undefined,
+ headers: { "X-Key": () => "from-fn" },
+ }),
+ ),
);
expect(headers).toEqual({ "X-Key": "from-fn" });
});
it("resolves a function-form headers definition", async () => {
- const headers = await resolveHeaders(
- makeConnection({
- authorization: undefined,
- headers: () => ({ "X-Dynamic": "all-at-once" }),
- }),
+ const headers = await contextStorage.run(ctxWithAuth(userAuth("alice")), () =>
+ resolveHeaders(
+ makeConnection({
+ authorization: undefined,
+ headers: () => ({ "X-Dynamic": "all-at-once" }),
+ }),
+ ),
);
expect(headers).toEqual({ "X-Dynamic": "all-at-once" });
@@ -524,6 +534,63 @@ describe("resolveHeaders", () => {
});
describe("resolveHeaders with an active context (principal resolution + cache)", () => {
+ it("resolves auth from the current session caller", async () => {
+ const aliceContext = ctxWithAuth(userAuth("alice"));
+ const bobContext = ctxWithAuth(userAuth("bob"));
+ let resolverCalls = 0;
+ let resolvedSessionId: string | undefined;
+
+ const connection = makeConnection({
+ authorization: async (callbackContext) => {
+ resolverCalls += 1;
+ resolvedSessionId = callbackContext.session.id;
+ const callerId = callbackContext.session.auth.current?.principalId;
+ return {
+ getToken: async () => ({ token: `token-for-${callerId}` }),
+ principalType: "user",
+ };
+ },
+ connectionName: "linear",
+ });
+
+ const aliceHeaders = await contextStorage.run(aliceContext, async () => {
+ const first = await resolveHeaders(connection);
+ await resolveHeaders(connection);
+ return first;
+ });
+ const bobHeaders = await contextStorage.run(bobContext, () => resolveHeaders(connection));
+
+ expect(aliceHeaders).toEqual({ Authorization: "Bearer token-for-alice" });
+ expect(bobHeaders).toEqual({ Authorization: "Bearer token-for-bob" });
+ expect(resolverCalls).toBe(2);
+ expect(resolvedSessionId).toBe("session-1");
+ });
+
+ it("passes the current session context to whole-map and per-header callbacks", async () => {
+ const ctx = ctxWithAuth(userAuth("alice"));
+ const wholeMap = makeConnection({
+ authorization: undefined,
+ headers: async (callbackContext: SessionContext) => ({
+ "X-Session": callbackContext.session.id,
+ "X-User": callbackContext.session.auth.current?.principalId ?? "anonymous",
+ }),
+ });
+ const perHeader = makeConnection({
+ authorization: undefined,
+ headers: {
+ "X-Turn": (callbackContext) => callbackContext.session.turn.id,
+ },
+ });
+
+ await expect(contextStorage.run(ctx, () => resolveHeaders(wholeMap))).resolves.toEqual({
+ "X-Session": "session-1",
+ "X-User": "alice",
+ });
+ await expect(contextStorage.run(ctx, () => resolveHeaders(perHeader))).resolves.toEqual({
+ "X-Turn": "turn-1",
+ });
+ });
+
it("projects the session's user auth into a user principal and passes it to getToken", async () => {
const ctx = ctxWithAuth(userAuth("alice"));
diff --git a/packages/eve/src/runtime/connections/mcp-client.ts b/packages/eve/src/runtime/connections/mcp-client.ts
index 27db60b88..cb046f456 100644
--- a/packages/eve/src/runtime/connections/mcp-client.ts
+++ b/packages/eve/src/runtime/connections/mcp-client.ts
@@ -1,11 +1,15 @@
import { createMCPClient, type MCPClient } from "#compiled/@ai-sdk/mcp/index.js";
import type { ToolSet } from "ai";
+import { buildCallbackContext } from "#context/build-callback-context.js";
import { ConnectionAuthorizationRequiredError } from "#public/connections/errors.js";
+import type { SessionContext } from "#public/definitions/callback-context.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
import { evictScopedToken, resolveScopedToken } from "#runtime/connections/scoped-authorization.js";
+import { resolveConnectionAuthorization } from "#runtime/connections/resolve-authorization.js";
import { isObject } from "#shared/guards.js";
import type {
+ AuthorizationDefinition,
ConnectionClient,
ConnectionToolMetadata,
HeadersDefinition,
@@ -227,7 +231,7 @@ export class McpConnectionClient implements ConnectionClient {
* the connection declares no authorization.
*/
async #evictCachedToken(): Promise<void> {
- const authorization = this.#connection.authorization;
+ const authorization = await resolveConnectionAuthorization(this.#connection);
if (authorization === undefined) return;
await evictScopedToken({
authorization,
@@ -342,9 +346,9 @@ export function passesToolFilter(
* Merges `authorization` (Bearer token) and `headers` into one
* flat `Record<string, string>` for the transport layer.
*
- * Resolves the {@link ConnectionPrincipal} from the active session
- * and invokes
- * `authorization.getToken({ principal })` to produce the bearer.
+ * Resolves dynamic `auth` and `headers` callbacks with the active
+ * {@link SessionContext}, then resolves the {@link ConnectionPrincipal}
+ * and invokes `authorization.getToken({ principal })` to produce the bearer.
* `getToken` may throw {@link ConnectionAuthorizationRequiredError};
* callers (`connection_search`, wrapped connection tools) catch it
* and it propagates as-is from here.
@@ -353,16 +357,23 @@ export async function resolveHeaders(
connection: ResolvedConnectionDefinition,
): Promise<Record<string, string>> {
const merged: Record<string, string> = {};
+ let callbackContext: SessionContext | undefined;
+ const getCallbackContext = (): SessionContext => (callbackContext ??= buildCallbackContext());
- if (connection.authorization !== undefined) {
- const result = await resolveToken(connection);
+ const authorization = await resolveConnectionAuthorization(
+ connection,
+ typeof connection.authorization === "function" ? getCallbackContext() : undefined,
+ );
+
+ if (authorization !== undefined) {
+ const result = await resolveToken(connection, authorization);
merged.Authorization = `Bearer ${result.token}`;
}
if (connection.headers !== undefined) {
- const resolved = await resolveHeadersDefinition(connection.headers);
+ const resolved = await resolveHeadersDefinition(connection.headers, getCallbackContext);
for (const [key, value] of Object.entries(resolved)) {
- if (connection.authorization !== undefined && key.toLowerCase() === "authorization") {
+ if (authorization !== undefined && key.toLowerCase() === "authorization") {
throw new Error(
`Connection "${connection.connectionName}" headers must not include an "Authorization" key when "authorization" is also provided.`,
);
@@ -379,13 +390,12 @@ export async function resolveHeaders(
* keyed by the connection name. See
* {@link resolveScopedToken} for the cache and principal semantics.
*/
-async function resolveToken(connection: ResolvedConnectionDefinition) {
- if (connection.authorization === undefined) {
- throw new Error(`Connection "${connection.connectionName}" does not define authorization.`);
- }
-
+async function resolveToken(
+ connection: ResolvedConnectionDefinition,
+ authorization: Readonly<AuthorizationDefinition>,
+) {
return await resolveScopedToken({
- authorization: connection.authorization,
+ authorization,
connection: { url: connection.url },
scope: connection.connectionName,
});
@@ -393,24 +403,28 @@ async function resolveToken(connection: ResolvedConnectionDefinition) {
async function resolveHeadersDefinition(
headers: Readonly<HeadersDefinition>,
+ getContext: () => SessionContext,
): Promise<Record<string, string>> {
if (typeof headers === "function") {
- return await headers();
+ return { ...(await headers(getContext())) };
}
const result: Record<string, string> = {};
const entries = Object.entries(headers);
for (const [key, value] of entries) {
- result[key] = await resolveHeaderValue(value);
+ result[key] = await resolveHeaderValue(value, getContext);
}
return result;
}
-async function resolveHeaderValue(value: HeaderValue): Promise<string> {
+async function resolveHeaderValue(
+ value: HeaderValue,
+ getContext: () => SessionContext,
+): Promise<string> {
if (typeof value === "function") {
- return await value();
+ return await value(getContext());
}
return await value;
}
diff --git a/packages/eve/src/runtime/connections/openapi-client.test.ts b/packages/eve/src/runtime/connections/openapi-client.test.ts
index 1750934cb..9d6bf5c47 100644
--- a/packages/eve/src/runtime/connections/openapi-client.test.ts
+++ b/packages/eve/src/runtime/connections/openapi-client.test.ts
@@ -1,5 +1,8 @@
import { afterEach, describe, expect, it, vi } from "vitest";
+import { contextStorage, ContextContainer } from "#context/container.js";
+import { AuthKey, SessionKey, type SessionAuthContext } from "#context/keys.js";
+import type { SessionContext } from "#public/definitions/callback-context.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
import { OpenApiConnectionClient } from "#runtime/connections/openapi-client.js";
@@ -268,6 +271,47 @@ describe("OpenApiConnectionClient", () => {
expect((init.headers as Record<string, string>).Authorization).toBe("Bearer secret");
});
+ it("resolves auth and headers from the active caller", async () => {
+ const fetchMock = vi.fn(
+ async (_url: URL, _init: RequestInit) => new Response(null, { status: 200 }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const current: SessionAuthContext = {
+ attributes: { tenant: "acme" },
+ authenticator: "oidc",
+ principalId: "alice",
+ principalType: "user",
+ };
+ const ctx = new ContextContainer();
+ ctx.set(AuthKey, current);
+ ctx.set(SessionKey, {
+ auth: { current, initiator: current },
+ sessionId: "session-1",
+ turn: { id: "turn-1", sequence: 0 },
+ });
+ const client = new OpenApiConnectionClient(
+ makeConnection({
+ authorization: (callbackContext: SessionContext) => ({
+ getToken: async () => ({
+ token: `token-for-${callbackContext.session.auth.current?.principalId}`,
+ }),
+ principalType: "user",
+ }),
+ headers: (callbackContext: SessionContext) => ({
+ "X-Tenant": String(callbackContext.session.auth.current?.attributes.tenant),
+ }),
+ }),
+ );
+
+ await contextStorage.run(ctx, () => client.executeTool("getProject", { id: "prj_1" }));
+
+ const [, init] = fetchMock.mock.calls[0]!;
+ expect(init.headers).toMatchObject({
+ Authorization: "Bearer token-for-alice",
+ "X-Tenant": "acme",
+ });
+ });
+
it("serializes the request body on execute", async () => {
const fetchMock = vi.fn(
async (_url: URL, _init: RequestInit) => new Response(null, { status: 201 }),
diff --git a/packages/eve/src/runtime/connections/resolve-authorization.ts b/packages/eve/src/runtime/connections/resolve-authorization.ts
new file mode 100644
index 000000000..02839d1cb
--- /dev/null
+++ b/packages/eve/src/runtime/connections/resolve-authorization.ts
@@ -0,0 +1,66 @@
+import { buildCallbackContext } from "#context/build-callback-context.js";
+import { type AlsContext, ContextContainer, contextStorage } from "#context/container.js";
+import { ContextKey } from "#context/key.js";
+import type { SessionContext } from "#public/definitions/callback-context.js";
+import type { ResolvedConnectionDefinition } from "#runtime/types.js";
+import type { AuthorizationDefinition } from "#runtime/connections/types.js";
+import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
+
+type ResolvedAuthorization = Readonly<AuthorizationDefinition> | undefined;
+type AuthorizationResolverCache = Map<ResolvedConnectionDefinition, Promise<ResolvedAuthorization>>;
+
+const ConnectionAuthorizationResolversKey = new ContextKey<AuthorizationResolverCache>(
+ "eve.connectionAuthorizationResolvers",
+);
+
+/**
+ * Resolves and validates the auth provider for the active connection call.
+ * Dynamic providers are cached for the execution step so token resolution,
+ * interactive OAuth, and eviction all use the same provider instance.
+ */
+export async function resolveConnectionAuthorization(
+ connection: ResolvedConnectionDefinition,
+ ctx?: SessionContext,
+): Promise<ResolvedAuthorization> {
+ const authorization = connection.authorization;
+ if (authorization === undefined || typeof authorization !== "function") {
+ return authorization;
+ }
+
+ const activeContext = contextStorage.getStore();
+ if (activeContext === undefined) {
+ return await resolveDynamicAuthorization(connection, ctx);
+ }
+
+ const cache = getResolverCache(activeContext);
+ let pending = cache.get(connection);
+ if (pending === undefined) {
+ pending = resolveDynamicAuthorization(connection, ctx);
+ cache.set(connection, pending);
+ }
+ return await pending;
+}
+
+async function resolveDynamicAuthorization(
+ connection: ResolvedConnectionDefinition,
+ ctx?: SessionContext,
+): Promise<ResolvedAuthorization> {
+ const authorization = connection.authorization;
+ if (typeof authorization !== "function") {
+ return authorization;
+ }
+ const provider = await authorization(ctx ?? buildCallbackContext());
+ return normalizeAuthorizationSpec(
+ provider,
+ `Connection "${connection.connectionName}" auth resolver:`,
+ );
+}
+
+function getResolverCache(ctx: AlsContext): AuthorizationResolverCache {
+ const existing = ctx.get(ConnectionAuthorizationResolversKey);
+ if (existing !== undefined) return existing;
+
+ const cache: AuthorizationResolverCache = new Map();
+ (ctx as ContextContainer).setVirtualContext(ConnectionAuthorizationResolversKey, cache);
+ return cache;
+}
diff --git a/packages/eve/src/runtime/connections/types.ts b/packages/eve/src/runtime/connections/types.ts
index faef6f9f0..c634abadc 100644
--- a/packages/eve/src/runtime/connections/types.ts
+++ b/packages/eve/src/runtime/connections/types.ts
@@ -9,6 +9,7 @@
import type { ToolSet } from "ai";
import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";
+import type { SessionContext } from "#public/definitions/callback-context.js";
import type { NeedsApprovalContext } from "#public/definitions/tool.js";
import type { JsonValue } from "#public/types/json.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
@@ -39,19 +40,26 @@ export interface TokenResult {
*/
export type ConnectionProtocol = "mcp" | "openapi";
-/** A single header value, supporting static strings and dynamic resolution. */
-export type HeaderValue = string | Promise<string> | (() => string | Promise<string>);
+/** A single header value, supporting static strings and per-caller resolution. */
+export type HeaderValue =
+ | string
+ | Promise<string>
+ | ((ctx: SessionContext) => string | Promise<string>);
/**
* Arbitrary HTTP headers sent with every request to a connection server.
*
* Static form: key-value pairs where each value may be a string, Promise,
- * or function. Function form: a callback returning the full headers map,
- * useful when multiple headers must be resolved together.
+ * or callback. Function form: a callback returning the full headers map,
+ * useful when multiple headers must be resolved together. Header callbacks
+ * receive the active {@link SessionContext}, so credentials and routing
+ * metadata can be selected from the current caller.
*/
export type HeadersDefinition =
| Readonly<Record<string, HeaderValue>>
- | (() => Record<string, string> | Promise<Record<string, string>>);
+ | ((
+ ctx: SessionContext,
+ ) => Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>);
/**
* Client-side tool filter applied after `listTools()`.
@@ -154,21 +162,38 @@ export type AuthorizationDefinition<Resume extends JsonValue = JsonValue> =
| InteractiveAuthorizationDefinition<Resume>;
/**
- * Protocol-agnostic `auth` shape accepted by every connection
- * `define*` factory (`defineMcpClientConnection`,
- * `defineOpenAPIConnection`, and so on).
+ * Auth provider returned directly from or resolved by a connection's `auth`
+ * field.
*
* Identical to {@link AuthorizationDefinition} except the
* non-interactive form may omit `principalType`; normalization
* defaults it to `"app"`. The resolved token is sent as
* `Authorization: Bearer <token>`.
*/
-export type ConnectionAuthDefinition =
+export type ConnectionAuthProvider =
| (Omit<NonInteractiveAuthorizationDefinition, "principalType"> & {
readonly principalType?: NonInteractiveAuthorizationDefinition["principalType"];
})
| AuthorizationDefinition;
+/**
+ * Resolves a connection auth provider from the active turn.
+ *
+ * Use this when the provider, connector, or credential source depends on
+ * `ctx.session`, such as selecting a tenant-specific Vercel Connect client.
+ * The returned provider is validated and normalized before use.
+ */
+export type ConnectionAuthResolver = (
+ ctx: SessionContext,
+) => ConnectionAuthProvider | Promise<ConnectionAuthProvider>;
+
+/**
+ * Protocol-agnostic `auth` shape accepted by every connection `define*`
+ * factory. Pass a provider directly for static configuration, or a resolver
+ * to select the provider from the current caller's session context.
+ */
+export type ConnectionAuthDefinition = ConnectionAuthProvider | ConnectionAuthResolver;
+
/**
* Fields shared by every {@link AuthorizationDefinition} shape.
*/
diff --git a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
index 7db90493a..ebbba343f 100644
--- a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
+++ b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
@@ -16,6 +16,7 @@ import type { JsonValue } from "#public/types/json.js";
import type { JsonObject } from "#shared/json.js";
import { writeCachedToken } from "#runtime/connections/authorization-tokens.js";
import { principalKey, resolveConnectionPrincipal } from "#runtime/connections/principal.js";
+import { resolveConnectionAuthorization } from "#runtime/connections/resolve-authorization.js";
import { stampChallengeDisplayName } from "#runtime/connections/scoped-authorization.js";
import {
type ConnectionRegistry,
@@ -115,14 +116,15 @@ function scoreMatch(queryTokens: string[], tool: ConnectionToolMetadata): number
return score;
}
-function resolveInteractiveAuth(
+async function resolveInteractiveAuth(
registry: ConnectionRegistry,
connectionName: string,
-): InteractiveAuthorizationDefinition | undefined {
+): Promise<InteractiveAuthorizationDefinition | undefined> {
const conn = registry.getConnections().find((c) => c.connectionName === connectionName);
- if (!conn?.authorization) return undefined;
- if (!supportsInteractiveAuthorization(conn.authorization)) return undefined;
- return conn.authorization as unknown as InteractiveAuthorizationDefinition;
+ if (conn === undefined) return undefined;
+ const authorization = await resolveConnectionAuthorization(conn);
+ if (!supportsInteractiveAuthorization(authorization)) return undefined;
+ return authorization as InteractiveAuthorizationDefinition;
}
/**
@@ -140,7 +142,7 @@ async function completePendingAuthorizations(registry: ConnectionRegistry): Prom
for (const conn of registry.getConnections()) {
const result = getAuthorizationResult(conn.connectionName);
if (!result) continue;
- const auth = resolveInteractiveAuth(registry, conn.connectionName);
+ const auth = await resolveInteractiveAuth(registry, conn.connectionName);
if (!auth) continue;
const principal = resolveConnectionPrincipal(conn.connectionName, auth);
const token = await (
@@ -204,7 +206,7 @@ async function executeConnectionSearch(
continue;
}
- const auth = resolveInteractiveAuth(registry, conn.connectionName);
+ const auth = await resolveInteractiveAuth(registry, conn.connectionName);
if (auth) {
const hookUrl = getHookUrl(conn.connectionName);
if (hookUrl) {
@@ -428,10 +430,9 @@ export function createConnectionSearchEvents(): DynamicToolEvents {
async execute(input: Record<string, unknown>) {
const reg = loadContext().get(ConnectionRegistryKey)!;
const conn = reg.getConnections().find((c) => c.connectionName === connectionName);
- const interactiveAuth: InteractiveAuthorizationDefinition<JsonValue> | undefined =
- conn?.authorization && supportsInteractiveAuthorization(conn.authorization)
- ? (conn.authorization as InteractiveAuthorizationDefinition<JsonValue>)
- : undefined;
+ const interactiveAuth = (await resolveInteractiveAuth(reg, connectionName)) as
+ | InteractiveAuthorizationDefinition<JsonValue>
+ | undefined;
let justCompletedAuth = false;
if (interactiveAuth) {
diff --git a/packages/eve/src/runtime/resolve-connection.test.ts b/packages/eve/src/runtime/resolve-connection.test.ts
new file mode 100644
index 000000000..d7cebe27f
--- /dev/null
+++ b/packages/eve/src/runtime/resolve-connection.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ ROOT_COMPILED_AGENT_NODE_ID,
+ type CompiledConnectionDefinition,
+} from "#compiler/manifest.js";
+import type { CompiledModuleMap } from "#compiler/module-map.js";
+import { resolveConnectionDefinition } from "#runtime/resolve-connection.js";
+import type { ConnectionAuthResolver, HeadersDefinition } from "#runtime/connections/types.js";
+
+describe("resolveConnectionDefinition", () => {
+ it("preserves context-aware auth and header callbacks for request-time resolution", async () => {
+ const auth: ConnectionAuthResolver = (ctx) => ({
+ getToken: async () => ({ token: ctx.session.id }),
+ });
+ const headers: HeadersDefinition = (ctx) => ({ "X-Session": ctx.session.id });
+ const definition: CompiledConnectionDefinition = {
+ connectionName: "warehouse",
+ description: "Tenant warehouse",
+ logicalPath: "connections/warehouse.ts",
+ protocol: "mcp",
+ sourceId: "connections/warehouse",
+ sourceKind: "module",
+ url: "https://warehouse.example.com/mcp",
+ };
+ const moduleMap: CompiledModuleMap = {
+ nodes: {
+ [ROOT_COMPILED_AGENT_NODE_ID]: {
+ modules: {
+ [definition.sourceId]: {
+ default: {
+ auth,
+ description: definition.description,
+ headers,
+ url: definition.url,
+ },
+ },
+ },
+ },
+ },
+ };
+
+ const resolved = await resolveConnectionDefinition(definition, moduleMap, undefined);
+
+ expect(resolved.authorization).toBe(auth);
+ expect(resolved.headers).toBe(headers);
+ });
+});
diff --git a/packages/eve/src/runtime/resolve-connection.ts b/packages/eve/src/runtime/resolve-connection.ts
index 55099b55c..bb43b2631 100644
--- a/packages/eve/src/runtime/resolve-connection.ts
+++ b/packages/eve/src/runtime/resolve-connection.ts
@@ -3,7 +3,11 @@ import type { CompiledModuleMap } from "#compiler/module-map.js";
import { expectObjectRecord } from "#internal/authored-module.js";
import { registerDefinitionSource, stampDefinitionKey } from "#public/tool-result-narrowing.js";
import { toErrorMessage } from "#shared/errors.js";
-import type { HeadersDefinition, ToolFilterDefinition } from "#runtime/connections/types.js";
+import type {
+ ConnectionAuthResolver,
+ HeadersDefinition,
+ ToolFilterDefinition,
+} from "#runtime/connections/types.js";
import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
import { loadResolvedModuleExport, ResolveAgentError } from "#runtime/resolve-helpers.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
@@ -84,16 +88,20 @@ export async function resolveConnectionDefinition(
};
if (hasAuth) {
- try {
- result.authorization = normalizeAuthorizationSpec(
- resolvedRecord.auth,
- `Connection "${definition.connectionName}" at "${definition.logicalPath}":`,
- );
- } catch (error) {
- throw new ResolveAgentError(toErrorMessage(error), {
- logicalPath: definition.logicalPath,
- sourceId: definition.sourceId,
- });
+ if (typeof resolvedRecord.auth === "function") {
+ result.authorization = resolvedRecord.auth as ConnectionAuthResolver;
+ } else {
+ try {
+ result.authorization = normalizeAuthorizationSpec(
+ resolvedRecord.auth,
+ `Connection "${definition.connectionName}" at "${definition.logicalPath}":`,
+ );
+ } catch (error) {
+ throw new ResolveAgentError(toErrorMessage(error), {
+ logicalPath: definition.logicalPath,
+ sourceId: definition.sourceId,
+ });
+ }
}
}
diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.ts
index 9f4de01b6..c171750d0 100644
--- a/packages/eve/src/runtime/types.ts
+++ b/packages/eve/src/runtime/types.ts
@@ -11,6 +11,7 @@ import type { StreamEventHook } from "#public/definitions/hook.js";
import type { NeedsApprovalContext, ToolModelOutput } from "#public/definitions/tool.js";
import type {
AuthorizationDefinition,
+ ConnectionAuthResolver,
ConnectionProtocol,
HeadersDefinition,
ToolFilterDefinition,
@@ -92,7 +93,7 @@ export type ResolvedSchedule = Readonly<
*/
export interface ResolvedConnectionDefinition extends ResolvedModuleSourceRef {
readonly approval?: (ctx: NeedsApprovalContext) => boolean;
- readonly authorization?: Readonly<AuthorizationDefinition>;
+ readonly authorization?: Readonly<AuthorizationDefinition> | ConnectionAuthResolver;
readonly connectionName: string;
readonly description: string;
readonly headers?: Readonly<HeadersDefinition>;