From 4a8b35d8dc288d19f05b2041659fc8afc6e054c5 Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Sat, 28 Nov 2026 13:09:13 +0800 Subject: [PATCH 1/3] docs: redesign README and reorganize documentation --- README.md | 160 +++++++++++++------ docs/contrib.md | 49 ++---- docs/experimental-v2.md | 132 ++++++--------- docs/index.md | 77 ++++----- docs/protocol-features.md | 113 +++++++++++++ docs/quickstart.md | 328 +++++++------------------------------- docs/releasing.md | 61 ++++--- docs/testing.md | 78 +++++++++ docs/use-cases.md | 29 ++-- docs/web-transport.md | 219 +++++++------------------ mkdocs.yml | 27 ++-- pyproject.toml | 2 +- 12 files changed, 575 insertions(+), 700 deletions(-) create mode 100644 docs/protocol-features.md create mode 100644 docs/testing.md diff --git a/README.md b/README.md index b8aaac8a..8af5cddc 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,16 @@ Agent Client Protocol -# Agent Client Protocol (Python) +# Agent Client Protocol — Python SDK -Build ACP-compliant agents and clients in Python with generated schema models, asyncio transports, and runnable demos. +[![PyPI](https://img.shields.io/pypi/v/agent-client-protocol)](https://pypi.org/project/agent-client-protocol/) +[![Python](https://img.shields.io/pypi/pyversions/agent-client-protocol)](https://pypi.org/project/agent-client-protocol/) +[![CI](https://github.com/agentclientprotocol/python-sdk/actions/workflows/main.yml/badge.svg)](https://github.com/agentclientprotocol/python-sdk/actions/workflows/main.yml) +[![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://agentclientprotocol.github.io/python-sdk/) -> Releases track the upstream ACP schema; contributions that tighten coverage or tooling are always welcome. +Python SDK for building [Agent Client Protocol (ACP)](https://agentclientprotocol.com/) agents and clients with generated Pydantic v2 models, asyncio JSON-RPC transports, and runnable examples. -## Install +## Installation ```bash pip install agent-client-protocol @@ -16,60 +19,123 @@ pip install agent-client-protocol uv add agent-client-protocol ``` -## At a glance +Optional extras: -- **Spec parity:** Generated Pydantic models in `acp.schema` track every ACP release so payloads stay valid. -- **Direct construction:** Generated discriminator fields have defaults, so models can be instantiated directly. -- **Runtime ergonomics:** Async base classes, stdio JSON-RPC plumbing, and lifecycle helpers keep custom agents tiny. -- **Examples ready:** Streaming, permissions, Gemini bridge, and duet demos live under `examples/`. -- **Contrib utilities:** Session accumulators, tool call trackers, and permission brokers share patterns from real deployments. +```bash +# Streamable HTTP and WebSocket transports (experimental) +pip install "agent-client-protocol[http]" + +# Logfire / OpenTelemetry instrumentation +pip install "agent-client-protocol[logfire]" +``` + +Requires Python 3.10–3.15. + +## Quick example + +### Build an agent + +```python +import asyncio +from typing import Any +from uuid import uuid4 + +from acp import PROTOCOL_VERSION, Agent, InitializeResponse, NewSessionResponse, PromptResponse, run_agent +from acp.interfaces import Client +from acp.schema import AgentMessageChunk, TextContentBlock + + +class EchoAgent(Agent): + def on_connect(self, conn: Client) -> None: + self._conn = conn -## Who benefits + async def initialize(self, protocol_version: int, **kwargs: Any) -> InitializeResponse: + return InitializeResponse(protocol_version=PROTOCOL_VERSION) -- Agent authors who need typed models and event-stream ergonomics for ACP-compatible assistants. -- Client integrators embedding ACP parties inside Python applications or wrapping existing CLIs via stdio. -- Tooling teams experimenting with permission flows, streaming UX, or Gemini bridges without re-implementing transports. -See real adopters like kimi-cli in the [Use Cases list](https://agentclientprotocol.github.io/python-sdk/use-cases/). + async def new_session(self, cwd: str, **kwargs: Any) -> NewSessionResponse: + return NewSessionResponse(session_id=uuid4().hex) -## How to get started + async def prompt(self, session_id: str, prompt: list[Any], **kwargs: Any) -> PromptResponse: + for block in prompt: + text = getattr(block, "text", "") + await self._conn.session_update( + session_id=session_id, + update=AgentMessageChunk(content=TextContentBlock(text=text)), + ) + return PromptResponse(stop_reason="end_turn") -- Follow the [Quickstart guide](https://agentclientprotocol.github.io/python-sdk/quickstart/) for installation, echo-agent validation, editor wiring (e.g. Zed), and programmatic launch recipes. -- Browse the [example gallery](https://github.com/agentclientprotocol/python-sdk/tree/main/examples) to see progressively richer integrations you can copy or extend. -- Skim the [docs hub](https://agentclientprotocol.github.io/python-sdk/) for focused references on contrib helpers, releasing, and transport details. -## Quick links +if __name__ == "__main__": + asyncio.run(run_agent(EchoAgent())) +``` + +### Connect from a client + +```python +import asyncio +import sys +from typing import Any + +from acp import PROTOCOL_VERSION, Client, spawn_agent_process +from acp.schema import TextContentBlock + -| Need | Link | -|--------------------|------------------------------------------------------------------------| -| Docs hub | | -| Quickstart | | -| Use cases | | -| Contrib helpers | | -| Releasing workflow | | -| Examples | | -| Tests | | -| PyPI | | +class SimpleClient(Client): + async def session_update(self, session_id: str, update: Any, **kwargs: Any) -> None: + print(session_id, update) -## Project layout -- `src/acp/`: runtime package (agents, clients, transports, schema bindings, contrib utilities) -- `schema/`: upstream JSON schema sources (regenerate via `make gen-all`) -- `docs/`: MkDocs content backing the published documentation -- `examples/`: runnable scripts covering stdio orchestration patterns -- `tests/`: pytest suite with golden fixtures and optional Gemini coverage +async def main() -> None: + async with spawn_agent_process(SimpleClient(), sys.executable, "examples/echo_agent.py") as (conn, _proc): + await conn.initialize(protocol_version=PROTOCOL_VERSION) + session = await conn.new_session(cwd=".", mcp_servers=[]) + await conn.prompt(session_id=session.session_id, prompt=[TextContentBlock(text="Hello ACP!")]) -## Developer commands -- `make install` provisions the `uv` virtualenv and installs pre-commit hooks. -- `make check` runs Ruff formatting/linting, type analysis, dependency hygiene, and lock verification. -- `make test` executes `pytest` (with doctests) inside the managed environment. -- `ACP_SCHEMA_VERSION= make gen-all` refreshes protocol artifacts when the schema advances. +asyncio.run(main()) +``` + +## Protocol and transport support + +| Capability | Import / Extra | Status | Reference | +| --- | --- | --- | --- | +| ACP v1 (`schema-v1.35.0`) | `acp`, `acp.schema` | Stable | [Quickstart](https://agentclientprotocol.github.io/python-sdk/quickstart/) · [Protocol Features](https://agentclientprotocol.github.io/python-sdk/protocol-features/) | +| ACP v2 (`schema-v2.0.0-beta.4`) + dual-stack router | `acp.experimental.v2`, `acp.experimental.AgentProtocolRouter` | Preview | [Experimental v2](https://agentclientprotocol.github.io/python-sdk/experimental-v2/) | +| Stdio JSON-RPC (NDJSON) | Built-in (`run_agent`, `connect_to_agent`, `spawn_agent_process`) | Stable | [Quickstart](https://agentclientprotocol.github.io/python-sdk/quickstart/) | +| Streamable HTTP & WebSocket | `acp.http`, `acp.ws` (`[http]`) | Experimental | [Web Transport](https://agentclientprotocol.github.io/python-sdk/web-transport/) | +| Stateless MCP-over-ACP | `acp` / `acp.experimental.v2` | Unstable / Preview | [Protocol Features](https://agentclientprotocol.github.io/python-sdk/protocol-features/#stateless-mcp-over-acp) | +| Session, tool call, and permission helpers | `acp.contrib` | Experimental | [Contrib Utilities](https://agentclientprotocol.github.io/python-sdk/contrib/) | + +## Documentation + +| Topic | Link | +| --- | --- | +| Documentation hub | | +| Quickstart | | +| Protocol features (v1) | | +| Web transport (HTTP & WebSocket) | | +| Experimental protocol v2 | | +| Contrib utilities | | +| Use cases | | +| Testing & conformance | | +| Releasing | | +| Runnable examples | | + +## Development + +```bash +make install # Create uv environment and install pre-commit hooks +make check # Lockfile check, Ruff lint/format, ty type check, deptry +make test # Run pytest with doctests +make gen-check # Verify generated schema bindings match schema/ +make docs-test # Build MkDocs site strictly +``` -Keep docs and examples current whenever you ship public API or transport changes, and prefer Conventional Commits (`feat:`, `fix:`, etc.) when submitting patches. +To regenerate protocol bindings when upstream schemas advance, run `ACP_SCHEMA_VERSION= make gen-all` (or `make gen-v2` for v2). -## Community & support +## Community -- File issues or feature requests at . -- Discuss ideas or get help via GitHub Discussions: . -- Join the broader ACP conversations at , the Zed community channels, or the community Zulip: . -- Shared learnings, integrations, or third-party transports are welcome additions to the documentation—open a PR! +- Issues and pull requests: +- Discussions: +- ACP specification and ecosystem: +- Zulip chat: diff --git a/docs/contrib.md b/docs/contrib.md index d13b516a..db81aaf9 100644 --- a/docs/contrib.md +++ b/docs/contrib.md @@ -1,41 +1,26 @@ -# Experimental Contrib Modules +# Contrib Utilities -The helpers under `acp.contrib` package recurring patterns we saw in integrations such as Toad, kimi-cli, and Gemini. Keep in mind they are experimental—APIs can still shift as we learn. Use this page as a menu: +> **Experimental.** Modules under `acp.contrib` package opt-in stateful helpers for common client and agent workflows. Their APIs may evolve across releases. -- **`session_state.SessionAccumulator`** — build a canonical, immutable snapshot of every session update so UIs can render tool calls and plans without re-implementing state machines. -- **`tool_calls.ToolCallTracker` + `permissions.PermissionBroker`** — coordinate streamed tool call updates and permission prompts from one place. +## Available helpers -## SessionAccumulator (`acp.contrib.session_state`) +- **`acp.contrib.session_state.SessionAccumulator`** — aggregates incoming `SessionNotification` updates into immutable `SessionSnapshot` models for UI rendering. +- **`acp.contrib.tool_calls.ToolCallTracker`** — tracks active tool call lifecycles and emits canonical `ToolCallStart` / `ToolCallProgress` updates. +- **`acp.contrib.permissions.PermissionBroker`** — coordinates `request_permission` prompts using tracked tool call state and default approve/reject options. -**Use it when:** you need a live, merged view of `SessionNotification` events (e.g. tool calls, plan entries, user/agent messages) to drive UI widgets. +## `SessionAccumulator` (`acp.contrib.session_state`) -**Key capabilities** +Feed raw `SessionNotification` events into one accumulator per UI controller and render from immutable snapshots: -- `SessionAccumulator.apply(notification)` reconciles `tool_call` and `tool_call_update` payloads, even if the start event arrives late. -- `snapshot()` returns an immutable `SessionSnapshot` Pydantic model containing the plan, current mode, commands, and ordered message history. -- Raw tool input/output payloads are copied when applying notifications and creating snapshots, so nested payload mutations do not change the accumulated state. -- `subscribe(callback)` lets you push snapshots into stores or UI components whenever state changes. -- Automatic reset on session-change (toggle with `auto_reset_on_session_change`). +- `apply(notification)` merges message chunks, plan updates, mode/config changes, and `tool_call` / `tool_call_update` payloads (including out-of-order updates). +- `snapshot()` returns an immutable `SessionSnapshot` Pydantic model with copied tool input/output payloads. +- `subscribe(callback)` pushes updated snapshots to subscribers whenever state changes. +- `auto_reset_on_session_change` resets accumulated state automatically when a new `session_id` arrives. -> Tip: Create one accumulator per UI controller. Feed every raw `SessionNotification` into it and render from `snapshot.tool_calls` / `snapshot.user_messages` instead of mutating state manually. +## `ToolCallTracker` and `PermissionBroker` (`acp.contrib.tool_calls`, `acp.contrib.permissions`) -## ToolCallTracker & PermissionBroker (`acp.contrib.tool_calls`, `acp.contrib.permissions`) +Share a single `ToolCallTracker` with `PermissionBroker` in your agent loop to keep tool updates and permission requests synchronized: -**Use them when:** your agent runtime synthesises tool call IDs, streams arguments, and prompts the user for approval. The helpers centralise the bookkeeping so you don’t juggle raw Pydantic models. - -- `ToolCallTracker.start()/progress()/append_stream_text()` emits canonical `ToolCallStart` / `ToolCallProgress` updates and keeps an in-memory view via `view()` or `tool_call_model()`. -- `PermissionBroker.request_for()` wraps `requestPermission` RPCs. It reuses tracker state (or a provided `ToolCall`), lets you append extra content, and defaults to Approve / Approve for session / Reject options. -- Omit `options` or pass `None` to use broker defaults. An explicit empty option list raises `MissingPermissionOptionsError` before the permission request is sent; the same applies to empty `default_options` when no per-request options are supplied. -- `default_permission_options()` exposes that canonical option triple if you need to customise it. - -> Tip: Keep one tracker near the agent event loop. Emit notifications through it and share the tracker with `PermissionBroker` so permission prompts always match the latest tool call state. - -## Design Guardrails - -To stay aligned with the ACP schema, the contrib layer follows a few rules: - -- Schema data classes continue to live in `acp.schema`. Contrib helpers clone them with `.model_copy(deep=True)` before mutation. -- The core runtime never imports contrib modules implicitly—you opt in when they help. -- Helpers focus on painful bookkeeping (tool call aggregation, permission UX) and leave product-specific policy to your application. - -Try the contrib modules, then open an issue or PR with feedback so we know which APIs should graduate into the stable surface. +- `ToolCallTracker.start()`, `progress()`, and `append_stream_text()` emit `ToolCallStart` and `ToolCallProgress` updates while maintaining an in-memory view via `view()` and `tool_call_model()`. +- `PermissionBroker.request_for()` builds and sends `request_permission` calls using tracked tool call state (or an explicit `ToolCall`) and optional extra content blocks. +- `default_permission_options()` provides the standard **Approve**, **Approve for session**, and **Reject** option triple. Omitting `options` or passing `None` applies the broker's defaults; passing an empty list raises `MissingPermissionOptionsError` before sending the request. diff --git a/docs/experimental-v2.md b/docs/experimental-v2.md index 693f795e..9680bad7 100644 --- a/docs/experimental-v2.md +++ b/docs/experimental-v2.md @@ -1,27 +1,24 @@ # Experimental Protocol v2 -> **Experimental.** Protocol v2 is in preview. Import it from `acp.experimental` -> and expect its API and generated models to change with the upstream schema. +> **Preview.** Protocol v2 lives under `acp.experimental` and tracks upstream beta releases. Its API and generated models evolve alongside the v2 specification. -The bindings use [`schema-v2.0.0-beta.4`](https://github.com/agentclientprotocol/agent-client-protocol/releases/tag/schema-v2.0.0-beta.4). -The upstream schema removes Next Edit Suggestions (`nes/*`) and the associated -document notifications from v2. +The v2 bindings target [`schema-v2.0.0-beta.4`](https://github.com/agentclientprotocol/agent-client-protocol/releases/tag/schema-v2.0.0-beta.4). Connection methods and agent/client handlers accept expanded snake_case parameters, responses and nested payloads use `acp.experimental.v2.schema` models, and extra keyword arguments serialize into `_meta`. -The v2 runtime is separate from the stable v1 API. Like v1, connection methods -and agent/client handlers accept expanded, snake-case parameters. Responses and -nested values (content blocks, updates, capabilities) use `v2.schema` models. -Extra keyword arguments carry request `_meta`. +## Client usage -Install update handlers before opening a session because updates are independent -connection traffic: +Register your `session_update` handler before opening a session so incoming updates are captured as soon as session traffic starts: ```python from typing import Any from acp.experimental import v2 + class MyClient(v2.Client): async def session_update( - self, session_id: str, update: v2.schema.SessionUpdate, **kwargs: Any, + self, + session_id: str, + update: v2.schema.SessionUpdate, + **kwargs: Any, ) -> None: handle_update(session_id, update) @@ -38,9 +35,15 @@ accepted = await connection.prompt( ) ``` -Implement an agent with the same expanded handler style: +## Agent usage + +Implement the methods your agent supports (subclassing `v2.Agent` is optional) and start serving with `v2.run_agent()`: ```python +from typing import Any +from acp.experimental import v2 + + class MyAgent(v2.Agent): async def initialize( self, @@ -68,65 +71,44 @@ class MyAgent(v2.Agent): await v2.run_agent(MyAgent()) ``` -`v2.Agent` and `v2.Client` describe the v2 handler signatures; subclassing is -optional. Implement only the methods you support. Unimplemented requests return -method-not-found, and unimplemented notifications are ignored. The v2 protocols -are separate from v1 because initialization, prompt responses, permissions, and -session updates have different contracts. Both versions use `param_model` -metadata to derive their routes. V2 retains strict request/response validation -and requires successful initialization before other traffic. +Unimplemented request handlers return JSON-RPC method-not-found (`-32601`), and unimplemented notifications are ignored. V2 connections require a successful `initialize` handshake before processing other methods and enforce strict request/response validation. -Previously, v2 methods accepted a whole request model. Replace -`connection.new_session(v2.schema.NewSessionRequest(cwd="/workspace"))` with -`connection.new_session(cwd="/workspace")`, and expand handler parameters likewise. +## Union requests -Union requests also use expanded parameters: +Config options and elicitation requests use expanded parameters: ```python +# `type` defaults to "boolean" for bool values and "id" otherwise. await connection.set_config_option(config_id="thinking", session_id=session.session_id, value=True) -# type defaults to "boolean" for bool values and "id" otherwise. await connection.set_config_option( - config_id="vendor/limit", session_id=session.session_id, value=10, type="vendor/number", + config_id="vendor/limit", + session_id=session.session_id, + value=10, + type="vendor/number", ) + await agent_connection.create_elicitation( - message="Sign in", mode="url", session_id=session.session_id, - elicitation_id="sign-in-1", url="https://example.com/login", + message="Sign in", + mode="url", + session_id=session.session_id, + elicitation_id="sign-in-1", + url="https://example.com/login", ) ``` -For elicitation, pass either `session_id` for session scope or a string or integer -`request_id` for request scope. Pass `requested_schema` for form mode, -or `elicitation_id` and `url` for URL mode. Handlers receive the validated -branch's fields, including `type` for config options and `mode` for elicitation. - -`session/prompt` returns after the agent inserts the user message into the ACP -conversation, without waiting for processing to finish. Callers can pass a -bounded `idempotency_key` (1–255 characters) so retries of the same submission -return the original `message_id` instead of inserting a duplicate. The response -requires a non-null `message_id`. Agents return `v2.schema.PromptResponse(message_id=...)` -and echo the user message in a `UserMessageUpdate` or `UserMessageChunk` carrying -the same ID. That update may arrive before or after the response; use -`accepted.message_id` to match it. Other session updates are independent traffic -and do not carry a prompt identifier. - -Agents can send `v2.schema.SessionNotice(severity="warning", title="Context is nearly full")` -with `await agent_connection.session_update(session_id=session_id, update=notice)`. V2 notices require no client capability and -are live advisory events, outside retained session history. Clients may ignore -them. Titles must be non-empty, and severity also accepts custom or future strings. - -For patch fields in session updates, omit a field to leave its current -value unchanged, or explicitly pass `None` to clear it. For example, -`v2.schema.SessionToolCallUpdate(tool_call_id="tool-1", name=None)` clears the -tool name, while omitting `name` leaves it unchanged. This also applies to -terminal updates and patch metadata. When applying received patches, use -`update.model_dump(by_alias=True, exclude_unset=True)` to retain that distinction. - -Setting `replay_from=v2.schema.ReplayFromStartVariant()` on `connection.resume_session(...)` -requests all retained conversation history; agents need not retain every message. -Accepted elicitation content preserves scalar values, string lists, and any -custom or extension JSON values. - -Agents that serve both versions use `AgentProtocolRouter`: +For `create_elicitation`, pass `session_id` for session scope or a string/integer `request_id` for request scope. Pass `requested_schema` for form mode, or `elicitation_id` and `url` for URL mode. Accepted elicitation content preserves scalars, string lists, and custom JSON values. + +## Prompts, updates, notices, and replay + +- **Prompt submission**: `session/prompt` returns `PromptResponse(message_id=...)` once the user message is accepted into the conversation, allowing independent streaming updates. Pass `idempotency_key` (1–255 characters) so retried submissions return the original `message_id`. Agents echo the user message in a `UserMessageUpdate` or `UserMessageChunk` carrying `accepted.message_id`. +- **Session notices**: Agents can emit live advisory events via `v2.schema.SessionNotice(severity="warning", title="Context is nearly full")` with `agent_connection.session_update(...)`. Titles must be non-empty; severity accepts standard and custom string values. +- **Patch semantics**: In patch updates such as `SessionToolCallUpdate` and `SessionTerminalUpdate`, omit a field to leave its current value unchanged, or pass `None` to clear it. Call `update.model_dump(by_alias=True, exclude_unset=True)` to preserve that distinction when applying patches. +- **Replay on resume**: Pass `replay_from=v2.schema.ReplayFromStartVariant()` to `connection.resume_session(...)` to request retained conversation history. +- **Reusable union aliases**: `v2.schema` exports `SessionUpdate`, `ContentBlock`, `StateUpdate`, `BackgroundWork`, and `AvailableCommand` for type annotations and validation. + +## Dual-stack v1/v2 negotiation + +Use `AgentProtocolRouter` to serve both protocol versions on the same endpoint (stdio, HTTP, or WebSocket): ```python from acp.experimental import AgentProtocolRouter @@ -138,35 +120,19 @@ router = AgentProtocolRouter( await router.run() ``` -The selected factory is called once per connection. Return a fresh agent from -each call to avoid sharing connection state. +The selected factory runs once per connection and should return a fresh agent instance. When an agent configured with v1 receives a v2 `initialize` request, the router translates the common initialization fields and negotiates down to v1; once negotiated, the connection enforces the selected protocol version strictly. -Extension method names are explicit and must include the protocol-required `_` -prefix: +## Extension methods and cancellation + +Extension method names carry the protocol-required `_` prefix: ```python result = await connection.send_extension_request("_vendor/method", {"value": 1}) await connection.send_extension_notification("_vendor/event", {"value": 1}) ``` -The selected runtime remains strict after initialization: v1 messages are not -accepted by a v2 connection, and v2 messages are not translated into v1 calls. -Only the initial v2 request is reduced to the common v1 initialization fields -when an agent selects v1. - -Client-side fallback is application controlled and may require opening a new -transport. Protocol-level request cancellation (`$/cancel_request`) is handled -by the shared connection layer, as in v1: cancelling the task awaiting a request -sends a best-effort cancellation to the peer, and an incoming cancellation -cancels the handler task, which answers with its result or `-32800`. -`session/cancel` remains available for cancelling active session work. +Protocol-level request cancellation (`$/cancel_request`) cancels the running handler task (answering with its return value if caught, or `-32800` otherwise), and cancelling a task awaiting an outgoing request sends a best-effort `$/cancel_request`. Use `connection.cancel_session(session_id=...)` to stop active session work. ## Stateless MCP-over-ACP -V2 uses the same [stateless MCP binding](quickstart.md#stateless-mcp-over-acp) -as v1. Use the independent `v2.schema.McpResultResponse`, `McpErrorResponse`, -`McpError`, and `MessageMcpResponse` types. The agent advertises support with -`capabilities.session.mcp.acp = {}`; omission or null does not advertise support. -After ACP initialization, agents send `mcp_message` requests and providers send -`notify_mcp` notifications with explicit `server_id` and `request_id` strings. -The old MCP connect/disconnect methods and reverse requests are removed. +V2 uses the same [stateless MCP binding](protocol-features.md#stateless-mcp-over-acp) with `v2.schema.McpResultResponse`, `McpErrorResponse`, `McpError`, and `MessageMcpResponse`. Agents advertise support via `capabilities.session.mcp.acp = {}`, send `mcp_message` requests with explicit `server_id` and `request_id` strings, and receive provider notifications through `notify_mcp`. diff --git a/docs/index.md b/docs/index.md index ba1c710b..4330f22b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -4,9 +4,9 @@ # Agent Client Protocol SDK (Python) -Ship ACP-compatible agents and clients in Python without rebuilding JSON-RPC transports or schema models. This SDK mirrors each ACP release so your integrations stay interoperable with editors, CLIs, and hosted clients. +Build ACP-compliant agents and clients in Python using generated Pydantic v2 models, asyncio JSON-RPC transports, and typed protocol interfaces. -## Install & verify +## Installation ```bash pip install agent-client-protocol @@ -14,51 +14,36 @@ pip install agent-client-protocol uv add agent-client-protocol ``` -Next steps live in the [Quickstart](quickstart.md): launch the echo agent, wire it to Zed (or another ACP client), and exercise the programmatic spawn helpers. +Install optional extras when you need remote transports or telemetry: -## ACP at a glance - -- ACP is the stdio protocol that lets “clients” (editors, shells, CLIs) orchestrate AI “agents.” -- Sessions exchange structured payloads (`session/update`, permission prompts, tool calls) defined in the upstream schema. -- Matching the schema version keeps your Python integrations compatible with tools such as Zed, Gemini CLI, or kimi-cli. - -## SDK building blocks - -- `acp.schema`: generated Pydantic models with defaults for protocol discriminator fields. -- `acp.agent` / `acp.client`: async base classes, JSON-RPC supervision, and lifecycle orchestration. -- `acp.contrib`: experimental utilities (session accumulators, permission brokers, tool call trackers) harvested from production deployments. -- `examples/`: runnable agents, clients, duet demos, and the Gemini CLI bridge. +```bash +pip install "agent-client-protocol[http]" # Streamable HTTP + WebSocket +pip install "agent-client-protocol[logfire]" # Logfire / OpenTelemetry +``` -## Quick links +## SDK overview -| Need | Link | +| Module | Purpose | | --- | --- | -| Quickstart walkthrough | [quickstart.md](quickstart.md) | -| Real-world adopters | [use-cases.md](use-cases.md) | -| Contrib helpers | [contrib.md](contrib.md) | -| Releasing workflow | [releasing.md](releasing.md) | -| Upgrade to 0.11 | [migration-guide-0.11.md](migration-guide-0.11.md) | -| Example scripts | [github.com/agentclientprotocol/python-sdk/tree/main/examples](https://github.com/agentclientprotocol/python-sdk/tree/main/examples) | - -## Choose a path - -- **Just exploring?** Skim [use-cases.md](use-cases.md) to see how kimi-cli, agent-client-kernel, and others use the SDK. -- **Building agents?** Copy `examples/echo_agent.py` or `examples/agent.py`, then use the generated models directly. Use `acp.contrib` for permission workflows and other stateful patterns. -- **Embedding clients?** Start with `examples/client.py` or the `spawn_agent_process` / `spawn_client_process` helpers in the [Quickstart](quickstart.md#programmatic-launch). - -## Reference material - -- [Quickstart](quickstart.md) — installation, editor wiring, and programmatic launch walkthroughs. -- [Use Cases](use-cases.md) — real adopters with succinct descriptions of what they build. -- [Experimental Contrib](contrib.md) — deep dives on the `acp.contrib` utilities. -- [Releasing](releasing.md) — schema upgrade process, versioning policy, and publishing checklist. -- [0.11 Migration Guide](migration-guide-0.11.md) — interface signature updates, elicitation, and schema notes for 0.10 users. - -Need API-level details? Browse the source in `src/acp/` or generate docs with `mkdocstrings`. - -## Feedback & support - -- Open issues or discussions on GitHub for bugs, feature requests, or integration help. -- Join [GitHub Discussions](https://github.com/agentclientprotocol/python-sdk/discussions) to swap ideas. -- Chat with the community on [agentclientprotocol.zulipchat.com](https://agentclientprotocol.zulipchat.com/). -- Follow ACP roadmap updates at [agentclientprotocol.com](https://agentclientprotocol.com/). +| `acp` & `acp.schema` | Stable ACP v1 runtime (`run_agent`, `connect_to_agent`, `spawn_agent_process`, `Agent`, `Client`) and generated Pydantic models (`schema-v1.35.0`) | +| `acp.experimental.v2` | Preview ACP v2 runtime and generated models (`schema-v2.0.0-beta.4`), plus `AgentProtocolRouter` for dual-stack negotiation | +| `acp.http` & `acp.ws` | Experimental Streamable HTTP (SSE + HTTP/2) and WebSocket client/server transports (`[http]` extra) | +| `acp.contrib` | Experimental stateful helpers: `SessionAccumulator`, `ToolCallTracker`, and `PermissionBroker` | + +## Documentation guide + +- **[Quickstart](quickstart.md)** — Install the SDK, run the echo agent, connect from an ACP client, and launch processes programmatically. +- **[Protocol Features (v1)](protocol-features.md)** — Session management, authentication, providers, notices, elicitation, stateless MCP-over-ACP, request cancellation, and extension methods. +- **[Web Transport (HTTP & WebSocket)](web-transport.md)** — Serve and consume ACP over Streamable HTTP and WebSocket with Starlette and HTTP/2. +- **[Experimental Protocol v2](experimental-v2.md)** — Preview v2 API, expanded handlers, patch updates, replay cursors, and dual-stack routing. +- **[Contrib Utilities](contrib.md)** — Higher-level session state accumulators, tool call trackers, and permission brokers. +- **[Use Cases](use-cases.md)** — Production agents and clients built with the SDK. +- **[Testing & Conformance](testing.md)** — Local test suites, ACP TCK conformance profiles, cross-SDK interop, and real-world client/agent verification. +- **[Releasing](releasing.md)** — Schema upgrades, verification gates, and PyPI/docs release workflow. + +## Community + +- Issues and pull requests: [agentclientprotocol/python-sdk](https://github.com/agentclientprotocol/python-sdk) +- Discussions: [GitHub Discussions](https://github.com/agentclientprotocol/python-sdk/discussions) +- Community chat: [agentclientprotocol.zulipchat.com](https://agentclientprotocol.zulipchat.com/) +- Protocol specification: [agentclientprotocol.com](https://agentclientprotocol.com/) diff --git a/docs/protocol-features.md b/docs/protocol-features.md new file mode 100644 index 00000000..c838a1e5 --- /dev/null +++ b/docs/protocol-features.md @@ -0,0 +1,113 @@ +# Protocol Features (v1) + +The stable v1 bindings track [`schema-v1.35.0`](https://github.com/agentclientprotocol/agent-client-protocol/releases/tag/schema-v1.35.0). Both `Agent` and `Client` interfaces expose expanded snake_case parameters, with extra keyword arguments carrying JSON-RPC `_meta`. + +## Enabling unstable protocol methods + +Unstable methods require explicit opt-in on the receiving side by passing `use_unstable_protocol=True` to `run_agent()`, `connect_to_agent()`, `AgentSideConnection`, or `ClientSideConnection`. Check the peer's advertised capabilities from `initialize` before calling optional or unstable methods. Unimplemented request handlers return JSON-RPC method-not-found (`-32601`). + +### Agent methods + +| Wire method | Python method | Stability | +| --- | --- | --- | +| `initialize` | `initialize` | Stable | +| `authenticate`, `logout` | `authenticate`, `logout` | Stable | +| `session/new`, `session/load`, `session/list` | `new_session`, `load_session`, `list_sessions` | Stable | +| `session/resume`, `session/close`, `session/delete` | `resume_session`, `close_session`, `delete_session` | Stable | +| `session/set_mode`, `session/set_config_option` | `set_session_mode`, `set_config_option` | Stable | +| `session/prompt`, `session/cancel` | `prompt`, `cancel` | Stable | +| `session/fork` | `fork_session` | Unstable | +| `session/archive`, `session/unarchive` | `archive_session`, `unarchive_session` | Unstable | +| `session/status`, `session/options`, `session/set_title` | `session_status`, `session_options`, `set_session_title` | Unstable | +| `auth/status` | `auth_status` | Unstable | +| `providers/list`, `providers/set`, `providers/disable` | `list_providers`, `set_provider`, `disable_provider` | Unstable | +| `mcp/message` (notification) | `notify_mcp` | Unstable | + +### Client methods + +| Wire method | Python method | Stability | +| --- | --- | --- | +| `session/request_permission`, `session/update` | `request_permission`, `session_update` | Stable | +| `fs/read_text_file`, `fs/write_text_file` | `read_text_file`, `write_text_file` | Stable | +| `terminal/create`, `terminal/output`, `terminal/wait_for_exit`, `terminal/kill`, `terminal/release` | `create_terminal`, `terminal_output`, `wait_for_terminal_exit`, `kill_terminal`, `release_terminal` | Stable | +| `elicitation/create`, `elicitation/complete` | `create_elicitation`, `complete_elicitation` | Unstable | +| `auth/status_update` (notification) | `auth_status_update` | Unstable | +| `mcp/message` (request) | `mcp_message` | Unstable | + +For example, an agent supporting session deletion implements `delete_session`: + +```python +from typing import Any +from acp import DeleteSessionResponse + + +async def delete_session(self, session_id: str, **kwargs: Any) -> DeleteSessionResponse: + await self.session_store.delete(session_id) + return DeleteSessionResponse() +``` + +Clients invoke `await conn.delete_session(session_id=session_id)` to remove persisted session state, and `await conn.close_session(session_id=session_id)` to close an active session handle. + +## Session notices + +Clients that render live advisory notices advertise `ClientCapabilities(session=ClientSessionCapabilities(notices=NoticeCapabilities()))` during `initialize`. When that capability is advertised, agents can send `SessionUpdateNotice` updates: + +```python +from acp.schema import SessionUpdateNotice + +await client.session_update( + session_id=session_id, + update=SessionUpdateNotice( + severity="warning", + title="Context is nearly full", + description="Start a new session soon.", + ), +) +``` + +Notices are live advisory events outside retained session history. `title` must be non-empty; `severity` accepts `"info"`, `"warning"`, `"error"`, and custom string values. + +## Stateless MCP-over-ACP + +The unstable native MCP binding targets **MCP 2026-07-28**. A client/provider declares an `AcpMcpServer(name=..., server_id=...)` during session setup when the agent advertises `mcpCapabilities.acp`, after registering its `mcp_message` handler so immediate calls from the agent are served. + +Agents send `mcp_message` requests with a fresh string `request_id` per operation and the required MCP metadata in `params["_meta"]`: + +```python +from uuid import uuid4 +from acp import McpErrorResponse + +response = await conn.mcp_message( + server_id="project-tools", + request_id=uuid4().hex, + method="tools/list", + params={ + "_meta": { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {}, + }, + }, + trace="outer ACP metadata", +) +if isinstance(response, McpErrorResponse): + handle_mcp_error(response.error) +else: + use_mcp_result(response.result) +``` + +Providers answer with `McpResultResponse(result=...)` or `McpErrorResponse(error=McpError(code=..., message=...))`. Outer ACP transport or routing errors raise `RequestError`; inner MCP errors stay inside `McpErrorResponse.error`. While a request is active, providers can emit progress via `notify_mcp(server_id=..., request_id=..., method=..., params=...)` using matching IDs, stopping notifications before returning the final response. + +MCP-over-ACP works across stdio, Streamable HTTP, and WebSocket connections. Run `uv run python examples/mcp_over_acp.py` for a runnable demo, and see the [ACP MCP-over-ACP specification](https://agentclientprotocol.com/rfds/mcp-over-acp) for registration and error-code rules. + +## Request cancellation + +Connections handle the protocol's `$/cancel_request` notification automatically: + +- **Incoming cancellation**: The SDK cancels the asyncio task running the target handler. If the handler catches `asyncio.CancelledError` and returns a value, that result is sent to the peer; otherwise the peer receives `-32800` (`Request cancelled`). +- **Outgoing cancellation**: Cancelling the task awaiting an outgoing request (for example via `asyncio.wait_for`) raises `asyncio.CancelledError` locally and sends a best-effort `$/cancel_request` notification to the peer. + +Use `session/cancel` (`conn.cancel(session_id=...)`) to stop active work inside a session turn. + +## Extension methods + +Custom vendor methods use the `_` prefix required by ACP. Implement `ext_method(self, method: str, params: dict[str, Any])` and `ext_notification(self, method: str, params: dict[str, Any])` on your `Agent` or `Client` to handle incoming extension traffic, and call `conn.ext_method(...)` / `conn.ext_notification(...)` to send outgoing extensions. diff --git a/docs/quickstart.md b/docs/quickstart.md index 0abbfd11..cbc772ac 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -1,26 +1,13 @@ # Quickstart -Spin up a working ACP agent/client loop in minutes. Keep this page beside the terminal and check off each section as you go. Want inspiration? Hop to the [Use Cases](use-cases.md) list to see how teams like kimi-cli or Zed apply the SDK in production. +Launch a working ACP agent and client in minutes. -## Quick checklist +## Prerequisites -| Goal | Command / Link | -| ----------------------------------- | --------------------------------------------------------------------- | -| Install the SDK | `pip install agent-client-protocol` or `uv add agent-client-protocol` | -| Run the echo agent | `python examples/echo_agent.py` | -| Point Zed (or another client) at it | Update `settings.json` as shown below | -| Programmatically drive an agent | Copy the `spawn_agent_process` example | -| Run tests before hacking further | `make check && make test` | +- Python 3.10–3.15 with `pip` or `uv` +- An ACP client (such as Zed, Toad, Lody, or T3 Code) or the SDK's programmatic client helpers -## Before you begin - -- Python 3.10–3.14 with `pip` or `uv` -- An ACP-capable client such as Zed (recommended for validation) -- Optional: the Gemini CLI (`gemini --acp`; use `--experimental-acp` for older versions) for the bridge example - -## Step 1 — Install the SDK - -_Install the library from PyPI or add it to your uv workspace._ +## 1. Install the SDK ```bash pip install agent-client-protocol @@ -28,39 +15,21 @@ pip install agent-client-protocol uv add agent-client-protocol ``` -## Step 2 — Launch the Echo agent - -_Run the provided streaming agent so clients have something to talk to._ +## 2. Run the echo agent -Start the ready-made echo example; it streams text blocks back to any ACP client. Leave it running in a terminal: +`examples/echo_agent.py` implements a minimal streaming agent over stdio: ```bash python examples/echo_agent.py ``` -## Step 3 — Connect from an ACP-aware client +The process reads newline-delimited JSON-RPC frames from `stdin` and writes responses and `session/update` notifications to `stdout`. -_Point a client at the script and confirm you can exchange streamed updates._ +## 3. Connect from an ACP client ### Zed -Add an Agent Server entry in `settings.json` (Zed → Settings → Agents panel): - -```json -{ - "agent_servers": { - "Echo Agent (Python)": { - "type": "custom", - "command": "/abs/path/to/python", - "args": [ - "/abs/path/to/agentclientprotocol/python-sdk/examples/echo_agent.py" - ] - } - } -} -``` - -Or, if using `uv`: +Add an entry to Zed's `settings.json`: ```json { @@ -70,22 +39,22 @@ Or, if using `uv`: "command": "uv", "args": [ "run", - "/abs/path/to/agentclientprotocol/python-sdk/examples/echo_agent.py" + "/abs/path/to/python-sdk/examples/echo_agent.py" ] } } } ``` -Open the Agents panel and start the session. Each message you send should be echoed back via streamed `session/update` notifications. +Open the Agents panel, select **Echo Agent (Python)**, and send a message to observe streamed `session/update` responses. -### Other clients +### Other stdio clients -Any ACP client that communicates over stdio can spawn the same script; no additional transport configuration is required. +Any ACP-compatible stdio client (including Toad, Lody, and T3 Code) can launch the same command and arguments directly. ### Programmatic launch -Prefer to drive agents directly from Python? The `spawn_agent_process` helper wires stdio and lifecycle management for you: +Use `spawn_agent_process` to start an agent subprocess, attach stdio framing, and close both the connection and subprocess on exit: ```python import asyncio @@ -93,18 +62,15 @@ import sys from pathlib import Path from typing import Any -from acp import PROTOCOL_VERSION, spawn_agent_process -from acp.interfaces import Client +from acp import PROTOCOL_VERSION, Client, spawn_agent_process from acp.schema import TextContentBlock class SimpleClient(Client): - async def request_permission( - self, session_id, tool_call, options, **kwargs: Any - ): + async def request_permission(self, session_id: str, tool_call: Any, options: list[Any], **kwargs: Any) -> Any: return {"outcome": {"outcome": "cancelled"}} - async def session_update(self, session_id, update, **kwargs): + async def session_update(self, session_id: str, update: Any, **kwargs: Any) -> None: print("update:", session_id, update) @@ -118,248 +84,72 @@ async def main() -> None: prompt=[TextContentBlock(text="Hello from spawn!")], ) + asyncio.run(main()) ``` -`spawn_agent_process` manages the child process, wires its stdio into ACP framing, and closes everything when the block exits. The mirror helper `spawn_client_process` lets you drive an ACP client from Python as well. +`spawn_client_process` provides the corresponding helper for spawning an ACP client subprocess from an agent. -## Step 4 — Extend the agent +## 4. Build a custom agent -_Swap the echo demo for your own `Agent` subclass._ - -Create your own agent by subclassing `acp.Agent`. The pattern mirrors the echo example: +Subclass `acp.Agent`, implement the methods your agent supports, and start the stdio loop with `acp.run_agent()`: ```python -from acp import Agent, PromptResponse - - -class MyAgent(Agent): - async def prompt(self, session_id, prompt, **kwargs) -> PromptResponse: - # inspect prompt, stream updates, then finish the turn - return PromptResponse(stop_reason="end_turn") -``` - -Run it with `run_agent()` inside an async entrypoint and wire it to your client. Refer to: - -- [`examples/echo_agent.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/echo_agent.py) for the smallest streaming agent -- [`examples/agent.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/agent.py) for an implementation that negotiates capabilities and streams richer updates -- [`examples/duet.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/duet.py) to see `spawn_agent_process` in action alongside the interactive client -- [`examples/gemini.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/gemini.py) to drive the Gemini CLI (`--acp`; use `--experimental-acp` for older versions) directly from Python - -Generated models provide defaults for discriminator fields such as `type` and -`sessionUpdate`, so they can be constructed directly: +import asyncio +from typing import Any +from uuid import uuid4 -```python +from acp import PROTOCOL_VERSION, Agent, InitializeResponse, NewSessionResponse, PromptResponse, run_agent +from acp.interfaces import Client from acp.schema import AgentMessageChunk, TextContentBlock -update = AgentMessageChunk( - content=TextContentBlock(text="File opened."), -) -``` - -## Session notices (unstable) - -The v1 bindings use `schema-v1.24.1`. Clients that can display live advisory -notices advertise `ClientCapabilities(session=ClientSessionCapabilities(notices=NoticeCapabilities()))` -in `initialize`; these models are available from `acp.schema`. - -After checking that capability, agents can send a notice: -```python -from acp.schema import SessionUpdateNotice - -await client.session_update( - session_id=session_id, - update=SessionUpdateNotice( - severity="warning", - title="Context is nearly full", - description="Start a new session soon.", - ), -) -``` - -Notices are live events, outside session history. The title must be non-empty; -severity accepts `info`, `warning`, `error`, and custom or future strings. -Agents must only send notices to clients that advertise support. - -Tool calls now expose the stable `name` field. Terminal authentication methods -are available as `TerminalAuthMethod`, replacing the incorrect `EnvVarAuthMethod` -name. Accepted elicitation content validates scalar values and string lists; -nested objects are not valid form values. - -## Additional v1 protocol methods - -The SDK exposes all agent and client methods in the bundled `schema-v1.24.1` -method tables. `session/delete` and `logout` are stable and do not require -`use_unstable_protocol=True`. The other methods in the table below are unstable; -enable that flag on the receiving connection (or `run_agent`) to route them. -Check the peer's advertised capabilities before calling these methods. - -| Wire method | Python method | Receiver | -| --- | --- | --- | -| `session/delete` | `delete_session(session_id=...)` | Agent | -| `providers/list`, `providers/set`, `providers/disable` | `list_providers`, `set_provider`, `disable_provider` | Agent | -| `logout` | `logout()` | Agent | -| `session/archive`, `session/unarchive` | `archive_session`, `unarchive_session` | Agent | -| `session/status`, `session/options`, `session/set_title` | `session_status`, `session_options`, `set_session_title` | Agent | -| `auth/status` | `auth_status()` | Agent | -| `auth/status_update` (notification) | `auth_status_update` | Client | -| `mcp/message` (request) | `mcp_message` | Client/provider | -| `mcp/message` (notification) | `notify_mcp` | Agent | - -For example, an agent that advertises session deletion implements: - -```python -from acp import DeleteSessionResponse - -async def delete_session(self, session_id: str, **kwargs) -> DeleteSessionResponse: - await self.session_store.delete(session_id) - return DeleteSessionResponse() -``` +class MyAgent(Agent): + def on_connect(self, conn: Client) -> None: + self._conn = conn -A client then calls `await connection.delete_session(session_id=session_id)`. -Deletion removes stored session data; `close_session` only closes the active -session. The SDK dispatches these calls to your implementation; it does not -provide session storage or provider management itself. Missing request handlers -return the JSON-RPC method-not-found error. + async def initialize(self, protocol_version: int, **kwargs: Any) -> InitializeResponse: + return InitializeResponse(protocol_version=PROTOCOL_VERSION) -## Stateless MCP-over-ACP + async def new_session(self, cwd: str, **kwargs: Any) -> NewSessionResponse: + return NewSessionResponse(session_id=uuid4().hex) -The unstable native binding targets **MCP 2026-07-28**. A provider advertises an -`AcpMcpServer(name=..., server_id=...)` in session setup after checking the -agent's `mcpCapabilities.acp` capability. Register the provider's handler before -publishing the declaration: the agent may call it before session setup returns. -There is no MCP initialization or connect/disconnect exchange. + async def prompt(self, session_id: str, prompt: list[Any], **kwargs: Any) -> PromptResponse: + await self._conn.session_update( + session_id=session_id, + update=AgentMessageChunk(content=TextContentBlock(text="Hello!")), + ) + return PromptResponse(stop_reason="end_turn") -An agent calls its connection's `mcp_message`; the client/provider implements -that handler. Supply a fresh string `request_id` for every operation, including -an interactive-tool retry. This logical MCP ID is separate from the outer ACP -JSON-RPC request ID. Include the required MCP metadata in the inner parameters: -```python -from uuid import uuid4 -from acp import McpErrorResponse - -response = await connection.mcp_message( - server_id="project-tools", - request_id=uuid4().hex, - method="tools/list", - params={ - "_meta": { - "io.modelcontextprotocol/protocolVersion": "2026-07-28", - "io.modelcontextprotocol/clientCapabilities": {}, - }, - }, - trace="outer ACP metadata", -) -if isinstance(response, McpErrorResponse): - handle_mcp_error(response.error) -else: - use_mcp_result(response.result) +if __name__ == "__main__": + asyncio.run(run_agent(MyAgent())) ``` -Providers return `McpResultResponse(result=...)` or -`McpErrorResponse(error=McpError(code=..., message=...))`. Results are opaque JSON, -including explicit `null`, tool errors with `isError`, and interactive -`input_required` results. Error data preserves omission versus explicit null, -and unknown inner error fields survive. Outer ACP failures raise `RequestError`; -an inner MCP error, even code `-32000`, remains inside the response carrier. -Send exactly one outcome; receivers prefer `result` if both keys are received. - -The provider sends `notify_mcp(server_id=..., request_id=..., method=..., params=...)` -for an active request; the agent implements `notify_mcp` to receive it. Keep the -same server and logical request IDs and stop notifications before sending the -final outcome. Consumers must correlate notifications with active operations -and ignore unknown or completed ones. There are no provider-originated MCP requests. - -The SDK provides typed envelopes and routing. Applications own server registrations, -MCP metadata/version validation, duplicate-active-ID rejection, operation admission, -and notification lifetimes. They also decide how to handle interactive input; -retry with fresh IDs and preserve opaque request state. Cancelling the task awaiting -`mcp_message` uses the existing ACP cancellation mechanism described below. -These methods work over stdio, HTTP, and WebSocket ACP connections. - -**Migration:** `connect_mcp`, `disconnect_mcp`, and `connection_id` are removed. -Replace them with server-addressed requests carrying `server_id` and `request_id`, -add per-request MCP metadata, and wrap handler outcomes in the typed carrier. -Older MCP revisions and the connection-oriented prototype are not supported. - -Run `uv run python examples/mcp_over_acp.py` for a local request/progress example. -See the [upstream binding specification](https://agentclientprotocol.com/rfds/mcp-over-acp) -for registration, subscription, and error-code requirements. - -## Request cancellation - -Connections handle the protocol's `$/cancel_request` notification. When the -peer cancels one of its requests, the SDK cancels the task running your handler. -The handler may catch `asyncio.CancelledError` and return a (partial) result; -otherwise the peer receives a `-32800` "Request cancelled" error. Cancellations -for unknown or already finished requests are ignored; a cancelled request still -gets exactly one response unless the connection is closed first. - -Cancelling the task that awaits an outgoing request (for example through -`asyncio.wait_for`) still raises `CancelledError` locally without waiting for the -peer, and additionally sends a best-effort `$/cancel_request` for that request. -Cancellation support is optional for peers. Use `session/cancel` to stop a -prompt turn. - -## Maintaining protocol routes - -The `Agent` and `Client` protocols in `src/acp/interfaces.py` are the source of -truth for incoming routes. Declare routing metadata alongside each method's -parameter model: +Generated schema models provide defaults for discriminator fields such as `type` and `sessionUpdate`, enabling direct construction: ```python -@param_model( - DeleteSessionRequest, - method=AGENT_METHODS["session_delete"], - adapt_result=normalize_result, -) -async def delete_session(self, session_id: str, **kwargs: Any) -> DeleteSessionResponse: ... -``` - -`build_agent_router` and `build_client_router` read these declarations through -`MessageRouter.from_protocol`. New protocol declarations automatically become -routes; implementation-only methods are not exposed. Use `kind="notification"` -for notifications and `unstable=True` for methods requiring explicit opt-in. -Optional handlers can declare `optional=True` and `default_result`. - -`param_model` takes exactly one type expression: a model, a union such as -`ModelA | ModelB`, or `Annotated[ModelA | ModelB, Field(discriminator="type")]`. -The router validates the original type with Pydantic's `TypeAdapter`, preserving -`Annotated` validation metadata. Union handlers receive the fields common to all -branches by default. The former `param_models(A, B, ...)` form is replaced by -`param_model(A | B, ...)`. - -`validate_params` and `adapt_params` provide custom validation and conversion -when the wire representation differs from the Python signature, as with config -options and elicitation. Legacy handlers still receive the validated request -model. Signature generation expands single-model fields and preserves handwritten -union signatures. Connection methods retain model-only decorators for signature generation -and legacy calls; they do not repeat the routing options. - -## Optional — Talk to the Gemini CLI - -_Have the Gemini CLI installed? Run the bridge to exercise permission flows._ - -If you have the Gemini CLI installed and authenticated: +from acp.schema import AgentMessageChunk, TextContentBlock -```bash -python examples/gemini.py --skip-trust --yolo # auto-approve permission prompts -python examples/gemini.py --skip-trust --sandbox --model gemini-1.5-pro +update = AgentMessageChunk(content=TextContentBlock(text="File opened.")) ``` -Environment helpers: +Handlers and connection methods accept expanded snake_case parameters, with additional keyword arguments serialized as request `_meta`. -- `ACP_GEMINI_BIN` — override the CLI path (defaults to `PATH` lookup) -- `ACP_GEMINI_TEST_ARGS` — extra flags forwarded during the smoke test -- `ACP_ENABLE_GEMINI_TESTS=1` — opt-in toggle for `tests/test_gemini_example.py` +## Runnable examples -Authentication hiccups (e.g. missing `GOOGLE_CLOUD_PROJECT`) are surfaced but treated as skips during testing so the suite stays green on machines without credentials. +- [`examples/echo_agent.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/echo_agent.py) — minimal streaming agent +- [`examples/agent.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/agent.py) — agent with capability negotiation and richer updates +- [`examples/client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/client.py) — interactive stdio client +- [`examples/duet.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/duet.py) — in-process client/agent pairing with `spawn_agent_process` +- [`examples/mcp_over_acp.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/mcp_over_acp.py) — stateless MCP-over-ACP exchange +- [`examples/gemini.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/gemini.py) — bridge to the Gemini CLI (`gemini --acp`) +- [`examples/http_server.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_server.py), [`examples/http_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_client.py), [`examples/ws_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/ws_client.py) — Streamable HTTP and WebSocket demos ## Next steps -- Compare what you built with the real integrations listed on the [Use Cases](use-cases.md) page. -- Explore `docs/contrib.md` for higher-level utilities like session accumulators and permission brokers. -- Run `make check` / `make test` before committing changes, and regenerate schema artifacts with `make gen-all` when ACP versions advance. -- Need help? Start a thread in [GitHub Discussions](https://github.com/agentclientprotocol/python-sdk/discussions) or chat with other ACP developers at [agentclientprotocol.zulipchat.com](https://agentclientprotocol.zulipchat.com/). +- Explore v1 capabilities in [Protocol Features (v1)](protocol-features.md). +- Serve agents remotely with [Web Transport (HTTP & WebSocket)](web-transport.md). +- Try the preview protocol in [Experimental Protocol v2](experimental-v2.md). +- Reuse stateful UI/agent helpers from [Contrib Utilities](contrib.md). +- Validate integrations with [Testing & Conformance](testing.md). diff --git a/docs/releasing.md b/docs/releasing.md index b4b2ba37..67d228a2 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,50 +1,43 @@ # Releasing -Every package release tracks an upstream ACP schema tag from [`agentclientprotocol/agent-client-protocol`](https://github.com/agentclientprotocol/agent-client-protocol). Follow this checklist to stay in lockstep. +Package releases track pinned upstream ACP schema tags from [`agentclientprotocol/agent-client-protocol`](https://github.com/agentclientprotocol/agent-client-protocol) (`schema/VERSION` for v1 and `schema/v2/VERSION` for experimental v2). -## Prep checklist +## Preparation checklist -1. **Choose the schema tag** (e.g. `schema-v1.16.0`) and regenerate artifacts: +1. **Refresh schema bindings** when targeting a new upstream schema tag: ```bash - ACP_SCHEMA_VERSION=schema-v1.16.0 make gen-all + # v1 bindings + ACP_SCHEMA_VERSION=schema-v1.35.0 make gen-all + + # Experimental v2 bindings + ACP_SCHEMA_VERSION=schema-v2.0.0-beta.4 make gen-v2 ``` - This refreshes `schema/` and the generated `src/acp/schema.py`. -2. **Bump the SDK version** in `pyproject.toml` using a PEP 440 version string (for example `0.9.0a1` for an alpha release), and sync `uv.lock` if the lockfile is tracked. -3. **Run the standard gates:** +2. **Bump the SDK version** in `pyproject.toml` using a PEP 440 version string (for example `1.0.0rc3` or `1.0.0`) and update `uv.lock` if dependencies changed. +3. **Run local verification gates:** ```bash - make check # Ruff format/lint, type analysis, dep hygiene - make test # pytest + doctests + make gen-check + make check + make test + make docs-test ``` -4. **Refresh docs + examples** so user-facing flows (e.g. Gemini bridge) reflect behaviour in the new schema. +4. **Run conformance and ecosystem checks** for schema, transport, or router changes: + - Run the [ACP TCK](testing.md#acp-tck-conformance) profiles (v1 baseline, v2 minimal/full capability, dual-stack router). + - Run the [S1–S6 real-world smoke playbook](testing.md#real-world-client-and-agent-verification) against available ACP clients and agents, and include the summary in the release PR. +5. **Update docs and examples** whenever public APIs, schema models, or transports change. -## Commit & review +## Commit and PR -- Keep the diff tight: regenerated schema files, version bumps, doc updates, and any required fixture refresh (goldens, RPC tests, etc.). -- Use a Conventional Commit such as `release: 0.9.0a1`. -- In the PR description, capture: - - The ACP schema tag you targeted. - - Output from `make check` / `make test` (and optional Gemini tests if you ran them). - - Behavioural or API highlights that reviewers should focus on. +- Use Conventional Commits (`release: 1.0.0`, `feat(schema)!: ...`, `docs: ...`). +- Record the targeted v1/v2 schema tags, verification outputs (`make check`, `make test`, TCK verdict), and user-visible highlights in the PR description. ## Publish via GitHub Release -Releases are automated by `on-release-main.yml` once the PR lands on `main`. - -1. Draft a GitHub Release for the new tag (the UI creates the tag if missing). - Use the exact package version as the tag, for example `0.9.0a1` or `0.9.0`. -2. Publishing the release triggers the workflow, which: - - Syncs the tag back into `pyproject.toml`. - - Builds and uploads to PyPI via `uv publish` using `PYPI_TOKEN`. -3. After `release-main` succeeds, **Publish release docs** starts on `main`. It builds the MkDocs site from the same commit as the release and deploys it to GitHub Pages. The repository's Pages source is **GitHub Actions**. - -No local build/publish steps are needed—just provide a clear release summary (highlights, compatibility notes, migration tips). - -## Republish docs for a release +Publishing is automated by `.github/workflows/on-release-main.yml`: -In **Actions → Publish release docs → Run workflow**, select the **`main`** branch and enter the published release tag (for example, `1.1.0`) in **release-tag**. The tag selects the docs to build; the deployment runs from `main`. This does not publish anything to PyPI. After deployment, check that the public quickstart matches the example at the release tag. +1. Create and publish a GitHub Release on `main` whose tag matches the package version (for example `1.0.0`). +2. The workflow syncs the version into `pyproject.toml`, builds the wheel/sdist, and publishes to PyPI via `uv publish`. +3. Once publishing succeeds, **Publish release docs** builds the MkDocs site from the release commit and deploys it to GitHub Pages. -## Extra tips +## Republishing docs for an existing release -- Breaking schema bumps often mean updating `tests/test_golden.py`, `tests/test_rpc.py`, and any examples touched by new fields. -- Use `make clean` if you need a fresh slate before re-running `make gen-all`. -- When available, run the Gemini smoke test (`ACP_ENABLE_GEMINI_TESTS=1`, set `ACP_GEMINI_BIN`) to catch regressions early. +Open **Actions → Publish release docs → Run workflow**, select the `main` branch, and enter the published release tag in `release-tag`. The workflow rebuilds and deploys documentation for that tag to GitHub Pages. diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 00000000..64247d06 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,78 @@ +# Testing & Conformance + +The SDK validates protocol behavior across four layers: local unit/contract tests, the official ACP Technology Compatibility Kit (TCK), cross-SDK wire interoperability, and real-world client/agent integration checks. + +## Local test suite + +Run the standard repository checks locally: + +```bash +make gen-check # Verify generated bindings match schema/ +make check # Lockfile consistency, Ruff lint/format, ty type check, deptry +make test # Pytest suite (including doctests) +make docs-test # Strict MkDocs build +``` + +The test suite under `tests/` covers: + +- Generated schema models, lenient deserialization (`x-deserialize-*`), and golden wire fixtures (`tests/test_golden.py`, `tests/test_deserialize.py`, `tests/test_v2_schema.py`) +- JSON-RPC framing, cancellation (`$/cancel_request`), routing, and protocol negotiation (`tests/test_rpc.py`, `tests/test_protocol_negotiation.py`, `tests/test_v2_runtime.py`) +- Streamable HTTP and WebSocket client/server transports (`tests/http/`) +- Contrib helpers (`tests/contrib/`) and stdio subprocess lifecycles (`tests/real_user/`) + +## ACP TCK conformance + +Protocol-level compliance is verified against the official [ACP TCK](https://github.com/agentclientprotocol/acp-tck) using reference agents built strictly on public SDK APIs. + +| Profile | Entry point | Scope | Expected result | +| --- | --- | --- | --- | +| **v1 baseline** | `acp.run_agent` | Stable v1 agent suite (`Agent` subclass and structural handler) | `CONFORMANT` | +| **v2 minimal** | `v2.run_agent` and `AgentProtocolRouter(v2=...)` | Minimal capabilities; validates error codes (`-32022`, `-32600`, `-32601`, `-32602`) and disabled-capability handling | `CONFORMANT`, 0 failures | +| **v2 full capability** | `v2.run_agent` and `AgentProtocolRouter(v2=...)` | All supported v2 capabilities enabled (sessions, fork/resume/replay, config options, elicitation, MCP-over-ACP, permissions, cancellation) | `CONFORMANT`, 0 failures | +| **Dual-stack negotiation** | `AgentProtocolRouter(v1=..., v2=...)` | v1/v2 version selection (`ACP-INIT-208`), repeat `initialize`, and v2-to-v1 fallback | 0 failures on initialization suite | + +When modifying schema base classes or deserialization helpers (`src/acp/_schema_base.py`, `src/acp/_deserialize.py`), also verify v1 `model_validate` latency on hot models (`AgentMessageChunk`, `SessionNotification`) to keep v1 validation performance steady. + +## Cross-SDK wire interoperability + +For schema upgrades and client-side behavior ahead of TCK releases, run live bidirectional stdio checks pairing this SDK with the official [TypeScript SDK](https://github.com/agentclientprotocol/typescript-sdk) and [Rust SDK](https://github.com/agentclientprotocol/rust-sdk) across all four directions (Python client ↔ TS/Rust agent, TS/Rust client ↔ Python agent). + +## Real-world client and agent verification + +Real-world checks validate end-to-end behavior with ecosystem tools across two roles: + +- **Real ACP clients** (exercising Python SDK agents): **Zed**, **T3 Code**, **Toad**, and **Lody** +- **Real ACP agents** (exercising Python SDK clients): **Gemini CLI** (`gemini --acp`), **Bub** (`bub-acp-server`), and **Mistral Vibe** + +### Standard smoke playbook (`S1–S6`) + +Use the same six scenarios across clients and agents when validating releases or transport changes: + +| ID | Scenario | Verified behavior | +| --- | --- | --- | +| **S1** | Handshake & negotiation | `initialize` exchanges protocol version, info, and capabilities; unsupported versions return clean errors | +| **S2** | Session & streaming | `session/new` followed by `session/prompt` streams `agent_message_chunk` updates through turn completion | +| **S3** | Tool calls & permissions | Tool call progress/content/diff updates and `request_permission` approve/reject flows complete end to end | +| **S4** | Cancellation & recovery | Sending `session/cancel` or `$/cancel_request` stops active work and leaves the session usable for the next prompt | +| **S5** | Session lifecycle & config | Advertised capabilities (`session/list`, `load`/`resume`, `fork`, `configOptions`, `mcp-over-acp`) round-trip cleanly | +| **S6** | Error handling & shutdown | Invalid frames or unimplemented methods keep the connection healthy; closing exits cleanly with zero orphan processes | + +### Running the opt-in Gemini CLI smoke test + +When the Gemini CLI is installed and authenticated locally, run the built-in smoke test in `tests/test_gemini_example.py`: + +```bash +ACP_ENABLE_GEMINI_TESTS=1 uv run python -m pytest tests/test_gemini_example.py +``` + +Optional environment variables: + +- `ACP_GEMINI_BIN` — custom path to the `gemini` executable (defaults to `PATH` lookup) +- `ACP_GEMINI_TEST_ARGS` — extra flags forwarded to `examples/gemini.py` + +You can also run the interactive bridge directly: + +```bash +python examples/gemini.py --skip-trust --yolo +python examples/gemini.py --skip-trust --sandbox --model gemini-1.5-pro +``` diff --git a/docs/use-cases.md b/docs/use-cases.md index dd7abd5d..7b4b4f9a 100644 --- a/docs/use-cases.md +++ b/docs/use-cases.md @@ -1,29 +1,24 @@ # Use Cases -This page mirrors the quick-read style of the README/index: skim the tables, copy links, and see how others apply the SDK. For the protocol overview itself, visit the official [agent](https://agentclientprotocol.com/overview/agents) and [client](https://agentclientprotocol.com/overview/clients) guides. +Projects using the ACP Python SDK in production. For the broader protocol directory across languages, visit [agentclientprotocol.com](https://agentclientprotocol.com/). ## Agents -| Project | What it showcases | +| Project | Highlights | | --- | --- | -| [MoonshotAI/kimi-cli](https://github.com/MoonshotAI/kimi-cli) | A CLI-first ACP+MCP agent that helps with software dev and terminal workflows. Highlights streaming updates, permission prompts, and tool call UX. | -| [MiniMax-AI/Mini-Agent](https://github.com/MiniMax-AI/Mini-Agent) | A minimal yet professional single agent demo project that showcases the core execution pipeline and production-grade features of agents. | -| [OpenHands/OpenHands-CLI](https://github.com/OpenHands/OpenHands-CLI) | A lightweight, modern CLI to interact with the OpenHands agent. | -| [evalstate/fast-agent](https://github.com/evalstate/fast-agent) | Define, Prompt and Test MCP enabled Agents and Workflows | +| [MoonshotAI/kimi-cli](https://github.com/MoonshotAI/kimi-cli) | CLI-first ACP+MCP coding agent showcasing streamed updates, permission prompts, and tool call UX. | +| [MiniMax-AI/Mini-Agent](https://github.com/MiniMax-AI/Mini-Agent) | Minimal single-agent reference implementation demonstrating a complete ACP execution loop. | +| [OpenHands/OpenHands-CLI](https://github.com/OpenHands/OpenHands-CLI) | Interactive CLI interface for the OpenHands coding agent over ACP. | +| [evalstate/fast-agent](https://github.com/evalstate/fast-agent) | Framework for defining, prompting, and testing MCP-enabled agents and workflows. | +| [bubbuild/bub-contrib (`bub-acp-server`)](https://github.com/bubbuild/bub-contrib) | ACP server bridge exposing Bub agents to editors and desktop orchestrators. | ## Clients -| Project | What it showcases | +| Project | Highlights | | --- | --- | -| [wiki3-ai/agent-client-kernel](https://github.com/wiki3-ai/agent-client-kernel) | A Jupyter kernel that speaks ACP so notebooks can chat with external agents. Great reference if you’re embedding ACP in notebook tooling. | -| [OhadRubin/simple-acp-client](https://github.com/OhadRubin/simple-acp-client) | A Claude Agent SDK–style Python client that wraps ACP executables with a friendly API. Use it as a starting point for bespoke clients. | +| [wiki3-ai/agent-client-kernel](https://github.com/wiki3-ai/agent-client-kernel) | Jupyter kernel speaking ACP so notebooks can interact with external agents. | +| [OhadRubin/simple-acp-client](https://github.com/OhadRubin/simple-acp-client) | High-level Python client wrapper for driving ACP agent executables. | -## Add your integration +## Add your project -Shipping something with this SDK? Tell us! - -- Open an issue or PR with a short blurb and link. -- Start a thread in [GitHub Discussions](https://github.com/agentclientprotocol/python-sdk/discussions). -- Drop a note in [agentclientprotocol.zulipchat.com](https://agentclientprotocol.zulipchat.com/). - -We’ll keep this list current so newcomers can see what’s possible. +Building an agent or client with this SDK? Open a pull request updating this page, or share your integration in [GitHub Discussions](https://github.com/agentclientprotocol/python-sdk/discussions) or on [Zulip](https://agentclientprotocol.zulipchat.com/). diff --git a/docs/web-transport.md b/docs/web-transport.md index 8798c470..a78774e2 100644 --- a/docs/web-transport.md +++ b/docs/web-transport.md @@ -1,38 +1,28 @@ # Web Transport (Streamable HTTP & WebSocket) -> **Experimental.** The remote web transports are experimental and may change. -> They ship as an optional extra and are import-guarded. +> **Experimental.** The remote web transports are experimental and shipped under the optional `[http]` extra. -The SDK can run ACP over two remote connectivity profiles in addition to stdio: +In addition to stdio, the SDK supports two remote JSON-RPC transports sharing the same ACP connection lifecycle (`initialize` → session operations → close): -- **Streamable HTTP** — `POST` for client→server messages, long-lived `GET` SSE - streams for server→client messages (one connection-scoped stream plus one per - session), and `DELETE` to terminate. `initialize` returns `200 OK` with a JSON - body; all other POSTs return `202 Accepted`. **Requires HTTP/2.** -- **WebSocket** — a `GET` upgrade on the same endpoint carrying full-duplex - JSON-RPC text frames, one message per frame. Binary frames are ignored, as - the transport RFD specifies; the server logs a warning on the first one. - -Both reuse the existing JSON-RPC message format and ACP lifecycle -(`initialize` → session methods → close). +- **Streamable HTTP** — `POST` carries client-to-server messages, long-lived `GET` Server-Sent Events (SSE) streams carry server-to-client messages (one connection stream plus one per session), and `DELETE` terminates the connection. `initialize` responds with `200 OK` and a JSON body; subsequent `POST` requests respond with `202 Accepted`. Requires HTTP/2. +- **WebSocket** — a `GET` WebSocket upgrade on the same endpoint carrying full-duplex JSON-RPC text frames (one message per frame). Binary frames are ignored and logged once on the server. ## Installation ```bash pip install "agent-client-protocol[http]" +# or +uv add "agent-client-protocol[http]" ``` -This pulls in `httpx2[http2]` (HTTP/2 + SSE consumption), `websockets`, and -`starlette` (the server application). The core SDK and stdio transport do not -require these optional dependencies. +This extra installs `httpx2[http2]`, `websockets`, and `starlette`. -## Client +## Client usage -Both transports produce a message-level `Transport` that plugs into the existing -`connect_to_agent`: +Both client factories return a `Transport` compatible with `connect_to_agent`: ```python -from acp import connect_to_agent +from acp import PROTOCOL_VERSION, connect_to_agent from acp.http import create_http_stream from acp.ws import create_websocket_stream @@ -40,179 +30,90 @@ from acp.ws import create_websocket_stream transport = create_http_stream("http://localhost:8000/acp") conn = connect_to_agent(my_client, transport) -# ...or WebSocket +# WebSocket transport = await create_websocket_stream("ws://localhost:8000/acp") conn = connect_to_agent(my_client, transport) -init = await conn.initialize(protocol_version=1) +await conn.initialize(protocol_version=PROTOCOL_VERSION) session = await conn.new_session(cwd="/tmp", mcp_servers=[]) await conn.prompt(session_id=session.session_id, prompt=[...]) await conn.close() await transport.close() ``` -The client sends `initialize` first, reads the `Acp-Connection-Id` response -header, then opens the connection-scoped SSE stream. When a new `sessionId` -appears it opens that session-scoped stream too. A single SSE attempt is made per -stream; reconnect/retry is the caller's responsibility (v1 of the RFD). - -When a server returns an inline JSON response in a `200 OK` POST body, invalid -JSON raises `json.JSONDecodeError` in the sending call. The request fails promptly -and the connection remains available for subsequent requests. +Over Streamable HTTP, the client sends `initialize` first, stores the returned `Acp-Connection-Id` header, and opens the connection-scoped SSE stream. When a session is created, loaded, or resumed, the client opens the corresponding session-scoped SSE stream. -### Loading an existing session +### Loading and resuming sessions -Both HTTP and WebSocket support `load_session()` when the agent advertises -`loadSession` and implements session persistence: +Both HTTP and WebSocket support `load_session()` and `resume_session()` when advertised by the agent: ```python -init = await conn.initialize(protocol_version=1) -if init.agent_capabilities.load_session: +init = await conn.initialize(protocol_version=PROTOCOL_VERSION) +if init.agent_capabilities and init.agent_capabilities.load_session: await conn.load_session(session_id="saved-session-id", cwd="/workspace", mcp_servers=[]) await conn.prompt(session_id="saved-session-id", prompt=[...]) ``` -For HTTP, history replay and the load response use the connection SSE stream. -The client correlates the response with the session ID from the load request, -then opens the session SSE stream for further prompts and agent callbacks. This -also works with an empty history: a load response need not contain `sessionId`. -Replay is consumed as it arrives, so histories larger than the SSE buffer do not -wait for a session stream to open. WebSocket uses its existing bidirectional -connection for both replay and subsequent messages. - -`resume_session()` (when the agent advertises `sessionCapabilities.resume`) -follows the same HTTP routing without replaying history: the response uses the -connection SSE stream, and the client then opens the session SSE stream. +Over HTTP, `session/load` history replay and the load/resume responses stream over the connection SSE channel; once established, subsequent session traffic uses the session SSE stream. Over WebSocket, replay and live traffic share the bidirectional socket. -A failed load returns its JSON-RPC error on the connection stream and can be -retried. The server removes streams provisioned only for failed loads, while -preserving established sessions and overlapping loads. It does not change the -agent's load response or automatically enable the agent's `loadSession` capability. +## Server usage -## Server - -The server uses Starlette for HTTP requests, responses, routing, streaming, -WebSocket handling, and application lifespan: +`create_asgi_app` builds a Starlette application serving `POST`/`GET`/`DELETE` and WebSocket upgrades at `/acp` by default, creating one agent instance per connection: ```python from acp.http.asgi import create_asgi_app -# One agent instance is created per connection. app = create_asgi_app(lambda conn: MyAgent()) ``` -`app` is a `starlette.applications.Starlette` instance handling -`POST`/`GET`/`DELETE` and WebSocket upgrades at `/acp` by default. Set the -keyword-only `path` argument to use a different endpoint for both transports: +Pass `path` to change the endpoint route: ```python app = create_asgi_app(lambda conn: MyAgent(), path="/rpc") ``` -Other paths do not serve ACP. Starlette supplies -`Request`, `JSONResponse`, `StreamingResponse`, and `WebSocket`; the SDK keeps -ACP connection and session routing. +### Serving v2 or dual-stack agents -### Mounting in another application +Pass an `AgentProtocolRouter` to `create_asgi_app` to negotiate v1 and v2 over both HTTP and WebSocket: -Mount the app at the desired prefix. The parent must enter the child lifespan -so HTTP connections are cleaned up during shutdown (mounted application -lifespans are not run automatically): +```python +from acp.experimental import AgentProtocolRouter +from acp.http.asgi import create_asgi_app + +router = AgentProtocolRouter( + v1=lambda conn: V1Agent(conn), + v2=lambda conn: V2Agent(conn), +) +app = create_asgi_app(router) +``` + +### Mounting in an existing Starlette app + +Enter the child lifespan from the parent application so active HTTP connections close cleanly during shutdown: ```python from contextlib import asynccontextmanager from starlette.applications import Starlette from starlette.routing import Mount +from acp.http.asgi import create_asgi_app + acp_app = create_asgi_app(lambda conn: MyAgent()) + @asynccontextmanager -async def lifespan(app): +async def lifespan(app: Starlette): async with acp_app.router.lifespan_context(acp_app): yield + app = Starlette(routes=[Mount("/agents", app=acp_app)], lifespan=lifespan) -# Connect to /agents/acp using either HTTP or WebSocket. +# Serves HTTP and WebSocket at /agents/acp ``` -With `path="/rpc"`, the mounted endpoint is `/agents/rpc`. Use `path="/"` to -serve ACP at the mount root (`/agents/`). - -### How the server fits together - -Start reading at `acp/http/asgi.py`. It creates Starlette routes, passes parsed -HTTP requests to `AcpServer`, and binds WebSockets in `acp/ws/server.py`. Both use the existing -`AgentSideConnection` and its message-level `Transport` interface: +### HTTP/2 server setup -```text -HTTP POST → _HttpTransport incoming queue → AgentSideConnection → agent -HTTP GET ← StreamingResponse ← SSE buffer ← _HttpTransport.send() ← agent output - -Starlette WebSocket ↔ _WebSocketTransport ↔ AgentSideConnection ↔ agent -``` - -For HTTP, `AcpServer` owns a dictionary of active connections. Each connection -has one incoming queue and one SSE buffer per stream. The incoming queue lets -POST return `202` while the agent handles the request. Output goes directly to -the relevant SSE buffer; there is no intermediate transport pair or pump task. - -HTTP output follows these routing rules: - -| Message | Destination | Why | -| --- | --- | --- | -| `initialize` response | POST body, via one Future | Establishes the connection before GET streams open | -| Response containing a new `sessionId` | Connection SSE stream | The client needs the ID before it can open the session stream | -| `session/load` replay and response, `session/resume` response | Connection SSE stream | Replay precedes the response; the client gets the session ID from the original request | -| Other messages | Session SSE stream when known, otherwise connection stream | Responses use their request's recorded session; requests/notifications carry `sessionId` | - -`OutboundStream` retains a bounded buffer, backpressure, and close handling. -Idle SSE streams emit keepalives. These support slow readers, streams that open -after messages arrive, and orderly teardown. `DELETE` and server shutdown close -the HTTP connections and cancel their agent work. - -WebSocket already provides one bidirectional stream. Its transport adapts -Starlette's socket to JSON-RPC messages; it needs no HTTP connection registry, -session routing, SSE buffers, or multiplex mode. The ASGI handler owns the agent -connection and closes it on socket disconnect or handler cancellation. - -### Simplification experiment - -The original 80 HTTP, WebSocket, and RPC tests passed after each ablation. -The Starlette migration also passes these behaviors; assertions now inspect -Starlette response objects and WebSocket tests use the framework's socket: - -| Stage | Removed | Lines across the three server files | -| --- | --- | ---: | -| Baseline | — | 715 | -| First ablation | `ConnectionRegistry`, WebSocket multiplex mode, WebSocket pump tasks, forwarding-only ASGI method | 647 | -| Second ablation | HTTP memory transport pair and pump, `ConnectionState`, generic response-waiter map | 581 | -| Starlette migration | Custom ASGI app, request/header parsing, response encoding, WebSocket state tracking, `PostResult` | 483 | - -This measures structural simplification and regression coverage, not throughput -or latency. Additional tests cover interrupted initialization, closing a full -SSE buffer, WebSocket cancellation/disconnect, invalid frames, and session routing -of concurrent success/error responses. - -`create_asgi_app(agent_factory, *, path="/acp")` returns a Starlette application. -The default route is now `/acp`, replacing the earlier catch-all route. -`AcpServer.handle_post()` and `handle_delete()` return -Starlette responses (`status_code`, byte `body`, and case-insensitive `headers`). -`open_stream()` and `close()` keep their signatures. -The experimental `AcpAsgiApp` and `PostResult` wrappers were removed, along with -`ConnectionRegistry`, `ConnectionState`, `AcpServer.registry`, and -`create_websocket_connection()`. Direct WebSocket integrations now use -`handle_websocket(agent_factory, websocket)` with a Starlette `WebSocket`. -WebSocket lifetimes belong to their ASGI handlers; `AcpServer.close()` manages -HTTP connections. - -The migration adds checks for HTTP error statuses, unsupported methods, mounting, -lifespan cleanup, and reopening an SSE stream after disconnect. - -### HTTP/2 server requirement - -> ⚠️ **Uvicorn does not serve HTTP/2.** For a spec-compliant Streamable HTTP -> server, run an HTTP/2-capable ASGI server (**Hypercorn**, Daphne, Granian) or -> terminate HTTP/2 at a proxy. The WebSocket profile works on Uvicorn. +Streamable HTTP requires an HTTP/2-capable ASGI server such as **Hypercorn**, **Daphne**, or **Granian** (or HTTP/2 termination at a reverse proxy). WebSocket works on any ASGI server, including Uvicorn. ```python import asyncio @@ -225,24 +126,22 @@ config.alpn_protocols = ["h2", "http/1.1"] asyncio.run(hypercorn.asyncio.serve(app, config)) ``` -## Examples +## HTTP headers and stream routing -- [`examples/http_server.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_server.py) — serve an agent over HTTP + WS (Hypercorn). -- [`examples/http_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_client.py) — connect over Streamable HTTP. -- [`examples/ws_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/ws_client.py) — connect over WebSocket. +| Header / Field | Role | +| --- | --- | +| `Acp-Connection-Id` | Returned on `initialize`; sent on subsequent HTTP `POST`/`GET`/`DELETE` requests | +| `Acp-Session-Id` | Sent on session-scoped `POST` requests and session-scoped `GET` SSE streams | +| `sessionId` | JSON-RPC payload field used to route server-to-client messages to the matching session stream | -## Identity model +## Examples -- `Acp-Connection-Id` (HTTP header) — returned by `initialize`; required on all - post-initialize HTTP requests and every GET stream. -- `Acp-Session-Id` (HTTP header) — required on session-scoped POSTs and the - session-scoped GET stream. -- `sessionId` (JSON-RPC field) — carried in params/results and used to route - messages to the correct stream. +- [`examples/http_server.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_server.py) — serve an agent over Streamable HTTP and WebSocket with Hypercorn +- [`examples/http_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_client.py) — connect over Streamable HTTP +- [`examples/ws_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/ws_client.py) — connect over WebSocket -## Not yet supported (deferred to a future revision) +## Current scope -- `Last-Event-ID` / SSE resumability and message sequencing. -- Client-side automatic reconnect/backoff. -- Batch JSON-RPC (the server returns `501`). -- `Acp-Protocol-Version` header enforcement. +- SSE keepalives, bounded outbound buffers, and orderly teardown on `DELETE` or server shutdown are built in. +- Reconnect/backoff policies, `Last-Event-ID` SSE resumability, and `Acp-Protocol-Version` header enforcement are planned for a future revision. +- JSON-RPC batch payloads over HTTP return `501`. diff --git a/mkdocs.yml b/mkdocs.yml index 1938cf48..c708ec57 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,23 +1,28 @@ site_name: Agent Client Protocol - Python SDK repo_url: https://github.com/agentclientprotocol/python-sdk site_url: https://agentclientprotocol.github.io/python-sdk -site_description: A Python implement of Agent Client Protocol (ACP, by Zed Industries) +site_description: A Python implementation of the Agent Client Protocol (ACP) site_author: Chojan Shang edit_uri: edit/main/docs/ repo_name: agentclientprotocol/python-sdk copyright: Maintained by psiace. nav: - - Home: index.md - - Quick Start: quickstart.md - - Use Cases: use-cases.md - - Web Transport (HTTP/WS): web-transport.md - - Experimental Protocol v2: experimental-v2.md - - Experimental Contrib: contrib.md - - Releasing: releasing.md - - 0.11 Migration Guide: migration-guide-0.11.md - - 0.7 Migration Guide: migration-guide-0.7.md - - 0.8 Migration Guide: migration-guide-0.8.md + - Overview: index.md + - Quickstart: quickstart.md + - Guides: + - Protocol Features (v1): protocol-features.md + - Web Transport (HTTP & WebSocket): web-transport.md + - Experimental Protocol v2: experimental-v2.md + - Contrib Utilities: contrib.md + - Ecosystem & Quality: + - Use Cases: use-cases.md + - Testing & Conformance: testing.md + - Releasing: releasing.md + - Migration Guides: + - 0.11 Migration Guide: migration-guide-0.11.md + - 0.8 Migration Guide: migration-guide-0.8.md + - 0.7 Migration Guide: migration-guide-0.7.md plugins: - search - mkdocstrings: diff --git a/pyproject.toml b/pyproject.toml index bcd5a374..43d0b1be 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "agent-client-protocol" version = "0.12.1" -description = "A Python implement of Agent Client Protocol (ACP, by Zed Industries)" +description = "A Python implementation of the Agent Client Protocol (ACP)" authors = [ { name = "Chojan Shang", email = "psiace@apache.org" }, { name = "Frost Ming", email = "me@frostming.com" }, From f700466e7eb09e2f7fb65d6a8e245140afd72f12 Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Sat, 28 Nov 2026 13:28:49 +0800 Subject: [PATCH 2/3] docs: replace oversized tables in README and guides with structured lists --- README.md | 43 ++++++++++++------------------------------- docs/index.md | 16 +++++++--------- docs/testing.md | 26 +++++++++++--------------- docs/web-transport.md | 8 +++----- 4 files changed, 33 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index 8af5cddc..65226046 100644 --- a/README.md +++ b/README.md @@ -22,11 +22,8 @@ uv add agent-client-protocol Optional extras: ```bash -# Streamable HTTP and WebSocket transports (experimental) -pip install "agent-client-protocol[http]" - -# Logfire / OpenTelemetry instrumentation -pip install "agent-client-protocol[logfire]" +pip install "agent-client-protocol[http]" # Streamable HTTP and WebSocket transports (experimental) +pip install "agent-client-protocol[logfire]" # Logfire / OpenTelemetry instrumentation ``` Requires Python 3.10–3.15. @@ -95,31 +92,15 @@ async def main() -> None: asyncio.run(main()) ``` -## Protocol and transport support - -| Capability | Import / Extra | Status | Reference | -| --- | --- | --- | --- | -| ACP v1 (`schema-v1.35.0`) | `acp`, `acp.schema` | Stable | [Quickstart](https://agentclientprotocol.github.io/python-sdk/quickstart/) · [Protocol Features](https://agentclientprotocol.github.io/python-sdk/protocol-features/) | -| ACP v2 (`schema-v2.0.0-beta.4`) + dual-stack router | `acp.experimental.v2`, `acp.experimental.AgentProtocolRouter` | Preview | [Experimental v2](https://agentclientprotocol.github.io/python-sdk/experimental-v2/) | -| Stdio JSON-RPC (NDJSON) | Built-in (`run_agent`, `connect_to_agent`, `spawn_agent_process`) | Stable | [Quickstart](https://agentclientprotocol.github.io/python-sdk/quickstart/) | -| Streamable HTTP & WebSocket | `acp.http`, `acp.ws` (`[http]`) | Experimental | [Web Transport](https://agentclientprotocol.github.io/python-sdk/web-transport/) | -| Stateless MCP-over-ACP | `acp` / `acp.experimental.v2` | Unstable / Preview | [Protocol Features](https://agentclientprotocol.github.io/python-sdk/protocol-features/#stateless-mcp-over-acp) | -| Session, tool call, and permission helpers | `acp.contrib` | Experimental | [Contrib Utilities](https://agentclientprotocol.github.io/python-sdk/contrib/) | - -## Documentation - -| Topic | Link | -| --- | --- | -| Documentation hub | | -| Quickstart | | -| Protocol features (v1) | | -| Web transport (HTTP & WebSocket) | | -| Experimental protocol v2 | | -| Contrib utilities | | -| Use cases | | -| Testing & conformance | | -| Releasing | | -| Runnable examples | | +## Capabilities and documentation + +- **ACP v1 (`acp`, `acp.schema`)** — Stable bindings for `schema-v1.35.0` with stdio JSON-RPC framing (`run_agent`, `connect_to_agent`, `spawn_agent_process`). Read the [Quickstart](https://agentclientprotocol.github.io/python-sdk/quickstart/) and [Protocol Features](https://agentclientprotocol.github.io/python-sdk/protocol-features/). +- **Experimental ACP v2 (`acp.experimental.v2`)** — Preview bindings for `schema-v2.0.0-beta.4` and dual-stack version negotiation via `AgentProtocolRouter`. Read [Experimental Protocol v2](https://agentclientprotocol.github.io/python-sdk/experimental-v2/). +- **Web transports (`acp.http`, `acp.ws`)** — Experimental Streamable HTTP (SSE + HTTP/2) and WebSocket client/server support via the `[http]` extra. Read [Web Transport](https://agentclientprotocol.github.io/python-sdk/web-transport/). +- **Stateless MCP-over-ACP** — Typed `mcp/message` request and notification envelopes across stdio, HTTP, and WebSocket. Read [MCP-over-ACP](https://agentclientprotocol.github.io/python-sdk/protocol-features/#stateless-mcp-over-acp). +- **Contrib utilities (`acp.contrib`)** — Experimental `SessionAccumulator`, `ToolCallTracker`, and `PermissionBroker` helpers. Read [Contrib Utilities](https://agentclientprotocol.github.io/python-sdk/contrib/). + +More resources: [Documentation Hub](https://agentclientprotocol.github.io/python-sdk/) · [Examples](https://github.com/agentclientprotocol/python-sdk/tree/main/examples) · [Use Cases](https://agentclientprotocol.github.io/python-sdk/use-cases/) · [Testing & Conformance](https://agentclientprotocol.github.io/python-sdk/testing/) · [Releasing](https://agentclientprotocol.github.io/python-sdk/releasing/) ## Development @@ -131,7 +112,7 @@ make gen-check # Verify generated schema bindings match schema/ make docs-test # Build MkDocs site strictly ``` -To regenerate protocol bindings when upstream schemas advance, run `ACP_SCHEMA_VERSION= make gen-all` (or `make gen-v2` for v2). +Regenerate bindings when upstream schemas advance with `ACP_SCHEMA_VERSION= make gen-all` (or `make gen-v2` for experimental v2). ## Community diff --git a/docs/index.md b/docs/index.md index 4330f22b..db45aa84 100644 --- a/docs/index.md +++ b/docs/index.md @@ -14,23 +14,21 @@ pip install agent-client-protocol uv add agent-client-protocol ``` -Install optional extras when you need remote transports or telemetry: +Optional extras: ```bash pip install "agent-client-protocol[http]" # Streamable HTTP + WebSocket pip install "agent-client-protocol[logfire]" # Logfire / OpenTelemetry ``` -## SDK overview +## Modules -| Module | Purpose | -| --- | --- | -| `acp` & `acp.schema` | Stable ACP v1 runtime (`run_agent`, `connect_to_agent`, `spawn_agent_process`, `Agent`, `Client`) and generated Pydantic models (`schema-v1.35.0`) | -| `acp.experimental.v2` | Preview ACP v2 runtime and generated models (`schema-v2.0.0-beta.4`), plus `AgentProtocolRouter` for dual-stack negotiation | -| `acp.http` & `acp.ws` | Experimental Streamable HTTP (SSE + HTTP/2) and WebSocket client/server transports (`[http]` extra) | -| `acp.contrib` | Experimental stateful helpers: `SessionAccumulator`, `ToolCallTracker`, and `PermissionBroker` | +- **`acp` and `acp.schema`** — Stable ACP v1 runtime (`run_agent`, `connect_to_agent`, `spawn_agent_process`, `Agent`, `Client`) and generated Pydantic models (`schema-v1.35.0`). +- **`acp.experimental.v2`** — Preview ACP v2 runtime and generated models (`schema-v2.0.0-beta.4`), plus `AgentProtocolRouter` for dual-stack negotiation. +- **`acp.http` and `acp.ws`** — Experimental Streamable HTTP (SSE + HTTP/2) and WebSocket client/server transports (`[http]` extra). +- **`acp.contrib`** — Experimental stateful helpers: `SessionAccumulator`, `ToolCallTracker`, and `PermissionBroker`. -## Documentation guide +## Guides - **[Quickstart](quickstart.md)** — Install the SDK, run the echo agent, connect from an ACP client, and launch processes programmatically. - **[Protocol Features (v1)](protocol-features.md)** — Session management, authentication, providers, notices, elicitation, stateless MCP-over-ACP, request cancellation, and extension methods. diff --git a/docs/testing.md b/docs/testing.md index 64247d06..0860764b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -22,14 +22,12 @@ The test suite under `tests/` covers: ## ACP TCK conformance -Protocol-level compliance is verified against the official [ACP TCK](https://github.com/agentclientprotocol/acp-tck) using reference agents built strictly on public SDK APIs. +Protocol-level compliance is verified against the official [ACP TCK](https://github.com/agentclientprotocol/acp-tck) using reference agents built strictly on public SDK APIs across four profiles: -| Profile | Entry point | Scope | Expected result | -| --- | --- | --- | --- | -| **v1 baseline** | `acp.run_agent` | Stable v1 agent suite (`Agent` subclass and structural handler) | `CONFORMANT` | -| **v2 minimal** | `v2.run_agent` and `AgentProtocolRouter(v2=...)` | Minimal capabilities; validates error codes (`-32022`, `-32600`, `-32601`, `-32602`) and disabled-capability handling | `CONFORMANT`, 0 failures | -| **v2 full capability** | `v2.run_agent` and `AgentProtocolRouter(v2=...)` | All supported v2 capabilities enabled (sessions, fork/resume/replay, config options, elicitation, MCP-over-ACP, permissions, cancellation) | `CONFORMANT`, 0 failures | -| **Dual-stack negotiation** | `AgentProtocolRouter(v1=..., v2=...)` | v1/v2 version selection (`ACP-INIT-208`), repeat `initialize`, and v2-to-v1 fallback | 0 failures on initialization suite | +- **v1 baseline (`acp.run_agent`)** — Stable v1 agent suite (`Agent` subclass and structural handler), expecting `CONFORMANT`. +- **v2 minimal (`v2.run_agent`, `AgentProtocolRouter(v2=...)`)** — Minimal capabilities, validating error codes (`-32022`, `-32600`, `-32601`, `-32602`) and disabled-capability handling with `CONFORMANT` and 0 failures. +- **v2 full capability (`v2.run_agent`, `AgentProtocolRouter(v2=...)`)** — All supported v2 capabilities enabled (sessions, fork/resume/replay, config options, elicitation, MCP-over-ACP, permissions, cancellation), expecting `CONFORMANT` and 0 failures. +- **Dual-stack negotiation (`AgentProtocolRouter(v1=..., v2=...)`)** — v1/v2 version selection (`ACP-INIT-208`), repeat `initialize`, and v2-to-v1 fallback with 0 failures on the initialization suite. When modifying schema base classes or deserialization helpers (`src/acp/_schema_base.py`, `src/acp/_deserialize.py`), also verify v1 `model_validate` latency on hot models (`AgentMessageChunk`, `SessionNotification`) to keep v1 validation performance steady. @@ -48,14 +46,12 @@ Real-world checks validate end-to-end behavior with ecosystem tools across two r Use the same six scenarios across clients and agents when validating releases or transport changes: -| ID | Scenario | Verified behavior | -| --- | --- | --- | -| **S1** | Handshake & negotiation | `initialize` exchanges protocol version, info, and capabilities; unsupported versions return clean errors | -| **S2** | Session & streaming | `session/new` followed by `session/prompt` streams `agent_message_chunk` updates through turn completion | -| **S3** | Tool calls & permissions | Tool call progress/content/diff updates and `request_permission` approve/reject flows complete end to end | -| **S4** | Cancellation & recovery | Sending `session/cancel` or `$/cancel_request` stops active work and leaves the session usable for the next prompt | -| **S5** | Session lifecycle & config | Advertised capabilities (`session/list`, `load`/`resume`, `fork`, `configOptions`, `mcp-over-acp`) round-trip cleanly | -| **S6** | Error handling & shutdown | Invalid frames or unimplemented methods keep the connection healthy; closing exits cleanly with zero orphan processes | +1. **S1 · Handshake & negotiation** — `initialize` exchanges protocol version, info, and capabilities; unsupported versions return clean errors. +2. **S2 · Session & streaming** — `session/new` followed by `session/prompt` streams `agent_message_chunk` updates through turn completion. +3. **S3 · Tool calls & permissions** — Tool call progress/content/diff updates and `request_permission` approve/reject flows complete end to end. +4. **S4 · Cancellation & recovery** — Sending `session/cancel` or `$/cancel_request` stops active work and leaves the session usable for the next prompt. +5. **S5 · Session lifecycle & config** — Advertised capabilities (`session/list`, `load`/`resume`, `fork`, `configOptions`, `mcp-over-acp`) round-trip cleanly. +6. **S6 · Error handling & shutdown** — Invalid frames or unimplemented methods keep the connection healthy; closing exits cleanly with zero orphan processes. ### Running the opt-in Gemini CLI smoke test diff --git a/docs/web-transport.md b/docs/web-transport.md index a78774e2..67d78ba1 100644 --- a/docs/web-transport.md +++ b/docs/web-transport.md @@ -128,11 +128,9 @@ asyncio.run(hypercorn.asyncio.serve(app, config)) ## HTTP headers and stream routing -| Header / Field | Role | -| --- | --- | -| `Acp-Connection-Id` | Returned on `initialize`; sent on subsequent HTTP `POST`/`GET`/`DELETE` requests | -| `Acp-Session-Id` | Sent on session-scoped `POST` requests and session-scoped `GET` SSE streams | -| `sessionId` | JSON-RPC payload field used to route server-to-client messages to the matching session stream | +- **`Acp-Connection-Id`** — Returned on `initialize`; sent on subsequent HTTP `POST`, `GET`, and `DELETE` requests. +- **`Acp-Session-Id`** — Sent on session-scoped `POST` requests and session-scoped `GET` SSE streams. +- **`sessionId`** — JSON-RPC payload field used to route server-to-client messages to the matching session stream. ## Examples From a680ce1e051302c4e1e185fb7683ed6ff8e00d9d Mon Sep 17 00:00:00 2001 From: Chojan Shang Date: Sat, 28 Nov 2026 13:45:32 +0800 Subject: [PATCH 3/3] docs: tighten README and guides to focus on core user-visible flows --- README.md | 42 ++++++----------- docs/experimental-v2.md | 94 +++++++++------------------------------ docs/index.md | 45 ++++++------------- docs/protocol-features.md | 71 +++++++---------------------- docs/quickstart.md | 74 +++++++----------------------- docs/releasing.md | 40 +++++------------ docs/testing.md | 71 +++++++++-------------------- docs/web-transport.md | 90 +++++-------------------------------- 8 files changed, 122 insertions(+), 405 deletions(-) diff --git a/README.md b/README.md index 65226046..4bbf8727 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ [![CI](https://github.com/agentclientprotocol/python-sdk/actions/workflows/main.yml/badge.svg)](https://github.com/agentclientprotocol/python-sdk/actions/workflows/main.yml) [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://agentclientprotocol.github.io/python-sdk/) -Python SDK for building [Agent Client Protocol (ACP)](https://agentclientprotocol.com/) agents and clients with generated Pydantic v2 models, asyncio JSON-RPC transports, and runnable examples. +Python SDK for building [Agent Client Protocol (ACP)](https://agentclientprotocol.com/) agents and clients, with generated Pydantic models and asyncio transports over stdio, Streamable HTTP, and WebSocket. ## Installation @@ -19,14 +19,7 @@ pip install agent-client-protocol uv add agent-client-protocol ``` -Optional extras: - -```bash -pip install "agent-client-protocol[http]" # Streamable HTTP and WebSocket transports (experimental) -pip install "agent-client-protocol[logfire]" # Logfire / OpenTelemetry instrumentation -``` - -Requires Python 3.10–3.15. +For experimental HTTP/WebSocket transports, install the `http` extra (`pip install "agent-client-protocol[http]"`). Requires Python 3.10–3.15. ## Quick example @@ -66,7 +59,7 @@ if __name__ == "__main__": asyncio.run(run_agent(EchoAgent())) ``` -### Connect from a client +### Drive an agent from Python ```python import asyncio @@ -92,31 +85,22 @@ async def main() -> None: asyncio.run(main()) ``` -## Capabilities and documentation - -- **ACP v1 (`acp`, `acp.schema`)** — Stable bindings for `schema-v1.35.0` with stdio JSON-RPC framing (`run_agent`, `connect_to_agent`, `spawn_agent_process`). Read the [Quickstart](https://agentclientprotocol.github.io/python-sdk/quickstart/) and [Protocol Features](https://agentclientprotocol.github.io/python-sdk/protocol-features/). -- **Experimental ACP v2 (`acp.experimental.v2`)** — Preview bindings for `schema-v2.0.0-beta.4` and dual-stack version negotiation via `AgentProtocolRouter`. Read [Experimental Protocol v2](https://agentclientprotocol.github.io/python-sdk/experimental-v2/). -- **Web transports (`acp.http`, `acp.ws`)** — Experimental Streamable HTTP (SSE + HTTP/2) and WebSocket client/server support via the `[http]` extra. Read [Web Transport](https://agentclientprotocol.github.io/python-sdk/web-transport/). -- **Stateless MCP-over-ACP** — Typed `mcp/message` request and notification envelopes across stdio, HTTP, and WebSocket. Read [MCP-over-ACP](https://agentclientprotocol.github.io/python-sdk/protocol-features/#stateless-mcp-over-acp). -- **Contrib utilities (`acp.contrib`)** — Experimental `SessionAccumulator`, `ToolCallTracker`, and `PermissionBroker` helpers. Read [Contrib Utilities](https://agentclientprotocol.github.io/python-sdk/contrib/). +## Documentation -More resources: [Documentation Hub](https://agentclientprotocol.github.io/python-sdk/) · [Examples](https://github.com/agentclientprotocol/python-sdk/tree/main/examples) · [Use Cases](https://agentclientprotocol.github.io/python-sdk/use-cases/) · [Testing & Conformance](https://agentclientprotocol.github.io/python-sdk/testing/) · [Releasing](https://agentclientprotocol.github.io/python-sdk/releasing/) +- [Quickstart](https://agentclientprotocol.github.io/python-sdk/quickstart/) — Connect your agent to Zed, Toad, Lody, or T3 Code, or drive agents programmatically. +- [Protocol Features](https://agentclientprotocol.github.io/python-sdk/protocol-features/) — Unstable opt-in methods, session notices, stateless MCP-over-ACP, cancellation, and extensions (`schema-v1.35.0`). +- [Web Transport](https://agentclientprotocol.github.io/python-sdk/web-transport/) — Serve and consume ACP over Streamable HTTP and WebSocket (`[http]`). +- [Experimental Protocol v2](https://agentclientprotocol.github.io/python-sdk/experimental-v2/) — Preview v2 runtime (`schema-v2.0.0-beta.4`) and dual-stack `AgentProtocolRouter`. +- [Examples](https://github.com/agentclientprotocol/python-sdk/tree/main/examples) · [Contrib](https://agentclientprotocol.github.io/python-sdk/contrib/) · [Use Cases](https://agentclientprotocol.github.io/python-sdk/use-cases/) · [Testing](https://agentclientprotocol.github.io/python-sdk/testing/) ## Development ```bash -make install # Create uv environment and install pre-commit hooks -make check # Lockfile check, Ruff lint/format, ty type check, deptry -make test # Run pytest with doctests -make gen-check # Verify generated schema bindings match schema/ -make docs-test # Build MkDocs site strictly +make install # Set up uv environment and pre-commit hooks +make check # Format, lint, type-check, and dependency check +make test # Run pytest suite ``` -Regenerate bindings when upstream schemas advance with `ACP_SCHEMA_VERSION= make gen-all` (or `make gen-v2` for experimental v2). - ## Community -- Issues and pull requests: -- Discussions: -- ACP specification and ecosystem: -- Zulip chat: +Join the conversation on [GitHub Discussions](https://github.com/agentclientprotocol/python-sdk/discussions), [Zulip](https://agentclientprotocol.zulipchat.com/), or [agentclientprotocol.com](https://agentclientprotocol.com/). diff --git a/docs/experimental-v2.md b/docs/experimental-v2.md index 9680bad7..318b0562 100644 --- a/docs/experimental-v2.md +++ b/docs/experimental-v2.md @@ -1,12 +1,12 @@ # Experimental Protocol v2 -> **Preview.** Protocol v2 lives under `acp.experimental` and tracks upstream beta releases. Its API and generated models evolve alongside the v2 specification. +> **Preview.** Protocol v2 lives under `acp.experimental` and tracks [`schema-v2.0.0-beta.4`](https://github.com/agentclientprotocol/agent-client-protocol/releases/tag/schema-v2.0.0-beta.4). -The v2 bindings target [`schema-v2.0.0-beta.4`](https://github.com/agentclientprotocol/agent-client-protocol/releases/tag/schema-v2.0.0-beta.4). Connection methods and agent/client handlers accept expanded snake_case parameters, responses and nested payloads use `acp.experimental.v2.schema` models, and extra keyword arguments serialize into `_meta`. +Connection methods and agent/client handlers accept expanded snake_case parameters, responses and nested payloads use `acp.experimental.v2.schema` models, and extra keyword arguments serialize into `_meta`. -## Client usage +## Client and agent usage -Register your `session_update` handler before opening a session so incoming updates are captured as soon as session traffic starts: +Register `session_update` before opening a session so streamed updates arrive as soon as traffic starts: ```python from typing import Any @@ -14,30 +14,20 @@ from acp.experimental import v2 class MyClient(v2.Client): - async def session_update( - self, - session_id: str, - update: v2.schema.SessionUpdate, - **kwargs: Any, - ) -> None: + async def session_update(self, session_id: str, update: v2.schema.SessionUpdate, **kwargs: Any) -> None: handle_update(session_id, update) connection = v2.connect_to_agent(MyClient(), transport) -initialized = await connection.initialize( +await connection.initialize( protocol_version=v2.PROTOCOL_VERSION, info=v2.schema.Implementation(name="my-client", version="1.0.0"), ) session = await connection.new_session(cwd="/workspace") -accepted = await connection.prompt( - session_id=session.session_id, - prompt=[v2.schema.TextContentBlock(text="Hello")], -) +accepted = await connection.prompt(session_id=session.session_id, prompt=[v2.schema.TextContentBlock(text="Hello")]) ``` -## Agent usage - -Implement the methods your agent supports (subclassing `v2.Agent` is optional) and start serving with `v2.run_agent()`: +Implement the handlers your agent supports (subclassing `v2.Agent` is optional) and serve with `v2.run_agent()`: ```python from typing import Any @@ -58,57 +48,26 @@ class MyAgent(v2.Agent): capabilities=v2.schema.AgentCapabilities(session=v2.schema.SessionCapabilities()), ) - async def new_session( - self, - cwd: str, - additional_directories: list[str] | None = None, - mcp_servers: list[Any] | None = None, - **kwargs: Any, - ) -> v2.schema.NewSessionResponse: + async def new_session(self, cwd: str, **kwargs: Any) -> v2.schema.NewSessionResponse: return v2.schema.NewSessionResponse(session_id="session-1") await v2.run_agent(MyAgent()) ``` -Unimplemented request handlers return JSON-RPC method-not-found (`-32601`), and unimplemented notifications are ignored. V2 connections require a successful `initialize` handshake before processing other methods and enforce strict request/response validation. +V2 connections require a successful `initialize` handshake before other methods and validate requests and responses strictly. -## Union requests +## Key v2 behaviors -Config options and elicitation requests use expanded parameters: - -```python -# `type` defaults to "boolean" for bool values and "id" otherwise. -await connection.set_config_option(config_id="thinking", session_id=session.session_id, value=True) -await connection.set_config_option( - config_id="vendor/limit", - session_id=session.session_id, - value=10, - type="vendor/number", -) - -await agent_connection.create_elicitation( - message="Sign in", - mode="url", - session_id=session.session_id, - elicitation_id="sign-in-1", - url="https://example.com/login", -) -``` - -For `create_elicitation`, pass `session_id` for session scope or a string/integer `request_id` for request scope. Pass `requested_schema` for form mode, or `elicitation_id` and `url` for URL mode. Accepted elicitation content preserves scalars, string lists, and custom JSON values. - -## Prompts, updates, notices, and replay - -- **Prompt submission**: `session/prompt` returns `PromptResponse(message_id=...)` once the user message is accepted into the conversation, allowing independent streaming updates. Pass `idempotency_key` (1–255 characters) so retried submissions return the original `message_id`. Agents echo the user message in a `UserMessageUpdate` or `UserMessageChunk` carrying `accepted.message_id`. -- **Session notices**: Agents can emit live advisory events via `v2.schema.SessionNotice(severity="warning", title="Context is nearly full")` with `agent_connection.session_update(...)`. Titles must be non-empty; severity accepts standard and custom string values. -- **Patch semantics**: In patch updates such as `SessionToolCallUpdate` and `SessionTerminalUpdate`, omit a field to leave its current value unchanged, or pass `None` to clear it. Call `update.model_dump(by_alias=True, exclude_unset=True)` to preserve that distinction when applying patches. -- **Replay on resume**: Pass `replay_from=v2.schema.ReplayFromStartVariant()` to `connection.resume_session(...)` to request retained conversation history. -- **Reusable union aliases**: `v2.schema` exports `SessionUpdate`, `ContentBlock`, `StateUpdate`, `BackgroundWork`, and `AvailableCommand` for type annotations and validation. +- **Asynchronous prompt submission**: `session/prompt` returns `PromptResponse(message_id=...)` once the user message is accepted, while updates stream independently. Pass `idempotency_key` (1–255 chars) so retried submissions reuse the original `message_id`. +- **Expanded union calls**: `set_config_option` infers `type` (`"boolean"` for `bool`, `"id"` otherwise, or pass a custom `type`); `create_elicitation` accepts either `session_id` or `request_id` along with form or URL parameters. +- **Patch updates**: In updates like `SessionToolCallUpdate` and `SessionTerminalUpdate`, omit a field to keep its value or pass `None` to clear it. Serialize with `update.model_dump(by_alias=True, exclude_unset=True)` to preserve that distinction. +- **Notices and replay**: Agents can emit live advisory `v2.schema.SessionNotice(...)` updates, and clients can request retained history via `resume_session(..., replay_from=v2.schema.ReplayFromStartVariant())`. +- **Reusable union aliases**: `v2.schema` exports `SessionUpdate`, `ContentBlock`, `StateUpdate`, `BackgroundWork`, and `AvailableCommand`. ## Dual-stack v1/v2 negotiation -Use `AgentProtocolRouter` to serve both protocol versions on the same endpoint (stdio, HTTP, or WebSocket): +Use `AgentProtocolRouter` to serve both protocol versions on one stdio, HTTP, or WebSocket endpoint: ```python from acp.experimental import AgentProtocolRouter @@ -120,19 +79,10 @@ router = AgentProtocolRouter( await router.run() ``` -The selected factory runs once per connection and should return a fresh agent instance. When an agent configured with v1 receives a v2 `initialize` request, the router translates the common initialization fields and negotiates down to v1; once negotiated, the connection enforces the selected protocol version strictly. - -## Extension methods and cancellation - -Extension method names carry the protocol-required `_` prefix: - -```python -result = await connection.send_extension_request("_vendor/method", {"value": 1}) -await connection.send_extension_notification("_vendor/event", {"value": 1}) -``` - -Protocol-level request cancellation (`$/cancel_request`) cancels the running handler task (answering with its return value if caught, or `-32800` otherwise), and cancelling a task awaiting an outgoing request sends a best-effort `$/cancel_request`. Use `connection.cancel_session(session_id=...)` to stop active session work. +Each connection invokes the selected factory once and runs strictly under the negotiated protocol version. -## Stateless MCP-over-ACP +## Extensions, cancellation, and MCP-over-ACP -V2 uses the same [stateless MCP binding](protocol-features.md#stateless-mcp-over-acp) with `v2.schema.McpResultResponse`, `McpErrorResponse`, `McpError`, and `MessageMcpResponse`. Agents advertise support via `capabilities.session.mcp.acp = {}`, send `mcp_message` requests with explicit `server_id` and `request_id` strings, and receive provider notifications through `notify_mcp`. +- Call `send_extension_request("_vendor/method", ...)` and `send_extension_notification("_vendor/event", ...)` for vendor extensions. +- `$/cancel_request` cancels running handler tasks and outgoing requests automatically; use `cancel_session(session_id=...)` for active session work. +- [Stateless MCP-over-ACP](protocol-features.md#stateless-mcp-over-acp) uses `v2.schema.McpResultResponse`, `McpErrorResponse`, and `MessageMcpResponse` when the agent advertises `capabilities.session.mcp.acp = {}`. diff --git a/docs/index.md b/docs/index.md index db45aa84..256cfabc 100644 --- a/docs/index.md +++ b/docs/index.md @@ -4,44 +4,25 @@ # Agent Client Protocol SDK (Python) -Build ACP-compliant agents and clients in Python using generated Pydantic v2 models, asyncio JSON-RPC transports, and typed protocol interfaces. - -## Installation +Build ACP agents and clients in Python with generated Pydantic models and asyncio transports over stdio, Streamable HTTP, and WebSocket. ```bash pip install agent-client-protocol -# or -uv add agent-client-protocol -``` - -Optional extras: - -```bash -pip install "agent-client-protocol[http]" # Streamable HTTP + WebSocket -pip install "agent-client-protocol[logfire]" # Logfire / OpenTelemetry +# Optional: pip install "agent-client-protocol[http]" ``` -## Modules - -- **`acp` and `acp.schema`** — Stable ACP v1 runtime (`run_agent`, `connect_to_agent`, `spawn_agent_process`, `Agent`, `Client`) and generated Pydantic models (`schema-v1.35.0`). -- **`acp.experimental.v2`** — Preview ACP v2 runtime and generated models (`schema-v2.0.0-beta.4`), plus `AgentProtocolRouter` for dual-stack negotiation. -- **`acp.http` and `acp.ws`** — Experimental Streamable HTTP (SSE + HTTP/2) and WebSocket client/server transports (`[http]` extra). -- **`acp.contrib`** — Experimental stateful helpers: `SessionAccumulator`, `ToolCallTracker`, and `PermissionBroker`. +## Where to start -## Guides +- **[Quickstart](quickstart.md)** — Run the echo agent, wire it into an editor or CLI client, and write your first custom agent. +- **[Protocol Features (v1)](protocol-features.md)** — Use unstable opt-in features, session notices, stateless MCP-over-ACP, request cancellation, and extension methods. +- **[Web Transport](web-transport.md)** — Run ACP over Streamable HTTP (HTTP/2 + SSE) and WebSocket with Starlette. +- **[Experimental Protocol v2](experimental-v2.md)** — Explore the preview v2 API (`schema-v2.0.0-beta.4`) and dual-stack `AgentProtocolRouter`. +- **[Contrib Utilities](contrib.md)** — Reuse stateful helpers for session aggregation, tool call tracking, and permission prompts. -- **[Quickstart](quickstart.md)** — Install the SDK, run the echo agent, connect from an ACP client, and launch processes programmatically. -- **[Protocol Features (v1)](protocol-features.md)** — Session management, authentication, providers, notices, elicitation, stateless MCP-over-ACP, request cancellation, and extension methods. -- **[Web Transport (HTTP & WebSocket)](web-transport.md)** — Serve and consume ACP over Streamable HTTP and WebSocket with Starlette and HTTP/2. -- **[Experimental Protocol v2](experimental-v2.md)** — Preview v2 API, expanded handlers, patch updates, replay cursors, and dual-stack routing. -- **[Contrib Utilities](contrib.md)** — Higher-level session state accumulators, tool call trackers, and permission brokers. -- **[Use Cases](use-cases.md)** — Production agents and clients built with the SDK. -- **[Testing & Conformance](testing.md)** — Local test suites, ACP TCK conformance profiles, cross-SDK interop, and real-world client/agent verification. -- **[Releasing](releasing.md)** — Schema upgrades, verification gates, and PyPI/docs release workflow. +## Ecosystem and operations -## Community +- **[Use Cases](use-cases.md)** — Agents and clients built with this SDK. +- **[Testing & Conformance](testing.md)** — Local checks, ACP TCK conformance, and real-world interoperability checks. +- **[Releasing](releasing.md)** — Schema updates and release workflow. -- Issues and pull requests: [agentclientprotocol/python-sdk](https://github.com/agentclientprotocol/python-sdk) -- Discussions: [GitHub Discussions](https://github.com/agentclientprotocol/python-sdk/discussions) -- Community chat: [agentclientprotocol.zulipchat.com](https://agentclientprotocol.zulipchat.com/) -- Protocol specification: [agentclientprotocol.com](https://agentclientprotocol.com/) +Questions and feedback are welcome in [GitHub Discussions](https://github.com/agentclientprotocol/python-sdk/discussions) and on [Zulip](https://agentclientprotocol.zulipchat.com/). diff --git a/docs/protocol-features.md b/docs/protocol-features.md index c838a1e5..d7e6407a 100644 --- a/docs/protocol-features.md +++ b/docs/protocol-features.md @@ -1,56 +1,20 @@ # Protocol Features (v1) -The stable v1 bindings track [`schema-v1.35.0`](https://github.com/agentclientprotocol/agent-client-protocol/releases/tag/schema-v1.35.0). Both `Agent` and `Client` interfaces expose expanded snake_case parameters, with extra keyword arguments carrying JSON-RPC `_meta`. - -## Enabling unstable protocol methods - -Unstable methods require explicit opt-in on the receiving side by passing `use_unstable_protocol=True` to `run_agent()`, `connect_to_agent()`, `AgentSideConnection`, or `ClientSideConnection`. Check the peer's advertised capabilities from `initialize` before calling optional or unstable methods. Unimplemented request handlers return JSON-RPC method-not-found (`-32601`). - -### Agent methods - -| Wire method | Python method | Stability | -| --- | --- | --- | -| `initialize` | `initialize` | Stable | -| `authenticate`, `logout` | `authenticate`, `logout` | Stable | -| `session/new`, `session/load`, `session/list` | `new_session`, `load_session`, `list_sessions` | Stable | -| `session/resume`, `session/close`, `session/delete` | `resume_session`, `close_session`, `delete_session` | Stable | -| `session/set_mode`, `session/set_config_option` | `set_session_mode`, `set_config_option` | Stable | -| `session/prompt`, `session/cancel` | `prompt`, `cancel` | Stable | -| `session/fork` | `fork_session` | Unstable | -| `session/archive`, `session/unarchive` | `archive_session`, `unarchive_session` | Unstable | -| `session/status`, `session/options`, `session/set_title` | `session_status`, `session_options`, `set_session_title` | Unstable | -| `auth/status` | `auth_status` | Unstable | -| `providers/list`, `providers/set`, `providers/disable` | `list_providers`, `set_provider`, `disable_provider` | Unstable | -| `mcp/message` (notification) | `notify_mcp` | Unstable | - -### Client methods - -| Wire method | Python method | Stability | -| --- | --- | --- | -| `session/request_permission`, `session/update` | `request_permission`, `session_update` | Stable | -| `fs/read_text_file`, `fs/write_text_file` | `read_text_file`, `write_text_file` | Stable | -| `terminal/create`, `terminal/output`, `terminal/wait_for_exit`, `terminal/kill`, `terminal/release` | `create_terminal`, `terminal_output`, `wait_for_terminal_exit`, `kill_terminal`, `release_terminal` | Stable | -| `elicitation/create`, `elicitation/complete` | `create_elicitation`, `complete_elicitation` | Unstable | -| `auth/status_update` (notification) | `auth_status_update` | Unstable | -| `mcp/message` (request) | `mcp_message` | Unstable | - -For example, an agent supporting session deletion implements `delete_session`: +The stable v1 bindings track [`schema-v1.35.0`](https://github.com/agentclientprotocol/agent-client-protocol/releases/tag/schema-v1.35.0). Handlers and connection methods accept expanded snake_case parameters, and extra keyword arguments serialize into JSON-RPC `_meta`. -```python -from typing import Any -from acp import DeleteSessionResponse +## Unstable protocol methods +Core session, authentication, filesystem, and terminal methods work out of the box, including `session/delete` (`delete_session`) and `logout`. Unstable protocol methods—such as session `fork`/`archive`/`status`/`options`/`set_title`, `providers/*`, `auth/status`, elicitation, and `mcp/message`—are enabled on the receiving connection by passing `use_unstable_protocol=True`: -async def delete_session(self, session_id: str, **kwargs: Any) -> DeleteSessionResponse: - await self.session_store.delete(session_id) - return DeleteSessionResponse() +```python +await run_agent(MyAgent(), use_unstable_protocol=True) ``` -Clients invoke `await conn.delete_session(session_id=session_id)` to remove persisted session state, and `await conn.close_session(session_id=session_id)` to close an active session handle. +Check the peer's advertised capabilities from `initialize` before calling optional or unstable methods. Unimplemented request handlers return JSON-RPC method-not-found (`-32601`). ## Session notices -Clients that render live advisory notices advertise `ClientCapabilities(session=ClientSessionCapabilities(notices=NoticeCapabilities()))` during `initialize`. When that capability is advertised, agents can send `SessionUpdateNotice` updates: +When a client advertises `ClientCapabilities(session=ClientSessionCapabilities(notices=NoticeCapabilities()))`, agents can send live advisory notices outside session history: ```python from acp.schema import SessionUpdateNotice @@ -65,13 +29,13 @@ await client.session_update( ) ``` -Notices are live advisory events outside retained session history. `title` must be non-empty; `severity` accepts `"info"`, `"warning"`, `"error"`, and custom string values. +`title` must be non-empty; `severity` accepts `"info"`, `"warning"`, `"error"`, and custom string values. ## Stateless MCP-over-ACP -The unstable native MCP binding targets **MCP 2026-07-28**. A client/provider declares an `AcpMcpServer(name=..., server_id=...)` during session setup when the agent advertises `mcpCapabilities.acp`, after registering its `mcp_message` handler so immediate calls from the agent are served. +The unstable MCP binding targets **MCP 2026-07-28**. When an agent advertises `mcpCapabilities.acp`, a client can pass `AcpMcpServer(name=..., server_id=...)` during session setup after registering its `mcp_message` handler. -Agents send `mcp_message` requests with a fresh string `request_id` per operation and the required MCP metadata in `params["_meta"]`: +Agents send `mcp_message` requests with a fresh string `request_id` per operation and MCP metadata in `params["_meta"]`: ```python from uuid import uuid4 @@ -87,7 +51,6 @@ response = await conn.mcp_message( "io.modelcontextprotocol/clientCapabilities": {}, }, }, - trace="outer ACP metadata", ) if isinstance(response, McpErrorResponse): handle_mcp_error(response.error) @@ -95,19 +58,19 @@ else: use_mcp_result(response.result) ``` -Providers answer with `McpResultResponse(result=...)` or `McpErrorResponse(error=McpError(code=..., message=...))`. Outer ACP transport or routing errors raise `RequestError`; inner MCP errors stay inside `McpErrorResponse.error`. While a request is active, providers can emit progress via `notify_mcp(server_id=..., request_id=..., method=..., params=...)` using matching IDs, stopping notifications before returning the final response. +Providers return `McpResultResponse(result=...)` or `McpErrorResponse(error=McpError(code=..., message=...))` and can send in-flight progress via `notify_mcp(...)` with matching `server_id` and `request_id`. Outer ACP failures raise `RequestError`; inner MCP errors stay inside `McpErrorResponse.error`. -MCP-over-ACP works across stdio, Streamable HTTP, and WebSocket connections. Run `uv run python examples/mcp_over_acp.py` for a runnable demo, and see the [ACP MCP-over-ACP specification](https://agentclientprotocol.com/rfds/mcp-over-acp) for registration and error-code rules. +Run `uv run python examples/mcp_over_acp.py` for a full local example. ## Request cancellation -Connections handle the protocol's `$/cancel_request` notification automatically: +Connections handle `$/cancel_request` automatically: -- **Incoming cancellation**: The SDK cancels the asyncio task running the target handler. If the handler catches `asyncio.CancelledError` and returns a value, that result is sent to the peer; otherwise the peer receives `-32800` (`Request cancelled`). -- **Outgoing cancellation**: Cancelling the task awaiting an outgoing request (for example via `asyncio.wait_for`) raises `asyncio.CancelledError` locally and sends a best-effort `$/cancel_request` notification to the peer. +- Cancelling a task awaiting an outgoing request sends a best-effort `$/cancel_request` to the peer and raises `asyncio.CancelledError` locally. +- Receiving `$/cancel_request` cancels the handler task; if the handler catches `asyncio.CancelledError` and returns a value, that result is sent back, otherwise the peer receives `-32800` (`Request cancelled`). -Use `session/cancel` (`conn.cancel(session_id=...)`) to stop active work inside a session turn. +Use `conn.cancel(session_id=...)` (`session/cancel`) to stop active work inside a prompt turn. ## Extension methods -Custom vendor methods use the `_` prefix required by ACP. Implement `ext_method(self, method: str, params: dict[str, Any])` and `ext_notification(self, method: str, params: dict[str, Any])` on your `Agent` or `Client` to handle incoming extension traffic, and call `conn.ext_method(...)` / `conn.ext_notification(...)` to send outgoing extensions. +Implement `ext_method` and `ext_notification` on your `Agent` or `Client` to handle vendor-prefixed `_` methods, and call `conn.ext_method(...)` / `conn.ext_notification(...)` to send them. diff --git a/docs/quickstart.md b/docs/quickstart.md index cbc772ac..a254d165 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -1,13 +1,8 @@ # Quickstart -Launch a working ACP agent and client in minutes. +Launch a streaming ACP agent and connect a client in a few minutes (requires Python 3.10–3.15). -## Prerequisites - -- Python 3.10–3.15 with `pip` or `uv` -- An ACP client (such as Zed, Toad, Lody, or T3 Code) or the SDK's programmatic client helpers - -## 1. Install the SDK +## 1. Install ```bash pip install agent-client-protocol @@ -15,21 +10,15 @@ pip install agent-client-protocol uv add agent-client-protocol ``` -## 2. Run the echo agent +## 2. Run the echo agent and connect a client -`examples/echo_agent.py` implements a minimal streaming agent over stdio: +`examples/echo_agent.py` is a runnable stdio agent that streams incoming prompt text back as `session/update` notifications: ```bash python examples/echo_agent.py ``` -The process reads newline-delimited JSON-RPC frames from `stdin` and writes responses and `session/update` notifications to `stdout`. - -## 3. Connect from an ACP client - -### Zed - -Add an entry to Zed's `settings.json`: +Point any stdio ACP client (such as Zed, Toad, Lody, or T3 Code) at that command. For example, in Zed's `settings.json`: ```json { @@ -37,24 +26,15 @@ Add an entry to Zed's `settings.json`: "Echo Agent (Python)": { "type": "custom", "command": "uv", - "args": [ - "run", - "/abs/path/to/python-sdk/examples/echo_agent.py" - ] + "args": ["run", "/abs/path/to/python-sdk/examples/echo_agent.py"] } } } ``` -Open the Agents panel, select **Echo Agent (Python)**, and send a message to observe streamed `session/update` responses. +## 3. Drive an agent from Python -### Other stdio clients - -Any ACP-compatible stdio client (including Toad, Lody, and T3 Code) can launch the same command and arguments directly. - -### Programmatic launch - -Use `spawn_agent_process` to start an agent subprocess, attach stdio framing, and close both the connection and subprocess on exit: +Use `spawn_agent_process` to start an agent subprocess, exchange JSON-RPC messages over stdio, and close both cleanly on exit: ```python import asyncio @@ -79,20 +59,17 @@ async def main() -> None: async with spawn_agent_process(SimpleClient(), sys.executable, str(script)) as (conn, _proc): await conn.initialize(protocol_version=PROTOCOL_VERSION) session = await conn.new_session(cwd=str(script.parent), mcp_servers=[]) - await conn.prompt( - session_id=session.session_id, - prompt=[TextContentBlock(text="Hello from spawn!")], - ) + await conn.prompt(session_id=session.session_id, prompt=[TextContentBlock(text="Hello from spawn!")]) asyncio.run(main()) ``` -`spawn_client_process` provides the corresponding helper for spawning an ACP client subprocess from an agent. +`spawn_client_process` provides the matching helper when an agent spawns a client subprocess. -## 4. Build a custom agent +## 4. Write your own agent -Subclass `acp.Agent`, implement the methods your agent supports, and start the stdio loop with `acp.run_agent()`: +Subclass `acp.Agent`, implement the methods your agent supports, and start serving with `acp.run_agent()`: ```python import asyncio @@ -126,30 +103,9 @@ if __name__ == "__main__": asyncio.run(run_agent(MyAgent())) ``` -Generated schema models provide defaults for discriminator fields such as `type` and `sessionUpdate`, enabling direct construction: - -```python -from acp.schema import AgentMessageChunk, TextContentBlock - -update = AgentMessageChunk(content=TextContentBlock(text="File opened.")) -``` - -Handlers and connection methods accept expanded snake_case parameters, with additional keyword arguments serialized as request `_meta`. - -## Runnable examples - -- [`examples/echo_agent.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/echo_agent.py) — minimal streaming agent -- [`examples/agent.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/agent.py) — agent with capability negotiation and richer updates -- [`examples/client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/client.py) — interactive stdio client -- [`examples/duet.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/duet.py) — in-process client/agent pairing with `spawn_agent_process` -- [`examples/mcp_over_acp.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/mcp_over_acp.py) — stateless MCP-over-ACP exchange -- [`examples/gemini.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/gemini.py) — bridge to the Gemini CLI (`gemini --acp`) -- [`examples/http_server.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_server.py), [`examples/http_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_client.py), [`examples/ws_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/ws_client.py) — Streamable HTTP and WebSocket demos +Generated schema models populate discriminator fields (`type`, `sessionUpdate`) automatically, so models like `AgentMessageChunk(content=TextContentBlock(text="Hello!"))` can be constructed directly. Extra keyword arguments on connection calls and handlers carry JSON-RPC `_meta`. ## Next steps -- Explore v1 capabilities in [Protocol Features (v1)](protocol-features.md). -- Serve agents remotely with [Web Transport (HTTP & WebSocket)](web-transport.md). -- Try the preview protocol in [Experimental Protocol v2](experimental-v2.md). -- Reuse stateful UI/agent helpers from [Contrib Utilities](contrib.md). -- Validate integrations with [Testing & Conformance](testing.md). +- Browse [`examples/`](https://github.com/agentclientprotocol/python-sdk/tree/main/examples) for fuller agent, client, HTTP/WS, MCP-over-ACP, and Gemini CLI demos. +- Continue to [Protocol Features (v1)](protocol-features.md), [Web Transport](web-transport.md), or [Experimental Protocol v2](experimental-v2.md). diff --git a/docs/releasing.md b/docs/releasing.md index 67d228a2..457e6dfe 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,43 +1,23 @@ # Releasing -Package releases track pinned upstream ACP schema tags from [`agentclientprotocol/agent-client-protocol`](https://github.com/agentclientprotocol/agent-client-protocol) (`schema/VERSION` for v1 and `schema/v2/VERSION` for experimental v2). +Releases track pinned upstream ACP schema tags (`schema/VERSION` for v1 and `schema/v2/VERSION` for experimental v2). -## Preparation checklist +## Release checklist -1. **Refresh schema bindings** when targeting a new upstream schema tag: +1. Refresh generated bindings when advancing the upstream schema: ```bash - # v1 bindings ACP_SCHEMA_VERSION=schema-v1.35.0 make gen-all - - # Experimental v2 bindings ACP_SCHEMA_VERSION=schema-v2.0.0-beta.4 make gen-v2 ``` -2. **Bump the SDK version** in `pyproject.toml` using a PEP 440 version string (for example `1.0.0rc3` or `1.0.0`) and update `uv.lock` if dependencies changed. -3. **Run local verification gates:** +2. Bump the version in `pyproject.toml` (PEP 440, e.g. `1.0.0rc3` or `1.0.0`) and refresh `uv.lock` when dependencies change. +3. Run the verification gates: ```bash - make gen-check - make check - make test - make docs-test + make gen-check && make check && make test && make docs-test ``` -4. **Run conformance and ecosystem checks** for schema, transport, or router changes: - - Run the [ACP TCK](testing.md#acp-tck-conformance) profiles (v1 baseline, v2 minimal/full capability, dual-stack router). - - Run the [S1–S6 real-world smoke playbook](testing.md#real-world-client-and-agent-verification) against available ACP clients and agents, and include the summary in the release PR. -5. **Update docs and examples** whenever public APIs, schema models, or transports change. - -## Commit and PR - -- Use Conventional Commits (`release: 1.0.0`, `feat(schema)!: ...`, `docs: ...`). -- Record the targeted v1/v2 schema tags, verification outputs (`make check`, `make test`, TCK verdict), and user-visible highlights in the PR description. - -## Publish via GitHub Release - -Publishing is automated by `.github/workflows/on-release-main.yml`: +4. For schema, transport, or router releases, run the [ACP TCK and real-world smoke checks](testing.md) and summarize the results in the release PR. -1. Create and publish a GitHub Release on `main` whose tag matches the package version (for example `1.0.0`). -2. The workflow syncs the version into `pyproject.toml`, builds the wheel/sdist, and publishes to PyPI via `uv publish`. -3. Once publishing succeeds, **Publish release docs** builds the MkDocs site from the release commit and deploys it to GitHub Pages. +## Publishing -## Republishing docs for an existing release +Create and publish a GitHub Release on `main` whose tag matches the package version (for example `1.0.0`). `.github/workflows/on-release-main.yml` syncs the version, builds and publishes to PyPI, and deploys the MkDocs site to GitHub Pages. -Open **Actions → Publish release docs → Run workflow**, select the `main` branch, and enter the published release tag in `release-tag`. The workflow rebuilds and deploys documentation for that tag to GitHub Pages. +To republish documentation for an existing tag, trigger **Actions → Publish release docs → Run workflow** on `main` with the target `release-tag`. diff --git a/docs/testing.md b/docs/testing.md index 0860764b..392e1915 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1,74 +1,47 @@ # Testing & Conformance -The SDK validates protocol behavior across four layers: local unit/contract tests, the official ACP Technology Compatibility Kit (TCK), cross-SDK wire interoperability, and real-world client/agent integration checks. +We validate SDK changes at three levels: fast local checks, official ACP TCK conformance, and real-world interoperability. -## Local test suite - -Run the standard repository checks locally: +## Local checks ```bash make gen-check # Verify generated bindings match schema/ -make check # Lockfile consistency, Ruff lint/format, ty type check, deptry +make check # Lockfile, Ruff lint/format, ty type check, deptry make test # Pytest suite (including doctests) make docs-test # Strict MkDocs build ``` -The test suite under `tests/` covers: - -- Generated schema models, lenient deserialization (`x-deserialize-*`), and golden wire fixtures (`tests/test_golden.py`, `tests/test_deserialize.py`, `tests/test_v2_schema.py`) -- JSON-RPC framing, cancellation (`$/cancel_request`), routing, and protocol negotiation (`tests/test_rpc.py`, `tests/test_protocol_negotiation.py`, `tests/test_v2_runtime.py`) -- Streamable HTTP and WebSocket client/server transports (`tests/http/`) -- Contrib helpers (`tests/contrib/`) and stdio subprocess lifecycles (`tests/real_user/`) - -## ACP TCK conformance - -Protocol-level compliance is verified against the official [ACP TCK](https://github.com/agentclientprotocol/acp-tck) using reference agents built strictly on public SDK APIs across four profiles: - -- **v1 baseline (`acp.run_agent`)** — Stable v1 agent suite (`Agent` subclass and structural handler), expecting `CONFORMANT`. -- **v2 minimal (`v2.run_agent`, `AgentProtocolRouter(v2=...)`)** — Minimal capabilities, validating error codes (`-32022`, `-32600`, `-32601`, `-32602`) and disabled-capability handling with `CONFORMANT` and 0 failures. -- **v2 full capability (`v2.run_agent`, `AgentProtocolRouter(v2=...)`)** — All supported v2 capabilities enabled (sessions, fork/resume/replay, config options, elicitation, MCP-over-ACP, permissions, cancellation), expecting `CONFORMANT` and 0 failures. -- **Dual-stack negotiation (`AgentProtocolRouter(v1=..., v2=...)`)** — v1/v2 version selection (`ACP-INIT-208`), repeat `initialize`, and v2-to-v1 fallback with 0 failures on the initialization suite. - -When modifying schema base classes or deserialization helpers (`src/acp/_schema_base.py`, `src/acp/_deserialize.py`), also verify v1 `model_validate` latency on hot models (`AgentMessageChunk`, `SessionNotification`) to keep v1 validation performance steady. +## Protocol conformance (ACP TCK) -## Cross-SDK wire interoperability +Schema, router, and transport changes are verified against the official [ACP TCK](https://github.com/agentclientprotocol/acp-tck) using reference agents built strictly on public SDK APIs: -For schema upgrades and client-side behavior ahead of TCK releases, run live bidirectional stdio checks pairing this SDK with the official [TypeScript SDK](https://github.com/agentclientprotocol/typescript-sdk) and [Rust SDK](https://github.com/agentclientprotocol/rust-sdk) across all four directions (Python client ↔ TS/Rust agent, TS/Rust client ↔ Python agent). +- **v1 baseline**: `acp.run_agent` passes the v1 suite (`CONFORMANT`). +- **v2 minimal and full capability**: both `v2.run_agent` and `AgentProtocolRouter(v2=...)` pass with 0 failures (`CONFORMANT`). +- **Dual-stack negotiation**: `AgentProtocolRouter(v1=..., v2=...)` passes v1/v2 version selection, repeat `initialize`, and v2-to-v1 fallback. -## Real-world client and agent verification +When changing shared schema or deserialization code, also check v1 `model_validate` latency on hot models (`AgentMessageChunk`, `SessionNotification`) to avoid regressions. -Real-world checks validate end-to-end behavior with ecosystem tools across two roles: +## Real-world interoperability -- **Real ACP clients** (exercising Python SDK agents): **Zed**, **T3 Code**, **Toad**, and **Lody** -- **Real ACP agents** (exercising Python SDK clients): **Gemini CLI** (`gemini --acp`), **Bub** (`bub-acp-server`), and **Mistral Vibe** +Before major releases or schema bumps, we run live end-to-end checks across two directions: -### Standard smoke playbook (`S1–S6`) +- **Real ACP clients** driving Python SDK agents: **Zed**, **T3 Code**, **Toad**, and **Lody**. +- **Real ACP agents** driven by Python SDK clients: **Gemini CLI** (`gemini --acp`), **Bub** (`bub-acp-server`), and **Mistral Vibe**, plus live stdio checks against the official [TypeScript](https://github.com/agentclientprotocol/typescript-sdk) and [Rust](https://github.com/agentclientprotocol/rust-sdk) SDKs. -Use the same six scenarios across clients and agents when validating releases or transport changes: +A standard end-to-end pass exercises one continuous flow: -1. **S1 · Handshake & negotiation** — `initialize` exchanges protocol version, info, and capabilities; unsupported versions return clean errors. -2. **S2 · Session & streaming** — `session/new` followed by `session/prompt` streams `agent_message_chunk` updates through turn completion. -3. **S3 · Tool calls & permissions** — Tool call progress/content/diff updates and `request_permission` approve/reject flows complete end to end. -4. **S4 · Cancellation & recovery** — Sending `session/cancel` or `$/cancel_request` stops active work and leaves the session usable for the next prompt. -5. **S5 · Session lifecycle & config** — Advertised capabilities (`session/list`, `load`/`resume`, `fork`, `configOptions`, `mcp-over-acp`) round-trip cleanly. -6. **S6 · Error handling & shutdown** — Invalid frames or unimplemented methods keep the connection healthy; closing exits cleanly with zero orphan processes. +1. **Handshake** — `initialize` negotiates version and capabilities cleanly. +2. **Streaming turn** — `session/new` and `session/prompt` stream updates through turn completion. +3. **Tools & permissions** — tool call updates and `request_permission` approve/reject flows complete cleanly. +4. **Cancel & continue** — cancelling mid-turn stops active work and leaves the session ready for the next prompt. +5. **Session lifecycle & exit** — advertised session/config/MCP features work and closing leaves zero orphan processes. -### Running the opt-in Gemini CLI smoke test +### Opt-in Gemini CLI smoke test -When the Gemini CLI is installed and authenticated locally, run the built-in smoke test in `tests/test_gemini_example.py`: +With the Gemini CLI installed and authenticated locally: ```bash ACP_ENABLE_GEMINI_TESTS=1 uv run python -m pytest tests/test_gemini_example.py ``` -Optional environment variables: - -- `ACP_GEMINI_BIN` — custom path to the `gemini` executable (defaults to `PATH` lookup) -- `ACP_GEMINI_TEST_ARGS` — extra flags forwarded to `examples/gemini.py` - -You can also run the interactive bridge directly: - -```bash -python examples/gemini.py --skip-trust --yolo -python examples/gemini.py --skip-trust --sandbox --model gemini-1.5-pro -``` +Set `ACP_GEMINI_BIN` to override the executable path or `ACP_GEMINI_TEST_ARGS` to pass extra flags to `examples/gemini.py`. diff --git a/docs/web-transport.md b/docs/web-transport.md index 67d78ba1..d145878f 100644 --- a/docs/web-transport.md +++ b/docs/web-transport.md @@ -1,25 +1,18 @@ # Web Transport (Streamable HTTP & WebSocket) -> **Experimental.** The remote web transports are experimental and shipped under the optional `[http]` extra. +> **Experimental.** Shipped under the optional `[http]` extra. -In addition to stdio, the SDK supports two remote JSON-RPC transports sharing the same ACP connection lifecycle (`initialize` → session operations → close): - -- **Streamable HTTP** — `POST` carries client-to-server messages, long-lived `GET` Server-Sent Events (SSE) streams carry server-to-client messages (one connection stream plus one per session), and `DELETE` terminates the connection. `initialize` responds with `200 OK` and a JSON body; subsequent `POST` requests respond with `202 Accepted`. Requires HTTP/2. -- **WebSocket** — a `GET` WebSocket upgrade on the same endpoint carrying full-duplex JSON-RPC text frames (one message per frame). Binary frames are ignored and logged once on the server. +Run ACP remotely over **Streamable HTTP** (`POST` requests + HTTP/2 SSE `GET` streams + `DELETE` teardown) or **WebSocket** (full-duplex JSON-RPC text frames) using the same `Agent` and `Client` APIs. ## Installation ```bash pip install "agent-client-protocol[http]" -# or -uv add "agent-client-protocol[http]" ``` -This extra installs `httpx2[http2]`, `websockets`, and `starlette`. - ## Client usage -Both client factories return a `Transport` compatible with `connect_to_agent`: +Pass a Streamable HTTP or WebSocket transport into `connect_to_agent`: ```python from acp import PROTOCOL_VERSION, connect_to_agent @@ -41,24 +34,11 @@ await conn.close() await transport.close() ``` -Over Streamable HTTP, the client sends `initialize` first, stores the returned `Acp-Connection-Id` header, and opens the connection-scoped SSE stream. When a session is created, loaded, or resumed, the client opens the corresponding session-scoped SSE stream. - -### Loading and resuming sessions - -Both HTTP and WebSocket support `load_session()` and `resume_session()` when advertised by the agent: - -```python -init = await conn.initialize(protocol_version=PROTOCOL_VERSION) -if init.agent_capabilities and init.agent_capabilities.load_session: - await conn.load_session(session_id="saved-session-id", cwd="/workspace", mcp_servers=[]) - await conn.prompt(session_id="saved-session-id", prompt=[...]) -``` - -Over HTTP, `session/load` history replay and the load/resume responses stream over the connection SSE channel; once established, subsequent session traffic uses the session SSE stream. Over WebSocket, replay and live traffic share the bidirectional socket. +Both transports also support `load_session()` and `resume_session()` when advertised by the agent, streaming replay updates over the connection channel before switching to live session traffic. ## Server usage -`create_asgi_app` builds a Starlette application serving `POST`/`GET`/`DELETE` and WebSocket upgrades at `/acp` by default, creating one agent instance per connection: +`create_asgi_app` creates a Starlette app serving both Streamable HTTP and WebSocket at `/acp` (or a custom `path`), instantiating one agent per connection: ```python from acp.http.asgi import create_asgi_app @@ -66,52 +46,18 @@ from acp.http.asgi import create_asgi_app app = create_asgi_app(lambda conn: MyAgent()) ``` -Pass `path` to change the endpoint route: - -```python -app = create_asgi_app(lambda conn: MyAgent(), path="/rpc") -``` - -### Serving v2 or dual-stack agents - -Pass an `AgentProtocolRouter` to `create_asgi_app` to negotiate v1 and v2 over both HTTP and WebSocket: +Pass an `AgentProtocolRouter` to serve v2 or negotiate v1/v2 over the same endpoint: ```python from acp.experimental import AgentProtocolRouter from acp.http.asgi import create_asgi_app -router = AgentProtocolRouter( - v1=lambda conn: V1Agent(conn), - v2=lambda conn: V2Agent(conn), -) -app = create_asgi_app(router) +app = create_asgi_app(AgentProtocolRouter(v1=lambda conn: V1Agent(conn), v2=lambda conn: V2Agent(conn))) ``` -### Mounting in an existing Starlette app - -Enter the child lifespan from the parent application so active HTTP connections close cleanly during shutdown: +When mounting `app` inside another Starlette application, enter `acp_app.router.lifespan_context(acp_app)` from the parent lifespan so active HTTP connections close cleanly on shutdown. -```python -from contextlib import asynccontextmanager -from starlette.applications import Starlette -from starlette.routing import Mount - -from acp.http.asgi import create_asgi_app - -acp_app = create_asgi_app(lambda conn: MyAgent()) - - -@asynccontextmanager -async def lifespan(app: Starlette): - async with acp_app.router.lifespan_context(acp_app): - yield - - -app = Starlette(routes=[Mount("/agents", app=acp_app)], lifespan=lifespan) -# Serves HTTP and WebSocket at /agents/acp -``` - -### HTTP/2 server setup +### Running with HTTP/2 Streamable HTTP requires an HTTP/2-capable ASGI server such as **Hypercorn**, **Daphne**, or **Granian** (or HTTP/2 termination at a reverse proxy). WebSocket works on any ASGI server, including Uvicorn. @@ -126,20 +72,4 @@ config.alpn_protocols = ["h2", "http/1.1"] asyncio.run(hypercorn.asyncio.serve(app, config)) ``` -## HTTP headers and stream routing - -- **`Acp-Connection-Id`** — Returned on `initialize`; sent on subsequent HTTP `POST`, `GET`, and `DELETE` requests. -- **`Acp-Session-Id`** — Sent on session-scoped `POST` requests and session-scoped `GET` SSE streams. -- **`sessionId`** — JSON-RPC payload field used to route server-to-client messages to the matching session stream. - -## Examples - -- [`examples/http_server.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_server.py) — serve an agent over Streamable HTTP and WebSocket with Hypercorn -- [`examples/http_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_client.py) — connect over Streamable HTTP -- [`examples/ws_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/ws_client.py) — connect over WebSocket - -## Current scope - -- SSE keepalives, bounded outbound buffers, and orderly teardown on `DELETE` or server shutdown are built in. -- Reconnect/backoff policies, `Last-Event-ID` SSE resumability, and `Acp-Protocol-Version` header enforcement are planned for a future revision. -- JSON-RPC batch payloads over HTTP return `501`. +See [`examples/http_server.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_server.py), [`examples/http_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/http_client.py), and [`examples/ws_client.py`](https://github.com/agentclientprotocol/python-sdk/blob/main/examples/ws_client.py) for complete runnable scripts.