diff --git a/README.md b/README.md index b8aaac8a..4bbf8727 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 models and asyncio transports over stdio, Streamable HTTP, and WebSocket. -## Install +## Installation ```bash pip install agent-client-protocol @@ -16,60 +19,88 @@ pip install agent-client-protocol uv add agent-client-protocol ``` -## At a glance +For experimental HTTP/WebSocket transports, install the `http` extra (`pip install "agent-client-protocol[http]"`). Requires Python 3.10–3.15. -- **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. +## Quick example -## Who benefits +### Build an agent -- 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/). +```python +import asyncio +from typing import Any +from uuid import uuid4 -## How to get started +from acp import PROTOCOL_VERSION, Agent, InitializeResponse, NewSessionResponse, PromptResponse, run_agent +from acp.interfaces import Client +from acp.schema import AgentMessageChunk, TextContentBlock -- 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 +class EchoAgent(Agent): + def on_connect(self, conn: Client) -> None: + self._conn = conn -| Need | Link | -|--------------------|------------------------------------------------------------------------| -| Docs hub | | -| Quickstart | | -| Use cases | | -| Contrib helpers | | -| Releasing workflow | | -| Examples | | -| Tests | | -| PyPI | | + async def initialize(self, protocol_version: int, **kwargs: Any) -> InitializeResponse: + return InitializeResponse(protocol_version=PROTOCOL_VERSION) -## Project layout + async def new_session(self, cwd: str, **kwargs: Any) -> NewSessionResponse: + return NewSessionResponse(session_id=uuid4().hex) -- `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 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") -## 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. +if __name__ == "__main__": + asyncio.run(run_agent(EchoAgent())) +``` + +### Drive an agent from Python + +```python +import asyncio +import sys +from typing import Any + +from acp import PROTOCOL_VERSION, Client, spawn_agent_process +from acp.schema import TextContentBlock + + +class SimpleClient(Client): + async def session_update(self, session_id: str, update: Any, **kwargs: Any) -> None: + print(session_id, update) + + +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!")]) -Keep docs and examples current whenever you ship public API or transport changes, and prefer Conventional Commits (`feat:`, `fix:`, etc.) when submitting patches. -## Community & support +asyncio.run(main()) +``` + +## Documentation + +- [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 # Set up uv environment and pre-commit hooks +make check # Format, lint, type-check, and dependency check +make test # Run pytest suite +``` + +## 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! +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/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..318b0562 100644 --- a/docs/experimental-v2.md +++ b/docs/experimental-v2.md @@ -1,46 +1,39 @@ # 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 [`schema-v2.0.0-beta.4`](https://github.com/agentclientprotocol/agent-client-protocol/releases/tag/schema-v2.0.0-beta.4). -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. +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 and agent usage -Install update handlers before opening a session because updates are independent -connection traffic: +Register `session_update` before opening a session so streamed updates arrive as soon as 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, - ) -> 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")]) ``` -Implement an agent with the same expanded handler style: +Implement the handlers your agent supports (subclassing `v2.Agent` is optional) and serve with `v2.run_agent()`: ```python +from typing import Any +from acp.experimental import v2 + + class MyAgent(v2.Agent): async def initialize( self, @@ -55,78 +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()) ``` -`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. +V2 connections require a successful `initialize` handshake before other methods and validate requests and responses strictly. -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. +## Key v2 behaviors -Union requests also use expanded parameters: +- **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`. -```python -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", -) -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", -) -``` +## Dual-stack v1/v2 negotiation -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`: +Use `AgentProtocolRouter` to serve both protocol versions on one stdio, HTTP, or WebSocket endpoint: ```python from acp.experimental import AgentProtocolRouter @@ -138,35 +79,10 @@ 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. +Each connection invokes the selected factory once and runs strictly under the negotiated protocol version. -Extension method names are explicit and must include the protocol-required `_` -prefix: - -```python -result = await connection.send_extension_request("_vendor/method", {"value": 1}) -await connection.send_extension_notification("_vendor/event", {"value": 1}) -``` +## Extensions, cancellation, and MCP-over-ACP -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. - -## 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. +- 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 ba1c710b..256cfabc 100644 --- a/docs/index.md +++ b/docs/index.md @@ -4,61 +4,25 @@ # 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. - -## Install & verify +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: pip install "agent-client-protocol[http]" ``` -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. - -## 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. - -## Quick links - -| Need | Link | -| --- | --- | -| 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 +## Where to start -- [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. +- **[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. -Need API-level details? Browse the source in `src/acp/` or generate docs with `mkdocstrings`. +## Ecosystem and operations -## Feedback & support +- **[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. -- 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/). +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 new file mode 100644 index 00000000..d7e6407a --- /dev/null +++ b/docs/protocol-features.md @@ -0,0 +1,76 @@ +# 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). Handlers and connection methods accept expanded snake_case parameters, and extra keyword arguments serialize into JSON-RPC `_meta`. + +## 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`: + +```python +await run_agent(MyAgent(), use_unstable_protocol=True) +``` + +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 + +When a client advertises `ClientCapabilities(session=ClientSessionCapabilities(notices=NoticeCapabilities()))`, agents can send live advisory notices outside session history: + +```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.", + ), +) +``` + +`title` must be non-empty; `severity` accepts `"info"`, `"warning"`, `"error"`, and custom string values. + +## Stateless MCP-over-ACP + +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 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": {}, + }, + }, +) +if isinstance(response, McpErrorResponse): + handle_mcp_error(response.error) +else: + use_mcp_result(response.result) +``` + +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`. + +Run `uv run python examples/mcp_over_acp.py` for a full local example. + +## Request cancellation + +Connections handle `$/cancel_request` automatically: + +- 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 `conn.cancel(session_id=...)` (`session/cancel`) to stop active work inside a prompt turn. + +## Extension methods + +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 0abbfd11..a254d165 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -1,26 +1,8 @@ # 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 streaming ACP agent and connect a client in a few minutes (requires Python 3.10–3.15). -## Quick checklist - -| 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` | - -## 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 ```bash pip install agent-client-protocol @@ -28,39 +10,15 @@ pip install agent-client-protocol uv add agent-client-protocol ``` -## Step 2 — Launch the Echo agent +## 2. Run the echo agent and connect a client -_Run the provided streaming agent so clients have something to talk to._ - -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` is a runnable stdio agent that streams incoming prompt text back as `session/update` notifications: ```bash python examples/echo_agent.py ``` -## Step 3 — Connect from an ACP-aware client - -_Point a client at the script and confirm you can exchange streamed updates._ - -### 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`: +Point any stdio ACP client (such as Zed, Toad, Lody, or T3 Code) at that command. For example, in Zed's `settings.json`: ```json { @@ -68,24 +26,15 @@ Or, if using `uv`: "Echo Agent (Python)": { "type": "custom", "command": "uv", - "args": [ - "run", - "/abs/path/to/agentclientprotocol/python-sdk/examples/echo_agent.py" - ] + "args": ["run", "/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. - -### Other clients - -Any ACP client that communicates over stdio can spawn the same script; no additional transport configuration is required. - -### Programmatic launch +## 3. Drive an agent from Python -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, exchange JSON-RPC messages over stdio, and close both cleanly on exit: ```python import asyncio @@ -93,18 +42,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) @@ -113,253 +59,53 @@ 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!")], - ) - -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. - -## Step 4 — Extend the agent + await conn.prompt(session_id=session.session_id, prompt=[TextContentBlock(text="Hello from spawn!")]) -_Swap the echo demo for your own `Agent` subclass._ -Create your own agent by subclassing `acp.Agent`. The pattern mirrors the echo example: - -```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: - -```python -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() +asyncio.run(main()) ``` -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. - -## Stateless MCP-over-ACP +`spawn_client_process` provides the matching helper when an agent spawns a client subprocess. -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. +## 4. Write your own agent -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: +Subclass `acp.Agent`, implement the methods your agent supports, and start serving with `acp.run_agent()`: ```python +import asyncio +from typing import Any 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) -``` - -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: -```python -@param_model( - DeleteSessionRequest, - method=AGENT_METHODS["session_delete"], - adapt_result=normalize_result, -) -async def delete_session(self, session_id: str, **kwargs: Any) -> DeleteSessionResponse: ... -``` +from acp import PROTOCOL_VERSION, Agent, InitializeResponse, NewSessionResponse, PromptResponse, run_agent +from acp.interfaces import Client +from acp.schema import AgentMessageChunk, TextContentBlock -`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, ...)`. +class MyAgent(Agent): + def on_connect(self, conn: Client) -> None: + self._conn = conn -`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. + async def initialize(self, protocol_version: int, **kwargs: Any) -> InitializeResponse: + return InitializeResponse(protocol_version=PROTOCOL_VERSION) -## Optional — Talk to the Gemini CLI + async def new_session(self, cwd: str, **kwargs: Any) -> NewSessionResponse: + return NewSessionResponse(session_id=uuid4().hex) -_Have the Gemini CLI installed? Run the bridge to exercise permission flows._ + 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") -If you have the Gemini CLI installed and authenticated: -```bash -python examples/gemini.py --skip-trust --yolo # auto-approve permission prompts -python examples/gemini.py --skip-trust --sandbox --model gemini-1.5-pro +if __name__ == "__main__": + asyncio.run(run_agent(MyAgent())) ``` -Environment helpers: - -- `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` - -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. +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 -- 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/). +- 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 b4b2ba37..457e6dfe 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,50 +1,23 @@ # 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. +Releases track pinned upstream ACP schema tags (`schema/VERSION` for v1 and `schema/v2/VERSION` for experimental v2). -## Prep checklist +## Release checklist -1. **Choose the schema tag** (e.g. `schema-v1.16.0`) and regenerate artifacts: +1. Refresh generated bindings when advancing the upstream schema: ```bash - ACP_SCHEMA_VERSION=schema-v1.16.0 make gen-all + ACP_SCHEMA_VERSION=schema-v1.35.0 make gen-all + 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 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 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. 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. -## Commit & review +## Publishing -- 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. +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. -## 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 - -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. - -## Extra tips - -- 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. +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 new file mode 100644 index 00000000..392e1915 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,47 @@ +# Testing & Conformance + +We validate SDK changes at three levels: fast local checks, official ACP TCK conformance, and real-world interoperability. + +## Local checks + +```bash +make gen-check # Verify generated bindings match schema/ +make check # Lockfile, Ruff lint/format, ty type check, deptry +make test # Pytest suite (including doctests) +make docs-test # Strict MkDocs build +``` + +## Protocol conformance (ACP TCK) + +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: + +- **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. + +When changing shared schema or deserialization code, also check v1 `model_validate` latency on hot models (`AgentMessageChunk`, `SessionNotification`) to avoid regressions. + +## Real-world interoperability + +Before major releases or schema bumps, we run live end-to-end checks across two directions: + +- **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. + +A standard end-to-end pass exercises one continuous flow: + +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. + +### Opt-in Gemini CLI smoke test + +With the Gemini CLI installed and authenticated locally: + +```bash +ACP_ENABLE_GEMINI_TESTS=1 uv run python -m pytest tests/test_gemini_example.py +``` + +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/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..d145878f 100644 --- a/docs/web-transport.md +++ b/docs/web-transport.md @@ -1,20 +1,8 @@ # 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.** Shipped under the optional `[http]` extra. -The SDK can run ACP over two remote connectivity profiles in addition to stdio: - -- **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). +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 @@ -22,17 +10,12 @@ Both reuse the existing JSON-RPC message format and ACP lifecycle pip install "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. +## Client usage -## Client - -Both transports produce a message-level `Transport` that plugs into the existing -`connect_to_agent`: +Pass a Streamable HTTP or WebSocket transport into `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 +23,43 @@ 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. +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. -### Loading an existing session +## Server usage -Both HTTP and WebSocket support `load_session()` when the agent advertises -`loadSession` and implements session persistence: - -```python -init = await conn.initialize(protocol_version=1) -if 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. - -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 - -The server uses Starlette for HTTP requests, responses, routing, streaming, -WebSocket handling, and application lifespan: +`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 -# 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: - -```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. - -### Mounting in another application - -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): +Pass an `AgentProtocolRouter` to serve v2 or negotiate v1/v2 over the same endpoint: ```python -from contextlib import asynccontextmanager -from starlette.applications import Starlette -from starlette.routing import Mount - -acp_app = create_asgi_app(lambda conn: MyAgent()) - -@asynccontextmanager -async def lifespan(app): - async with acp_app.router.lifespan_context(acp_app): - yield +from acp.experimental import AgentProtocolRouter +from acp.http.asgi import create_asgi_app -app = Starlette(routes=[Mount("/agents", app=acp_app)], lifespan=lifespan) -# Connect to /agents/acp using either HTTP or WebSocket. +app = create_asgi_app(AgentProtocolRouter(v1=lambda conn: V1Agent(conn), v2=lambda conn: V2Agent(conn))) ``` -With `path="/rpc"`, the mounted endpoint is `/agents/rpc`. Use `path="/"` to -serve ACP at the mount root (`/agents/`). +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. -### How the server fits together +### Running with HTTP/2 -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: - -```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 +72,4 @@ config.alpn_protocols = ["h2", "http/1.1"] asyncio.run(hypercorn.asyncio.serve(app, config)) ``` -## Examples - -- [`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. - -## Identity model - -- `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. - -## Not yet supported (deferred to a future revision) - -- `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. +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. 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" },