Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/experimental-v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ await v2.run_agent(MyAgent())
```

V2 connections require a successful `initialize` handshake before other methods and validate requests and responses strictly.
If the agent rejects `initialize`, the client can retry on the same connection. A rejected repeat leaves the previous successful initialization in effect.

## Key v2 behaviors

Expand All @@ -79,7 +80,7 @@ router = AgentProtocolRouter(
await router.run()
```

Each connection invokes the selected factory once and runs strictly under the negotiated protocol version.
The router calls each version's factory and `on_connect` at most once per connection. Before sending another request, the client can repeat `initialize` with the selected version or downgrade to a lower supported version. The router switches protocol versions after a successful downgrade.

## Extensions, cancellation, and MCP-over-ACP

Expand Down
7 changes: 7 additions & 0 deletions src/acp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from importlib.metadata import PackageNotFoundError, version
from typing import Any

from .core import (
Expand Down Expand Up @@ -94,6 +95,11 @@
from .stdio import spawn_agent_process, spawn_client_process, spawn_stdio_connection, stdio_streams
from .transports import default_environment, spawn_stdio_transport

try:
__version__ = version("agent-client-protocol")
except PackageNotFoundError:
__version__ = "0.0.0"

_DEPRECATED_NAMES = [
(
"AgentSideConnection",
Expand All @@ -109,6 +115,7 @@

__all__ = [ # noqa: RUF022
# constants
"__version__",
"PROTOCOL_VERSION",
"AGENT_METHODS",
"CLIENT_METHODS",
Expand Down
6 changes: 4 additions & 2 deletions src/acp/agent/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,16 @@ def __init__(
if isinstance(input_stream, Transport):
if output_stream is not None:
raise TypeError(_AGENT_CONNECTION_ERROR)
self._conn = Connection(handler, input_stream, listening=listening, **connection_kwargs)
self._conn = Connection(handler, input_stream, listening=False, **connection_kwargs)
else:
if not isinstance(input_stream, asyncio.StreamWriter) or not isinstance(
output_stream, asyncio.StreamReader
):
raise TypeError(_AGENT_CONNECTION_ERROR)
self._conn = Connection(handler, input_stream, output_stream, listening=listening, **connection_kwargs)
self._conn = Connection(handler, input_stream, output_stream, listening=False, **connection_kwargs)
self._notify_connected(agent)
if listening:
self._conn.start_listening()

@classmethod
def attach(
Expand Down
7 changes: 5 additions & 2 deletions src/acp/client/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ def __init__(
output_stream: Any = None,
*,
use_unstable_protocol: bool = False,
listening: bool = True,
**connection_kwargs: Any,
) -> None:
client = to_client(self) if callable(to_client) else to_client
Expand All @@ -151,15 +152,17 @@ def __init__(
if isinstance(input_stream, Transport):
if output_stream is not None:
raise TypeError(_CLIENT_CONNECTION_ERROR)
self._conn = Connection(handler, input_stream, **connection_kwargs)
self._conn = Connection(handler, input_stream, listening=False, **connection_kwargs)
else:
if not isinstance(input_stream, asyncio.StreamWriter) or not isinstance(
output_stream, asyncio.StreamReader
):
raise TypeError(_CLIENT_CONNECTION_ERROR)
self._conn = Connection(handler, input_stream, output_stream, **connection_kwargs)
self._conn = Connection(handler, input_stream, output_stream, listening=False, **connection_kwargs)
if on_connect := getattr(client, "on_connect", None):
on_connect(self)
if listening:
self._conn.start_listening()

@param_model(InitializeRequest)
async def initialize(
Expand Down
22 changes: 15 additions & 7 deletions src/acp/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,19 @@ def __init__(
sender = MessageSender(cast("asyncio.StreamWriter", writer))
self._transport = NdjsonTransport(reader, sender, receive_timeout=receive_timeout)
self._observers: list[StreamObserver] = list(observers or [])
self._recv_task: asyncio.Task[Any] | None = None
if listening:
self._recv_task = self._tasks.create(
self._receive_loop(),
name="acp.Connection.receive",
on_error=self._on_receive_error,
)
else:
self._recv_task = None
self.start_listening()

def start_listening(self) -> None:
"""Start the background receive loop."""
if self._recv_task is not None:
return
self._recv_task = self._tasks.create(
self._receive_loop(),
name="acp.Connection.receive",
on_error=self._on_receive_error,
)

async def close(self) -> None:
"""Stop receiving and cancel other in-flight tasks.
Expand All @@ -106,6 +111,9 @@ async def close(self) -> None:
await self._tasks.shutdown()

async def main_loop(self) -> None:
if self._recv_task is not None:
await self._recv_task
return
try:
await self._receive_loop()
except Exception as exc:
Expand Down
69 changes: 43 additions & 26 deletions src/acp/experimental/negotiation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import asyncio
from collections.abc import Callable
from typing import Any
from typing import Any, cast

from pydantic import BaseModel

Expand Down Expand Up @@ -66,6 +66,7 @@ def __init__(
self._v1_agent = v1_agent
self._v2_agent = v2_agent
self._connection: Connection | None = None
self._candidates: dict[int, tuple[V1AgentSideConnection | V2AgentSideConnection, MethodHandler]] = {}
self._selected: MethodHandler | None = None
self._selected_version: int | None = None
self._locked = False
Expand All @@ -75,38 +76,30 @@ def bind_connection(self, connection: Connection) -> None:
self._connection = connection

async def __call__(self, method: str, params: Any | None, is_notification: bool) -> Any:
is_initialize = not is_notification and method == V2_AGENT_METHODS["initialize"]
if self._selected is None and not is_initialize:
if is_notification:
return None
raise RequestError.invalid_request({"details": "The first ACP request must be initialize"})

async with self._lock:
if not is_notification and method == V2_AGENT_METHODS["initialize"]:
if is_initialize:
if self._locked:
raise RequestError.invalid_request({"details": "ACP connections may only be initialized once"})
raise RequestError.invalid_request({
"details": "ACP connections cannot initialize after another request"
})
return await self._initialize(method, params)
handler = self._selected
if handler is None:
raise RequestError.invalid_request({"details": "The first ACP request must be initialize"})
handler = cast("MethodHandler", self._selected)
if not is_notification:
self._locked = True
return await handler(method, params, is_notification)

async def _initialize(self, method: str, params: Any) -> Any:
requested = read_protocol_version(params)
connection = self._connection
if connection is None:
raise RuntimeError("Protocol router is not connected")

if self._v2_agent is not None and requested >= v2.PROTOCOL_VERSION:
selected = v2.PROTOCOL_VERSION
handler = (
self._selected
if self._selected is not None and self._selected_version == selected
else V2AgentSideConnection.attach(self._v2_agent, connection)[1]
)
elif self._v1_agent is not None and requested >= v1_meta.PROTOCOL_VERSION:
selected = v1_meta.PROTOCOL_VERSION
handler = (
self._selected
if self._selected is not None and self._selected_version == selected
else V1AgentSideConnection.attach(self._v1_agent, connection)[1]
)
else:
supported = [
version
Expand All @@ -117,6 +110,12 @@ async def _initialize(self, method: str, params: Any) -> Any:
if implementation is not None
]
raise RequestError.unsupported_protocol_version(requested, supported)

if self._selected_version is not None and selected > self._selected_version:
raise RequestError.invalid_request({
"details": f"ACP connection already negotiated protocol {self._selected_version}"
})
handler = self._candidate_handler(selected)
if selected == v1_meta.PROTOCOL_VERSION:
params = _normalize_v1_initialize(params, requested)
response = await handler(method, params, False)
Expand All @@ -129,20 +128,38 @@ async def _initialize(self, method: str, params: Any) -> Any:
raise RequestError.invalid_request({
"details": f"initialize response selected protocol {parsed_version}, expected {selected}"
})
if selected == v1_meta.PROTOCOL_VERSION:
previous = self._candidates.get(v2.PROTOCOL_VERSION)
if previous is not None and isinstance(previous[0], V2AgentSideConnection):
previous[0]._state.fail(RequestError.invalid_request({"details": "ACP v2 is no longer active"}))
self._selected = handler
self._selected_version = selected
return response

def _candidate_handler(self, version: int) -> MethodHandler:
candidate = self._candidates.get(version)
if candidate is not None:
return candidate[1]

connection = self._connection
if connection is None:
raise RuntimeError("Protocol router is not connected")
if version == v2.PROTOCOL_VERSION and self._v2_agent is not None:
candidate = V2AgentSideConnection.attach(self._v2_agent, connection)
elif self._v1_agent is not None:
candidate = V1AgentSideConnection.attach(self._v1_agent, connection)
else:
raise RuntimeError("No agent factory configured for selected protocol")
self._candidates[version] = candidate
return candidate[1]


class AgentProtocolConnection:
def __init__(self, connection: Connection) -> None:
self._connection = connection

async def _listen(self) -> None:
await self._connection.main_loop()

async def listen(self) -> None:
await self._listen()
await self._connection.main_loop()

async def close(self) -> None:
await self._connection.close()
Expand All @@ -155,7 +172,7 @@ async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:


class AgentProtocolRouter:
"""Select one strict agent runtime from the first initialize request."""
"""Select an agent runtime through protocol version negotiation."""

def __init__(
self,
Expand Down Expand Up @@ -214,6 +231,6 @@ async def run(
**connection_kwargs,
)
try:
await connection._listen()
await connection.listen()
finally:
await asyncio.shield(connection.close())
84 changes: 49 additions & 35 deletions src/acp/experimental/v2/_initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,25 @@ class InitializationState:
def __init__(self) -> None:
self._phase: InitializationPhase = "uninitialized"
self._failure: BaseException | None = None
self._ready = asyncio.Event()
# Waiters retain the result of their attempt even if a retry has already started.
self._ready: asyncio.Future[BaseException | None] | None = None
self._lock = asyncio.Lock()
self._locked = False
self._initialized_once: bool = False

@property
def phase(self) -> InitializationPhase:
return self._phase

def begin(self, request: schema.InitializeRequest) -> None:
if self._phase != "uninitialized":
raise RequestError.invalid_request({"details": "ACP v2 connections may only be initialized once"})
if self._locked or self._phase in {"initializing", "failed"}:
raise RequestError.invalid_request({"details": "ACP v2 connection cannot initialize at this point"})
if request.protocol_version != PROTOCOL_VERSION:
raise RequestError.invalid_params({
"expectedProtocolVersion": PROTOCOL_VERSION,
"receivedProtocolVersion": request.protocol_version,
})
self._phase = "initializing"
self._start()

def complete(self, response: schema.InitializeResponse) -> None:
if self._phase != "initializing":
Expand All @@ -51,60 +53,72 @@ def complete(self, response: schema.InitializeResponse) -> None:
"expectedProtocolVersion": PROTOCOL_VERSION,
"receivedProtocolVersion": response.protocol_version,
})
self._phase = "initialized"
self._failure = None
self._ready.set()
self._initialized_once = True
self._finish("initialized")

def reject(self, error: BaseException) -> None:
if self._initialized_once:
self._finish("initialized")
else:
self._finish("uninitialized", error)

def fail(self, error: BaseException) -> None:
if self._phase == "initialized":
return
self._phase = "failed"
self._finish("failed", error)

def _start(self) -> None:
self._phase = "initializing"
self._failure = None
if self._ready is not None and self._ready.done():
self._ready = None

def _finish(self, phase: InitializationPhase, error: BaseException | None = None) -> None:
self._phase = phase
self._failure = error
self._ready.set()
if self._ready is not None and not self._ready.done():
self._ready.set_result(error)

async def initialized(self) -> None:
if self._phase in {"uninitialized", "initializing"}:
await self._ready.wait()
if self._phase == "initialized":
if self._phase in {"uninitialized", "initializing"} and self._failure is None:
if self._ready is None:
self._ready = asyncio.get_running_loop().create_future()
error = await asyncio.shield(self._ready)
if error is not None:
raise error
return
if self._failure is not None:
raise self._failure
raise RequestError.invalid_request({"details": "ACP v2 connection has not been initialized"})

async def initialize_agent(
self, params: Any, handle: Callable[[dict[str, Any]], Awaitable[schema.InitializeResponse]]
) -> schema.InitializeResponse:
async with self._lock:
if self._locked:
raise RequestError.invalid_request({"details": "ACP v2 connections may only be initialized once"})
if self._locked or self._phase == "failed":
raise RequestError.invalid_request({
"details": "ACP v2 connection cannot initialize after another request"
})
requested = read_protocol_version(params)
if requested < PROTOCOL_VERSION:
raise RequestError.unsupported_protocol_version(requested, [PROTOCOL_VERSION])
normalized = {**params, "protocolVersion": PROTOCOL_VERSION}

was_initialized = self._phase == "initialized"
self._phase = "initializing"
self._ready.clear()
self._start()
try:
response = await handle(normalized)
self.complete(response)
except BaseException as error:
if was_initialized:
self._phase = "initialized"
self._ready.set()
else:
self.fail(error)
self.reject(error)
raise
return response

async def require(self, method: str, *, lock: bool = False) -> None:
async with self._lock:
if self._phase == "initialized":
if lock:
self._locked = True
return
if self._phase != "initializing":
raise RequestError.invalid_request({
"details": f"ACP v2 connection must be initialized before {method!r}"
})
await self.initialized()
while True:
async with self._lock:
if self._phase == "initialized":
if lock:
self._locked = True
return
if self._phase != "initializing":
raise RequestError.invalid_request({
"details": f"ACP v2 connection must be initialized before {method!r}"
})
await self.initialized()
Loading
Loading