Skip to content

connection

Class info

Classes

Name Children Inherits
AgentSideConnection
aclientp.agent.connection
Agent-side connection.

    🛈 DocStrings

    Agent ACP Connection.

    AgentSideConnection

    Bases: Client

    Agent-side connection.

    Use when you implement the Agent and need to talk to a Client.

    Parameters:

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

    factory that receives this connection and returns your Agent

    required
    input

    ByteSendStream (local -> peer)

    required
    output

    ByteReceiveStream (peer -> local)

    required
    Source code in src/aclientp/agent/connection.py
    class AgentSideConnection(Client):
        """Agent-side connection.
    
        Use when you implement the Agent and need to talk to a Client.
    
        Args:
            to_agent: factory that receives this connection and returns your Agent
            input: ByteSendStream (local -> peer)
            output: ByteReceiveStream (peer -> local)
        """
    
        def __init__(
            self,
            to_agent: Callable[[AgentSideConnection], Agent] | Agent,
            input_stream: ByteSendStream,
            output_stream: ByteReceiveStream,
            observers: list[StreamObserver] | None = None,
            *,
            debug_file: str | None = None,
        ) -> None:
            """Initialize the agent-side connection.
    
            Args:
                to_agent: factory that receives this connection and returns your Agent
                input_stream: ByteSendStream (local -> peer)
                output_stream: ByteReceiveStream (peer -> local)
                observers: list of StreamObserver instances to observe the connection
                debug_file: path to a file to write debug information to
            """
            agent = to_agent if isinstance(to_agent, Agent) else to_agent(self)
            handler = partial(_agent_handler, agent)
            store = DebuggingMessageStateStore(debug_file=debug_file) if debug_file else None
            self._conn = Connection(
                handler,
                input_stream,
                output_stream,
                state_store=store,
                observers=observers,
            )
    
        @classmethod
        def on_connection(
            cls,
            connection: Connection,
            to_agent: Callable[[AgentSideConnection], Agent] | Agent,
        ) -> tuple[AgentSideConnection, MethodHandler]:
            """Serve v1 on an existing connection, returning the side and its handler.
    
            Used by the version router (:mod:`aclientp.router`), which owns the connection
            until ``initialize`` and then delegates incoming messages to the handler.
            """
            self = cls.__new__(cls)
            agent = to_agent if isinstance(to_agent, Agent) else to_agent(self)
            self._conn = connection
            return self, partial(_agent_handler, agent)
    
        # client-bound methods (agent -> client)
        async def session_update(self, params: SessionNotification) -> None:
            """Send session update notification."""
            try:
                dct = params.model_dump(by_alias=True, exclude_none=True)
            except TypeError as e:
                log.exception(
                    "Failed to serialize SessionNotification",
                    error=str(e),
                    params_type=type(params).__name__,
                    update_type=type(getattr(params, "update", None)).__name__,
                    update_repr=repr(getattr(params, "update", None))[:500],
                )
                raise
            await self._conn.send_notification("session/update", dct)
    
        async def request_permission(
            self, params: RequestPermissionRequest
        ) -> RequestPermissionResponse:
            """Request permission from the client."""
            dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
            method = "session/request_permission"
            resp = await self._conn.request_object(method, dct)
            return RequestPermissionResponse.model_validate(resp)
    
        async def read_text_file(self, params: ReadTextFileRequest) -> ReadTextFileResponse:
            """Read text file from the client."""
            dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
            resp = await self._conn.request_object("fs/read_text_file", dct)
            return ReadTextFileResponse.model_validate(resp)
    
        async def write_text_file(self, params: WriteTextFileRequest) -> WriteTextFileResponse:
            """Write text file to the client."""
            dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
            r = await self._conn.request_object("fs/write_text_file", dct)
            return WriteTextFileResponse.model_validate(r)
    
        # async def createTerminal(self, params: CreateTerminalRequest) -> TerminalHandle:
        async def create_terminal(self, params: CreateTerminalRequest) -> CreateTerminalResponse:
            """Create a terminal on the client."""
            dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
            resp = await self._conn.request_object("terminal/create", dct)
            #  resp = CreateTerminalResponse.model_validate(resp)
            #  return TerminalHandle(resp.terminal_id, params.session_id, self._conn)
            return CreateTerminalResponse.model_validate(resp)
    
        async def ext_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
            """Call an extension method on the client."""
            return await self._conn.request_object(f"_{method}", params)
    
        async def ext_notification(self, method: str, params: dict[str, Any]) -> None:
            """Send an extension notification to the client."""
            await self._conn.send_notification(f"_{method}", params)
    
        async def terminal_output(self, params: TerminalOutputRequest) -> TerminalOutputResponse:
            """Show terminal output on the client."""
            dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
            resp = await self._conn.request_object("terminal/output", dct)
            return TerminalOutputResponse.model_validate(resp)
    
        async def release_terminal(self, params: ReleaseTerminalRequest) -> ReleaseTerminalResponse:
            """Release a terminal on the client."""
            dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
            resp = await self._conn.request_object("terminal/release", dct)
            return ReleaseTerminalResponse.model_validate(resp)
    
        async def wait_for_terminal_exit(
            self, params: WaitForTerminalExitRequest
        ) -> WaitForTerminalExitResponse:
            """Wait for a terminal to exit on the client."""
            dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
            resp = await self._conn.request_object("terminal/wait_for_exit", dct)
            return WaitForTerminalExitResponse.model_validate(resp)
    
        async def kill_terminal(self, params: KillTerminalRequest) -> KillTerminalResponse:
            """Kill a terminal on the client."""
            dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
            resp = await self._conn.request_object("terminal/kill", dct)
            return KillTerminalResponse.model_validate(resp)
    
        async def elicitation(self, params: ElicitationRequest) -> ElicitationResponse:
            """Request structured user input from the client."""
            dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
            resp = await self._conn.request_object("elicitation/create", dct)
            return ElicitationResponse.model_validate(resp)
    
        async def elicitation_complete(self, params: ElicitationCompleteNotification) -> None:
            """Notify the client that a URL-based elicitation has completed."""
            dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
            await self._conn.send_notification("elicitation/complete", dct)
    
        async def auth_status_update(self, params: AuthStatusUpdateNotification) -> None:
            """**UNSTABLE**: Notify the client that the authentication state changed."""
            dct = params.model_dump(by_alias=True, exclude_none=True)
            await self._conn.send_notification("auth/status_update", dct)
    
        async def mcp_message(self, params: MessageMcpRequest) -> MessageMcpResponse:
            """**UNSTABLE**: Send an inner MCP request to an ``acp`` MCP server the client declared."""
            dct = params.model_dump(by_alias=True, exclude_none=True)
            resp = await self._conn.request_object("mcp/message", dct)
            return MessageMcpResponse.model_validate(resp)
    
        async def mcp_notification(self, params: MessageMcpNotification) -> None:
            """**UNSTABLE**: Send an inner MCP notification over ``mcp/message``."""
            dct = params.model_dump(by_alias=True, exclude_none=True)
            await self._conn.send_notification("mcp/message", dct)
    
        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()
    
        async def __aenter__(self) -> Self:
            """Enter the async context."""
            return self
    
        async def __aexit__(self, *args: object) -> None:
            """Exit the async context (close the connection)."""
            await self.close()
    

    __aenter__ async

    __aenter__() -> Self
    

    Enter the async context.

    Source code in src/aclientp/agent/connection.py
    async def __aenter__(self) -> Self:
        """Enter the async context."""
        return self
    

    __aexit__ async

    __aexit__(*args: object) -> None
    

    Exit the async context (close the connection).

    Source code in src/aclientp/agent/connection.py
    async def __aexit__(self, *args: object) -> None:
        """Exit the async context (close the connection)."""
        await self.close()
    

    __init__

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

    Initialize the agent-side connection.

    Parameters:

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

    factory that receives this connection and returns your Agent

    required
    input_stream ByteSendStream

    ByteSendStream (local -> peer)

    required
    output_stream ByteReceiveStream

    ByteReceiveStream (peer -> local)

    required
    observers list[StreamObserver] | None

    list of StreamObserver instances to observe the connection

    None
    debug_file str | None

    path to a file to write debug information to

    None
    Source code in src/aclientp/agent/connection.py
    def __init__(
        self,
        to_agent: Callable[[AgentSideConnection], Agent] | Agent,
        input_stream: ByteSendStream,
        output_stream: ByteReceiveStream,
        observers: list[StreamObserver] | None = None,
        *,
        debug_file: str | None = None,
    ) -> None:
        """Initialize the agent-side connection.
    
        Args:
            to_agent: factory that receives this connection and returns your Agent
            input_stream: ByteSendStream (local -> peer)
            output_stream: ByteReceiveStream (peer -> local)
            observers: list of StreamObserver instances to observe the connection
            debug_file: path to a file to write debug information to
        """
        agent = to_agent if isinstance(to_agent, Agent) else to_agent(self)
        handler = partial(_agent_handler, agent)
        store = DebuggingMessageStateStore(debug_file=debug_file) if debug_file else None
        self._conn = Connection(
            handler,
            input_stream,
            output_stream,
            state_store=store,
            observers=observers,
        )
    

    auth_status_update async

    auth_status_update(params: AuthStatusUpdateNotification) -> None
    

    UNSTABLE: Notify the client that the authentication state changed.

    Source code in src/aclientp/agent/connection.py
    async def auth_status_update(self, params: AuthStatusUpdateNotification) -> None:
        """**UNSTABLE**: Notify the client that the authentication state changed."""
        dct = params.model_dump(by_alias=True, exclude_none=True)
        await self._conn.send_notification("auth/status_update", dct)
    

    close async

    close() -> None
    

    Close the connection.

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

    create_terminal async

    create_terminal(params: CreateTerminalRequest) -> CreateTerminalResponse
    

    Create a terminal on the client.

    Source code in src/aclientp/agent/connection.py
    async def create_terminal(self, params: CreateTerminalRequest) -> CreateTerminalResponse:
        """Create a terminal on the client."""
        dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
        resp = await self._conn.request_object("terminal/create", dct)
        #  resp = CreateTerminalResponse.model_validate(resp)
        #  return TerminalHandle(resp.terminal_id, params.session_id, self._conn)
        return CreateTerminalResponse.model_validate(resp)
    

    elicitation async

    elicitation(params: ElicitationRequest) -> ElicitationResponse
    

    Request structured user input from the client.

    Source code in src/aclientp/agent/connection.py
    async def elicitation(self, params: ElicitationRequest) -> ElicitationResponse:
        """Request structured user input from the client."""
        dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
        resp = await self._conn.request_object("elicitation/create", dct)
        return ElicitationResponse.model_validate(resp)
    

    elicitation_complete async

    elicitation_complete(params: ElicitationCompleteNotification) -> None
    

    Notify the client that a URL-based elicitation has completed.

    Source code in src/aclientp/agent/connection.py
    async def elicitation_complete(self, params: ElicitationCompleteNotification) -> None:
        """Notify the client that a URL-based elicitation has completed."""
        dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
        await self._conn.send_notification("elicitation/complete", dct)
    

    ext_method async

    ext_method(method: str, params: dict[str, Any]) -> dict[str, Any]
    

    Call an extension method on the client.

    Source code in src/aclientp/agent/connection.py
    async def ext_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
        """Call an extension method on the client."""
        return await self._conn.request_object(f"_{method}", params)
    

    ext_notification async

    ext_notification(method: str, params: dict[str, Any]) -> None
    

    Send an extension notification to the client.

    Source code in src/aclientp/agent/connection.py
    async def ext_notification(self, method: str, params: dict[str, Any]) -> None:
        """Send an extension notification to the client."""
        await self._conn.send_notification(f"_{method}", params)
    

    kill_terminal async

    kill_terminal(params: KillTerminalRequest) -> KillTerminalResponse
    

    Kill a terminal on the client.

    Source code in src/aclientp/agent/connection.py
    async def kill_terminal(self, params: KillTerminalRequest) -> KillTerminalResponse:
        """Kill a terminal on the client."""
        dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
        resp = await self._conn.request_object("terminal/kill", dct)
        return KillTerminalResponse.model_validate(resp)
    

    mcp_message async

    mcp_message(params: MessageMcpRequest) -> MessageMcpResponse
    

    UNSTABLE: Send an inner MCP request to an acp MCP server the client declared.

    Source code in src/aclientp/agent/connection.py
    async def mcp_message(self, params: MessageMcpRequest) -> MessageMcpResponse:
        """**UNSTABLE**: Send an inner MCP request to an ``acp`` MCP server the client declared."""
        dct = params.model_dump(by_alias=True, exclude_none=True)
        resp = await self._conn.request_object("mcp/message", dct)
        return MessageMcpResponse.model_validate(resp)
    

    mcp_notification async

    mcp_notification(params: MessageMcpNotification) -> None
    

    UNSTABLE: Send an inner MCP notification over mcp/message.

    Source code in src/aclientp/agent/connection.py
    async def mcp_notification(self, params: MessageMcpNotification) -> None:
        """**UNSTABLE**: Send an inner MCP notification over ``mcp/message``."""
        dct = params.model_dump(by_alias=True, exclude_none=True)
        await self._conn.send_notification("mcp/message", dct)
    

    on_connection classmethod

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

    Serve v1 on an existing connection, returning the side and its handler.

    Used by the version router (:mod:aclientp.router), which owns the connection until initialize and then delegates incoming messages to the handler.

    Source code in src/aclientp/agent/connection.py
    @classmethod
    def on_connection(
        cls,
        connection: Connection,
        to_agent: Callable[[AgentSideConnection], Agent] | Agent,
    ) -> tuple[AgentSideConnection, MethodHandler]:
        """Serve v1 on an existing connection, returning the side and its handler.
    
        Used by the version router (:mod:`aclientp.router`), which owns the connection
        until ``initialize`` and then delegates incoming messages to the handler.
        """
        self = cls.__new__(cls)
        agent = to_agent if isinstance(to_agent, Agent) else to_agent(self)
        self._conn = connection
        return self, partial(_agent_handler, agent)
    

    read_text_file async

    read_text_file(params: ReadTextFileRequest) -> ReadTextFileResponse
    

    Read text file from the client.

    Source code in src/aclientp/agent/connection.py
    async def read_text_file(self, params: ReadTextFileRequest) -> ReadTextFileResponse:
        """Read text file from the client."""
        dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
        resp = await self._conn.request_object("fs/read_text_file", dct)
        return ReadTextFileResponse.model_validate(resp)
    

    release_terminal async

    release_terminal(params: ReleaseTerminalRequest) -> ReleaseTerminalResponse
    

    Release a terminal on the client.

    Source code in src/aclientp/agent/connection.py
    async def release_terminal(self, params: ReleaseTerminalRequest) -> ReleaseTerminalResponse:
        """Release a terminal on the client."""
        dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
        resp = await self._conn.request_object("terminal/release", dct)
        return ReleaseTerminalResponse.model_validate(resp)
    

    request_permission async

    request_permission(params: RequestPermissionRequest) -> RequestPermissionResponse
    

    Request permission from the client.

    Source code in src/aclientp/agent/connection.py
    async def request_permission(
        self, params: RequestPermissionRequest
    ) -> RequestPermissionResponse:
        """Request permission from the client."""
        dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
        method = "session/request_permission"
        resp = await self._conn.request_object(method, dct)
        return RequestPermissionResponse.model_validate(resp)
    

    session_update async

    session_update(params: SessionNotification) -> None
    

    Send session update notification.

    Source code in src/aclientp/agent/connection.py
    async def session_update(self, params: SessionNotification) -> None:
        """Send session update notification."""
        try:
            dct = params.model_dump(by_alias=True, exclude_none=True)
        except TypeError as e:
            log.exception(
                "Failed to serialize SessionNotification",
                error=str(e),
                params_type=type(params).__name__,
                update_type=type(getattr(params, "update", None)).__name__,
                update_repr=repr(getattr(params, "update", None))[:500],
            )
            raise
        await self._conn.send_notification("session/update", dct)
    

    terminal_output async

    terminal_output(params: TerminalOutputRequest) -> TerminalOutputResponse
    

    Show terminal output on the client.

    Source code in src/aclientp/agent/connection.py
    async def terminal_output(self, params: TerminalOutputRequest) -> TerminalOutputResponse:
        """Show terminal output on the client."""
        dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
        resp = await self._conn.request_object("terminal/output", dct)
        return TerminalOutputResponse.model_validate(resp)
    

    wait_closed async

    wait_closed() -> None
    

    Wait until the client disconnected or the connection was closed.

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

    wait_for_terminal_exit async

    wait_for_terminal_exit(params: WaitForTerminalExitRequest) -> WaitForTerminalExitResponse
    

    Wait for a terminal to exit on the client.

    Source code in src/aclientp/agent/connection.py
    async def wait_for_terminal_exit(
        self, params: WaitForTerminalExitRequest
    ) -> WaitForTerminalExitResponse:
        """Wait for a terminal to exit on the client."""
        dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
        resp = await self._conn.request_object("terminal/wait_for_exit", dct)
        return WaitForTerminalExitResponse.model_validate(resp)
    

    write_text_file async

    write_text_file(params: WriteTextFileRequest) -> WriteTextFileResponse
    

    Write text file to the client.

    Source code in src/aclientp/agent/connection.py
    async def write_text_file(self, params: WriteTextFileRequest) -> WriteTextFileResponse:
        """Write text file to the client."""
        dct = params.model_dump(by_alias=True, exclude_none=True, exclude_defaults=True)
        r = await self._conn.request_object("fs/write_text_file", dct)
        return WriteTextFileResponse.model_validate(r)