Metadata-Version: 2.5
Name: pydantic-claude-code
Version: 0.7.7
Summary: Use your Claude Code subscription from a Pydantic AI Agent or CLAI2, with full tool support
Project-URL: Source, https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3
Project-URL: Homepage, https://pypi.org/project/pydantic-claude-code/
Author: Michael Pfaffenberger
License: MIT
License-File: LICENSE
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: <3.15,>=3.10
Requires-Dist: keyring<26,>=23
Requires-Dist: pydantic-ai-slim[anthropic]<3,>=2.38.0
Provides-Extra: clai2
Requires-Dist: pydantic-clai2>=0.53.0; extra == 'clai2'
Provides-Extra: dev
Requires-Dist: pyright>=1.1.400; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.1; extra == 'dev'
Requires-Dist: pytest>=8.3.4; extra == 'dev'
Requires-Dist: ruff<0.16,>=0.15; extra == 'dev'
Description-Content-Type: text/markdown

# pydantic-claude-code

Use your Claude Code subscription from a plain pydantic-ai `Agent` or from
[CLAI2](https://github.com/pydantic/pydantic-ai/tree/main/src/pydantic_clai2),
with full pydantic-ai tool support. No API key, no separate billing: if Claude
Code works from your terminal, this works too.

The repo is `mpfaffenberger/pydantic-ai-claude-code` and the import is
`pydantic_ai_claude_code`; the PyPI project is `pydantic-claude-code`
(`pip install pydantic-claude-code`).

## Models

| Model | ID |
|---|---|
| Claude Opus 5.5 | `claude-opus-5-5` |
| Claude Sonnet 5.5 | `claude-sonnet-5-5` |
| Claude Fable 5.1 | `claude-fable-5-1` |
| Claude Haiku 4.5 | `claude-haiku-4-5` |

These are the current models, the ones CLAI2's menus offer (`config.MODELS`).
They were checked on 2026-09-30 against Anthropic's
[models overview](https://docs.anthropic.com/en/docs/about-claude/models/overview),
against the `anthropic` SDK's model list that pydantic-ai's `KnownModelName` is
built from, and live against a Claude subscription. Any other model ID your
subscription serves, such as `claude-opus-4-8`, works too; it just isn't listed.

## Use it in CLAI2

The plugin adds `claude-code:MODEL` models to CLAI2, next to its own providers,
so the stock agent, Coder, and your other plugins all keep working.

### Install

One line installs the latest release of the plugin, and running it again updates it.

**macOS and Linux:**

```bash
curl -fsSL https://gist.githubusercontent.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3/raw/install.sh | sh
```

**Windows (PowerShell):**

```powershell
irm https://gist.githubusercontent.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3/raw/install.ps1 | iex
```

The plugin is published as a [gist](https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3): its files are this repo's
`src/pydantic_ai_claude_code` folder at the latest release, plus `install.sh` and `install.ps1`.
The script downloads the gist and puts its files in CLAI2's plugins folder as
`claude_code`, replacing any older copy. To pin a release, pass a gist
revision (`... | sh -s -- REVISION` on macOS/Linux, or
`$env:CLAUDE_CODE_REVISION = 'REVISION'; irm .../install.ps1 | iex` on Windows;
the gist's revisions are named after releases). Nothing to `pip install`: everything
the plugin imports (`pydantic-ai` with Anthropic support, `httpx2`, `keyring`)
already ships with CLAI2.

The plugins folder is `$XDG_CONFIG_HOME/pydantic-clai2/plugins/`, which defaults to
`~/.config/pydantic-clai2/plugins/` on macOS and Linux and
`%USERPROFILE%\.config\pydantic-clai2\plugins\` on Windows: the folder
next to CLAI2's `config.db`. To install by hand, clone the gist there yourself
(`git pull` in that folder then updates it):

```bash
# macOS / Linux
mkdir -p ~/.config/pydantic-clai2/plugins
git clone https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3.git ~/.config/pydantic-clai2/plugins/claude_code
```

```powershell
# Windows (PowerShell)
New-Item -ItemType Directory -Force "$HOME\.config\pydantic-clai2\plugins" | Out-Null
git clone https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3.git "$HOME\.config\pydantic-clai2\plugins\claude_code"
```

To hack on the plugin, symlink the folder instead of copying it:
`ln -s "$PWD/src/pydantic_ai_claude_code" ~/.config/pydantic-clai2/plugins/claude_code`
(on Windows PowerShell: `New-Item -ItemType Junction -Path "$HOME\.config\pydantic-clai2\plugins\claude_code" -Target "$PWD\src\pydantic_ai_claude_code"`).

Dropped-in plugins load when CLAI2 starts. Inside CLAI2, `/plugins` lists it as
`claude_code`, where Space turns it off and on. (The shell's `clai2 plugins list`
shows only plugins added by name, so it won't appear there.)

**Updates:** each time CLAI2 starts, the plugin checks PyPI in the background.
When a newer release is out, it says so once, after your first reply, with the
one-liner to update. Being offline is silent. Set `CLAUDE_CODE_NO_UPDATE_CHECK=1`
to turn the check off.

**Pax:** If you already run `pax`, use the same drop-in install and `/login claude-code`.
Pax reads the same `pydantic-clai2/plugins` folder. No legacy package is required.

**Legacy CLAI2 version:** the plugin is a class-based CLAI2 `Plugin`
([pydantic/pydantic-ai#9493](https://github.com/pydantic/pydantic-ai/pull/9493)),
which needs `pydantic-clai2` 0.53.0 or later, on Python 3.10 to 3.14. Run it
without installing anything:

```bash
uvx --from pydantic-clai2 clai2
```

(The PyPI package is `pydantic-clai2`; plain `uvx clai2` looks for a package
named `clai2`, which does not exist.) Plugin 0.5.0 was the last `activate(host)`
plugin, for CLAI2 `main` before #9493.

Or install it as a package instead, into CLAI2's environment, and point CLAI2
at it: `uv tool install pydantic-clai2 --with pydantic-claude-code`, then
`/plugins add claude_code pydantic_ai_claude_code`.


### Sign in

Run `/login claude-code` (it was `/login claude` before 0.7.0). Your browser opens Claude's sign-in page, and CLAI2
prints the URL in case it doesn't. On a machine whose browser can't reach CLAI2
(over SSH, or a remote box), open that URL on any machine and sign in. The
browser then ends on a `http://localhost:.../callback?code=...` page that fails
to load; copy that whole address and paste it at CLAI2's prompt, then press
Enter. CLAI2 counts the characters instead of echoing the code. Or open the settings menu with `/claude_code`
(or `C` on the plugin in `/plugins`), choose **Sign-in**, and press Enter.

### Pick a model

Signing in, with `/login claude-code` or from the settings menu, asks your
account which models it can run and adds every one of them to your model list,
so `/model` offers them right away. That is more than the table above, which
is only what the plugin knew of when it was released: a subscription listed 15
in November 2026. If the list cannot be read, the sign-in still stands and the
message says so.

`/model_settings` sets thinking mode, effort, and the rest for each model.
What you leave unset there follows the defaults under
[Use it from Python](#use-it-from-python): adaptive thinking, shown
as a summary, at medium effort. The menu shows those rows as not set.

For a model that isn't in your list, open `/add_model` and choose the
`claude-code` provider, or type one directly:

```text
/add_model claude-code:claude-opus-5-5
/model claude-code:claude-sonnet-5-5
```

Headless runs work the same way:
`clai2 -p "Summarize this repo" -m claude-code:claude-fable-5-1`.

### Several accounts

On a CLAI2 build with auth profiles, `/login claude-code@NAME` signs in another
account under the profile `NAME` (lowercase letters, digits, `-` and `_`), and
`claude-code@NAME:MODEL` runs on it, for example
`/model claude-code@work:claude-opus-5-5`. Models without `@NAME` keep using
the default sign-in. Each profile has its own tokens: keyring user name `NAME`,
or the file `auth-NAME.json` next to `auth.json`. To pool accounts, put them in
a CLAI2 fallback chain, `/chain NAME MODEL MODEL...`, then `/model chain:NAME`.
Older CLAI2 builds ignore profiles.

On a CLAI2 build with account usage, `/accounts` shows each signed-in account's
five-hour and weekly usage, read from the endpoint Claude Code's `/usage` uses,
with the same tokens and refresh as model requests.

### Settings menu

`/plugins configure claude_code`, `C` in `/plugins`, or a bare `/claude_code`
opens it. Every change is saved right away and applies from the next run.

| Row | What it does | Stored in |
|---|---|---|
| Sign-in | Enter signs in through the browser; R signs out | the token store below, never in plugin settings |
| Credential storage | `auto` (`CLAUDE_CODE_CREDENTIALS`, else keyring, else a file), `keyring`, or `file` | plugin settings (`credentials`) |

`/claude_code logout` and `/claude_code status` do the
same without the menu; add a profile name (`/claude_code logout work`) for
another account.

### Where the sign-in lives

The sign-in is an OAuth token pair, not an API key, so it does not go in
`/keys`. It is kept where this package keeps it outside CLAI2, which means one
sign-in serves both CLAI2 and your own agents: the OS keyring (service
`pydantic-ai-claude-code`), or, without a keychain, a file readable only by
you. CLAI2's plugin settings are plaintext SQLite, so they hold only the
storage choice. Tokens are refreshed automatically and the refreshed pair is
saved back. The **Credential storage** row's `auto` follows the
`CLAUDE_CODE_CREDENTIALS` variable described below when it is set; `keyring`
and `file` override it.

Signing out deletes the stored tokens; they stay valid at Anthropic until they
expire. Switching storage does not move an existing sign-in, so sign in again
after switching.

If a run says `Sign in to Claude Code first` or `Your Claude Code sign-in has
expired`, run `/login claude-code`. If the
plugin fails to load with `cannot import name 'Plugin' from
'pydantic_clai2.plugins'`, your CLAI2 predates class-based plugins: upgrade it as described under
[Install](#install), or pin plugin 0.5.0.

## Use it from Python

pydantic-ai owns the loop: its `Agent` drives the conversation, runs your
tools, and validates structured output. This package is just a model plus a
provider. Instead of a `claude-code:` model string, construct
`ClaudeCodeModel('claude-fable-5-1')` directly; it connects itself to a
`ClaudeCodeProvider` by default.

`ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default, on the conversation and on the
static prefix: the tool definitions and the instructions get breakpoints of their own, so a new conversation
reads the prefix earlier ones cached instead of writing it again at the 1-hour price. Passing any
`anthropic_cache*` setting to the model replaces this default as a whole: for example
`settings=AnthropicModelSettings(anthropic_cache="5m")` caches only the conversation, for 5 minutes, and
`settings=AnthropicModelSettings(anthropic_cache=False)` turns caching off. Per-request settings take precedence
key by key, so to turn caching off for one request, set `anthropic_cache`, `anthropic_cache_instructions` and
`anthropic_cache_tool_definitions` to `False`.

`ClaudeCodeModel` also turns **thinking** on by default, and shows it. Left to the API, a model's reasoning comes
back hidden, so a turn looks idle until its first word of text. Each request gets whatever of these its settings
leave open:

| Default | Setting | Applies to |
| --- | --- | --- |
| Adaptive thinking | `anthropic_thinking={"type": "adaptive"}` | Models that take adaptive thinking |
| Shown as a summary | `"display": "summarized"` in it | Any thinking that is on |
| A stale block is dropped, not an error | `"block_binding": {"prefix_mismatch_behavior": "drop_block"}` in it | Adaptive thinking |
| Medium effort | `anthropic_effort="medium"` | Models that take an effort |

Which model takes what comes from its Pydantic AI profile. Opus 4.5, Sonnet 4.5 and Haiku 4.5 do not take adaptive
thinking, so they think only when you ask them to, and the last two take no effort. The defaults fill gaps one value
at a time: `anthropic_thinking={"type": "adaptive"}` alone is still shown as a summary, and
`{"type": "adaptive", "display": "omitted"}` hides it again. `anthropic_thinking={"type": "disabled"}` or
Pydantic AI's own `thinking=False` turns thinking off, and a level such as `thinking="high"` sets the effort.

### Quick start

```python
import asyncio

from pydantic_ai import Agent

from pydantic_ai_claude_code import ClaudeCodeModel, default_store, login


async def main() -> None:
    # One-time: opens your browser, mints tokens, stores them
    # (it only needs to run again when the tokens are revoked).
    if default_store().load() is None:
        await login()

    agent = Agent(ClaudeCodeModel('claude-opus-5-5'))

    result = await agent.run('Say hi in three words.')
    print(result.output)


asyncio.run(main())
```

You can also sign in from the shell: `python -m pydantic_ai_claude_code login`.

### With tools

```python
from pydantic_ai import Agent
from pydantic_ai_claude_code import ClaudeCodeModel

agent = Agent(ClaudeCodeModel('claude-sonnet-5-5'))

@agent.tool_plain
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b
```

Tools defined on the agent are sent to the API as standard Anthropic tool
definitions. Structured output works the same way as with the built-in
`anthropic` provider.

### Structured output

```python
from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_ai_claude_code import ClaudeCodeModel

class Weather(BaseModel):
    city: str
    temperature_c: float

agent = Agent(ClaudeCodeModel('claude-fable-5-1'), output_type=Weather)
result = await agent.run('Weather in Paris right now?')
assert result.output.city == 'Paris'
```

### Streaming

```python
from pydantic_ai import Agent
from pydantic_ai_claude_code import ClaudeCodeModel

agent = Agent(ClaudeCodeModel('claude-haiku-4-5'))
async with agent.run_stream('Count from 1 to 3.') as stream:
    async for chunk in stream.stream_text():
        print(chunk, end='', flush=True)
```

## How auth works

The flow uses the same shared public OAuth client that the Claude Code CLI
uses:

- Authorization URL: `https://claude.ai/oauth/authorize`
- Token URL: `https://platform.claude.com/v1/oauth/token`
- Scopes: `org:create_api_key user:profile user:inference`

Tokens are saved to the OS keyring by default: the Keychain on macOS,
Credential Manager on Windows, and Secret Service on Linux. On machines without
a keychain (including headless Linux, where `keyring` reports its `fail`
backend), credentials go to a JSON file instead, created `0600`. You can
override its path with `CLAUDE_CODE_AUTH_FILE`:

```
~/.local/share/pydantic-ai-claude-code/auth.json
```

The file only ever contains what the issuer gave us. We never read the CLI's
own credential files.

Force a backend with the `CLAUDE_CODE_CREDENTIALS` env var (`keyring` or
`file`), or pass one to `default_store('file')`.

Refreshes happen automatically: the auth shim refreshes before expiry and
retries once on a 401, exactly like pydantic-ai's Codex provider. When the
refresh token itself is rejected, runs raise `ClaudeCodeSignInExpiredError`
(a `UserError`) telling you to sign in again.

Requests identify as Claude Code 2.1.290. The persona
`"You are Claude Code, Anthropic's official CLI for Claude."` is prepended to
the system context (position 0), as the CLI sends it. The client version
matters: the subscription backend refuses newer models to older CLI versions
(Opus 5.5 needs 2.1.280 or newer).

## Security and scope

This is a plain Anthropic Messages API client, authenticated by your Claude
subscription tokens. It does not run the Claude Code CLI in a subprocess, so it
does not inherit Claude Code's sandboxing, permission prompts, or hooks. Treat
it like any agent that runs code: only give it tools you trust.

Projects using this are responsible for following Anthropic's rules for using
Claude Code credentials in their own products.

## Development

```bash
uv sync --extra dev --extra clai2
uv run ruff check src tests && uv run ruff format --check src tests
uv run pyright
uv run pytest
```

To release, bump `version` in `pyproject.toml` and `__version__` in
`src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
push a matching tag (`git tag v0.7.7 && git push origin v0.7.7`). The `Publish` workflow tests,
builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret. Then run
`scripts/sync_gist.sh` to publish the release to the install gist, which is what the one-liner and the
update notice install from.

The tests never touch your real keychain or token file. They run against a
local Messages API stub, including a full CLAI2 turn through the plugin.

## Prior art

The OAuth mechanics (shared client ID, PKCE, token storage and refresh) are
lifted from the `claude_code_oauth` plugin in
[`code_puppy_core_plugins`](https://github.com/mpfaffenberger/code_puppy_core_plugins),
cleaned up and reshaped around the provider pattern in pydantic-ai.
