Skip to content

Cursor Agent SDK

Keycard auth for Cursor Agent SDK agents. A Zone token verifier for a channel's bearerAuth policy, and Keycard-backed connection auth that acts as the agent, on behalf of the caller, or for a mapped User. TypeScript.

@keycardai/cursor-agent-sdk plugs into two Cursor Agent SDK primitives. keycardAuth() is the verifier for bearerAuth() in a channel’s auth policy chain, and it turns a Zone-issued bearer into the SDK’s AuthContext for the caller. Keycard.onBehalfOf(), Keycard.asSelf(), and Keycard.impersonate() are defineConnection({ auth }) providers: the SDK runs them on the host before every model turn and merges the headers they return over the connection’s static headers.

The token comes from the Zone, minted for the connection’s Resource under the identity of the session: the caller keycardAuth() verified, the agent’s own Application, or a mapped User. It never enters the transcript and never reaches the model.

  • Cursor Agent SDK agents whose MCP connections should act for the person who called
  • Scheduled or webhook-created sessions that act as the agent’s own Application
  • Agents on Cursor hosting that need a per-user identity on top of the deployment alias token
Terminal window
pnpm add @keycardai/cursor-agent-sdk

@keycardai/cursor-agent-sdk

Export Description
keycardAuth The bearerAuth verifier. Admits a Zone bearer as AuthContext and retains the token for a later exchange
Keycard onBehalfOf(), asSelf(), impersonate() connection auth providers
headersFor Asks a provider for the turn’s headers from a server tool or route handler, where the SDK does not run auth
ConnectionAuthError, FailureReason The error a provider throws and its reason codes
subjectTokenExpired, decodeClaims The decode-only expiry check, exported for hosts
memorySubjectTokenStore, DEFAULT_EXPIRY_SKEW_SECONDS The default in-process subject token store and the 60 second refresh margin

@keycardai/cursor-agent-sdk/testing

Export Description
fakeZoneClient Records every exchange, impersonation, and client-credentials call; can fail one Resource or every call
keycardPrincipal, session, validJwt Build a Keycard principal, a session carrying it, and a JWT for tests

Verify the caller on the channel, then give a connection a token exchanged for that caller:

agent/channels/http.ts
import { bearerAuth, httpChannel, localDev } from "@grok/agent-sdk/channels";
import { keycardAuth } from "@keycardai/cursor-agent-sdk";
export default httpChannel({
auth: [
bearerAuth(keycardAuth({ zoneUrl: process.env.KEYCARD_ISSUER!, audience: "https://<your-agent-resource>" })),
localDev(),
],
});
agent/mcp-connections/calendar.ts
import { defineConnection } from "@grok/agent-sdk/connections";
import { Keycard } from "@keycardai/cursor-agent-sdk";
export default defineConnection({
url: "https://calendar-mcp.example.com/mcp",
advertiseTools: true,
auth: Keycard.onBehalfOf({
zoneUrl: process.env.KEYCARD_ISSUER!,
resource: "https://calendar-mcp.example.com",
requestScopes: ["calendar.read"],
clientId: process.env.KEYCARD_CLIENT_ID!,
clientSecret: { secretName: "KEYCARD_CLIENT_SECRET" },
}),
});

bearerAuth’s verifier can only admit or pass, so keycardAuth() returns null for a bearer this Zone did not issue, for a Zone token that does not verify, and for one missing a requiredScopes entry, and the chain continues. A deployment that must refuse such a request places no admitting policy after the Keycard entry. This is the one place the package differs from eve, whose auth entry can reject and stop the walk.

A verified bearer becomes { authenticator: "keycard", principalId: sub, principalType: "user", attributes }. The SDK persists AuthContext in the session record, so the token itself is never placed on it; it is retained in a process-local store (retainSubjectToken: "memory", the default). "none" retains nothing.

On Cursor hosting, on-behalf-of therefore works for a turn that runs on the instance that verified the caller’s request. Hosted agents can be stopped and replaced between turns, so a reminder wake, a retry, or a turn resumed on a fresh instance finds no token and fails closed with subject_token_unavailable; the caller’s next request verifies again. Agents that act without a request in hand use Keycard.asSelf or Keycard.impersonate, and self-hosting with agent-sdk serve keeps one process. There is no persisted option: whatever the verifier returns becomes session.auth, which Cursor saves with the session. Cursor advises against putting the raw token there, and a ctx.host.kv-backed store would put the token at rest the same way.

clientSecret takes a string or the SDK’s SecretRef ({ secretName }), read from process.env when the provider runs rather than at import, because Cursor hosting binds a deployment’s secrets per request after discovery imported the module without them. Declare the name in secretNames and set it with agent-sdk secret set <slug> KEYCARD_CLIENT_SECRET. applicationCredential takes any ApplicationCredential instead.

Provider Identity Grant
Keycard.onBehalfOf() The session’s Keycard principal RFC 8693 exchange of the token keycardAuth() retained
Keycard.asSelf() The agent’s own Application, ignoring session.auth Client credentials; one token per connection across every session
Keycard.impersonate() The session’s Keycard principal, or userIdentifier(auth) mapping any principal to a Zone User Substitute-user exchange; needs an impersonation policy in the Zone

Nothing falls back to the agent’s authority. A user-pattern connection in a session with no Keycard user principal throws principal_required; an onBehalfOf turn on an instance that never saw the caller’s token throws subject_token_unavailable; an expired one throws subject_token_expired after a decode-only check; an unset secret throws credential_unavailable naming the variable. A thrown provider fails the turn, or skips the connection when it is advertised with optional: true.

Every provider caches the minted token per principal (one slot for asSelf) until expirySkewSeconds (default 60) before expiry and builds one warm Zone client.

The built-in session, MCP, and playground routes also sit behind the deployment alias token (X-Agent-Alias-Token); a Keycard bearer adds a per-user identity on top of it. For end users calling the agent directly, a custom httpChannel route opts out with [bearerAuth(keycardAuth(...)), publicEndpoint()]. Because publicEndpoint() admits everyone as an anonymous principal, the handler must reject any request whose auth.authenticator is not "keycard" before it sends a message.

ctx.host.mcp and a route handler’s host.mcp receive a connection’s static headers only; the SDK never runs auth for them. Code on those paths asks the same provider for what the turn received:

import { headersFor, Keycard, type SessionLike } from "@keycardai/cursor-agent-sdk";
const calendar = Keycard.onBehalfOf({
zoneUrl: process.env.KEYCARD_ISSUER!,
resource: "https://calendar-mcp.example.com",
clientId: process.env.KEYCARD_CLIENT_ID!,
clientSecret: { secretName: "KEYCARD_CLIENT_SECRET" },
});
async function execute(input: unknown, ctx: { session: SessionLike }) {
const { headers } = await headersFor(calendar, ctx.session);
return fetch("https://calendar-mcp.example.com/free", { headers });
}

It shares the provider’s cache and throws the same errors. It is not called grant() because the LangChain grant() yields an AccessContext with per-Resource errors, a contract this seam does not keep.

import { fakeZoneClient, keycardPrincipal, session, validJwt } from "@keycardai/cursor-agent-sdk/testing";
import { Keycard, memorySubjectTokenStore } from "@keycardai/cursor-agent-sdk";
const client = fakeZoneClient();
const subjectTokens = memorySubjectTokenStore();
subjectTokens.set("https://<zone-id>.keycard.cloud|user-1", validJwt(3600));
const auth = Keycard.onBehalfOf({
zoneUrl: "https://<zone-id>.keycard.cloud",
resource: "https://calendar-mcp.example.com",
client,
subjectTokens,
});
const { headers } = await auth(session(keycardPrincipal()));
client.calls.exchanges; // one exchange for user-1's token

An injected client replaces the Zone’s token endpoint, but onBehalfOf and impersonate still need zoneUrl: it is the Zone they check the caller’s principal against. keycardAuth() takes a verify seam in place of the JWKS-backed verifier. The SDK’s own seam also works: a connection under test can declare auth: async () => ({ headers: { authorization: "Bearer test-token" } }).

  • No sign-in pause. The SDK’s action.auth_requested pause fires only for host OAuth (oauth: true) connections, and an auth provider cannot trigger it, so a denied grant or an expired token is a failed turn, never a prompt to sign in. Host OAuth against a Keycard Zone works unchanged as one host-level identity for every caller; it cannot be combined with auth on one connection.
  • On-behalf-of is per instance: a turn on an instance that never verified the caller’s request fails closed with subject_token_unavailable. Use Keycard.asSelf or Keycard.impersonate for turns without a request in hand.
  • Hosted agents need a stored client secret, because Cursor hosting documents no workload identity. Self-hosted agents with a platform OIDC token use WorkloadIdentity instead.
  • One Zone per provider.