Skip to content

ws_transport

Class info

Classes

Name Children Inherits
WebSocketTransportError
aclientp.ws_transport
The WebSocket connection to the ACP server could not be opened.

    🛈 DocStrings

    Client side of ACP's WebSocket transport (experimental).

    Implements the WebSocket mode of the "Streamable HTTP & WebSocket Transport" RFD: a GET with Upgrade: websocket on the agent's /acp endpoint (the server answers with Acp-Connection-Id), then one JSON-RPC message per text frame in both directions. Binary frames are ignored. The first message must still be initialize.

    Like :func:aclientp.http_transport.connect_http_transport, the transport is exposed as byte streams carrying newline-delimited JSON-RPC. :func:connect_remote_transport picks the transport from the URL scheme.

    MAX_MESSAGE_BYTES module-attribute

    MAX_MESSAGE_BYTES = 64 * 1024 * 1024
    

    Largest message accepted from the server (file contents and images can be large).

    WebSocketTransportError

    Bases: ConnectionError

    The WebSocket connection to the ACP server could not be opened.

    Source code in src/aclientp/ws_transport.py
    class WebSocketTransportError(ConnectionError):
        """The WebSocket connection to the ACP server could not be opened."""
    

    connect_remote_transport async

    connect_remote_transport(
        url: str, *, headers: Mapping[str, str] | None = None
    ) -> AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream]]
    

    Connect to a remote agent, choosing the transport by URL scheme.

    ws:// / wss:// use the WebSocket transport, http:// / https:// the Streamable HTTP transport. Both yield newline-delimited JSON-RPC byte streams.

    Raises:

    Type Description
    ValueError

    The URL has another scheme.

    Source code in src/aclientp/ws_transport.py
    @asynccontextmanager
    async def connect_remote_transport(
        url: str, *, headers: Mapping[str, str] | None = None
    ) -> AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream]]:
        """Connect to a remote agent, choosing the transport by URL scheme.
    
        ``ws://`` / ``wss://`` use the WebSocket transport, ``http://`` / ``https://`` the
        Streamable HTTP transport. Both yield newline-delimited JSON-RPC byte streams.
    
        Raises:
            ValueError: The URL has another scheme.
        """
        from aclientp.http_transport import connect_http_transport
    
        scheme = url.split("://", 1)[0].lower() if "://" in url else ""
        match scheme:
            case "ws" | "wss":
                async with connect_websocket_transport(url, headers=headers) as streams:
                    yield streams
            case "http" | "https":
                async with connect_http_transport(url, headers=headers) as streams:
                    yield streams
            case _:
                msg = f"Unsupported ACP URL {url!r}: use http(s):// or ws(s)://"
                raise ValueError(msg)
    

    connect_websocket_transport async

    connect_websocket_transport(
        url: str, *, headers: Mapping[str, str] | None = None, open_timeout: float = 30.0
    ) -> AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream]]
    

    Connect to an ACP server's WebSocket endpoint (ws:// or wss://).

    Parameters:

    Name Type Description Default
    url str

    The /acp endpoint.

    required
    headers Mapping[str, str] | None

    Extra headers for the upgrade request (e.g. authentication).

    None
    open_timeout float

    Timeout for the opening handshake.

    30.0

    Yields:

    Type Description
    AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream]]

    (reader, writer) byte streams.

    Raises:

    Type Description
    WebSocketTransportError

    The server rejected the upgrade or is unreachable.

    Source code in src/aclientp/ws_transport.py
    @asynccontextmanager
    async def connect_websocket_transport(
        url: str,
        *,
        headers: Mapping[str, str] | None = None,
        open_timeout: float = 30.0,
    ) -> AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream]]:
        """Connect to an ACP server's WebSocket endpoint (``ws://`` or ``wss://``).
    
        Args:
            url: The ``/acp`` endpoint.
            headers: Extra headers for the upgrade request (e.g. authentication).
            open_timeout: Timeout for the opening handshake.
    
        Yields:
            (reader, writer) byte streams.
    
        Raises:
            WebSocketTransportError: The server rejected the upgrade or is unreachable.
        """
        from websockets.asyncio.client import connect
        from websockets.exceptions import InvalidHandshake, InvalidStatus
    
        try:
            websocket = await connect(
                url,
                additional_headers=dict(headers or {}),
                open_timeout=open_timeout,
                max_size=MAX_MESSAGE_BYTES,
            )
        except InvalidStatus as exc:
            response = exc.response
            body = response.body.decode(errors="replace")[:200] if response.body else ""
            msg = f"ACP WebSocket upgrade rejected ({response.status_code}): {body}".rstrip(": ")
            raise WebSocketTransportError(msg) from exc
        except (InvalidHandshake, OSError, TimeoutError) as exc:
            raise WebSocketTransportError(f"ACP WebSocket connection failed: {exc}") from exc
        if websocket.response is not None:
            connection_id = websocket.response.headers.get(HEADER_CONNECTION_ID)
            logger.debug("ACP WebSocket connected (%s)", connection_id or "no connection ID")
        try:
            yield _FrameReader(websocket), _FrameWriter(websocket)
        finally:
            await websocket.close()