Skip to content

AgentSideConnection

🛈 DocStrings

UNSTABLE: Connection of a v2 agent to a client.

Enforces the v2 rules: requests before initialize get -32600 and notifications are ignored, initialize may only be repeated before other requests, request IDs must be strings or integers, and batches get -32600.

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

    Enforces the v2 rules: requests before ``initialize`` get ``-32600`` and
    notifications are ignored, ``initialize`` may only be repeated before other
    requests, request IDs must be strings or integers, and batches get ``-32600``.
    """

    PROTOCOL_VERSION = PROTOCOL_VERSION
    """The protocol version this connection speaks."""

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

        Args:
            to_agent: The agent, or a factory receiving this connection.
            input_stream: Stream to the client.
            output_stream: Stream from the client.
            observers: Observers of the raw messages.
        """
        self._agent = to_agent if isinstance(to_agent, Agent) else to_agent(self)
        self._requests = _request_handlers(self._agent)
        self._notifications = _notification_handlers(self._agent)
        self.phase: InitializationPhase = "uninitialized"
        self.initialize_request: InitializeRequest | None = None
        self._other_request_seen = False
        self._conn = Connection(
            self.handle,
            input_stream,
            output_stream,
            observers=observers,
            reject_batches=True,
            strict_request_ids=True,
        )

    @classmethod
    def on_connection(
        cls,
        connection: Connection,
        to_agent: Callable[[AgentSideConnection], Agent] | Agent,
    ) -> AgentSideConnection:
        """Serve v2 on an existing connection whose handler delegates to :meth:`handle`.

        Used by the version router, which owns the connection until ``initialize``.
        """
        self = cls.__new__(cls)
        self._agent = to_agent if isinstance(to_agent, Agent) else to_agent(self)
        self._requests = _request_handlers(self._agent)
        self._notifications = _notification_handlers(self._agent)
        self.phase = "uninitialized"
        self.initialize_request = None
        self._other_request_seen = False
        connection.reject_batches = True
        connection.strict_request_ids = True
        self._conn = connection
        return self

    @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)."""
        if is_notification:
            await self._handle_notification(method, params)
            return None
        if method == "initialize":
            return await self._initialize(params)
        if self.phase != "initialized":
            details = f"ACP v2 connection must be initialized before {method!r}"
            raise RequestError.invalid_request({"details": details})
        self._other_request_seen = True
        if method.startswith("_"):
            return await self._agent.ext_method(method, params)
        if (handler := self._requests.get(method)) is None:
            raise RequestError.method_not_found(method)
        parsed = AGENT_REQUESTS[method].params.validate_python(params or {})
        return to_wire(await handler(parsed))

    async def _initialize(self, params: Any) -> dict[str, Any]:
        if self.phase == "initializing":
            raise RequestError.invalid_request({"details": "initialize is already in progress"})
        if self.phase == "initialized" and self._other_request_seen:
            details = "initialize must not be repeated after other requests"
            raise RequestError.invalid_request({"details": details})
        request = parse_initialize(params)
        previous = self.phase
        self.phase = "initializing"
        try:
            response = await self._agent.initialize(request)
        except BaseException:
            self.phase = previous
            raise
        if response.protocol_version != PROTOCOL_VERSION:
            self.phase = previous
            raise RequestError.internal_error({"details": "agent answered a non-v2 version"})
        self.initialize_request = request
        self.phase = "initialized"
        return to_wire(response)

    async def _handle_notification(self, method: str, params: Any) -> None:
        if self.phase != "initialized":
            return  # ignored before initialization, as v2 requires
        if method.startswith("_"):
            await self._agent.ext_notification(method, params)
            return
        if (handler := self._notifications.get(method)) is None:
            return
        await handler(AGENT_NOTIFICATIONS[method].validate_python(params or {}))

    # --- Calls to the client --------------------------------------------------------

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

    async def session_update(self, params: UpdateSessionNotification) -> None:
        """Send a ``session/update`` notification."""
        await self._conn.send_notification("session/update", to_wire(params))

    async def request_permission(
        self, params: RequestPermissionRequest
    ) -> RequestPermissionResponse:
        """Ask the user for permission (``session/request_permission``)."""
        response: RequestPermissionResponse = await self._request(
            "session/request_permission", params
        )
        return response

    async def create_elicitation(
        self, params: CreateElicitationRequest
    ) -> CreateElicitationResponse:
        """Ask the user for structured input (``elicitation/create``)."""
        response: CreateElicitationResponse = await self._request("elicitation/create", params)
        return response

    async def complete_elicitation(self, params: CompleteElicitationNotification) -> None:
        """Report that a URL elicitation is complete (``elicitation/complete``)."""
        await self._conn.send_notification("elicitation/complete", to_wire(params))

    async def auth_status_update(self, params: AuthStatusUpdateNotification) -> None:
        """Report a change of the authentication status (``auth/status_update``)."""
        await self._conn.send_notification("auth/status_update", to_wire(params))

    async def mcp_message(self, params: MessageMcpRequest) -> MessageMcpResponse:
        """Send an ``mcp/message`` request to the client."""
        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 client."""
        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 client disconnected or the connection was closed."""
        await self._conn.wait_closed()

PROTOCOL_VERSION class-attribute instance-attribute

PROTOCOL_VERSION = PROTOCOL_VERSION

The protocol version this connection speaks.

connection property

connection: Connection

The underlying JSON-RPC connection.

__init__

__init__(
    to_agent: Callable[[AgentSideConnection], Agent] | Agent,
    input_stream: ByteSendStream,
    output_stream: ByteReceiveStream,
    observers: list[StreamObserver] | None = None,
) -> None

Start the connection.

Parameters:

Name Type Description Default
to_agent Callable[[AgentSideConnection], Agent] | Agent

The agent, or a factory receiving this connection.

required
input_stream ByteSendStream

Stream to the client.

required
output_stream ByteReceiveStream

Stream from the client.

required
observers list[StreamObserver] | None

Observers of the raw messages.

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

    Args:
        to_agent: The agent, or a factory receiving this connection.
        input_stream: Stream to the client.
        output_stream: Stream from the client.
        observers: Observers of the raw messages.
    """
    self._agent = to_agent if isinstance(to_agent, Agent) else to_agent(self)
    self._requests = _request_handlers(self._agent)
    self._notifications = _notification_handlers(self._agent)
    self.phase: InitializationPhase = "uninitialized"
    self.initialize_request: InitializeRequest | None = None
    self._other_request_seen = False
    self._conn = Connection(
        self.handle,
        input_stream,
        output_stream,
        observers=observers,
        reject_batches=True,
        strict_request_ids=True,
    )

auth_status_update async

auth_status_update(params: AuthStatusUpdateNotification) -> None

Report a change of the authentication status (auth/status_update).

Source code in src/aclientp/v2/agent.py
async def auth_status_update(self, params: AuthStatusUpdateNotification) -> None:
    """Report a change of the authentication status (``auth/status_update``)."""
    await self._conn.send_notification("auth/status_update", to_wire(params))

close async

close() -> None

Close the connection.

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

complete_elicitation async

complete_elicitation(params: CompleteElicitationNotification) -> None

Report that a URL elicitation is complete (elicitation/complete).

Source code in src/aclientp/v2/agent.py
async def complete_elicitation(self, params: CompleteElicitationNotification) -> None:
    """Report that a URL elicitation is complete (``elicitation/complete``)."""
    await self._conn.send_notification("elicitation/complete", to_wire(params))

create_elicitation async

create_elicitation(params: CreateElicitationRequest) -> CreateElicitationResponse

Ask the user for structured input (elicitation/create).

Source code in src/aclientp/v2/agent.py
async def create_elicitation(
    self, params: CreateElicitationRequest
) -> CreateElicitationResponse:
    """Ask the user for structured input (``elicitation/create``)."""
    response: CreateElicitationResponse = await self._request("elicitation/create", 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/agent.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/agent.py
async def ext_notification(self, method: str, params: JsonValue = None) -> None:
    """Send a custom (``_``-prefixed) notification."""
    await self._conn.send_notification(method, params)

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/agent.py
async def handle(self, method: str, params: Any, is_notification: bool) -> Any:
    """Handle one incoming message (the connection's handler)."""
    if is_notification:
        await self._handle_notification(method, params)
        return None
    if method == "initialize":
        return await self._initialize(params)
    if self.phase != "initialized":
        details = f"ACP v2 connection must be initialized before {method!r}"
        raise RequestError.invalid_request({"details": details})
    self._other_request_seen = True
    if method.startswith("_"):
        return await self._agent.ext_method(method, params)
    if (handler := self._requests.get(method)) is None:
        raise RequestError.method_not_found(method)
    parsed = AGENT_REQUESTS[method].params.validate_python(params or {})
    return to_wire(await handler(parsed))

mcp_message async

mcp_message(params: MessageMcpRequest) -> MessageMcpResponse

Send an mcp/message request to the client.

Source code in src/aclientp/v2/agent.py
async def mcp_message(self, params: MessageMcpRequest) -> MessageMcpResponse:
    """Send an ``mcp/message`` request to the client."""
    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 client.

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

on_connection classmethod

on_connection(
    connection: Connection, to_agent: Callable[[AgentSideConnection], Agent] | Agent
) -> AgentSideConnection

Serve v2 on an existing connection whose handler delegates to :meth:handle.

Used by the version router, which owns the connection until initialize.

Source code in src/aclientp/v2/agent.py
@classmethod
def on_connection(
    cls,
    connection: Connection,
    to_agent: Callable[[AgentSideConnection], Agent] | Agent,
) -> AgentSideConnection:
    """Serve v2 on an existing connection whose handler delegates to :meth:`handle`.

    Used by the version router, which owns the connection until ``initialize``.
    """
    self = cls.__new__(cls)
    self._agent = to_agent if isinstance(to_agent, Agent) else to_agent(self)
    self._requests = _request_handlers(self._agent)
    self._notifications = _notification_handlers(self._agent)
    self.phase = "uninitialized"
    self.initialize_request = None
    self._other_request_seen = False
    connection.reject_batches = True
    connection.strict_request_ids = True
    self._conn = connection
    return self

request_permission async

request_permission(params: RequestPermissionRequest) -> RequestPermissionResponse

Ask the user for permission (session/request_permission).

Source code in src/aclientp/v2/agent.py
async def request_permission(
    self, params: RequestPermissionRequest
) -> RequestPermissionResponse:
    """Ask the user for permission (``session/request_permission``)."""
    response: RequestPermissionResponse = await self._request(
        "session/request_permission", params
    )
    return response

session_update async

session_update(params: UpdateSessionNotification) -> None

Send a session/update notification.

Source code in src/aclientp/v2/agent.py
async def session_update(self, params: UpdateSessionNotification) -> None:
    """Send a ``session/update`` notification."""
    await self._conn.send_notification("session/update", to_wire(params))

wait_closed async

wait_closed() -> None

Wait until the client disconnected or the connection was closed.

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

:fa-brands-github: Show source on GitHub