Skip to content

ClientSideConnection

🛈 DocStrings

UNSTABLE: Connection of a v2 client to an agent.

Requests from the agent are answered with -32600 until initialize has completed; earlier notifications are ignored.

Source code in src/aclientp/v2/client.py
class ClientSideConnection:
    """**UNSTABLE**: Connection of a v2 client to an agent.

    Requests from the agent are answered with ``-32600`` until ``initialize`` has
    completed; earlier notifications are ignored.
    """

    def __init__(
        self,
        to_client: Callable[[ClientSideConnection], Client] | Client,
        input_stream: ByteSendStream,
        output_stream: ByteReceiveStream,
        observers: list[StreamObserver] | None = None,
    ) -> None:
        """Start the connection.

        Args:
            to_client: The client, or a factory receiving this connection.
            input_stream: Stream to the agent.
            output_stream: Stream from the agent.
            observers: Observers of the raw messages.
        """
        self._client = to_client if isinstance(to_client, Client) else to_client(self)
        self._requests = _request_handlers(self._client)
        self._notifications = _notification_handlers(self._client)
        self.initialize_response: InitializeResponse | None = None
        self._conn = Connection(
            self.handle,
            input_stream,
            output_stream,
            observers=observers,
            reject_batches=True,
            strict_request_ids=True,
        )

    @property
    def connection(self) -> Connection:
        """The underlying JSON-RPC connection."""
        return self._conn

    async def handle(self, method: str, params: Any, is_notification: bool) -> Any:
        """Handle one incoming message (the connection's handler)."""
        initialized = self.initialize_response is not None
        if is_notification:
            if not initialized:
                return None
            if method.startswith("_"):
                await self._client.ext_notification(method, params)
            elif handler := self._notifications.get(method):
                await handler(CLIENT_NOTIFICATIONS[method].validate_python(params or {}))
            return None
        if not initialized:
            details = f"ACP v2 connection must be initialized before {method!r}"
            raise RequestError.invalid_request({"details": details})
        if method.startswith("_"):
            return await self._client.ext_method(method, params)
        if (request_handler := self._requests.get(method)) is None:
            raise RequestError.method_not_found(method)
        parsed = CLIENT_REQUESTS[method].params.validate_python(params or {})
        return to_wire(await request_handler(parsed))

    async def _request(self, method: str, params: BaseModel) -> Any:
        result = await self._conn.send_request(method, to_wire(params))
        try:
            return AGENT_REQUESTS[method].result.validate_python(result)
        except ValidationError as exc:
            raise InvalidResponseError.from_validation_error(method, exc) from exc

    # --- Calls to the agent ---------------------------------------------------------

    async def initialize(self, params: InitializeRequest) -> InitializeResponse:
        """Send ``initialize``; the agent must answer with protocol version 2.

        Raises:
            ProtocolVersionError: The agent answered with another protocol version,
                e.g. ``1`` from an agent that only speaks v1. Checked before the rest
                of the response is validated, since its shape depends on the version.
        """
        result = await self._conn.send_request("initialize", to_wire(params))
        received = result.get("protocolVersion") if isinstance(result, dict) else None
        if received != PROTOCOL_VERSION:
            raise ProtocolVersionError(PROTOCOL_VERSION, received, result)
        try:
            response: InitializeResponse = AGENT_REQUESTS["initialize"].result.validate_python(
                result
            )
        except ValidationError as exc:
            raise InvalidResponseError.from_validation_error("initialize", exc) from exc
        self.initialize_response = response
        return response

    async def login(self, params: LoginAuthRequest) -> LoginAuthResponse:
        """Send ``auth/login``."""
        response: LoginAuthResponse = await self._request("auth/login", params)
        return response

    async def logout(self, params: LogoutAuthRequest) -> LogoutAuthResponse:
        """Send ``auth/logout``."""
        response: LogoutAuthResponse = await self._request("auth/logout", params)
        return response

    async def auth_status(self, params: AuthStatusRequest) -> AuthStatusResponse:
        """Send ``auth/status``."""
        response: AuthStatusResponse = await self._request("auth/status", params)
        return response

    async def list_providers(self, params: ListProvidersRequest) -> ListProvidersResponse:
        """Send ``providers/list``."""
        response: ListProvidersResponse = await self._request("providers/list", params)
        return response

    async def set_provider(self, params: SetProviderRequest) -> SetProviderResponse:
        """Send ``providers/set``."""
        response: SetProviderResponse = await self._request("providers/set", params)
        return response

    async def disable_provider(self, params: DisableProviderRequest) -> DisableProviderResponse:
        """Send ``providers/disable``."""
        response: DisableProviderResponse = await self._request("providers/disable", params)
        return response

    async def new_session(self, params: NewSessionRequest) -> NewSessionResponse:
        """Send ``session/new``."""
        response: NewSessionResponse = await self._request("session/new", params)
        return response

    async def resume_session(self, params: ResumeSessionRequest) -> ResumeSessionResponse:
        """Send ``session/resume``."""
        response: ResumeSessionResponse = await self._request("session/resume", params)
        return response

    async def fork_session(self, params: ForkSessionRequest) -> ForkSessionResponse:
        """Send ``session/fork``."""
        response: ForkSessionResponse = await self._request("session/fork", params)
        return response

    async def close_session(self, params: CloseSessionRequest) -> CloseSessionResponse:
        """Send ``session/close``."""
        response: CloseSessionResponse = await self._request("session/close", params)
        return response

    async def list_sessions(self, params: ListSessionsRequest) -> ListSessionsResponse:
        """Send ``session/list``."""
        response: ListSessionsResponse = await self._request("session/list", params)
        return response

    async def delete_session(self, params: DeleteSessionRequest) -> DeleteSessionResponse:
        """Send ``session/delete``."""
        response: DeleteSessionResponse = await self._request("session/delete", params)
        return response

    async def archive_session(self, params: ArchiveSessionRequest) -> ArchiveSessionResponse:
        """Send ``session/archive``."""
        response: ArchiveSessionResponse = await self._request("session/archive", params)
        return response

    async def unarchive_session(self, params: UnarchiveSessionRequest) -> UnarchiveSessionResponse:
        """Send ``session/unarchive``."""
        response: UnarchiveSessionResponse = await self._request("session/unarchive", params)
        return response

    async def session_status(self, params: SessionStatusRequest) -> SessionStatusResponse:
        """Send ``session/status``."""
        response: SessionStatusResponse = await self._request("session/status", params)
        return response

    async def session_options(self, params: SessionOptionsRequest) -> SessionOptionsResponse:
        """Send ``session/options``."""
        response: SessionOptionsResponse = await self._request("session/options", params)
        return response

    async def set_session_title(self, params: SetSessionTitleRequest) -> SetSessionTitleResponse:
        """Send ``session/set_title``."""
        response: SetSessionTitleResponse = await self._request("session/set_title", params)
        return response

    async def set_session_config_option(
        self, params: SetSessionConfigOptionRequest
    ) -> SetSessionConfigOptionResponse:
        """Send ``session/set_config_option``."""
        response: SetSessionConfigOptionResponse = await self._request(
            "session/set_config_option", params
        )
        return response

    async def prompt(self, params: PromptRequest) -> PromptResponse:
        """Send ``session/prompt``; returns once the message is inserted, not when the turn ends."""
        response: PromptResponse = await self._request("session/prompt", params)
        return response

    async def cancel(self, params: CancelSessionNotification) -> None:
        """Send ``session/cancel``."""
        await self._conn.send_notification("session/cancel", to_wire(params))

    async def cancel_tool_call(self, params: CancelToolCallRequest) -> CancelToolCallResponse:
        """Send ``tool_call/cancel``."""
        response: CancelToolCallResponse = await self._request("tool_call/cancel", params)
        return response

    async def cancel_terminal(self, params: CancelTerminalRequest) -> CancelTerminalResponse:
        """Send ``terminal/cancel``."""
        response: CancelTerminalResponse = await self._request("terminal/cancel", params)
        return response

    async def mcp_message(self, params: MessageMcpRequest) -> MessageMcpResponse:
        """Send an ``mcp/message`` request to the agent."""
        response: MessageMcpResponse = await self._request("mcp/message", params)
        return response

    async def mcp_notification(self, params: MessageMcpNotification) -> None:
        """Send an ``mcp/message`` notification to the agent."""
        await self._conn.send_notification("mcp/message", to_wire(params))

    async def ext_method(self, method: str, params: JsonValue = None) -> JsonValue:
        """Send a custom (``_``-prefixed) request."""
        return await self._conn.send_request(method, params)

    async def ext_notification(self, method: str, params: JsonValue = None) -> None:
        """Send a custom (``_``-prefixed) notification."""
        await self._conn.send_notification(method, params)

    async def close(self) -> None:
        """Close the connection."""
        await self._conn.close()

    async def wait_closed(self) -> None:
        """Wait until the agent disconnected or the connection was closed."""
        await self._conn.wait_closed()

connection property

connection: Connection

The underlying JSON-RPC connection.

__init__

__init__(
    to_client: Callable[[ClientSideConnection], Client] | Client,
    input_stream: ByteSendStream,
    output_stream: ByteReceiveStream,
    observers: list[StreamObserver] | None = None,
) -> None

Start the connection.

Parameters:

Name Type Description Default
to_client Callable[[ClientSideConnection], Client] | Client

The client, or a factory receiving this connection.

required
input_stream ByteSendStream

Stream to the agent.

required
output_stream ByteReceiveStream

Stream from the agent.

required
observers list[StreamObserver] | None

Observers of the raw messages.

None
Source code in src/aclientp/v2/client.py
def __init__(
    self,
    to_client: Callable[[ClientSideConnection], Client] | Client,
    input_stream: ByteSendStream,
    output_stream: ByteReceiveStream,
    observers: list[StreamObserver] | None = None,
) -> None:
    """Start the connection.

    Args:
        to_client: The client, or a factory receiving this connection.
        input_stream: Stream to the agent.
        output_stream: Stream from the agent.
        observers: Observers of the raw messages.
    """
    self._client = to_client if isinstance(to_client, Client) else to_client(self)
    self._requests = _request_handlers(self._client)
    self._notifications = _notification_handlers(self._client)
    self.initialize_response: InitializeResponse | None = None
    self._conn = Connection(
        self.handle,
        input_stream,
        output_stream,
        observers=observers,
        reject_batches=True,
        strict_request_ids=True,
    )

archive_session async

archive_session(params: ArchiveSessionRequest) -> ArchiveSessionResponse

Send session/archive.

Source code in src/aclientp/v2/client.py
async def archive_session(self, params: ArchiveSessionRequest) -> ArchiveSessionResponse:
    """Send ``session/archive``."""
    response: ArchiveSessionResponse = await self._request("session/archive", params)
    return response

auth_status async

auth_status(params: AuthStatusRequest) -> AuthStatusResponse

Send auth/status.

Source code in src/aclientp/v2/client.py
async def auth_status(self, params: AuthStatusRequest) -> AuthStatusResponse:
    """Send ``auth/status``."""
    response: AuthStatusResponse = await self._request("auth/status", params)
    return response

cancel async

cancel(params: CancelSessionNotification) -> None

Send session/cancel.

Source code in src/aclientp/v2/client.py
async def cancel(self, params: CancelSessionNotification) -> None:
    """Send ``session/cancel``."""
    await self._conn.send_notification("session/cancel", to_wire(params))

cancel_terminal async

cancel_terminal(params: CancelTerminalRequest) -> CancelTerminalResponse

Send terminal/cancel.

Source code in src/aclientp/v2/client.py
async def cancel_terminal(self, params: CancelTerminalRequest) -> CancelTerminalResponse:
    """Send ``terminal/cancel``."""
    response: CancelTerminalResponse = await self._request("terminal/cancel", params)
    return response

cancel_tool_call async

cancel_tool_call(params: CancelToolCallRequest) -> CancelToolCallResponse

Send tool_call/cancel.

Source code in src/aclientp/v2/client.py
async def cancel_tool_call(self, params: CancelToolCallRequest) -> CancelToolCallResponse:
    """Send ``tool_call/cancel``."""
    response: CancelToolCallResponse = await self._request("tool_call/cancel", params)
    return response

close async

close() -> None

Close the connection.

Source code in src/aclientp/v2/client.py
async def close(self) -> None:
    """Close the connection."""
    await self._conn.close()

close_session async

close_session(params: CloseSessionRequest) -> CloseSessionResponse

Send session/close.

Source code in src/aclientp/v2/client.py
async def close_session(self, params: CloseSessionRequest) -> CloseSessionResponse:
    """Send ``session/close``."""
    response: CloseSessionResponse = await self._request("session/close", params)
    return response

delete_session async

delete_session(params: DeleteSessionRequest) -> DeleteSessionResponse

Send session/delete.

Source code in src/aclientp/v2/client.py
async def delete_session(self, params: DeleteSessionRequest) -> DeleteSessionResponse:
    """Send ``session/delete``."""
    response: DeleteSessionResponse = await self._request("session/delete", params)
    return response

disable_provider async

disable_provider(params: DisableProviderRequest) -> DisableProviderResponse

Send providers/disable.

Source code in src/aclientp/v2/client.py
async def disable_provider(self, params: DisableProviderRequest) -> DisableProviderResponse:
    """Send ``providers/disable``."""
    response: DisableProviderResponse = await self._request("providers/disable", params)
    return response

ext_method async

ext_method(method: str, params: JsonValue = None) -> JsonValue

Send a custom (_-prefixed) request.

Source code in src/aclientp/v2/client.py
async def ext_method(self, method: str, params: JsonValue = None) -> JsonValue:
    """Send a custom (``_``-prefixed) request."""
    return await self._conn.send_request(method, params)

ext_notification async

ext_notification(method: str, params: JsonValue = None) -> None

Send a custom (_-prefixed) notification.

Source code in src/aclientp/v2/client.py
async def ext_notification(self, method: str, params: JsonValue = None) -> None:
    """Send a custom (``_``-prefixed) notification."""
    await self._conn.send_notification(method, params)

fork_session async

fork_session(params: ForkSessionRequest) -> ForkSessionResponse

Send session/fork.

Source code in src/aclientp/v2/client.py
async def fork_session(self, params: ForkSessionRequest) -> ForkSessionResponse:
    """Send ``session/fork``."""
    response: ForkSessionResponse = await self._request("session/fork", params)
    return response

handle async

handle(method: str, params: Any, is_notification: bool) -> Any

Handle one incoming message (the connection's handler).

Source code in src/aclientp/v2/client.py
async def handle(self, method: str, params: Any, is_notification: bool) -> Any:
    """Handle one incoming message (the connection's handler)."""
    initialized = self.initialize_response is not None
    if is_notification:
        if not initialized:
            return None
        if method.startswith("_"):
            await self._client.ext_notification(method, params)
        elif handler := self._notifications.get(method):
            await handler(CLIENT_NOTIFICATIONS[method].validate_python(params or {}))
        return None
    if not initialized:
        details = f"ACP v2 connection must be initialized before {method!r}"
        raise RequestError.invalid_request({"details": details})
    if method.startswith("_"):
        return await self._client.ext_method(method, params)
    if (request_handler := self._requests.get(method)) is None:
        raise RequestError.method_not_found(method)
    parsed = CLIENT_REQUESTS[method].params.validate_python(params or {})
    return to_wire(await request_handler(parsed))

initialize async

initialize(params: InitializeRequest) -> InitializeResponse

Send initialize; the agent must answer with protocol version 2.

Raises:

Type Description
ProtocolVersionError

The agent answered with another protocol version, e.g. 1 from an agent that only speaks v1. Checked before the rest of the response is validated, since its shape depends on the version.

Source code in src/aclientp/v2/client.py
async def initialize(self, params: InitializeRequest) -> InitializeResponse:
    """Send ``initialize``; the agent must answer with protocol version 2.

    Raises:
        ProtocolVersionError: The agent answered with another protocol version,
            e.g. ``1`` from an agent that only speaks v1. Checked before the rest
            of the response is validated, since its shape depends on the version.
    """
    result = await self._conn.send_request("initialize", to_wire(params))
    received = result.get("protocolVersion") if isinstance(result, dict) else None
    if received != PROTOCOL_VERSION:
        raise ProtocolVersionError(PROTOCOL_VERSION, received, result)
    try:
        response: InitializeResponse = AGENT_REQUESTS["initialize"].result.validate_python(
            result
        )
    except ValidationError as exc:
        raise InvalidResponseError.from_validation_error("initialize", exc) from exc
    self.initialize_response = response
    return response

list_providers async

list_providers(params: ListProvidersRequest) -> ListProvidersResponse

Send providers/list.

Source code in src/aclientp/v2/client.py
async def list_providers(self, params: ListProvidersRequest) -> ListProvidersResponse:
    """Send ``providers/list``."""
    response: ListProvidersResponse = await self._request("providers/list", params)
    return response

list_sessions async

list_sessions(params: ListSessionsRequest) -> ListSessionsResponse

Send session/list.

Source code in src/aclientp/v2/client.py
async def list_sessions(self, params: ListSessionsRequest) -> ListSessionsResponse:
    """Send ``session/list``."""
    response: ListSessionsResponse = await self._request("session/list", params)
    return response

login async

Send auth/login.

Source code in src/aclientp/v2/client.py
async def login(self, params: LoginAuthRequest) -> LoginAuthResponse:
    """Send ``auth/login``."""
    response: LoginAuthResponse = await self._request("auth/login", params)
    return response

logout async

Send auth/logout.

Source code in src/aclientp/v2/client.py
async def logout(self, params: LogoutAuthRequest) -> LogoutAuthResponse:
    """Send ``auth/logout``."""
    response: LogoutAuthResponse = await self._request("auth/logout", params)
    return response

mcp_message async

mcp_message(params: MessageMcpRequest) -> MessageMcpResponse

Send an mcp/message request to the agent.

Source code in src/aclientp/v2/client.py
async def mcp_message(self, params: MessageMcpRequest) -> MessageMcpResponse:
    """Send an ``mcp/message`` request to the agent."""
    response: MessageMcpResponse = await self._request("mcp/message", params)
    return response

mcp_notification async

mcp_notification(params: MessageMcpNotification) -> None

Send an mcp/message notification to the agent.

Source code in src/aclientp/v2/client.py
async def mcp_notification(self, params: MessageMcpNotification) -> None:
    """Send an ``mcp/message`` notification to the agent."""
    await self._conn.send_notification("mcp/message", to_wire(params))

new_session async

new_session(params: NewSessionRequest) -> NewSessionResponse

Send session/new.

Source code in src/aclientp/v2/client.py
async def new_session(self, params: NewSessionRequest) -> NewSessionResponse:
    """Send ``session/new``."""
    response: NewSessionResponse = await self._request("session/new", params)
    return response

prompt async

prompt(params: PromptRequest) -> PromptResponse

Send session/prompt; returns once the message is inserted, not when the turn ends.

Source code in src/aclientp/v2/client.py
async def prompt(self, params: PromptRequest) -> PromptResponse:
    """Send ``session/prompt``; returns once the message is inserted, not when the turn ends."""
    response: PromptResponse = await self._request("session/prompt", params)
    return response

resume_session async

resume_session(params: ResumeSessionRequest) -> ResumeSessionResponse

Send session/resume.

Source code in src/aclientp/v2/client.py
async def resume_session(self, params: ResumeSessionRequest) -> ResumeSessionResponse:
    """Send ``session/resume``."""
    response: ResumeSessionResponse = await self._request("session/resume", params)
    return response

session_options async

session_options(params: SessionOptionsRequest) -> SessionOptionsResponse

Send session/options.

Source code in src/aclientp/v2/client.py
async def session_options(self, params: SessionOptionsRequest) -> SessionOptionsResponse:
    """Send ``session/options``."""
    response: SessionOptionsResponse = await self._request("session/options", params)
    return response

session_status async

session_status(params: SessionStatusRequest) -> SessionStatusResponse

Send session/status.

Source code in src/aclientp/v2/client.py
async def session_status(self, params: SessionStatusRequest) -> SessionStatusResponse:
    """Send ``session/status``."""
    response: SessionStatusResponse = await self._request("session/status", params)
    return response

set_provider async

set_provider(params: SetProviderRequest) -> SetProviderResponse

Send providers/set.

Source code in src/aclientp/v2/client.py
async def set_provider(self, params: SetProviderRequest) -> SetProviderResponse:
    """Send ``providers/set``."""
    response: SetProviderResponse = await self._request("providers/set", params)
    return response

set_session_config_option async

set_session_config_option(params: SetSessionConfigOptionRequest) -> SetSessionConfigOptionResponse

Send session/set_config_option.

Source code in src/aclientp/v2/client.py
async def set_session_config_option(
    self, params: SetSessionConfigOptionRequest
) -> SetSessionConfigOptionResponse:
    """Send ``session/set_config_option``."""
    response: SetSessionConfigOptionResponse = await self._request(
        "session/set_config_option", params
    )
    return response

set_session_title async

set_session_title(params: SetSessionTitleRequest) -> SetSessionTitleResponse

Send session/set_title.

Source code in src/aclientp/v2/client.py
async def set_session_title(self, params: SetSessionTitleRequest) -> SetSessionTitleResponse:
    """Send ``session/set_title``."""
    response: SetSessionTitleResponse = await self._request("session/set_title", params)
    return response

unarchive_session async

unarchive_session(params: UnarchiveSessionRequest) -> UnarchiveSessionResponse

Send session/unarchive.

Source code in src/aclientp/v2/client.py
async def unarchive_session(self, params: UnarchiveSessionRequest) -> UnarchiveSessionResponse:
    """Send ``session/unarchive``."""
    response: UnarchiveSessionResponse = await self._request("session/unarchive", params)
    return response

wait_closed async

wait_closed() -> None

Wait until the agent disconnected or the connection was closed.

Source code in src/aclientp/v2/client.py
async def wait_closed(self) -> None:
    """Wait until the agent disconnected or the connection was closed."""
    await self._conn.wait_closed()

:fa-brands-github: Show source on GitHub