Metadata-Version: 2.4
Name: aclientp
Version: 0.7.1
Summary: Agent Client Protocol (ACP) for Python: typed v1 and draft v2, checked against the upstream schema
Keywords: acp,agent-client-protocol,agents,ai,json-rpc,llm,zed
Author: Philipp Temminghoff
Author-email: Philipp Temminghoff <philipptemminghoff@googlemail.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: Pydantic
Classifier: Framework :: Pydantic :: 2
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Dist: anyenv[httpx2]>=2.1.0
Requires-Dist: anyio>=4.0
Requires-Dist: httpx2>=2.16
Requires-Dist: pydantic>=2.14
Requires-Dist: structlog>=25.0
Requires-Dist: upathtools>=1.20
Requires-Dist: starlette ; extra == 'bridge'
Requires-Dist: uvicorn ; extra == 'bridge'
Requires-Dist: websockets ; extra == 'bridge'
Requires-Dist: fastapi ; extra == 'debug'
Requires-Dist: uvicorn ; extra == 'debug'
Requires-Dist: httpx2[http2] ; extra == 'http2'
Requires-Dist: logfire ; extra == 'tracing'
Requires-Dist: websockets ; extra == 'websocket'
Requires-Python: >=3.14
Project-URL: Code coverage, https://app.codecov.io/gh/phil65/aclientp
Project-URL: Documentation, https://phil65.github.io/aclientp/
Project-URL: Issues, https://github.com/phil65/aclientp/issues
Project-URL: Source, https://github.com/phil65/aclientp
Project-URL: Spec: ACP schema releases, https://github.com/agentclientprotocol/agent-client-protocol/releases
Project-URL: Spec: Agent Client Protocol, https://agentclientprotocol.com
Provides-Extra: bridge
Provides-Extra: debug
Provides-Extra: http2
Provides-Extra: tracing
Provides-Extra: websocket
Description-Content-Type: text/markdown

# AClientP

[![PyPI License](https://img.shields.io/pypi/l/aclientp.svg)](https://pypi.org/project/aclientp/)
[![Package status](https://img.shields.io/pypi/status/aclientp.svg)](https://pypi.org/project/aclientp/)
[![Monthly downloads](https://img.shields.io/pypi/dm/aclientp.svg)](https://pypi.org/project/aclientp/)
[![Distribution format](https://img.shields.io/pypi/format/aclientp.svg)](https://pypi.org/project/aclientp/)
[![Wheel availability](https://img.shields.io/pypi/wheel/aclientp.svg)](https://pypi.org/project/aclientp/)
[![Python version](https://img.shields.io/pypi/pyversions/aclientp.svg)](https://pypi.org/project/aclientp/)
[![Implementation](https://img.shields.io/pypi/implementation/aclientp.svg)](https://pypi.org/project/aclientp/)
[![Releases](https://img.shields.io/github/downloads/phil65/aclientp/total.svg)](https://github.com/phil65/aclientp/releases)
[![Github Contributors](https://img.shields.io/github/contributors/phil65/aclientp)](https://github.com/phil65/aclientp/graphs/contributors)
[![Github Forks](https://img.shields.io/github/forks/phil65/aclientp)](https://github.com/phil65/aclientp/forks)
[![Github Issues](https://img.shields.io/github/issues/phil65/aclientp)](https://github.com/phil65/aclientp/issues)
[![Github Issues](https://img.shields.io/github/issues-pr/phil65/aclientp)](https://github.com/phil65/aclientp/pulls)
[![Github Watchers](https://img.shields.io/github/watchers/phil65/aclientp)](https://github.com/phil65/aclientp/watchers)
[![Github Stars](https://img.shields.io/github/stars/phil65/aclientp)](https://github.com/phil65/aclientp/stars)
[![Github Repository size](https://img.shields.io/github/repo-size/phil65/aclientp)](https://github.com/phil65/aclientp)
[![Github last commit](https://img.shields.io/github/last-commit/phil65/aclientp)](https://github.com/phil65/aclientp/commits)
[![Github release date](https://img.shields.io/github/release-date/phil65/aclientp)](https://github.com/phil65/aclientp/releases)
[![Github language count](https://img.shields.io/github/languages/count/phil65/aclientp)](https://github.com/phil65/aclientp)
[![Github commits this month](https://img.shields.io/github/commit-activity/m/phil65/aclientp)](https://github.com/phil65/aclientp)
[![Package status](https://codecov.io/gh/phil65/aclientp/branch/main/graph/badge.svg)](https://codecov.io/gh/phil65/aclientp/)
[![PyUp](https://pyup.io/repos/github/phil65/aclientp/shield.svg)](https://pyup.io/repos/github/phil65/aclientp/)

[Read the documentation!](https://phil65.github.io/aclientp/)

**AClientP** implements the [Agent Client Protocol](https://agentclientprotocol.com)
(ACP, the protocol between code editors and AI coding agents) in typed Python: both
the agent and the client side, for the released **v1** protocol and the **draft v2**.

The name sets it apart from the other "ACP"s (Agent Communication Protocol,
Agent Connect Protocol, Agentic Commerce Protocol): **a**gent **client** **p**rotocol.

## Why another ACP library?

- **Checked against upstream.** The models are hand-written, but every release pins
  an upstream schema release (`schema/v1`, `schema/v2`) and a conformance check
  compares the models with it: fields, required/optional, nullability, limits, enums,
  union variants and methods. Known differences are documented with a reason.
- **v1 and v2.** v2 lives next to v1 (`aclientp.schema.v2`, `aclientp.v2`), and
  `RoutedAgentConnection` serves a client with the v1 or v2 agent, chosen by its
  `initialize` request, like the official TypeScript SDK's router.
- **Typed throughout.** Pydantic models, `mypy --strict`, discriminated unions with
  fallback variants that keep unknown fields (so custom and future messages survive a
  round trip).
- **Small core.** pydantic, anyio, anyenv, httpx2, structlog and upathtools; web
  servers, WebSockets and tracing are extras.

## Installation

```bash
uv add aclientp
```

| Extra | Adds |
| --- | --- |
| `websocket` | WebSocket transport |
| `http2` | HTTP/2 for the Streamable HTTP client |
| `bridge` | HTTP server transport, `aclientp-bridge`: expose a stdio agent over HTTP / WebSocket |
| `debug` | `aclientp-debug-server`: a mock agent with a web UI |
| `tracing` | logfire spans for handled requests |

## Quick start

### A v1 agent over stdio

```python
import anyio

from aclientp import Agent, run_agent
from aclientp.schema import (
    InitializeRequest,
    InitializeResponse,
    NewSessionRequest,
    NewSessionResponse,
    PromptRequest,
    PromptResponse,
)


class EchoAgent(Agent):
    async def initialize(self, params: InitializeRequest) -> InitializeResponse:
        return InitializeResponse(protocol_version=1)

    async def new_session(self, params: NewSessionRequest) -> NewSessionResponse:
        return NewSessionResponse(session_id="session-1")

    async def prompt(self, params: PromptRequest) -> PromptResponse:
        return PromptResponse(stop_reason="end_turn")


anyio.run(run_agent, EchoAgent())
```

### Serving v1 and v2

```python
from aclientp.router import RoutedAgentConnection
from aclientp.stdio import stdio_streams


async def main() -> None:
    stdin, stdout = await stdio_streams()
    conn = RoutedAgentConnection(stdout, stdin, v1=MyV1Agent(), v2=MyV2Agent)
    await conn.wait_closed()
```

A v2 agent subclasses `aclientp.v2.agent.Agent` and overrides the methods it supports;
the rest answer `-32601`. v2 models follow the v2 patch rules: optional fields default
to `MISSING` and are left out, `None` is sent as `null`. Serialize with `to_wire` and
test fields with `is_set` (`MISSING` is truthy).

A v2 client subclasses `aclientp.v2.client.Client` and talks through
`aclientp.v2.client.ClientSideConnection`:

- `initialize` raises `ProtocolVersionError` (with `.received` and the raw `.result`)
  when the agent answers with another protocol version, e.g. a v1-only agent.
- Every typed call raises `InvalidResponseError` (a `RequestError`, code `-32603`, with
  `.method`, `.errors` and the `pydantic.ValidationError` as `__cause__`) when the peer's
  result does not match the method's schema. The agent side's calls to the client do the
  same.
- Custom (`_`-prefixed) methods and notifications take and return `JsonValue` on both
  sides; omitted params arrive as `None`.
- `supports(capabilities, "session.systemPrompt.mode.override")` tests a capability
  marker by its dotted camelCase path (omitted or `null` anywhere on the path means
  unsupported).

A v2 agent that advertises `capabilities.session` MUST deduplicate `session/prompt`
retries by `idempotencyKey`: see [Prompt retries](#prompt-retries-v2-idempotency-keys).

`spawn_stdio_transport` always reads a piped stderr in the background, so an agent
can never block on a full pipe: pass `on_stderr=` for the lines (or `log_stderr=True`),
otherwise they are discarded. To read stderr yourself, pass another `stderr=`.

### Remote agents over Streamable HTTP (experimental)

`connect_remote_transport` is the client side of ACP's remote transports (the
"Streamable HTTP & WebSocket Transport" RFD), compatible with the TypeScript SDK's
experimental server: `http(s)://` URLs use Streamable HTTP (`connect_http_transport`),
`ws(s)://` URLs the WebSocket transport (`connect_websocket_transport`, needs the
`websocket` extra). It yields byte streams like a stdio agent's:

```python
from aclientp import connect_remote_transport
from aclientp.client.connection import ClientSideConnection


async with connect_remote_transport(url, headers={"X-API-Key": key}) as (reader, writer):
    conn = ClientSideConnection(lambda agent: MyClient(), writer, reader)
    await conn.initialize(InitializeRequest(protocol_version=1))
```

Serving an agent the same way (Streamable HTTP and WebSocket on one endpoint, compatible
with the TypeScript SDK's experimental clients):

```python
from aclientp import HttpTransport, serve
from aclientp.server_auth import bearer_token_auth


auth = bearer_token_auth(token)
await serve(lambda conn: MyAgent(conn), HttpTransport(host="0.0.0.0", port=8765, authenticate=auth))
```

`WebSocketTransport(host=..., port=..., authenticate=auth)` serves plain WebSocket (any
path, one JSON-RPC message per text frame).

Agents run tools on the serving machine, so every server (both transports and the
bridges) checks the handshake before any ACP message (`aclientp.server_auth`):

- Off loopback it refuses to start without `authenticate` (`InsecureServerError`; pass
  `allow_unauthenticated=True` behind an authenticating proxy). Callers it rejects get
  401. Tokens travel as `Authorization: Bearer <token>`, for WebSocket on the upgrade
  request (`connect_remote_transport(url, headers=...)`); query parameters are not
  accepted.
- Requests with an `Origin` header (browsers) get 403 unless the origin is in
  `allow_origins` (`"*"`: any). Browsers apply no CORS to WebSockets, so without this
  any web page could drive a local agent. Requests without `Origin` pass. Browsers
  cannot set headers on a WebSocket: browser clients use Streamable HTTP.

`aclientp-bridge -- my-agent --flag` serves a stdio agent this way, one subprocess per
connection (`--token` or `ACP_BRIDGE_TOKEN`, `--allow-origin`).

For clients that only launch local agents, `aclientp-connect` relays stdio to a remote
agent (either transport, by URL scheme). Header values may reference environment
variables:

```json
{
  "command": "uvx",
  "args": ["--from", "aclientp[http2]", "aclientp-connect", "https://example.com/api/acp",
           "-H", "X-API-Key: ${MY_API_KEY}"],
  "env": { "MY_API_KEY": "..." }
}
```

## Prompt retries (v2 idempotency keys)

A v2 client sends the same `idempotencyKey` on every attempt of one `session/prompt`.
An agent advertising `capabilities.session` inserts at most one user message per key and
session, answers a retry with the original `messageId` and starts no second turn, and
recognizes the key as long as it keeps the message, across restarts. Invalid keys (empty,
over 255 characters, not a string) fail validation of `PromptRequest`, which the connection
answers with `-32602`.

`aclientp.v2.idempotency.IdempotencyStore` does the bookkeeping; give it a backend on your
session storage (anything with async `get(session_id, key)` and
`put(session_id, key, message_id)`; the default keeps records in memory):

```python
from aclientp.v2.idempotency import IdempotencyStore

store = IdempotencyStore(MySessionStorageBackend(storage))


async def prompt(self, params: PromptRequest) -> PromptResponse:
    async with store.claim(params.session_id, params.idempotency_key) as claim:
        if claim.message_id is not None:  # a retry: already inserted
            return PromptResponse(message_id=claim.message_id)
        message_id = insert_user_message(params)  # raising records nothing
        await claim.record(message_id)
    start_turn(params.session_id, message_id)
    return PromptResponse(message_id=message_id)
```

Attempts with the same key wait for each other, so a retry that arrives while the first
attempt is still inserting gets its `messageId` instead of inserting again.

## Message ordering

Incoming requests and notifications are handled concurrently, each in its own task,
started in the order they arrived. One guarantee holds on both sides (client and agent)
and for every transport, since they all feed the same connection:

**A request returns, or raises the peer's error, only once the notifications received
before its response have been handled.** What the peer sent before answering (a turn's
or a replay's updates, the first updates of a new session, a `session/cancel` before a
permission answer) is visible when the call returns.

- Not waited for: the notification the calling task itself is handling (a notification
  handler that sends a request does not wait for itself), and notifications received
  after the response.
- "Received" is the order the connection reads messages in. stdio and WebSocket keep
  the sender's order; over Streamable HTTP, messages on different SSE streams (e.g. a
  `session/load` answered on the connection stream while its replay goes to the
  session stream) arrive in the order the network delivers them.
- A notification handler must not wait for something the caller of a later request
  only does after that request returns: that would deadlock.

`Connection.wait_for_notifications()` still waits for everything received so far.

## Staying in sync with upstream

```bash
uv run python -m aclientp.schema_reference latest           # pinned vs newest tag
uv run python -m aclientp.schema_reference sync --dry-run   # changelog of the newest tag
uv run python -m aclientp.schema_reference sync             # pin it
uv run python -m aclientp.schema_reference check            # models vs pinned schema
uv run python -m aclientp.schema_reference refs             # changes in reference implementations
```

Use `--protocol 2` for v2, and `check --root DIR` to check against another directory of
references (e.g. a downloaded tag). The check compares fields, required/optional,
nullability, limits (also behind `$ref`s), enums, union variants and methods, and probes
`not` and `if`/`then` constraints with payloads upstream rejects (the models must reject
them too). `schema/<version>/conformance.toml` lists renames and known differences; the
test suite runs the same check, so undocumented drift fails CI.
`schema/references.toml` pins reference implementations (the official TypeScript SDK
and claude-agent-acp) by commit; `refs` lists the upstream commits since each pin with
a compare link.

The official Python SDK is pinned in `schema/references.toml` as well (last reviewed
`9aedba3`, 2026-11-25): `refs` lists its commits since, so check them for bug fixes
(transport, connection lifecycle, deserialization) when moving schema pins. Moving the
pin with `refs --update python-sdk` records the next review.

### Lenient deserialization

The schema marks fields whose bad values must not fail a whole message
(`x-deserialize-default-on-error`, `-skip-invalid-items`, `-default-on-null`). The
models carry matching markers from `aclientp.schema.lenient` (`DefaultOnError`,
`SkipInvalidItems`, `DefaultOnNull`), so a message from a newer peer still parses: an
unknown tool kind or status, a malformed `_meta`, an unknown content block, config
option or auth method type is replaced by the default or dropped, not the whole
`session/update`, `session/new` or `initialize`. Invalid model instances built by local
code still raise. The check compares the markers with the annotations, so new ones
upstream show up as drift.

## Status

v1 follows `schema-v1.35.0`, v2 follows the draft `schema-v2.0.0-beta.4` (pinned in
`schema/v1/VERSION` and `schema/v2/VERSION`). The v2 API is **unstable** and follows the
draft as it changes.
