Skip to content

agent

Class info

Re-exported classes

Class Module Description
ACPAgentAPI aclientp.agent.acp_agent_api Thin wrapper for client-to-agent ACP interactions.
Agent aclientp.agent.protocol Base agent interface for ACP.
AgentSideConnection aclientp.agent.connection Agent-side connection.

🛈 DocStrings

Agent (Server) ACP Connection.

ACPAgentAPI

Thin wrapper for client-to-agent ACP interactions.

Avoids manual instantiation of request/notification objects.

Source code in src/aclientp/agent/acp_agent_api.py
class ACPAgentAPI:
    """Thin wrapper for client-to-agent ACP interactions.

    Avoids manual instantiation of request/notification objects.
    """

    def __init__(self, connection: Agent) -> None:
        """Initialize agent API helper.

        Args:
            connection: The Agent protocol connection (e.g., ClientSideConnection)
        """
        self.connection = connection

    async def initialize(
        self,
        *,
        title: str,
        version: str,
        name: str,
        protocol_version: int = 1,
        terminal: bool = True,
        read_text_file: bool = True,
        write_text_file: bool = True,
        terminal_auth: bool = False,
        metadata: dict[str, Any] | None = None,
    ) -> InitializeResponse:
        """Initialize the ACP connection."""
        request = InitializeRequest.create(
            title=title,
            version=version,
            name=name,
            protocol_version=protocol_version,
            terminal=terminal,
            read_text_file=read_text_file,
            write_text_file=write_text_file,
            terminal_auth=terminal_auth,
            metadata=metadata,
        )
        return await self.connection.initialize(request)

    async def new_session(
        self,
        cwd: str | None = None,
        mcp_servers: Sequence[McpServer] | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> NewSessionResponse:
        """Create a new ACP session."""
        request = NewSessionRequest(
            cwd=cwd or str(Path.cwd()),
            mcp_servers=list(mcp_servers or []),
            field_meta=metadata,
        )
        return await self.connection.new_session(request)

    async def load_session(
        self,
        session_id: str,
        cwd: str,
        mcp_servers: Sequence[McpServer] | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> LoadSessionResponse:
        """Load an existing session."""
        request = LoadSessionRequest(
            session_id=session_id,
            cwd=cwd,
            mcp_servers=list(mcp_servers or []),
            field_meta=metadata,
        )
        return await self.connection.load_session(request)

    async def list_sessions(
        self,
        cwd: str | None = None,
        cursor: str | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> ListSessionsResponse:
        """List available sessions."""
        request = ListSessionsRequest(cwd=cwd, cursor=cursor, field_meta=metadata)
        return await self.connection.list_sessions(request)

    async def fork_session(
        self,
        session_id: str,
        cwd: str,
        mcp_servers: Sequence[McpServer] | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> ForkSessionResponse:
        """Fork an existing session."""
        request = ForkSessionRequest(
            session_id=session_id,
            cwd=cwd,
            mcp_servers=list(mcp_servers) if mcp_servers else [],
            field_meta=metadata,
        )
        return await self.connection.fork_session(request)

    async def resume_session(
        self,
        session_id: str,
        cwd: str,
        mcp_servers: Sequence[McpServer] | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> ResumeSessionResponse:
        """Resume a paused session."""
        servers = list(mcp_servers) if mcp_servers else []
        request = ResumeSessionRequest(
            session_id=session_id,
            cwd=cwd,
            mcp_servers=servers,
            field_meta=metadata,
        )
        return await self.connection.resume_session(request)

    async def prompt(
        self,
        session_id: str,
        prompt: Sequence[ContentBlock],
        metadata: dict[str, Any] | None = None,
    ) -> PromptResponse:
        """Send a prompt to the agent."""
        request = PromptRequest(
            session_id=session_id,
            prompt=list(prompt),
            field_meta=metadata,
        )
        return await self.connection.prompt(request)

    async def cancel(self, session_id: str) -> None:
        """Cancel the current operation in a session."""
        notification = CancelNotification(session_id=session_id)
        await self.connection.cancel(notification)

    async def set_session_mode(
        self,
        session_id: str,
        mode_id: str,
    ) -> SetSessionModeResponse | None:
        """Set the session mode."""
        request = SetSessionModeRequest(session_id=session_id, mode_id=mode_id)
        return await self.connection.set_session_mode(request)

    async def set_session_config_option(
        self,
        session_id: str,
        config_id: str,
        value: str | bool,
    ) -> SetSessionConfigOptionResponse | None:
        """Set a session configuration option.

        Args:
            session_id: The session ID.
            config_id: The config option ID.
            value: String value ID for select options, or bool for boolean options.
        """
        type_field = "boolean" if isinstance(value, bool) else None
        req = SetSessionConfigOptionRequest(
            session_id=session_id, config_id=config_id, value=value, type=type_field
        )
        return await self.connection.set_session_config_option(req)

    async def authenticate(
        self,
        method_id: str,
    ) -> AuthenticateResponse | None:
        """Authenticate with the agent."""
        request = AuthenticateRequest(method_id=method_id)
        return await self.connection.authenticate(request)

    async def logout(self) -> LogoutResponse | None:
        """Log out of the current authenticated state."""
        request = LogoutRequest()
        return await self.connection.logout(request)

    async def ext_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
        """Call an extension method on the agent."""
        return await self.connection.ext_method(method, params)

    async def ext_notification(self, method: str, params: dict[str, Any]) -> None:
        """Send an extension notification to the agent."""
        await self.connection.ext_notification(method, params)

__init__

__init__(connection: Agent) -> None

Initialize agent API helper.

Parameters:

Name Type Description Default
connection Agent

The Agent protocol connection (e.g., ClientSideConnection)

required
Source code in src/aclientp/agent/acp_agent_api.py
def __init__(self, connection: Agent) -> None:
    """Initialize agent API helper.

    Args:
        connection: The Agent protocol connection (e.g., ClientSideConnection)
    """
    self.connection = connection

authenticate async

authenticate(method_id: str) -> AuthenticateResponse | None

Authenticate with the agent.

Source code in src/aclientp/agent/acp_agent_api.py
async def authenticate(
    self,
    method_id: str,
) -> AuthenticateResponse | None:
    """Authenticate with the agent."""
    request = AuthenticateRequest(method_id=method_id)
    return await self.connection.authenticate(request)

cancel async

cancel(session_id: str) -> None

Cancel the current operation in a session.

Source code in src/aclientp/agent/acp_agent_api.py
async def cancel(self, session_id: str) -> None:
    """Cancel the current operation in a session."""
    notification = CancelNotification(session_id=session_id)
    await self.connection.cancel(notification)

ext_method async

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

Call an extension method on the agent.

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

ext_notification async

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

Send an extension notification to the agent.

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

fork_session async

fork_session(
    session_id: str,
    cwd: str,
    mcp_servers: Sequence[McpServer] | None = None,
    metadata: dict[str, Any] | None = None,
) -> ForkSessionResponse

Fork an existing session.

Source code in src/aclientp/agent/acp_agent_api.py
async def fork_session(
    self,
    session_id: str,
    cwd: str,
    mcp_servers: Sequence[McpServer] | None = None,
    metadata: dict[str, Any] | None = None,
) -> ForkSessionResponse:
    """Fork an existing session."""
    request = ForkSessionRequest(
        session_id=session_id,
        cwd=cwd,
        mcp_servers=list(mcp_servers) if mcp_servers else [],
        field_meta=metadata,
    )
    return await self.connection.fork_session(request)

initialize async

initialize(
    *,
    title: str,
    version: str,
    name: str,
    protocol_version: int = 1,
    terminal: bool = True,
    read_text_file: bool = True,
    write_text_file: bool = True,
    terminal_auth: bool = False,
    metadata: dict[str, Any] | None = None,
) -> InitializeResponse

Initialize the ACP connection.

Source code in src/aclientp/agent/acp_agent_api.py
async def initialize(
    self,
    *,
    title: str,
    version: str,
    name: str,
    protocol_version: int = 1,
    terminal: bool = True,
    read_text_file: bool = True,
    write_text_file: bool = True,
    terminal_auth: bool = False,
    metadata: dict[str, Any] | None = None,
) -> InitializeResponse:
    """Initialize the ACP connection."""
    request = InitializeRequest.create(
        title=title,
        version=version,
        name=name,
        protocol_version=protocol_version,
        terminal=terminal,
        read_text_file=read_text_file,
        write_text_file=write_text_file,
        terminal_auth=terminal_auth,
        metadata=metadata,
    )
    return await self.connection.initialize(request)

list_sessions async

list_sessions(
    cwd: str | None = None, cursor: str | None = None, metadata: dict[str, Any] | None = None
) -> ListSessionsResponse

List available sessions.

Source code in src/aclientp/agent/acp_agent_api.py
async def list_sessions(
    self,
    cwd: str | None = None,
    cursor: str | None = None,
    metadata: dict[str, Any] | None = None,
) -> ListSessionsResponse:
    """List available sessions."""
    request = ListSessionsRequest(cwd=cwd, cursor=cursor, field_meta=metadata)
    return await self.connection.list_sessions(request)

load_session async

load_session(
    session_id: str,
    cwd: str,
    mcp_servers: Sequence[McpServer] | None = None,
    metadata: dict[str, Any] | None = None,
) -> LoadSessionResponse

Load an existing session.

Source code in src/aclientp/agent/acp_agent_api.py
async def load_session(
    self,
    session_id: str,
    cwd: str,
    mcp_servers: Sequence[McpServer] | None = None,
    metadata: dict[str, Any] | None = None,
) -> LoadSessionResponse:
    """Load an existing session."""
    request = LoadSessionRequest(
        session_id=session_id,
        cwd=cwd,
        mcp_servers=list(mcp_servers or []),
        field_meta=metadata,
    )
    return await self.connection.load_session(request)

logout async

logout() -> LogoutResponse | None

Log out of the current authenticated state.

Source code in src/aclientp/agent/acp_agent_api.py
async def logout(self) -> LogoutResponse | None:
    """Log out of the current authenticated state."""
    request = LogoutRequest()
    return await self.connection.logout(request)

new_session async

new_session(
    cwd: str | None = None,
    mcp_servers: Sequence[McpServer] | None = None,
    metadata: dict[str, Any] | None = None,
) -> NewSessionResponse

Create a new ACP session.

Source code in src/aclientp/agent/acp_agent_api.py
async def new_session(
    self,
    cwd: str | None = None,
    mcp_servers: Sequence[McpServer] | None = None,
    metadata: dict[str, Any] | None = None,
) -> NewSessionResponse:
    """Create a new ACP session."""
    request = NewSessionRequest(
        cwd=cwd or str(Path.cwd()),
        mcp_servers=list(mcp_servers or []),
        field_meta=metadata,
    )
    return await self.connection.new_session(request)

prompt async

prompt(
    session_id: str, prompt: Sequence[ContentBlock], metadata: dict[str, Any] | None = None
) -> PromptResponse

Send a prompt to the agent.

Source code in src/aclientp/agent/acp_agent_api.py
async def prompt(
    self,
    session_id: str,
    prompt: Sequence[ContentBlock],
    metadata: dict[str, Any] | None = None,
) -> PromptResponse:
    """Send a prompt to the agent."""
    request = PromptRequest(
        session_id=session_id,
        prompt=list(prompt),
        field_meta=metadata,
    )
    return await self.connection.prompt(request)

resume_session async

resume_session(
    session_id: str,
    cwd: str,
    mcp_servers: Sequence[McpServer] | None = None,
    metadata: dict[str, Any] | None = None,
) -> ResumeSessionResponse

Resume a paused session.

Source code in src/aclientp/agent/acp_agent_api.py
async def resume_session(
    self,
    session_id: str,
    cwd: str,
    mcp_servers: Sequence[McpServer] | None = None,
    metadata: dict[str, Any] | None = None,
) -> ResumeSessionResponse:
    """Resume a paused session."""
    servers = list(mcp_servers) if mcp_servers else []
    request = ResumeSessionRequest(
        session_id=session_id,
        cwd=cwd,
        mcp_servers=servers,
        field_meta=metadata,
    )
    return await self.connection.resume_session(request)

set_session_config_option async

set_session_config_option(
    session_id: str, config_id: str, value: str | bool
) -> SetSessionConfigOptionResponse | None

Set a session configuration option.

Parameters:

Name Type Description Default
session_id str

The session ID.

required
config_id str

The config option ID.

required
value str | bool

String value ID for select options, or bool for boolean options.

required
Source code in src/aclientp/agent/acp_agent_api.py
async def set_session_config_option(
    self,
    session_id: str,
    config_id: str,
    value: str | bool,
) -> SetSessionConfigOptionResponse | None:
    """Set a session configuration option.

    Args:
        session_id: The session ID.
        config_id: The config option ID.
        value: String value ID for select options, or bool for boolean options.
    """
    type_field = "boolean" if isinstance(value, bool) else None
    req = SetSessionConfigOptionRequest(
        session_id=session_id, config_id=config_id, value=value, type=type_field
    )
    return await self.connection.set_session_config_option(req)

set_session_mode async

set_session_mode(session_id: str, mode_id: str) -> SetSessionModeResponse | None

Set the session mode.

Source code in src/aclientp/agent/acp_agent_api.py
async def set_session_mode(
    self,
    session_id: str,
    mode_id: str,
) -> SetSessionModeResponse | None:
    """Set the session mode."""
    request = SetSessionModeRequest(session_id=session_id, mode_id=mode_id)
    return await self.connection.set_session_mode(request)

Agent

Bases: Protocol

Base agent interface for ACP.

Methods with a default body are optional and gated by a capability the agent advertises. Their defaults reject the call with method not found.

Source code in src/aclientp/agent/protocol.py
@runtime_checkable
class Agent(Protocol):
    """Base agent interface for ACP.

    Methods with a default body are optional and gated by a capability the agent
    advertises. Their defaults reject the call with ``method not found``.
    """

    async def initialize(self, params: InitializeRequest) -> InitializeResponse: ...

    async def new_session(self, params: NewSessionRequest) -> NewSessionResponse: ...

    async def prompt(self, params: PromptRequest) -> PromptResponse: ...

    async def cancel(self, params: CancelNotification) -> None: ...

    async def load_session(self, params: LoadSessionRequest) -> LoadSessionResponse: ...

    async def list_sessions(self, params: ListSessionsRequest) -> ListSessionsResponse: ...

    async def fork_session(self, params: ForkSessionRequest) -> ForkSessionResponse: ...

    async def resume_session(self, params: ResumeSessionRequest) -> ResumeSessionResponse: ...

    async def close_session(self, params: CloseSessionRequest) -> CloseSessionResponse: ...

    async def authenticate(self, params: AuthenticateRequest) -> AuthenticateResponse | None: ...

    async def logout(self, params: LogoutRequest) -> LogoutResponse | None: ...

    async def set_session_mode(
        self, params: SetSessionModeRequest
    ) -> SetSessionModeResponse | None: ...

    async def set_session_config_option(
        self, params: SetSessionConfigOptionRequest
    ) -> SetSessionConfigOptionResponse | None: ...

    async def ext_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]: ...

    async def ext_notification(self, method: str, params: dict[str, Any]) -> None: ...

    async def delete_session(self, params: DeleteSessionRequest) -> DeleteSessionResponse:
        raise RequestError.method_not_found("session/delete")

    async def archive_session(self, params: ArchiveSessionRequest) -> ArchiveSessionResponse:
        """**UNSTABLE**."""
        raise RequestError.method_not_found("session/archive")

    async def unarchive_session(self, params: UnarchiveSessionRequest) -> UnarchiveSessionResponse:
        """**UNSTABLE**."""
        raise RequestError.method_not_found("session/unarchive")

    async def session_status(self, params: SessionStatusRequest) -> SessionStatusResponse:
        """**UNSTABLE**."""
        raise RequestError.method_not_found("session/status")

    async def session_options(self, params: SessionOptionsRequest) -> SessionOptionsResponse:
        """**UNSTABLE**."""
        raise RequestError.method_not_found("session/options")

    async def set_session_title(self, params: SetSessionTitleRequest) -> SetSessionTitleResponse:
        """**UNSTABLE**."""
        raise RequestError.method_not_found("session/set_title")

    async def auth_status(self, params: AuthStatusRequest) -> AuthStatusResponse:
        """**UNSTABLE**."""
        raise RequestError.method_not_found("auth/status")

    async def list_providers(self, params: ListProvidersRequest) -> ListProvidersResponse:
        """**UNSTABLE**."""
        raise RequestError.method_not_found("providers/list")

    async def set_provider(self, params: SetProviderRequest) -> SetProviderResponse:
        """**UNSTABLE**."""
        raise RequestError.method_not_found("providers/set")

    async def disable_provider(self, params: DisableProviderRequest) -> DisableProviderResponse:
        """**UNSTABLE**."""
        raise RequestError.method_not_found("providers/disable")

    async def mcp_message(self, params: MessageMcpRequest) -> MessageMcpResponse:
        """**UNSTABLE**: Inner MCP request to an ``acp`` MCP server the agent declared."""
        raise RequestError.method_not_found("mcp/message")

    async def mcp_notification(self, params: MessageMcpNotification) -> None:
        """**UNSTABLE**: Inner MCP notification for an ``acp`` MCP server the agent declared."""
        return

archive_session async

archive_session(params: ArchiveSessionRequest) -> ArchiveSessionResponse

UNSTABLE.

Source code in src/aclientp/agent/protocol.py
async def archive_session(self, params: ArchiveSessionRequest) -> ArchiveSessionResponse:
    """**UNSTABLE**."""
    raise RequestError.method_not_found("session/archive")

auth_status async

auth_status(params: AuthStatusRequest) -> AuthStatusResponse

UNSTABLE.

Source code in src/aclientp/agent/protocol.py
async def auth_status(self, params: AuthStatusRequest) -> AuthStatusResponse:
    """**UNSTABLE**."""
    raise RequestError.method_not_found("auth/status")

disable_provider async

disable_provider(params: DisableProviderRequest) -> DisableProviderResponse

UNSTABLE.

Source code in src/aclientp/agent/protocol.py
async def disable_provider(self, params: DisableProviderRequest) -> DisableProviderResponse:
    """**UNSTABLE**."""
    raise RequestError.method_not_found("providers/disable")

list_providers async

list_providers(params: ListProvidersRequest) -> ListProvidersResponse

UNSTABLE.

Source code in src/aclientp/agent/protocol.py
async def list_providers(self, params: ListProvidersRequest) -> ListProvidersResponse:
    """**UNSTABLE**."""
    raise RequestError.method_not_found("providers/list")

mcp_message async

mcp_message(params: MessageMcpRequest) -> MessageMcpResponse

UNSTABLE: Inner MCP request to an acp MCP server the agent declared.

Source code in src/aclientp/agent/protocol.py
async def mcp_message(self, params: MessageMcpRequest) -> MessageMcpResponse:
    """**UNSTABLE**: Inner MCP request to an ``acp`` MCP server the agent declared."""
    raise RequestError.method_not_found("mcp/message")

mcp_notification async

mcp_notification(params: MessageMcpNotification) -> None

UNSTABLE: Inner MCP notification for an acp MCP server the agent declared.

Source code in src/aclientp/agent/protocol.py
async def mcp_notification(self, params: MessageMcpNotification) -> None:
    """**UNSTABLE**: Inner MCP notification for an ``acp`` MCP server the agent declared."""
    return

session_options async

session_options(params: SessionOptionsRequest) -> SessionOptionsResponse

UNSTABLE.

Source code in src/aclientp/agent/protocol.py
async def session_options(self, params: SessionOptionsRequest) -> SessionOptionsResponse:
    """**UNSTABLE**."""
    raise RequestError.method_not_found("session/options")

session_status async

session_status(params: SessionStatusRequest) -> SessionStatusResponse

UNSTABLE.

Source code in src/aclientp/agent/protocol.py
async def session_status(self, params: SessionStatusRequest) -> SessionStatusResponse:
    """**UNSTABLE**."""
    raise RequestError.method_not_found("session/status")

set_provider async

set_provider(params: SetProviderRequest) -> SetProviderResponse

UNSTABLE.

Source code in src/aclientp/agent/protocol.py
async def set_provider(self, params: SetProviderRequest) -> SetProviderResponse:
    """**UNSTABLE**."""
    raise RequestError.method_not_found("providers/set")

set_session_title async

set_session_title(params: SetSessionTitleRequest) -> SetSessionTitleResponse

UNSTABLE.

Source code in src/aclientp/agent/protocol.py
async def set_session_title(self, params: SetSessionTitleRequest) -> SetSessionTitleResponse:
    """**UNSTABLE**."""
    raise RequestError.method_not_found("session/set_title")

unarchive_session async

unarchive_session(params: UnarchiveSessionRequest) -> UnarchiveSessionResponse

UNSTABLE.

Source code in src/aclientp/agent/protocol.py
async def unarchive_session(self, params: UnarchiveSessionRequest) -> UnarchiveSessionResponse:
    """**UNSTABLE**."""
    raise RequestError.method_not_found("session/unarchive")

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)