The LangChain packages add one middleware to your agent. It runs at LangChain’s tool-call boundary (wrap_tool_call in Python, wrapToolCall in TypeScript), so before each tool executes it gets a Keycard token for the Resources that tool needs, under the identity the run acts for, and the tool reads it with get_access_context() or getAccessContext().
The identity rides the run’s context, not the deployment: a user-facing agent exchanges the caller’s token on every call (RFC 8693), a background agent acts as its own Application, and the same middleware instance serves every run. The Python package is keycardai-langchain; the TypeScript package is @keycardai/langchain. They implement one contract, so the interrupt payloads and the defaults are the same on both sides, and this page calls out where they differ.
When to use
Section titled “When to use”create_agent/createAgentagents whose tools call external APIs for the person in the chat- Raw LangGraph graphs and deep agents built on the same middleware system
- Background agents that act as themselves against vaulted or brokered Resources
- A LangGraph server that serves many callers and needs each run to act for its own verified caller
Installation
Section titled “Installation”pip install keycardai-langchain
# For a served LangGraph agent (adds langgraph-sdk and starlette)pip install "keycardai-langchain[serve]"npm install @keycardai/langchain langchain @langchain/core @langchain/langgraph
# For a served LangGraph agentnpm install @langchain/langgraph-sdkKey exports
Section titled “Key exports”Python (keycardai.langchain) |
TypeScript (@keycardai/langchain) |
Description |
|---|---|---|
KeycardGrantMiddleware |
keycardGrantMiddleware |
The middleware. Acquires a token per tool call and provides grant() for code outside the agent loop |
Access |
Access |
Factories for the run’s identity: on_behalf_of() / onBehalfOf(), as_self() / asSelf(), impersonate() |
KeycardIdentity |
KeycardIdentity, keycardIdentitySchema |
The identity value Access builds. Python passes it as the agent’s context_schema; the TypeScript middleware carries the schema itself |
get_access_context |
getAccessContext |
Returns the AccessContext for the current tool call |
AccessContext |
AccessContext |
Token container shared with the other Keycard packages |
ResourceAccessError |
ResourceAccessError |
Raised by access(resource) when that Resource was not granted |
Caller, caller_from_config |
callerFromRuntime, ServedCaller |
The verified caller of a served run, for tools that need to know who is calling |
| Python | TypeScript | Description |
|---|---|---|
keycardai.langchain.auth (serve extra) |
@keycardai/langchain/serve |
zone_authenticator / zoneAuthenticator and install_owner_authorization / installOwnerAuthorization for a LangGraph server |
keycardai.langchain.testing |
@keycardai/langchain/testing |
mock_access_context / mockAccessContext and override_access_context / overrideAccessContext |
Quickstart
Section titled “Quickstart”An agent that lists the caller’s calendar, acting on behalf of whoever ran it:
import os
from langchain.agents import create_agentfrom langchain.tools import tool
from keycardai.langchain import Access, KeycardGrantMiddleware, KeycardIdentity, get_access_context
CALENDAR = "https://www.googleapis.com/calendar/v3"
keycard = KeycardGrantMiddleware( zone_url=os.environ["KEYCARD_ISSUER"], resources=[CALENDAR], client_id=os.environ["KEYCARD_CLIENT_ID"], client_secret=os.environ["KEYCARD_CLIENT_SECRET"],)
@tooldef list_events(days_ahead: int = 0) -> str: """List the user's calendar events for a day, 0 being today.""" access = get_access_context() if access.has_resource_error(CALENDAR): return f"Calendar access not granted: {access.get_resource_error(CALENDAR)}" token = access.access(CALENDAR).access_token ... # call the Calendar API with the token
agent = create_agent( "anthropic:claude-sonnet-5-5", tools=[list_events], middleware=[keycard], context_schema=KeycardIdentity,)
agent.invoke( {"messages": [{"role": "user", "content": "What is on my calendar today?"}]}, context=Access.on_behalf_of("<user-access-token>"),)import { createAgent } from "langchain";import { tool } from "@langchain/core/tools";import { z } from "zod";import { Access, getAccessContext, keycardGrantMiddleware } from "@keycardai/langchain";
const CALENDAR = "https://www.googleapis.com/calendar/v3";
const keycard = keycardGrantMiddleware({ zoneUrl: process.env.KEYCARD_ISSUER!, resources: [CALENDAR], clientId: process.env.KEYCARD_CLIENT_ID!, clientSecret: process.env.KEYCARD_CLIENT_SECRET!,});
const listEvents = tool( async ({ daysAhead }) => { const access = getAccessContext(); if (access.getResourceError(CALENDAR)) { return `Calendar access not granted: ${JSON.stringify(access.getResourceError(CALENDAR))}`; } const token = access.access(CALENDAR).accessToken; // ... call the Calendar API with the token }, { name: "list_events", description: "List the user's calendar events for a day, 0 being today.", schema: z.object({ daysAhead: z.number().default(0) }), },);
const agent = createAgent({ model: "anthropic:claude-sonnet-5-5", tools: [listEvents], middleware: [keycard],});
await agent.invoke( { messages: [{ role: "user", content: "What is on my calendar today?" }] }, { context: Access.onBehalfOf("<user-access-token>") },);The middleware runs before the tool body. A failed acquisition is recorded on the AccessContext per Resource rather than raised, so one denied Resource does not break a granted one; access(resource) is the only call that raises, with ResourceAccessError. Returning a readable sentence from the tool beats throwing: in a chat UI a thrown error reads as an internal error, when the truthful message is “you have not granted this yet.”
client_id / client_secret (clientId / clientSecret) are shorthand for a ClientSecret application credential. Pass application_credential= (applicationCredential:) for the other credential types, such as Workload Identity, so a deployed agent holds no static secret. Pass one form or the other, never both.
Create the middleware once at module scope and share it across runs and users. It keeps one Zone client, which caches the Zone’s token endpoint after its first call, so a tool call pays neither client construction nor rediscovery.
Identity modes
Section titled “Identity modes”The run’s context is the framework’s per-run data, so that is where the identity lives. Access builds the KeycardIdentity for each mode:
agent.invoke(state, context=Access.on_behalf_of(subject_token)) # user-facingagent.invoke(state, context=Access.as_self()) # background jobagent.invoke(state, context=Access.impersonate("troy.barnes@example.com"))await agent.invoke(state, { context: Access.onBehalfOf(subjectToken) }); // user-facingawait agent.invoke(state, { context: Access.asSelf() }); // background jobawait agent.invoke(state, { context: Access.impersonate("troy.barnes@example.com") });| Identity | Grant | Audit actor |
|---|---|---|
on_behalf_of(token) / onBehalfOf(token) |
RFC 8693 token exchange | Application for User |
as_self() / asSelf() |
Client credentials | The Application |
impersonate(user) |
Substitute-user token | Application as User |
A run with no identity fails with a missing_identity error, or pauses for sign-in when sign_in_url is set. It never falls back to the agent’s own authority: acting as itself is always an explicit choice. Impersonation is forbidden by default and needs an impersonation policy in the Zone.
Two more places an identity can come from:
fallback_identity=(fallbackIdentity:) applies when the run carries none. Pass a callable so it is resolved per tool call, and a sign-in that happens mid-conversation takes effect on resume.identity_source="auth_user"(identitySource: "auth_user") reads the caller a LangGraph server verified; see Serving the agent. It cannot be combined with a fallback identity.
The two packages differ in who declares the context schema. Python passes context_schema=KeycardIdentity to create_agent; the TypeScript middleware declares contextSchema itself, which is how LangChain 1.x middleware contributes context, so the agent declares nothing.
Sign-in and consent pauses
Section titled “Sign-in and consent pauses”With sign_in_url and authorization_url set, a run that has no identity, an expired subject token, or a missing grant pauses with a LangGraph interrupt instead of recording an error, so the whole flow can live in your chat surface:
keycard = KeycardGrantMiddleware( zone_url=os.environ["KEYCARD_ISSUER"], resources=[CALENDAR], client_id=os.environ["KEYCARD_CLIENT_ID"], client_secret=os.environ["KEYCARD_CLIENT_SECRET"], sign_in_url="https://<your-app>/signin", authorization_url=lambda resources: f"https://<your-app>/authorize?r={resources[0]}",)const keycard = keycardGrantMiddleware({ zoneUrl: process.env.KEYCARD_ISSUER!, resources: [CALENDAR], clientId: process.env.KEYCARD_CLIENT_ID!, clientSecret: process.env.KEYCARD_CLIENT_SECRET!, signInUrl: "https://<your-app>/signin", authorizationUrl: (resources) => `https://<your-app>/authorize?r=${encodeURIComponent(resources[0])}`,});Payload type |
Fires when | On resume |
|---|---|---|
sign_in_required |
No identity on the run, or its subject token has expired | The identity is re-resolved and the exchange runs |
authorization_required |
Identity present and valid, grant missing | The exchange is retried |
The payloads are the contract, so they keep the same snake_case fields in both languages: { type: "sign_in_required", sign_in_url, reason, message } and { type: "authorization_required", authorization_url, resources, errors, message }. reason is missing_identity or subject_token_expired; expiry is a decode-only check of the token’s exp, so a dead session routes to sign-in rather than to a consent page that cannot fix it.
Interrupts need a checkpointer, and three details follow from how LangGraph resumes:
- Resume needs no new token. Consent changes the grant in the Zone, not the token in your session.
- Runtime context is not checkpointed, so a resume must re-supply the identity, which a server does on every run anyway.
- A resume without authorizing retries acquisition and pauses again, up to three attempts per tool call. After the cap the failure stays on the
AccessContextfor the tool to read.
Set interrupt_on_auth=False (interruptOnAuth: false) for a deployment with no checkpointer: the same failure is delivered to the model as failed tool output carrying the URL, the wrapped tool does not run, and the user’s next turn retries it.
Per-tool Resources and scopes
Section titled “Per-tool Resources and scopes”resources is the default for every tool. tool_resources (toolResources) overrides it per tool name, and an empty list means the middleware exchanges nothing for that tool. request_scopes (requestScopes) is the outbound scope requested from Keycard for the exchange or the as-itself grant, distinct from any scope enforced on the caller’s inbound token.
Neither package has an MCP dependency. The middleware brokers credentials for tools that call APIs directly; an MCP server that runs its own interactive OAuth is the MCP package’s concern. A Unified Access Gateway rides the plain exchange path like any other Resource; Autonomous Agent Access shows it with keycard.grant().
Serving the agent
Section titled “Serving the agent”The identity modes answer what a run acts as. A deployed LangGraph server has a second question, who is calling, and without an answer one deployment holds one identity. The served-agent module verifies each caller’s own Zone-issued bearer per request, hands the run that identity, and scopes threads, runs, and store items to their owner:
import os
from langgraph_sdk import Auth
from keycardai.langchain.auth import install_owner_authorization, zone_authenticator
auth = Auth()auth.authenticate( zone_authenticator( zone_url=os.environ["KEYCARD_ISSUER"], resource="https://<your-agent-resource>", ))install_owner_authorization(auth)import { Auth } from "@langchain/langgraph-sdk/auth";import { installOwnerAuthorization, zoneAuthenticator } from "@keycardai/langchain/serve";
export const auth = installOwnerAuthorization( new Auth().authenticate( zoneAuthenticator({ zoneUrl: process.env.KEYCARD_ISSUER!, resource: "https://<your-agent-resource>", }), ),);Then point the middleware at the verified caller with identity_source="auth_user" (identitySource: "auth_user") instead of at per-run context. Nothing in the request body can name an identity. resource is the agent’s own Resource, so a token minted for anything else is rejected with a 401 and the RFC 6750 challenge.
install_owner_authorization is not optional. Authentication says who is calling but grants no ownership; without it any valid caller can read and resume any other caller’s thread. It stamps the owner on thread and run creation, filters reads and deletes by owner, prefixes store namespaces with the owner, and denies every unmatched resource and action, because LangGraph’s authorization handlers otherwise fail open. In langgraph.json, set "auth": { "path": "...", "disable_studio_auth": true }; with it unset, a request carrying x-auth-scheme: langsmith skips your hook.
Where the two runtimes differ:
- The Python server serves
/ok,/info,/docs,/openapi.json,/metrics,GET /ui/*, and/noauth*without the hook. The JS server runs it on everything exceptGET /infoandGET /ui/*, so a liveness probe there needs a token or should target/info. - Listing store namespaces without a prefix is scoped to the owner on Python and denied (403) on JS, where the server’s filter can be forged by caller-chosen labels.
Outside the agent
Section titled “Outside the agent”get_access_context() normally only works inside a run. grant() enters the same access context explicitly, for code that calls a tool without the agent loop or needs a Resource with no tool attached:
with keycard.grant(Access.on_behalf_of(session_token)): events = list_events.invoke({"days_ahead": 0})
with keycard.grant(Access.as_self(), resources=[LLM_KEY]) as access: key = access.access(LLM_KEY).access_tokenconst events = await keycard.grant( { identity: Access.onBehalfOf(sessionToken) }, () => listEvents.invoke({ daysAhead: 0 }),);
const key = await keycard.grant( { identity: Access.asSelf(), resources: [LLM_KEY] }, (access) => access.access(LLM_KEY).accessToken,);Python’s grant() is a context manager with an async twin, agrant(). TypeScript’s grant() takes the body as a callback and is always awaited, so there is no separate async form. Both take tool_name / toolName to apply that tool’s override, or resources to grant exactly the listed Resources (one or the other), and fall back to the fallback identity when none is passed. There is no run to pause, so nothing interrupts here.
Testing
Section titled “Testing”from keycardai.langchain.testing import mock_access_context
def test_list_events(): with mock_access_context(resource_tokens={CALENDAR: "test-token"}): assert list_events.invoke({"days_ahead": 0})import { mockAccessContext } from "@keycardai/langchain/testing";
it("lists events", async () => { await mockAccessContext({ resourceTokens: { [CALENDAR]: "test-token" } }, () => listEvents.invoke({ daysAhead: 0 }), );});access_token / accessToken serves one token for any Resource; resource_tokens / resourceTokens asserts which Resource a tool reads; resource_errors and error_message (resourceErrors, errorMessage) cover the failure paths; and override_access_context / overrideAccessContext takes a hand-built context.
Limitations
Section titled “Limitations”- Interrupts need a checkpointer. Stateless deployments use
interrupt_on_auth=False/interruptOnAuth: falseand get the URL as tool output instead. - As-itself runs never pause, even with the URLs set: there is no user to send to a consent page, so a denied grant stays on the
AccessContext. - Resuming an interrupt runs the resumed node under the resumer’s identity, not the identity that parked it. Thread ownership from
install_owner_authorizationis what keeps a resume with its owner. - One Zone per middleware.