The Pydantic AI package adds one capability, KeycardGrant, to your agent. You pass the identity a run acts for in the run’s deps. Before each tool call, the capability gets a Keycard token for the Resources that tool needs, and the tool reads it with get_access_context().
A user-facing agent exchanges the caller’s token on every call (RFC 8693). A background agent acts as its own Application. Either way, tools read one accessor and never take a secret as an argument.
When to use
Section titled “When to use”- Pydantic AI agents whose tools call external APIs on behalf of the person in the chat
- Background agents that act as themselves against vaulted or brokered Resources
- Agents that mix function tools with MCP toolsets and need each authenticated under the same identity
- Serving an agent over HTTP where every request acts for its verified caller
Installation
Section titled “Installation”pip install keycardai-pydantic-ai
# With the framework's MCP support, for MCPToolset (see below)pip install "keycardai-pydantic-ai[mcp]"Key exports
Section titled “Key exports”keycardai.pydantic_ai
| Export | Description |
|---|---|
KeycardGrant |
The capability. Acquires a token per tool call and provides mcp_auth(), grant(), agrant() |
Access |
Factories for the run’s identity: on_behalf_of(), as_self(), impersonate() |
KeycardIdentity |
The identity value Access builds, used as deps_type or carried on your own deps |
get_access_context |
Returns the AccessContext for the current tool call |
resume_results |
Builds DeferredToolResults for a resume, handing each pause’s metadata back |
MCPAuthError |
Raised when an MCP session cannot be authenticated. Carries code and resource, never a token |
AccessContext |
Token container shared with the other SDK packages |
ResourceAccessError |
Raised by access.access(resource) when that Resource was not granted |
keycardai.pydantic_ai.testing
| Export | Description |
|---|---|
mock_access_context |
Serves test tokens or errors to tools called outside an agent run |
override_access_context |
Serves a hand-built AccessContext |
Quickstart
Section titled “Quickstart”An agent that lists the caller’s calendar, acting on behalf of whoever ran it:
from pydantic_ai import Agent
from keycardai.pydantic_ai import Access, KeycardGrant, KeycardIdentity, get_access_context
CALENDAR = "https://www.googleapis.com/calendar/v3"
keycard = KeycardGrant( zone_url="https://<zone-id>.keycard.cloud", resources=[CALENDAR], client_id="<client-id>", client_secret="<client-secret>",)
agent = Agent( "anthropic:claude-sonnet-5-5", deps_type=KeycardIdentity, capabilities=[keycard], instructions="You are a calendar assistant. Use the tool, then answer briefly.",)
@agent.tool_plaindef 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_error(): return f"Calendar unavailable: {access.get_error()['message']}" 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
result = agent.run_sync("What is on my calendar today?", deps=Access.on_behalf_of("<user-access-token>"))The capability 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.access(resource) is the only call that raises, with ResourceAccessError.
client_id and client_secret are shorthand for a ClientSecret application credential. Pass application_credential= for the other credential types in keycardai.oauth.server.credentials, such as Workload Identity.
Identity modes
Section titled “Identity modes”deps is the framework’s per-run data, so that is where the identity lives. Access builds the KeycardIdentity for each mode:
agent.run_sync(prompt, deps=Access.on_behalf_of(subject_token)) # user-facingagent.run_sync(prompt, deps=Access.as_self()) # background jobagent.run_sync(prompt, deps=Access.impersonate("troy.barnes@example.com"))| Identity | Grant | Audit actor |
|---|---|---|
Access.on_behalf_of(token) |
RFC 8693 token exchange | Application for user |
Access.as_self() |
Client credentials | The Application |
Access.impersonate(user) |
Substitute-user token | Application as user |
Impersonation is a different trust model from delegation: the agent asserts who the user is, and Zone policy is the control.
The capability finds the identity in one of three places, in order. deps is itself a KeycardIdentity; deps carries one as a keycard_identity attribute; or identity_from=lambda ctx: ... reads it from the RunContext. When nothing is found, fallback_identity= applies (a callable is resolved per tool call, so a sign-in that happens mid-run is picked up on resume). RunContext.metadata is never read.
@dataclassclass Deps: db: Database keycard_identity: KeycardIdentity | None = None
agent = Agent(model, deps_type=Deps, capabilities=[keycard])agent.run_sync(prompt, deps=Deps(db, keycard_identity=Access.on_behalf_of(token)))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 through the framework’s deferred tool approval instead of recording an error. Add DeferredToolRequests to the agent’s output_type, show the user the URL in the pause’s metadata, and resume with resume_results():
from pydantic_ai import Agent, DeferredToolRequests
from keycardai.pydantic_ai import resume_results
keycard = KeycardGrant( zone_url="https://<zone-id>.keycard.cloud", resources=[CALENDAR], client_id="<client-id>", client_secret="<client-secret>", sign_in_url="https://<your-app>/signin", authorization_url="https://<zone-id>.keycard.cloud",)agent = Agent(model, deps_type=KeycardIdentity, output_type=[str, DeferredToolRequests], capabilities=[keycard])
identity = Access.on_behalf_of("<user-access-token>")result = agent.run_sync(question, deps=identity)while isinstance(result.output, DeferredToolRequests): for call in result.output.approvals: payload = result.output.metadata[call.tool_call_id] print(f"[{payload['type']}] {payload['message']}") print(payload.get("sign_in_url") or payload.get("authorization_url")) input("Press Enter after completing it to resume... ") result = agent.run_sync( message_history=result.all_messages(), deps=identity, # deps are not part of the message history deferred_tool_results=resume_results(result.output, approve_all=True), )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 tool runs |
authorization_required |
Identity present and valid, grant missing | The exchange is retried |
resume_results() takes the same arguments as DeferredToolRequests.build_results() and also hands each call’s pause metadata back. Use it whenever a tool also sets requires_approval=True. The framework asks for that approval before KeycardGrant runs, and the handed-back metadata is how KeycardGrant tells the user’s approval apart from a resume of its own pause.
- With
resume_results(), the tool pauses once for consent after the user approves it. - With plain
build_results(), a missing grant ends the call inToolFailed, with the consent URL in the message.
Either way, a call never pauses twice for Keycard, and ToolDenied on resume skips the tool.
Set defer_on_auth=False to skip the pause: the call ends in ToolFailed with the URL in its message, for hosts that cannot resume a run.
MCP toolsets
Section titled “MCP toolsets”An MCP server is authenticated per run, not per tool call, because the session opens before any tool runs. mcp_auth(resource) returns the per-run auth function MCPToolset accepts: the framework calls it once per run, the returned auth acquires a token for the Resource on the session’s first request, sends it as a bearer, and replaces it within expiry_skew_seconds (default 60) of its expiry. Each run opens its own session as its own user.
from pydantic_ai.mcp import MCPToolset
CRM = "https://crm.<your-domain>/mcp"
keycard = KeycardGrant( zone_url="https://<zone-id>.keycard.cloud", client_id="<client-id>", client_secret="<client-secret>", resources=[CALENDAR], tool_resources=lambda name: [] if name.startswith("crm_") else None,)crm = MCPToolset(CRM, auth=keycard.mcp_auth(CRM)).prefixed("crm")agent = Agent(model, deps_type=KeycardIdentity, toolsets=[crm], capabilities=[keycard])The tool_resources callable matters: the capability cannot tell an MCP tool from a function tool, so without it every crm_* call would also acquire, and could pause for, the default resources. Returning [] for the toolset’s prefix acquires nothing for those tools; the session’s bearer is the only credential they use. request_scopes= on mcp_auth() overrides the capability’s entry for that Resource.
A run with no identity, an expired subject token, or no grant for the Resource fails the connection with MCPAuthError instead of pausing: there is no tool call to defer yet. Sign the user in, or grant access, before the run.
Serving the agent
Section titled “Serving the agent”Most deployments serve the agent over HTTP to a chat UI, with every request acting for whoever called. keycardai-starlette verifies the Zone bearer and exposes it as request.user.access_token; Pydantic AI’s UI adapters take the run’s deps per request. Joining the two is one route:
from fastapi import FastAPI, Request, Responsefrom pydantic_ai.ui.ag_ui import AGUIAdapter
from keycardai.oauth.server import ClientSecretfrom keycardai.pydantic_ai import Accessfrom keycardai.starlette import AuthProvider, KeycardUser, requires
auth = AuthProvider( zone_url="https://<zone-id>.keycard.cloud", application_credential=ClientSecret(("<client-id>", "<client-secret>")), audience="https://<your-agent-resource>",)app = FastAPI()auth.install(app)
@app.post("/chat")@requires("authenticated")async def chat(request: Request) -> Response: user: KeycardUser = request.user return await AGUIAdapter.dispatch_request( request, agent=agent, deps=Access.on_behalf_of(user.access_token) )The caller’s verified token becomes the run’s identity, and nothing else carries one. audience is the agent’s own Resource, so the route rejects a token minted for anything else before the agent runs. A request without a bearer gets a 401 with the RFC 6750 challenge.
The AG-UI adapter sends a Keycard pause to the client as an interrupt, with the pause payload as its metadata. When the client resumes with an approval, the tool runs with the caller’s exchanged token. Set output_type=[str, DeferredToolRequests] on the agent yourself, because the adapters add it only when the client sends frontend tools.
Served agents do not get the consent pause for approval-gated tools: the AG-UI and Vercel AI adapters resume with plain approvals and no metadata, the same as build_results(), so a tool that also sets requires_approval=True ends in ToolFailed with the consent URL when its grant is missing.
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 function without the agent loop or needs a Resource with no tool attached:
with keycard.grant(Access.on_behalf_of(session_token)): events = list_events(days_ahead=0)
with keycard.grant(Access.as_self(), resources=[LLM_KEY]) as access: key = access.access(LLM_KEY).access_tokenagrant() is the async variant. Both accept tool_name= to apply that tool’s tool_resources entry, or resources= to grant exactly the listed Resources (one or the other), and fall back to fallback_identity when no identity is passed. There is no run to pause, so nothing defers here: failures stay on the yielded AccessContext, exactly as tools see them.
Testing
Section titled “Testing”from keycardai.pydantic_ai.testing import mock_access_context
def test_list_events(): with mock_access_context(resource_tokens={CALENDAR: "test-token"}): assert list_events(days_ahead=0)mock_access_context(access_token=...) serves one token for any Resource; resource_tokens= asserts which Resource a tool reads; resource_errors= and error_message= cover the failure paths; and override_access_context takes a hand-built context. Pair it with the framework’s TestModel or FunctionModel and models.ALLOW_MODEL_REQUESTS = False.
Limitations
Section titled “Limitations”- Durable execution fails closed. Under
TemporalDurability,DBOSDurability, or any other durability capability,KeycardGrantraises a configuration error before acquiring anything, because deps are serialized into the durable history and a token would be replayed. Run such agents without the durability capability for now. - Approval-gated tools get their consent pause only when the host resumes through
resume_results(); the UI adapters do not (see Serving the agent). - One Zone per capability.