# Pydantic AI

Per-tool-call Keycard tokens for Pydantic AI agents. One capability on the agent, the identity on the run's deps, consent pauses through deferred tool approval, and per-run MCP toolset auth.

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

- 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

> **Note:** This package is Python only, on `pydantic-ai-slim` 2.60+ and Python 3.11+. It shares `AccessContext` and the identity types with the other Keycard Python packages.

## Installation

```bash
pip install keycardai-pydantic-ai

# With the framework's MCP support, for MCPToolset (see below)
pip install "keycardai-pydantic-ai[mcp]"
```

## 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

An agent that lists the caller's calendar, acting on behalf of whoever ran it:

```python
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_plain
def 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

`deps` is the framework's per-run data, so that is where the identity lives. `Access` builds the `KeycardIdentity` for each mode:

```python
agent.run_sync(prompt, deps=Access.on_behalf_of(subject_token))         # user-facing
agent.run_sync(prompt, deps=Access.as_self())                            # background job
agent.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.

```python
@dataclass
class 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

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()`:

```python
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 in `ToolFailed`, 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

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.

```python
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

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:

```python
from fastapi import FastAPI, Request, Response
from pydantic_ai.ui.ag_ui import AGUIAdapter

from keycardai.oauth.server import ClientSecret
from keycardai.pydantic_ai import Access
from 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

`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:

```python
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_token
```

`agrant()` 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

```python
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

- Durable execution fails closed. Under `TemporalDurability`, `DBOSDurability`, or any other durability capability, `KeycardGrant` raises 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.

## Related

<div class="docs-section">
  <div class="docs-section-header">
    <span class="docs-section-label docs-section-label--plain">SEE ALSO</span>
  </div>
  <div class="docs-grid docs-grid--2">
    <a href="/guides/access-apis-on-behalf-of-users/" class="docs-card">
      <div class="docs-card-icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="5" x2="19" y1="12" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>
      </div>
      <span class="docs-card-title">Access APIs on behalf of users</span>
      <span class="docs-card-desc">How delegated access and token exchange work across the SDKs</span>
    </a>
    <a href="/sdk/temporal/" class="docs-card">
      <div class="docs-card-icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="5" x2="19" y1="12" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>
      </div>
      <span class="docs-card-title">Temporal</span>
      <span class="docs-card-desc">Per-execution tokens for durable workflows</span>
    </a>
  </div>
</div>

## Source

<div class="docs-section">
  <div class="docs-grid docs-grid--2">
    <a href="https://github.com/keycardai/python-sdk/tree/main/packages/pydantic-ai" class="docs-card">
      <div class="docs-card-icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"/><path d="M9 18c-4.51 2-5-2-7-2"/></svg>
      </div>
      <span class="docs-card-title">Python SDK</span>
      <span class="docs-card-desc">Source for keycardai-pydantic-ai in the Python SDK repo</span>
    </a>
    <a href="https://pypi.org/project/keycardai-pydantic-ai/" class="docs-card">
      <div class="docs-card-icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="5" x2="19" y1="12" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>
      </div>
      <span class="docs-card-title">PyPI</span>
      <span class="docs-card-desc">Releases and changelog for keycardai-pydantic-ai</span>
    </a>
  </div>
</div>
