@keycardai/eve plugs into three eve primitives instead of wrapping the framework. keycardAuth() goes in a channel’s ordered auth array and verifies the caller’s Zone-issued bearer. Keycard.onBehalfOf(), Keycard.asSelf(), and Keycard.impersonate() are connection auth definitions: eve calls them at the tool-call boundary and attaches the token they return. Keycard.interactive() is a defineInteractiveAuthorization definition that runs the Zone’s browser flow and lets eve park the turn until the user consents.
The token for a connection comes from the Zone, minted for the connection’s Resource under the identity of the turn: the caller keycardAuth() verified, the agent’s own Application, or a mapped User. There is no middleware to install and no tool wrapper; eve keeps credentials out of the model’s view by construction, since auth never appears in a tool’s input schema.
When to use
Section titled “When to use”- eve agents whose connections call MCP servers or APIs for the person in the chat
- Scheduled or subagent turns that act as the agent’s own Application
- Connections that need the user to sign in to the Zone before they work, with the turn parked in the meantime
- Channels that should accept a Keycard bearer alongside eve’s other auth entries
Installation
Section titled “Installation”pnpm add @keycardai/eveKey exports
Section titled “Key exports”@keycardai/eve
| Export | Description |
|---|---|
keycardAuth |
Channel auth entry. Verifies a Zone bearer, projects its claims onto SessionAuthContext, and retains the token for a later exchange |
Keycard |
onBehalfOf(), asSelf(), impersonate() connection auth factories, and interactive() |
keycardCallbackRoute |
The stable callback route for sign-in as the agent’s Application |
requireToolScopes, missingToolScopes |
Check the inbound token’s scopes inside one tool body |
requireAuthOnUnauthorized |
Maps a 401 from a downstream call to ctx.requireAuth, so eve evicts the bearer and re-challenges |
subjectTokenExpired, decodeClaims |
The decode-only expiry check the package uses, exported for hosts |
memorySubjectTokenStore, memoryAuthorizedTokenStore |
In-process stores for retained subject tokens and interactive grants |
GrantStore, AuthorizedGrant |
The interface a durable grant store implements |
FailureReason, AuthorizationRequiredError, AuthorizationFailedError, RouteRejectedError |
Error types and reason codes |
@keycardai/eve/testing
| Export | Description |
|---|---|
fakeZoneClient |
Records every exchange, impersonation, and client-credentials call; can fail one Resource or every call |
userPrincipal, validJwt |
Build a connection principal and a signed-looking JWT for tests |
Quickstart
Section titled “Quickstart”Verify the caller on the channel, then give a connection a token exchanged for that caller:
import { eveChannel } from "eve/channels/eve";import { localDev } from "eve/channels/auth";import { keycardAuth } from "@keycardai/eve";
export default eveChannel({ auth: [ keycardAuth({ zoneUrl: process.env.KEYCARD_ISSUER!, audience: "https://<your-agent-resource>", }), localDev(), ],});import { defineMcpClientConnection } from "eve/connections";import { Keycard } from "@keycardai/eve";
export default defineMcpClientConnection({ url: "https://calendar.example.com/mcp", description: "The signed-in user's calendar.", auth: Keycard.onBehalfOf({ zoneUrl: process.env.KEYCARD_ISSUER!, resource: "https://calendar.example.com", requestScopes: ["calendar.read"], clientId: process.env.KEYCARD_CLIENT_ID!, clientSecret: process.env.KEYCARD_CLIENT_SECRET!, }),});keycardAuth() follows eve’s ordered walk. No bearer, or one this Zone did not issue, returns null so the next entry gets a turn. A bearer this Zone issued that does not verify, has expired, or names another audience throws a 401 and ends the walk: a broken Keycard credential is a rejection, not an invitation to fall through to something weaker. A verified bearer becomes { principalId, principalType, attributes, issuer, subject } on ctx.session.auth.current.
The retained subject token stays out of durable state by default: it lives in a process-local store keyed by the principal, so it never reaches the model, the session record, or the event stream. Pass retainSubjectToken: "attributes" when connections run in a different process from the request that authenticated the caller, which accepts a bearer in eve’s session attributes in exchange for surviving restarts, or "none" when connections only ever run asSelf or impersonate.
clientId / clientSecret is shorthand for a client-secret credential. applicationCredential takes any ApplicationCredential, including assertion-based workload credentials. Setting both is a configuration error. Every factory builds one warm Zone client and reuses it.
Identity modes
Section titled “Identity modes”| Factory | Scope | Grant |
|---|---|---|
Keycard.onBehalfOf() |
User | RFC 8693 exchange of the subject token keycardAuth() verified for the turn’s principal |
Keycard.asSelf() |
App | Client credentials under the agent’s own Application; works on schedules and subagent turns |
Keycard.impersonate({ userIdentifier }) |
App with a fixed identifier, User with a function of the principal | Substitute-user exchange for a User the agent holds no token for |
The scope decides how eve caches the token: once per connection for app-scoped definitions, once per connection principal for user-scoped ones. Non-interactive definitions declare it as principalType: "app" | "user".
Nothing falls back to the agent’s authority. A user-scoped connection with no user principal fails with principal_required, a turn whose subject token was never retained in this process with subject_token_unavailable, and an expired subject token with subject_token_expired. The last is the sign-in signal, decided by a decode-only expiry check, so a dead token never costs an exchange round trip.
A grant revoked while a tool is in flight surfaces as a 401 inside execute. Map it with requireAuthOnUnauthorized(res, ctx, calendarAuth) so eve evicts the rejected bearer and re-challenges instead of handing the model a dead-token error.
Scopes a single tool requires
Section titled “Scopes a single tool requires”keycardAuth({ requiredScopes }) gates the whole channel. For a scope only one tool needs, check inside the tool body:
import { requireToolScopes } from "@keycardai/eve";import { defineTool } from "eve/tools";import { z } from "zod";
export default defineTool({ description: "Delete an invoice", inputSchema: z.object({ id: z.string() }), async execute({ id }, ctx) { requireToolScopes(ctx, ["invoices:delete"]); return deleteInvoice(id); },});It reads the scope attribute keycardAuth() placed on the current principal, only from a Keycard principal, and throws InsufficientScopeError from @keycardai/oauth, which eve hands to the model as a failed tool call naming the missing scopes.
Sign-in and consent pauses
Section titled “Sign-in and consent pauses”Keycard.interactive() is for a connection the user must authorize in a browser first. It implements eve’s three-method interactive authorization over the Zone’s web flow:
import { defineMcpClientConnection } from "eve/connections";import { Keycard } from "@keycardai/eve";
export default defineMcpClientConnection({ url: "https://docs.example.com/mcp", description: "Documents the user has authorized.", auth: Keycard.interactive({ zoneUrl: process.env.KEYCARD_ISSUER!, resource: "https://docs.example.com", requestScopes: ["documents.read"], connectionName: "Docs", }),});getTokenlooks up the principal’s stored grants and returns the access token of one that covers this connection’sresourceandrequestScopes, refreshing it first within 60 seconds of expiry when it holds a refresh token. With no usable grant it throwsConnectionAuthorizationRequiredError, so eve emitsauthorization.required, runsstartAuthorizationin a durable step, and parks the turn.startAuthorizationbegins the Zone’s authorization flow against eve’s minted callback URL and returns the challenge URL plus thestate, PKCE verifier, and client id as resume state.completeAuthorizationredeems eve’s callback params and stores the resulting grant: access token and expiry, refresh token, client id, and the Resources and scopes granted.
Resume without authorization cannot yield a credential: getToken reads a store only completeAuthorization writes, so a denied, forged, or failed callback writes nothing and the turn parks again. User denial is reported with reason: "access_denied" and retryable: false, so eve stops re-prompting.
Two ways to run the flow:
- Without
clientId, a public, PKCE-bound client is registered per attempt (RFC 7591), because eve mints a fresh callback URL per attempt and RFC 9700 requires an exactredirect_urimatch. Per-attempt clients accumulate in the Zone, and a durable grant on this path can be refreshed by anyone who can read the store. - With
clientIdandclientSecret, users sign in as the agent’s own Application through one stable callback this package serves. MountkeycardCallbackRoute()from a channel file (default path/keycard/callback), add<origin>/keycard/callbackto the Application’s redirect URIs, and use a password credential of that Application as the client id and secret. Refresh then runs as that confidential client.
expectedSubject binds the sign-in to the User who asked: a function from eve’s ConnectionPrincipal to the sub of the Zone User that principal must sign in as. The package checks it before the link, after the sign-in through the Zone’s UserInfo endpoint, and on every use, failing closed with identity_mismatch or identity_unverifiable. Pair it with prompt: "login" so the browser re-authenticates instead of reusing a session that belongs to someone else. Matching needs the Zone’s Identity Provider configured with a User Identifier Claim your function returns.
The default grant store is process-local, so a restarted agent parks once more per user. Pass tokens a GrantStore (list, put, remove, all async) to keep grants across processes. That puts refresh tokens at rest in your backend; the package never writes a grant into eve’s session attributes for the same reason.
Every connection above is already an MCP client connection, and a Unified Access Gateway is one more: point defineMcpClientConnection at the gateway’s MCP Access URL with the same auth factory. The token the factory exchanges for that Resource carries the target claim the gateway routes on. See Autonomous Agent Access.
Testing
Section titled “Testing”import { fakeZoneClient, userPrincipal, validJwt } from "@keycardai/eve/testing";import { Keycard, memorySubjectTokenStore } from "@keycardai/eve";
const client = fakeZoneClient({ failResources: { "https://calendar.example.com": new Error("exchange refused") },});const subjectTokens = memorySubjectTokenStore();subjectTokens.set("https://<zone-id>.keycard.cloud|user-1", validJwt(3600));
const auth = Keycard.onBehalfOf({ resource: "https://calendar.example.com", client, subjectTokens,});An injected client supersedes zoneUrl, so a test needs no Zone. keycardAuth() takes a verify seam in place of the JWKS-backed verifier, and Keycard.interactive() takes a flow seam (begin, complete, register, refresh, userinfo) in place of the web-flow calls. Combinations that cannot work in production are rejected at construction.
Limitations
Section titled “Limitations”Keycard.interactive()authenticates code redemption and refresh with a client secret only;applicationCredentialis rejected there at definition time.- On-behalf-of across processes needs
retainSubjectToken: "attributes", which puts the caller’s bearer in eve’s session attributes. The default fails closed withsubject_token_unavailableon a replica that never saw the token. - A durable
GrantStoreholds refresh tokens at rest; its access control and encryption are yours. - On eve before 0.81.0, a sign-in the
expectedSubjectcheck rejects is first reported as connected and then fails on first use. No grant is stored, so the misreport is cosmetic. - One Zone per factory.