Skip to content

aclientp

Class info

Re-exported classes

Class Module Description
Agent aclientp.agent.protocol Base agent interface for ACP.
AgentAuthCapabilities aclientp.schema.capabilities Authentication-related capabilities supported by the agent.
AgentMessageChunk aclientp.schema.session_updates A chunk of the agent's response being streamed.
AgentSideConnection aclientp.agent.connection Agent-side connection.
AllowedOutcome aclientp.schema.tool_call The user selected one of the provided options.
Annotations aclientp.schema.content_blocks Optional annotations for the client.
ArchiveSessionRequest aclientp.schema.client_requests UNSTABLE: Request parameters for archiving a session.
ArchiveSessionResponse aclientp.schema.agent_responses UNSTABLE: Response to session/archive.
AuthCapabilities aclientp.schema.capabilities Authentication capabilities supported by the client.
AuthMethodAgent aclientp.schema.common Agent handles authentication itself.
AuthMethodTerminal aclientp.schema.common Terminal authentication method.
AuthStatusRequest aclientp.schema.client_requests UNSTABLE: Request the agent's current authentication state.
AuthStatusResponse aclientp.schema.agent_responses UNSTABLE: Response to auth/status.
AuthStatusUpdateNotification aclientp.schema.notifications UNSTABLE: The agent's authentication state changed (auth/status_update).
AuthenticateRequest aclientp.schema.client_requests Request parameters for the authenticate method.
AuthenticateResponse aclientp.schema.agent_responses Response to authenticate method.
AvailableCommand aclientp.schema.slash_commands Information about a command.
BooleanPropertySchema aclientp.schema.elicitation Schema for boolean properties in an elicitation form.
CancelNotification aclientp.schema.notifications Notification to cancel ongoing operations for a session.
CancelRequestNotification aclientp.schema.notifications Notification to cancel an ongoing request ($/cancel_request).
Client aclientp.client.protocol Base client interface for ACP.
ClientCapabilities aclientp.schema.capabilities Capabilities supported by the client.
ClientSideConnection aclientp.client.connection Client-side connection.
CloseSessionRequest aclientp.schema.client_requests Request parameters for closing an active session.
CloseSessionResponse aclientp.schema.agent_responses Response from closing a session.
CreateTerminalRequest aclientp.schema.agent_requests Request to create a new terminal and execute a command.
CreateTerminalResponse aclientp.schema.client_responses Response containing the ID of the created terminal.
DefaultACPClient aclientp.client.implementations.default_client Default implementation of ACP Client interface for basic operations.
DeleteSessionRequest aclientp.schema.client_requests Request parameters for deleting a session from session/list.
DeleteSessionResponse aclientp.schema.agent_responses Response to session/delete.
DeniedOutcome aclientp.schema.tool_call The prompt turn was cancelled before the user responded.
ElicitationCapabilities aclientp.schema.elicitation Elicitation capabilities supported by the client.
ElicitationCompleteNotification aclientp.schema.elicitation Notification sent by the agent when a URL-based elicitation is complete.
ElicitationFormCapabilities aclientp.schema.elicitation Form-based elicitation capabilities.
ElicitationRequest aclientp.schema.elicitation Request from the agent to elicit structured user input (elicitation/create).
ElicitationResponse aclientp.schema.elicitation Response from the client to an elicitation request.
ElicitationSchema aclientp.schema.elicitation Type-safe elicitation schema for requesting structured user input.
ElicitationUrlCapabilities aclientp.schema.elicitation URL-based elicitation capabilities.
EnumOption aclientp.schema.elicitation A titled enum option with a const value, human-readable title and optional description.
EnvVariable aclientp.schema.common An environment variable to set when launching an MCP server.
FileSystemCapabilities aclientp.schema.capabilities File system capabilities that a client may support.
ForkSessionRequest aclientp.schema.client_requests UNSTABLE: Request parameters for forking an existing session.
ForkSessionResponse aclientp.schema.agent_responses UNSTABLE: Response from forking an existing session.
HeadlessACPClient aclientp.client.implementations.headless_client Headless ACP client with real filesystem and terminal operations.
HttpMcpServer aclientp.schema.mcp HTTP transport configuration.
HttpTransport aclientp.transports Configuration for the Streamable HTTP & WebSocket server transport (experimental).
HttpTransportError aclientp.http_transport The ACP server rejected the connection or became unreachable.
Implementation aclientp.schema.common Describes the name and version of an ACP implementation.
InitializeRequest aclientp.schema.client_requests Request parameters for the initialize method.
InitializeResponse aclientp.schema.agent_responses Response from the initialize method.
IntegerPropertySchema aclientp.schema.elicitation Schema for integer properties in an elicitation form.
KillTerminalRequest aclientp.schema.agent_requests Request to kill a terminal command without releasing the terminal.
KillTerminalResponse aclientp.schema.client_responses Response to the terminal/kill method.
ListSessionsRequest aclientp.schema.client_requests Request parameters for listing existing sessions.
ListSessionsResponse aclientp.schema.agent_responses Response from listing sessions.
LoadSessionRequest aclientp.schema.client_requests Request parameters for loading an existing session.
LoadSessionResponse aclientp.schema.agent_responses Response from loading an existing session.
LogoutCapabilities aclientp.schema.capabilities Logout capabilities supported by the agent.
LogoutRequest aclientp.schema.client_requests Request parameters for the logout method.
LogoutResponse aclientp.schema.agent_responses Response to the logout method.
MessageMcpNotification aclientp.schema.mcp UNSTABLE: An inner MCP notification tied to an active inner MCP request.
MessageMcpRequest aclientp.schema.mcp UNSTABLE: An inner MCP request sent to an acp MCP server via mcp/message.
MessageMcpResponse aclientp.schema.mcp UNSTABLE: Response to mcp/message: exactly one inner MCP outcome.
MultiSelectPropertySchema aclientp.schema.elicitation Schema for multi-select (array) properties in an elicitation form.
NewSessionRequest aclientp.schema.client_requests Request parameters for creating a new session.
NewSessionResponse aclientp.schema.agent_responses Response from creating a new session.
NoOpClient aclientp.client.implementations.noop_client Minimal client that returns default responses for all operations.
NumberPropertySchema aclientp.schema.elicitation Schema for number (floating-point) properties in an elicitation form.
PermissionOption aclientp.schema.tool_call An option presented to the user when requesting permission.
PlanEntry aclientp.schema.agent_plan A single entry in the execution plan.
PromptRequest aclientp.schema.client_requests Request parameters for sending a user prompt to the agent.
PromptResponse aclientp.schema.agent_responses Response from processing a user prompt.
ProtocolVersionError aclientp.exceptions The peer answered initialize with a protocol version this side does not speak.
ReadTextFileRequest aclientp.schema.agent_requests Request to read content from a text file.
ReadTextFileResponse aclientp.schema.client_responses Response containing the contents of a text file.
ReleaseTerminalRequest aclientp.schema.agent_requests Request to release a terminal and free its resources.
ReleaseTerminalResponse aclientp.schema.client_responses Response to terminal/release method.
RequestError aclientp.exceptions Raised when a JSON-RPC request fails.
RequestPermissionRequest aclientp.schema.agent_requests Request for user permission to execute a tool call.
RequestPermissionResponse aclientp.schema.client_responses Response to a permission request.
ResumeSessionRequest aclientp.schema.client_requests Request parameters for resuming an existing session.
ResumeSessionResponse aclientp.schema.agent_responses Response from resuming an existing session.
SessionMode aclientp.schema.session_state A mode the agent can operate in.
SessionModeState aclientp.schema.session_state The set of modes and the one currently active.
SessionNotification aclientp.schema.notifications Notification containing a session update from the agent.
SessionOptionsRequest aclientp.schema.client_requests UNSTABLE: Request the modes and config options a session would start with.
SessionOptionsResponse aclientp.schema.agent_responses UNSTABLE: The modes and config options a session would start with.
SessionStatusRequest aclientp.schema.client_requests UNSTABLE: Request parameters for checking whether the Agent has a session in memory.
SessionStatusResponse aclientp.schema.agent_responses UNSTABLE: Response to session/status.
SetSessionConfigOptionRequest aclientp.schema.client_requests Request parameters for setting a session configuration option.
SetSessionConfigOptionResponse aclientp.schema.agent_responses Response to session/set_config_option method.
SetSessionModeRequest aclientp.schema.client_requests Request parameters for setting a session mode.
SetSessionModeResponse aclientp.schema.agent_responses Response to session/set_mode method.
SetSessionTitleRequest aclientp.schema.client_requests UNSTABLE: Request parameters for renaming a session.
SetSessionTitleResponse aclientp.schema.agent_responses UNSTABLE: Response to session/set_title.
SseMcpServer aclientp.schema.mcp SSE transport configuration.
StdioMcpServer aclientp.schema.mcp Stdio transport configuration.
StdioTransport aclientp.transports Configuration for stdio transport.
StreamTransport aclientp.transports Configuration for custom stream transport.
StringPropertySchema aclientp.schema.elicitation Schema for string properties in an elicitation form.
SystemPrompt aclientp.schema.client_requests Client-provided system-level instructions for a session.
TerminalHandle aclientp.terminal_handle Handle for a terminal session.
TerminalOutputRequest aclientp.schema.agent_requests Request to get the current output and status of a terminal.
TerminalOutputResponse aclientp.schema.client_responses Response containing the terminal output and exit status.
TextContentBlock aclientp.schema.content_blocks Text content.
TitledMultiSelectItems aclientp.schema.elicitation Items definition for titled multi-select enum properties.
ToolCallLocation aclientp.schema.tool_call A file location being accessed or modified by a tool.
ToolCallState aclientp.tool_call_state Tracks tool call state and sends delta updates.
ToolCallUpdate aclientp.schema.tool_call Details about the tool call requiring permission.
UnarchiveSessionRequest aclientp.schema.client_requests UNSTABLE: Request parameters for unarchiving a session.
UnarchiveSessionResponse aclientp.schema.agent_responses UNSTABLE: Response to session/unarchive.
UntitledMultiSelectItems aclientp.schema.elicitation Items definition for untitled multi-select enum properties.
UserMessageChunk aclientp.schema.session_updates A chunk of the user's message being streamed.
WaitForTerminalExitRequest aclientp.schema.agent_requests Request to wait for a terminal command to exit.
WaitForTerminalExitResponse aclientp.schema.client_responses Response containing the exit status of a terminal command.
WebSocketTransport aclientp.transports Configuration for WebSocket server transport.
WebSocketTransportError aclientp.ws_transport The WebSocket connection to the ACP server could not be opened.
WriteTextFileRequest aclientp.schema.agent_requests Request to write content to a text file.
WriteTextFileResponse aclientp.schema.client_responses Response to fs/write_text_file.

🛈 DocStrings

Agent Client protocol (ACP) implementation.

AgentMethod module-attribute

AgentMethod = Literal[
    "auth/status",
    "authenticate",
    "initialize",
    "logout",
    "mcp/message",
    "providers/disable",
    "providers/list",
    "providers/set",
    "session/archive",
    "session/cancel",
    "session/close",
    "session/delete",
    "session/fork",
    "session/list",
    "session/load",
    "session/new",
    "session/options",
    "session/prompt",
    "session/resume",
    "session/set_config_option",
    "session/set_mode",
    "session/set_title",
    "session/status",
    "session/unarchive",
]

Methods handled by the agent.

AuthMethod module-attribute

AuthMethod = Annotated[
    Annotated[AuthMethodAgent, Tag("agent")] | Annotated[AuthMethodTerminal, Tag("terminal")],
    Discriminator(_auth_method_discriminator),
]

Describes an available authentication method.

The type field acts as the discriminator. When no type is present, the method is treated as agent.

ClientMethod module-attribute

ClientMethod = Literal[
    "auth/status_update",
    "elicitation/complete",
    "elicitation/create",
    "fs/read_text_file",
    "fs/write_text_file",
    "mcp/message",
    "session/request_permission",
    "session/update",
    "terminal/create",
    "terminal/kill",
    "terminal/output",
    "terminal/release",
    "terminal/wait_for_exit",
]

Methods handled by the client.

ElicitationContentValue module-attribute

ElicitationContentValue = str | int | float | bool | Sequence[str]

Possible value types in elicitation content.

ElicitationPropertySchema module-attribute

ElicitationPropertySchema = Annotated[
    Annotated[StringPropertySchema, Tag("string")]
    | Annotated[NumberPropertySchema, Tag("number")]
    | Annotated[IntegerPropertySchema, Tag("integer")]
    | Annotated[BooleanPropertySchema, Tag("boolean")]
    | Annotated[MultiSelectPropertySchema, Tag("array")],
    Discriminator(_property_schema_discriminator),
]

Property schema for elicitation form fields.

Each variant corresponds to a JSON Schema "type" value.

MultiSelectItems module-attribute

MultiSelectItems = Annotated[
    Annotated[UntitledMultiSelectItems, Tag("untitled")]
    | Annotated[TitledMultiSelectItems, Tag("titled")],
    Discriminator(_multi_select_items_discriminator),
]

Items for a multi-select (array) property schema.

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")

AgentAuthCapabilities

Bases: AnnotatedObject

Authentication-related capabilities supported by the agent.

Source code in src/aclientp/schema/capabilities.py
class AgentAuthCapabilities(AnnotatedObject):
    """Authentication-related capabilities supported by the agent."""

    logout: LogoutCapabilities | None = None
    """Whether the agent supports the logout method."""

    status: AuthStatusCapabilities | None = None
    """**UNSTABLE**: Whether the agent supports ``auth/status``."""

logout class-attribute instance-attribute

logout: LogoutCapabilities | None = None

Whether the agent supports the logout method.

status class-attribute instance-attribute

status: AuthStatusCapabilities | None = None

UNSTABLE: Whether the agent supports auth/status.

AgentMessageChunk

Bases: BaseChunk

A chunk of the agent's response being streamed.

Source code in src/aclientp/schema/session_updates.py
class AgentMessageChunk(BaseChunk):
    """A chunk of the agent's response being streamed."""

    session_update: Literal["agent_message_chunk"] = Field(
        default="agent_message_chunk", init=False
    )
    """Agent message chunk."""

session_update class-attribute instance-attribute

session_update: Literal['agent_message_chunk'] = Field(default='agent_message_chunk', init=False)

Agent message chunk.

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)

AllowedOutcome

Bases: AnnotatedObject

The user selected one of the provided options.

Source code in src/aclientp/schema/tool_call.py
class AllowedOutcome(AnnotatedObject):
    """The user selected one of the provided options."""

    option_id: str
    """The ID of the option the user selected."""

    outcome: Literal["selected"] = Field(default="selected", init=False)

option_id instance-attribute

option_id: str

The ID of the option the user selected.

Annotations

Bases: AnnotatedObject

Optional annotations for the client.

The client can use annotations to inform how objects are used or displayed.

Source code in src/aclientp/schema/content_blocks.py
class Annotations(AnnotatedObject):
    """Optional annotations for the client.

    The client can use annotations to inform how objects are used or displayed.
    """

    audience: Audience | None = None
    """Audience for the annotated resource."""

    last_modified: str | None = None
    """Last modified timestamp of the annotated resource."""

    priority: float | None = None
    """Priority of the annotated resource."""

    @classmethod
    def optionally_create(
        cls,
        audience: Audience | None = None,
        last_modified: datetime | str | None = None,
        priority: float | None = None,
    ) -> Self | None:
        """Create an annotations object if any value is given, otherwise return None."""
        if audience is None and last_modified is None and priority is None:
            return None
        if isinstance(last_modified, datetime):
            last_modified = last_modified.strftime("%Y-%m-%dT%H:%M:%SZ")
        return cls(audience=audience, last_modified=last_modified, priority=priority)

audience class-attribute instance-attribute

audience: Audience | None = None

Audience for the annotated resource.

last_modified class-attribute instance-attribute

last_modified: str | None = None

Last modified timestamp of the annotated resource.

priority class-attribute instance-attribute

priority: float | None = None

Priority of the annotated resource.

optionally_create classmethod

optionally_create(
    audience: Audience | None = None,
    last_modified: datetime | str | None = None,
    priority: float | None = None,
) -> Self | None

Create an annotations object if any value is given, otherwise return None.

Source code in src/aclientp/schema/content_blocks.py
@classmethod
def optionally_create(
    cls,
    audience: Audience | None = None,
    last_modified: datetime | str | None = None,
    priority: float | None = None,
) -> Self | None:
    """Create an annotations object if any value is given, otherwise return None."""
    if audience is None and last_modified is None and priority is None:
        return None
    if isinstance(last_modified, datetime):
        last_modified = last_modified.strftime("%Y-%m-%dT%H:%M:%SZ")
    return cls(audience=audience, last_modified=last_modified, priority=priority)

ArchiveSessionRequest

Bases: Request

UNSTABLE: Request parameters for archiving a session.

Only available if the Agent supports the session.archive capability.

Source code in src/aclientp/schema/client_requests.py
class ArchiveSessionRequest(Request):
    """**UNSTABLE**: Request parameters for archiving a session.

    Only available if the Agent supports the ``session.archive`` capability.
    """

    session_id: str
    """The ID of the session to archive."""

session_id instance-attribute

session_id: str

The ID of the session to archive.

ArchiveSessionResponse

Bases: Response

UNSTABLE: Response to session/archive.

Source code in src/aclientp/schema/agent_responses.py
class ArchiveSessionResponse(Response):
    """**UNSTABLE**: Response to ``session/archive``."""

AuthCapabilities

Bases: AnnotatedObject

Authentication capabilities supported by the client.

Advertised during initialization to inform the agent which authentication method types the client can handle.

Source code in src/aclientp/schema/capabilities.py
class AuthCapabilities(AnnotatedObject):
    """Authentication capabilities supported by the client.

    Advertised during initialization to inform the agent which authentication
    method types the client can handle.
    """

    terminal: bool = False
    """Whether the client supports ``terminal`` authentication methods."""

terminal class-attribute instance-attribute

terminal: bool = False

Whether the client supports terminal authentication methods.

AuthMethodAgent

Bases: AnnotatedObject

Agent handles authentication itself.

This is the default authentication method type. When no type field is present, the method is treated as agent.

Source code in src/aclientp/schema/common.py
class AuthMethodAgent(AnnotatedObject):
    """Agent handles authentication itself.

    This is the default authentication method type.
    When no ``type`` field is present, the method is treated as ``agent``.
    """

    type: Literal["agent"] = Field(default="agent", exclude=True)
    """Discriminator field.  Defaults to ``"agent"`` and is excluded from serialization
    for backward compatibility."""

    id: str
    """Unique identifier for this authentication method."""

    name: str
    """Human-readable name of the authentication method."""

    description: str | None = None
    """Optional description providing more details about this authentication method."""

description class-attribute instance-attribute

description: str | None = None

Optional description providing more details about this authentication method.

id instance-attribute

id: str

Unique identifier for this authentication method.

name instance-attribute

name: str

Human-readable name of the authentication method.

type class-attribute instance-attribute

type: Literal['agent'] = Field(default='agent', exclude=True)

Discriminator field. Defaults to "agent" and is excluded from serialization for backward compatibility.

AuthMethodTerminal

Bases: AnnotatedObject

Terminal authentication method.

Client runs the configured agent program as a separate interactive process for the user to authenticate.

Source code in src/aclientp/schema/common.py
class AuthMethodTerminal(AnnotatedObject):
    """Terminal authentication method.

    Client runs the configured agent program as a separate interactive process
    for the user to authenticate.
    """

    type: Literal["terminal"] = "terminal"
    """Discriminator field."""

    id: str
    """Unique identifier for this authentication method."""

    name: str
    """Human-readable name of the authentication method."""

    description: str | None = None
    """Optional description providing more details about this authentication method."""

    args: Sequence[str] = ()
    """Additional arguments to pass when running the agent binary for terminal auth."""

    env: dict[str, str] = Field(default_factory=dict)
    """Additional environment variables to set when running the agent binary for terminal auth."""

args class-attribute instance-attribute

args: Sequence[str] = ()

Additional arguments to pass when running the agent binary for terminal auth.

description class-attribute instance-attribute

description: str | None = None

Optional description providing more details about this authentication method.

env class-attribute instance-attribute

env: dict[str, str] = Field(default_factory=dict)

Additional environment variables to set when running the agent binary for terminal auth.

id instance-attribute

id: str

Unique identifier for this authentication method.

name instance-attribute

name: str

Human-readable name of the authentication method.

type class-attribute instance-attribute

type: Literal['terminal'] = 'terminal'

Discriminator field.

AuthStatusRequest

Bases: Request

UNSTABLE: Request the agent's current authentication state.

Only available if the Agent supports the auth.status capability.

Source code in src/aclientp/schema/client_requests.py
class AuthStatusRequest(Request):
    """**UNSTABLE**: Request the agent's current authentication state.

    Only available if the Agent supports the ``auth.status`` capability.
    """

AuthStatusResponse

Bases: Response

UNSTABLE: Response to auth/status.

Source code in src/aclientp/schema/agent_responses.py
class AuthStatusResponse(Response):
    """**UNSTABLE**: Response to ``auth/status``."""

    state: AuthState
    """Whether the agent can start sessions without the user signing in first."""

    accounts: Sequence[AuthAccount] = Field(default_factory=list)
    """The accounts the agent has configured, for display."""

accounts class-attribute instance-attribute

accounts: Sequence[AuthAccount] = Field(default_factory=list)

The accounts the agent has configured, for display.

state instance-attribute

state: AuthState

Whether the agent can start sessions without the user signing in first.

AuthStatusUpdateNotification

Bases: AnnotatedObject

UNSTABLE: The agent's authentication state changed (auth/status_update).

Source code in src/aclientp/schema/notifications.py
class AuthStatusUpdateNotification(AnnotatedObject):
    """**UNSTABLE**: The agent's authentication state changed (``auth/status_update``)."""

    state: AuthState
    """Whether the agent can start sessions without the user signing in first."""

    accounts: Sequence[AuthAccount] = Field(default_factory=list)
    """The accounts the agent has configured, for display."""

accounts class-attribute instance-attribute

accounts: Sequence[AuthAccount] = Field(default_factory=list)

The accounts the agent has configured, for display.

state instance-attribute

state: AuthState

Whether the agent can start sessions without the user signing in first.

AuthenticateRequest

Bases: Request

Request parameters for the authenticate method.

Specifies which authentication method to use.

Source code in src/aclientp/schema/client_requests.py
class AuthenticateRequest(Request):
    """Request parameters for the authenticate method.

    Specifies which authentication method to use.
    """

    method_id: str
    """The ID of the authentication method to use.

    Must be one of the methods advertised in the initialize response.
    """

method_id instance-attribute

method_id: str

The ID of the authentication method to use.

Must be one of the methods advertised in the initialize response.

AuthenticateResponse

Bases: Response

Response to authenticate method.

Source code in src/aclientp/schema/agent_responses.py
class AuthenticateResponse(Response):
    """Response to authenticate method."""

AvailableCommand

Bases: AnnotatedObject

Information about a command.

Source code in src/aclientp/schema/slash_commands.py
class AvailableCommand(AnnotatedObject):
    """Information about a command."""

    description: str
    """Human-readable description of what the command does."""

    input: AvailableCommandInput | None = None
    """Input for the command if required."""

    name: str
    """Command name (e.g., `create_plan`, `research_codebase`)."""

    @classmethod
    def create(cls, name: str, description: str, input_hint: str | None = None) -> Self:
        """Create a new Command.

        Args:
            name: Name of the command.
            description: Description of the command.
            input_hint: Hint for the input.

        Returns:
            A new available command.
        """
        spec = AvailableCommandInput(root=CommandInputHint(hint=input_hint)) if input_hint else None
        return cls(name=name, description=description, input=spec)

description instance-attribute

description: str

Human-readable description of what the command does.

input class-attribute instance-attribute

input: AvailableCommandInput | None = None

Input for the command if required.

name instance-attribute

name: str

Command name (e.g., create_plan, research_codebase).

create classmethod

create(name: str, description: str, input_hint: str | None = None) -> Self

Create a new Command.

Parameters:

Name Type Description Default
name str

Name of the command.

required
description str

Description of the command.

required
input_hint str | None

Hint for the input.

None

Returns:

Type Description
Self

A new available command.

Source code in src/aclientp/schema/slash_commands.py
@classmethod
def create(cls, name: str, description: str, input_hint: str | None = None) -> Self:
    """Create a new Command.

    Args:
        name: Name of the command.
        description: Description of the command.
        input_hint: Hint for the input.

    Returns:
        A new available command.
    """
    spec = AvailableCommandInput(root=CommandInputHint(hint=input_hint)) if input_hint else None
    return cls(name=name, description=description, input=spec)

BooleanPropertySchema

Bases: AnnotatedObject

Schema for boolean properties in an elicitation form.

Source code in src/aclientp/schema/elicitation.py
class BooleanPropertySchema(AnnotatedObject):
    """Schema for boolean properties in an elicitation form."""

    type: Literal["boolean"] = "boolean"
    """Type discriminator."""

    title: str | None = None
    """Optional title for the property."""

    description: str | None = None
    """Human-readable description."""

    default: bool | None = None
    """Default value."""

default class-attribute instance-attribute

default: bool | None = None

Default value.

description class-attribute instance-attribute

description: str | None = None

Human-readable description.

title class-attribute instance-attribute

title: str | None = None

Optional title for the property.

type class-attribute instance-attribute

type: Literal['boolean'] = 'boolean'

Type discriminator.

CancelNotification

Bases: AnnotatedObject

Notification to cancel ongoing operations for a session.

This is a notification sent by the client to cancel an ongoing prompt turn.

Upon receiving this notification, the Agent SHOULD: - Stop all language model requests as soon as possible - Abort all tool call invocations in progress - Send any pending session/update notifications - Respond to the original session/prompt request with StopReason::Cancelled

See protocol docs: Cancellation

Source code in src/aclientp/schema/notifications.py
class CancelNotification(AnnotatedObject):
    """Notification to cancel ongoing operations for a session.

    This is a notification sent by the client to cancel an ongoing prompt turn.

    Upon receiving this notification, the Agent SHOULD:
    - Stop all language model requests as soon as possible
    - Abort all tool call invocations in progress
    - Send any pending `session/update` notifications
    - Respond to the original `session/prompt` request with `StopReason::Cancelled`

    See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)
    """

    session_id: str
    """The ID of the session to cancel operations for."""

session_id instance-attribute

session_id: str

The ID of the session to cancel operations for.

CancelRequestNotification

Bases: AnnotatedObject

Notification to cancel an ongoing request ($/cancel_request).

Either side may send it for a request it issued. The receiver should stop the work and may reply with a -32800 (request cancelled) error or a normal response. Unknown or already answered request IDs are ignored.

Source code in src/aclientp/schema/notifications.py
class CancelRequestNotification(AnnotatedObject):
    """Notification to cancel an ongoing request (``$/cancel_request``).

    Either side may send it for a request it issued. The receiver should stop
    the work and may reply with a ``-32800`` (request cancelled) error or a normal
    response. Unknown or already answered request IDs are ignored.
    """

    request_id: int | str | None
    """The ID of the request to cancel."""

request_id instance-attribute

request_id: int | str | None

The ID of the request to cancel.

Client

Bases: Protocol

Base client interface for ACP.

Methods with a default body are optional and gated by a capability the client advertises (or by an acp MCP server the client declared).

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

    Methods with a default body are optional and gated by a capability the client
    advertises (or by an ``acp`` MCP server the client declared).
    """

    async def request_permission(
        self, params: RequestPermissionRequest
    ) -> RequestPermissionResponse: ...

    async def session_update(self, params: SessionNotification) -> None: ...

    async def write_text_file(
        self, params: WriteTextFileRequest
    ) -> WriteTextFileResponse | None: ...

    async def read_text_file(self, params: ReadTextFileRequest) -> ReadTextFileResponse: ...

    async def create_terminal(self, params: CreateTerminalRequest) -> CreateTerminalResponse: ...

    async def terminal_output(self, params: TerminalOutputRequest) -> TerminalOutputResponse: ...

    async def release_terminal(
        self, params: ReleaseTerminalRequest
    ) -> ReleaseTerminalResponse | None: ...

    async def wait_for_terminal_exit(
        self, params: WaitForTerminalExitRequest
    ) -> WaitForTerminalExitResponse: ...

    async def kill_terminal(self, params: KillTerminalRequest) -> KillTerminalResponse | None: ...

    async def elicitation(self, params: ElicitationRequest) -> ElicitationResponse: ...

    async def elicitation_complete(self, params: ElicitationCompleteNotification) -> 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 auth_status_update(self, params: AuthStatusUpdateNotification) -> None:
        """**UNSTABLE**: The agent's authentication state changed."""
        return

    async def mcp_message(self, params: MessageMcpRequest) -> MessageMcpResponse:
        """**UNSTABLE**: Inner MCP request to an ``acp`` MCP server the client 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 client declared."""
        return

auth_status_update async

auth_status_update(params: AuthStatusUpdateNotification) -> None

UNSTABLE: The agent's authentication state changed.

Source code in src/aclientp/client/protocol.py
async def auth_status_update(self, params: AuthStatusUpdateNotification) -> None:
    """**UNSTABLE**: The agent's authentication state changed."""
    return

mcp_message async

mcp_message(params: MessageMcpRequest) -> MessageMcpResponse

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

Source code in src/aclientp/client/protocol.py
async def mcp_message(self, params: MessageMcpRequest) -> MessageMcpResponse:
    """**UNSTABLE**: Inner MCP request to an ``acp`` MCP server the client 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 client declared.

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

ClientCapabilities

Bases: AnnotatedObject

Capabilities supported by the client.

Advertised during initialization to inform the agent about available features and methods.

See protocol docs: Client Capabilities

Source code in src/aclientp/schema/capabilities.py
class ClientCapabilities(AnnotatedObject):
    """Capabilities supported by the client.

    Advertised during initialization to inform the agent about
    available features and methods.

    See protocol docs: [Client Capabilities](https://agentclientprotocol.com/protocol/initialization#client-capabilities)
    """

    auth: AuthCapabilities | None = Field(default_factory=AuthCapabilities)
    """Authentication capabilities supported by the client."""

    elicitation: ElicitationCapabilities | None = None
    """Elicitation capabilities supported by the client.

    Determines which elicitation modes the agent may use.
    """

    session: ClientSessionCapabilities | None = None
    """Session-related capabilities supported by the client."""

    subagents: SubagentCapabilities | None = None
    """**UNSTABLE**: Client support for ``subagent_update`` session updates."""

    plan: PlanCapabilities | None = None
    """**UNSTABLE**: Client support for ID-addressed plan updates."""

    fs: FileSystemCapabilities | None = Field(default_factory=FileSystemCapabilities)
    """File system capabilities supported by the client.

    Determines which file operations the agent can request.
    """

    terminal: bool | None = False
    """Whether the Client support all `terminal/*` methods."""

    @classmethod
    def create(
        cls,
        read_text_file: bool | None = False,
        write_text_file: bool | None = False,
        terminal: bool | None = False,
        auth: AuthCapabilities | None = None,
    ) -> Self:
        """Create a new instance of ClientCapabilities.

        Args:
            read_text_file: Whether the Client supports `fs/read_text_file` requests.
            write_text_file: Whether the Client supports `fs/write_text_file` requests.
            terminal: Whether the Client supports all `terminal/*` methods.
            auth: Authentication capabilities supported by the client.

        Returns:
            A new instance of ClientCapabilities.
        """
        fs = FileSystemCapabilities(read_text_file=read_text_file, write_text_file=write_text_file)
        return cls(fs=fs, terminal=terminal, auth=auth)

auth class-attribute instance-attribute

auth: AuthCapabilities | None = Field(default_factory=AuthCapabilities)

Authentication capabilities supported by the client.

elicitation class-attribute instance-attribute

elicitation: ElicitationCapabilities | None = None

Elicitation capabilities supported by the client.

Determines which elicitation modes the agent may use.

fs class-attribute instance-attribute

fs: FileSystemCapabilities | None = Field(default_factory=FileSystemCapabilities)

File system capabilities supported by the client.

Determines which file operations the agent can request.

plan class-attribute instance-attribute

plan: PlanCapabilities | None = None

UNSTABLE: Client support for ID-addressed plan updates.

session class-attribute instance-attribute

session: ClientSessionCapabilities | None = None

Session-related capabilities supported by the client.

subagents class-attribute instance-attribute

subagents: SubagentCapabilities | None = None

UNSTABLE: Client support for subagent_update session updates.

terminal class-attribute instance-attribute

terminal: bool | None = False

Whether the Client support all terminal/* methods.

create classmethod

create(
    read_text_file: bool | None = False,
    write_text_file: bool | None = False,
    terminal: bool | None = False,
    auth: AuthCapabilities | None = None,
) -> Self

Create a new instance of ClientCapabilities.

Parameters:

Name Type Description Default
read_text_file bool | None

Whether the Client supports fs/read_text_file requests.

False
write_text_file bool | None

Whether the Client supports fs/write_text_file requests.

False
terminal bool | None

Whether the Client supports all terminal/* methods.

False
auth AuthCapabilities | None

Authentication capabilities supported by the client.

None

Returns:

Type Description
Self

A new instance of ClientCapabilities.

Source code in src/aclientp/schema/capabilities.py
@classmethod
def create(
    cls,
    read_text_file: bool | None = False,
    write_text_file: bool | None = False,
    terminal: bool | None = False,
    auth: AuthCapabilities | None = None,
) -> Self:
    """Create a new instance of ClientCapabilities.

    Args:
        read_text_file: Whether the Client supports `fs/read_text_file` requests.
        write_text_file: Whether the Client supports `fs/write_text_file` requests.
        terminal: Whether the Client supports all `terminal/*` methods.
        auth: Authentication capabilities supported by the client.

    Returns:
        A new instance of ClientCapabilities.
    """
    fs = FileSystemCapabilities(read_text_file=read_text_file, write_text_file=write_text_file)
    return cls(fs=fs, terminal=terminal, auth=auth)

ClientSideConnection

Bases: Agent

Client-side connection.

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

Parameters:

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

factory that receives this connection and returns your Client

required
input

ByteSendStream (local -> peer)

required
output

ByteReceiveStream (peer -> local)

required
Source code in src/aclientp/client/connection.py
class ClientSideConnection(Agent):
    """Client-side connection.

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

    Args:
      to_client: factory that receives this connection and returns your Client
      input: ByteSendStream (local -> peer)
      output: ByteReceiveStream (peer -> local)
    """

    def __init__(
        self,
        to_client: Callable[[Agent], Client] | Client,
        input_stream: ByteSendStream,
        output_stream: ByteReceiveStream,
        observers: list[StreamObserver] | None = None,
    ) -> None:
        # Build client first so handler can delegate
        client = to_client if isinstance(to_client, Client) else to_client(self)
        handler = partial(_handle_client_method, client)
        self._conn = Connection(handler, input_stream, output_stream, observers=observers)

    async def _request[T: BaseModel](
        self, method: str, params: BaseModel, response_type: type[T]
    ) -> T:
        dct = params.model_dump(mode="json", by_alias=True, exclude_none=True)
        resp = await self._conn.request_object(method, dct)
        return response_type.model_validate(resp)

    # agent-bound methods (client -> agent)
    async def initialize(self, params: InitializeRequest) -> InitializeResponse:
        dct = params.model_dump(
            mode="json", by_alias=True, exclude_none=True, exclude_defaults=True
        )
        resp = await self._conn.request_object("initialize", dct)
        return InitializeResponse.model_validate(resp)

    async def new_session(self, params: NewSessionRequest) -> NewSessionResponse:
        # Don't exclude_defaults - MCP server 'type' field is required for discriminated unions
        dct = params.model_dump(mode="json", by_alias=True, exclude_none=True)
        resp = await self._conn.request_object("session/new", dct)
        return NewSessionResponse.model_validate(resp)

    async def load_session(self, params: LoadSessionRequest) -> LoadSessionResponse:
        dct = params.model_dump(
            mode="json", by_alias=True, exclude_none=True, exclude_defaults=True
        )
        resp = await self._conn.request_object("session/load", dct)
        return LoadSessionResponse.model_validate(resp)

    async def list_sessions(self, params: ListSessionsRequest) -> ListSessionsResponse:
        dct = params.model_dump(
            mode="json", by_alias=True, exclude_none=True, exclude_defaults=True
        )
        resp = await self._conn.request_object("session/list", dct)
        return ListSessionsResponse.model_validate(resp)

    async def fork_session(self, params: ForkSessionRequest) -> ForkSessionResponse:
        dct = params.model_dump(
            mode="json", by_alias=True, exclude_none=True, exclude_defaults=True
        )
        resp = await self._conn.request_object("session/fork", dct)
        return ForkSessionResponse.model_validate(resp)

    async def resume_session(self, params: ResumeSessionRequest) -> ResumeSessionResponse:
        dct = params.model_dump(
            mode="json", by_alias=True, exclude_none=True, exclude_defaults=True
        )
        resp = await self._conn.request_object("session/resume", dct)
        return ResumeSessionResponse.model_validate(resp)

    async def close_session(self, params: CloseSessionRequest) -> CloseSessionResponse:
        dct = params.model_dump(
            mode="json", by_alias=True, exclude_none=True, exclude_defaults=True
        )
        resp = await self._conn.request_object("session/close", dct)
        return CloseSessionResponse.model_validate(resp)

    async def set_session_mode(self, params: SetSessionModeRequest) -> SetSessionModeResponse:
        dct = params.model_dump(
            mode="json", by_alias=True, exclude_none=True, exclude_defaults=True
        )
        resp = await self._conn.request_object("session/set_mode", dct)
        return SetSessionModeResponse.model_validate(resp)

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

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

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

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

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

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

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

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

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

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

    async def mcp_message(self, params: MessageMcpRequest) -> MessageMcpResponse:
        return await self._request("mcp/message", params, MessageMcpResponse)

    async def mcp_notification(self, params: MessageMcpNotification) -> None:
        dct = params.model_dump(mode="json", by_alias=True, exclude_none=True)
        await self._conn.send_notification("mcp/message", dct)

    async def set_session_config_option(
        self, params: SetSessionConfigOptionRequest
    ) -> SetSessionConfigOptionResponse:
        dct = params.model_dump(
            mode="json", by_alias=True, exclude_none=True, exclude_defaults=True
        )
        resp = await self._conn.request_object("session/set_config_option", dct)
        return SetSessionConfigOptionResponse.model_validate(resp)

    async def authenticate(self, params: AuthenticateRequest) -> AuthenticateResponse:
        dct = params.model_dump(
            mode="json", by_alias=True, exclude_none=True, exclude_defaults=True
        )
        resp = await self._conn.request_object("authenticate", dct)
        return AuthenticateResponse.model_validate(resp)

    async def logout(self, params: LogoutRequest) -> LogoutResponse:
        dct = params.model_dump(
            mode="json", by_alias=True, exclude_none=True, exclude_defaults=True
        )
        resp = await self._conn.request_object("logout", dct)
        return LogoutResponse.model_validate(resp)

    async def prompt(self, params: PromptRequest) -> PromptResponse:
        # Don't exclude_defaults here - the 'type' field in content blocks has a default
        # value but is required for discriminated unions to work
        dct = params.model_dump(mode="json", by_alias=True, exclude_none=True)
        # The turn's updates, sent before the response, are handled when this returns
        resp = await self._conn.request_object("session/prompt", dct)
        return PromptResponse.model_validate(resp)

    async def cancel(self, params: CancelNotification) -> None:
        dct = params.model_dump(
            mode="json", by_alias=True, exclude_none=True, exclude_defaults=True
        )
        await self._conn.send_notification("session/cancel", dct)

    async def ext_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
        return await self._conn.request_object(f"_{method}", params)

    async def ext_notification(self, method: str, params: dict[str, Any]) -> None:
        await self._conn.send_notification(f"_{method}", params)

    async def close(self) -> None:
        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()

    async def __aenter__(self) -> Self:
        return self

    async def __aexit__(self, *args: object) -> None:
        await self.close()

wait_closed async

wait_closed() -> None

Wait until the agent disconnected or the connection was closed.

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

CloseSessionRequest

Bases: Request

Request parameters for closing an active session.

The agent must cancel any ongoing work related to the session (treat it as if session/cancel was called) and then free up any resources associated with the session.

Only available if the Agent supports the session.close capability.

Source code in src/aclientp/schema/client_requests.py
class CloseSessionRequest(Request):
    """Request parameters for closing an active session.

    The agent **must** cancel any ongoing work related to the session
    (treat it as if ``session/cancel`` was called) and then free up any resources
    associated with the session.

    Only available if the Agent supports the ``session.close`` capability.
    """

    session_id: str
    """The ID of the session to close."""

session_id instance-attribute

session_id: str

The ID of the session to close.

CloseSessionResponse

Bases: Response

Response from closing a session.

Source code in src/aclientp/schema/agent_responses.py
class CloseSessionResponse(Response):
    """Response from closing a session."""

CreateTerminalRequest

Bases: BaseAgentRequest

Request to create a new terminal and execute a command.

Source code in src/aclientp/schema/agent_requests.py
class CreateTerminalRequest(BaseAgentRequest):
    """Request to create a new terminal and execute a command."""

    args: Sequence[str] | None = None
    """Array of command arguments."""

    command: str
    """The command to execute."""

    cwd: str | None = None
    """Working directory for the command (absolute path)."""

    env: Sequence[EnvVariable] | None = None
    """Environment variables for the command."""

    output_byte_limit: int | None = Field(default=None, ge=0)
    """Maximum number of output bytes to retain.

    When the limit is exceeded, the Client truncates from the beginning of the output
    to stay within the limit.

    The Client MUST ensure truncation happens at a character boundary to maintain valid
    string output, even if this means the retained output is slightly less than the
    specified limit."""

args class-attribute instance-attribute

args: Sequence[str] | None = None

Array of command arguments.

command instance-attribute

command: str

The command to execute.

cwd class-attribute instance-attribute

cwd: str | None = None

Working directory for the command (absolute path).

env class-attribute instance-attribute

env: Sequence[EnvVariable] | None = None

Environment variables for the command.

output_byte_limit class-attribute instance-attribute

output_byte_limit: int | None = Field(default=None, ge=0)

Maximum number of output bytes to retain.

When the limit is exceeded, the Client truncates from the beginning of the output to stay within the limit.

The Client MUST ensure truncation happens at a character boundary to maintain valid string output, even if this means the retained output is slightly less than the specified limit.

CreateTerminalResponse

Bases: Response

Response containing the ID of the created terminal.

Source code in src/aclientp/schema/client_responses.py
class CreateTerminalResponse(Response):
    """Response containing the ID of the created terminal."""

    terminal_id: str
    """The unique identifier for the created terminal."""

terminal_id instance-attribute

terminal_id: str

The unique identifier for the created terminal.

DefaultACPClient

Bases: Client

Default implementation of ACP Client interface for basic operations.

This provides a basic client implementation that can be used for testing or as a base for more sophisticated client implementations.

Source code in src/aclientp/client/implementations/default_client.py
class DefaultACPClient(Client):
    """Default implementation of ACP Client interface for basic operations.

    This provides a basic client implementation that can be used for testing
    or as a base for more sophisticated client implementations.
    """

    def __init__(
        self,
        *,
        allow_file_operations: bool = False,
        permission_outcomes: list[dict[str, DeniedOutcome | AllowedOutcome]] | None = None,
        use_real_files: bool = True,
    ) -> None:
        """Initialize default ACP client.

        Args:
            allow_file_operations: Whether to allow file read/write operations
            permission_outcomes: Queue of permission outcomes for testing
            use_real_files: Whether to use real filesystem or in-memory storage
        """
        self.allow_file_operations = allow_file_operations
        self.use_real_files = use_real_files
        self.permission_outcomes = permission_outcomes or []
        self.files: dict[str, str] = {}  # In-memory file storage for testing
        self.ext_calls: list[tuple[str, dict[str, Any]]] = []
        self.ext_notes: list[tuple[str, dict[str, Any]]] = []
        self.notifications: list[SessionNotification] = []

    async def request_permission(
        self, params: RequestPermissionRequest
    ) -> RequestPermissionResponse:
        """Default permission handler - grants all permissions or uses test queue."""
        title = params.tool_call.title or "operation"
        logger.info("Permission requested", title=title)

        # If we have test outcomes queued, use them
        if self.permission_outcomes:
            outcome = self.permission_outcomes.pop(0)
            return RequestPermissionResponse.model_validate({"outcome": outcome})

        # Default: grant permission for the first option
        if params.options:
            id_ = params.options[0].option_id
            return RequestPermissionResponse.allowed(id_)

        # No options - deny
        return RequestPermissionResponse.denied()

    async def session_update(self, params: SessionNotification) -> None:
        """Handle session update notifications."""
        msg = "Session update for %s: %s"
        logger.debug(msg, params.session_id, params.update.session_update)
        self.notifications.append(params)

    async def write_text_file(self, params: WriteTextFileRequest) -> WriteTextFileResponse:
        """Write text to file (if allowed)."""
        if not self.allow_file_operations:
            raise RuntimeError("File operations not allowed")

        if self.use_real_files:
            try:
                path = Path(params.path)
                path.write_text(params.content, encoding="utf-8")
                logger.info("Wrote file", path=params.path)
            except Exception:
                logger.exception("Failed to write file", path=params.path)
                raise
        else:
            # In-memory storage for testing
            self.files[str(params.path)] = params.content

        return WriteTextFileResponse()

    async def read_text_file(self, params: ReadTextFileRequest) -> ReadTextFileResponse:
        """Read text from file (if allowed)."""
        if not self.allow_file_operations:
            raise RuntimeError("File operations not allowed")

        if self.use_real_files:
            try:
                path = Path(params.path)

                if not path.exists():
                    raise FileNotFoundError(f"File not found: {params.path}")  # noqa: TRY301

                content = path.read_text(encoding="utf-8")

                # Apply line filtering if requested
                if params.line is not None or params.limit is not None:
                    lines = content.splitlines()
                    start_line = (params.line - 1) if params.line else 0
                    end_line = start_line + params.limit if params.limit else len(lines)
                    content = "\n".join(lines[start_line:end_line])

                logger.info("Read file", path=params.path)
                return ReadTextFileResponse(content=content)

            except Exception:
                logger.exception("Failed to read file", path=params.path)
                raise
        else:
            # In-memory storage for testing
            content = self.files.get(str(params.path), "default content")
            return ReadTextFileResponse(content=content)

    async def create_terminal(self, params: CreateTerminalRequest) -> CreateTerminalResponse:
        """Create terminal (not implemented)."""
        raise NotImplementedError("Terminal operations not implemented")

    async def terminal_output(self, params: TerminalOutputRequest) -> TerminalOutputResponse:
        """Get terminal output (not implemented)."""
        raise NotImplementedError("Terminal operations not implemented")

    async def release_terminal(
        self, params: ReleaseTerminalRequest
    ) -> ReleaseTerminalResponse | None:
        """Release terminal (not implemented)."""
        raise NotImplementedError("Terminal operations not implemented")

    async def wait_for_terminal_exit(
        self, params: WaitForTerminalExitRequest
    ) -> WaitForTerminalExitResponse:
        """Wait for terminal exit (not implemented)."""
        raise NotImplementedError("Terminal operations not implemented")

    async def kill_terminal(self, params: KillTerminalRequest) -> KillTerminalResponse | None:
        """Kill terminal (not implemented)."""
        raise NotImplementedError("Terminal operations not implemented")

    def get_session_updates(self) -> list[SessionNotification]:
        """Get all received session updates."""
        return self.notifications.copy()

    def clear_session_updates(self) -> None:
        """Clear all stored session updates."""
        self.notifications.clear()

    async def ext_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
        self.ext_calls.append((method, params))
        return {"ok": True, "method": method}

    async def elicitation(self, params: ElicitationRequest) -> ElicitationResponse:
        """Decline elicitation by default."""
        from aclientp.schema.elicitation import ElicitationResponse

        return ElicitationResponse.decline()

    async def elicitation_complete(self, params: ElicitationCompleteNotification) -> None:
        """Ignore elicitation complete notifications."""

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

__init__

__init__(
    *,
    allow_file_operations: bool = False,
    permission_outcomes: list[dict[str, DeniedOutcome | AllowedOutcome]] | None = None,
    use_real_files: bool = True,
) -> None

Initialize default ACP client.

Parameters:

Name Type Description Default
allow_file_operations bool

Whether to allow file read/write operations

False
permission_outcomes list[dict[str, DeniedOutcome | AllowedOutcome]] | None

Queue of permission outcomes for testing

None
use_real_files bool

Whether to use real filesystem or in-memory storage

True
Source code in src/aclientp/client/implementations/default_client.py
def __init__(
    self,
    *,
    allow_file_operations: bool = False,
    permission_outcomes: list[dict[str, DeniedOutcome | AllowedOutcome]] | None = None,
    use_real_files: bool = True,
) -> None:
    """Initialize default ACP client.

    Args:
        allow_file_operations: Whether to allow file read/write operations
        permission_outcomes: Queue of permission outcomes for testing
        use_real_files: Whether to use real filesystem or in-memory storage
    """
    self.allow_file_operations = allow_file_operations
    self.use_real_files = use_real_files
    self.permission_outcomes = permission_outcomes or []
    self.files: dict[str, str] = {}  # In-memory file storage for testing
    self.ext_calls: list[tuple[str, dict[str, Any]]] = []
    self.ext_notes: list[tuple[str, dict[str, Any]]] = []
    self.notifications: list[SessionNotification] = []

clear_session_updates

clear_session_updates() -> None

Clear all stored session updates.

Source code in src/aclientp/client/implementations/default_client.py
def clear_session_updates(self) -> None:
    """Clear all stored session updates."""
    self.notifications.clear()

create_terminal async

create_terminal(params: CreateTerminalRequest) -> CreateTerminalResponse

Create terminal (not implemented).

Source code in src/aclientp/client/implementations/default_client.py
async def create_terminal(self, params: CreateTerminalRequest) -> CreateTerminalResponse:
    """Create terminal (not implemented)."""
    raise NotImplementedError("Terminal operations not implemented")

elicitation async

elicitation(params: ElicitationRequest) -> ElicitationResponse

Decline elicitation by default.

Source code in src/aclientp/client/implementations/default_client.py
async def elicitation(self, params: ElicitationRequest) -> ElicitationResponse:
    """Decline elicitation by default."""
    from aclientp.schema.elicitation import ElicitationResponse

    return ElicitationResponse.decline()

elicitation_complete async

elicitation_complete(params: ElicitationCompleteNotification) -> None

Ignore elicitation complete notifications.

Source code in src/aclientp/client/implementations/default_client.py
async def elicitation_complete(self, params: ElicitationCompleteNotification) -> None:
    """Ignore elicitation complete notifications."""

get_session_updates

get_session_updates() -> list[SessionNotification]

Get all received session updates.

Source code in src/aclientp/client/implementations/default_client.py
def get_session_updates(self) -> list[SessionNotification]:
    """Get all received session updates."""
    return self.notifications.copy()

kill_terminal async

kill_terminal(params: KillTerminalRequest) -> KillTerminalResponse | None

Kill terminal (not implemented).

Source code in src/aclientp/client/implementations/default_client.py
async def kill_terminal(self, params: KillTerminalRequest) -> KillTerminalResponse | None:
    """Kill terminal (not implemented)."""
    raise NotImplementedError("Terminal operations not implemented")

read_text_file async

read_text_file(params: ReadTextFileRequest) -> ReadTextFileResponse

Read text from file (if allowed).

Source code in src/aclientp/client/implementations/default_client.py
async def read_text_file(self, params: ReadTextFileRequest) -> ReadTextFileResponse:
    """Read text from file (if allowed)."""
    if not self.allow_file_operations:
        raise RuntimeError("File operations not allowed")

    if self.use_real_files:
        try:
            path = Path(params.path)

            if not path.exists():
                raise FileNotFoundError(f"File not found: {params.path}")  # noqa: TRY301

            content = path.read_text(encoding="utf-8")

            # Apply line filtering if requested
            if params.line is not None or params.limit is not None:
                lines = content.splitlines()
                start_line = (params.line - 1) if params.line else 0
                end_line = start_line + params.limit if params.limit else len(lines)
                content = "\n".join(lines[start_line:end_line])

            logger.info("Read file", path=params.path)
            return ReadTextFileResponse(content=content)

        except Exception:
            logger.exception("Failed to read file", path=params.path)
            raise
    else:
        # In-memory storage for testing
        content = self.files.get(str(params.path), "default content")
        return ReadTextFileResponse(content=content)

release_terminal async

release_terminal(params: ReleaseTerminalRequest) -> ReleaseTerminalResponse | None

Release terminal (not implemented).

Source code in src/aclientp/client/implementations/default_client.py
async def release_terminal(
    self, params: ReleaseTerminalRequest
) -> ReleaseTerminalResponse | None:
    """Release terminal (not implemented)."""
    raise NotImplementedError("Terminal operations not implemented")

request_permission async

request_permission(params: RequestPermissionRequest) -> RequestPermissionResponse

Default permission handler - grants all permissions or uses test queue.

Source code in src/aclientp/client/implementations/default_client.py
async def request_permission(
    self, params: RequestPermissionRequest
) -> RequestPermissionResponse:
    """Default permission handler - grants all permissions or uses test queue."""
    title = params.tool_call.title or "operation"
    logger.info("Permission requested", title=title)

    # If we have test outcomes queued, use them
    if self.permission_outcomes:
        outcome = self.permission_outcomes.pop(0)
        return RequestPermissionResponse.model_validate({"outcome": outcome})

    # Default: grant permission for the first option
    if params.options:
        id_ = params.options[0].option_id
        return RequestPermissionResponse.allowed(id_)

    # No options - deny
    return RequestPermissionResponse.denied()

session_update async

session_update(params: SessionNotification) -> None

Handle session update notifications.

Source code in src/aclientp/client/implementations/default_client.py
async def session_update(self, params: SessionNotification) -> None:
    """Handle session update notifications."""
    msg = "Session update for %s: %s"
    logger.debug(msg, params.session_id, params.update.session_update)
    self.notifications.append(params)

terminal_output async

terminal_output(params: TerminalOutputRequest) -> TerminalOutputResponse

Get terminal output (not implemented).

Source code in src/aclientp/client/implementations/default_client.py
async def terminal_output(self, params: TerminalOutputRequest) -> TerminalOutputResponse:
    """Get terminal output (not implemented)."""
    raise NotImplementedError("Terminal operations not implemented")

wait_for_terminal_exit async

wait_for_terminal_exit(params: WaitForTerminalExitRequest) -> WaitForTerminalExitResponse

Wait for terminal exit (not implemented).

Source code in src/aclientp/client/implementations/default_client.py
async def wait_for_terminal_exit(
    self, params: WaitForTerminalExitRequest
) -> WaitForTerminalExitResponse:
    """Wait for terminal exit (not implemented)."""
    raise NotImplementedError("Terminal operations not implemented")

write_text_file async

write_text_file(params: WriteTextFileRequest) -> WriteTextFileResponse

Write text to file (if allowed).

Source code in src/aclientp/client/implementations/default_client.py
async def write_text_file(self, params: WriteTextFileRequest) -> WriteTextFileResponse:
    """Write text to file (if allowed)."""
    if not self.allow_file_operations:
        raise RuntimeError("File operations not allowed")

    if self.use_real_files:
        try:
            path = Path(params.path)
            path.write_text(params.content, encoding="utf-8")
            logger.info("Wrote file", path=params.path)
        except Exception:
            logger.exception("Failed to write file", path=params.path)
            raise
    else:
        # In-memory storage for testing
        self.files[str(params.path)] = params.content

    return WriteTextFileResponse()

DeleteSessionRequest

Bases: Request

Request parameters for deleting a session from session/list.

Only available if the Agent supports the session.delete capability.

Source code in src/aclientp/schema/client_requests.py
class DeleteSessionRequest(Request):
    """Request parameters for deleting a session from ``session/list``.

    Only available if the Agent supports the ``session.delete`` capability.
    """

    session_id: str
    """The ID of the session to delete."""

session_id instance-attribute

session_id: str

The ID of the session to delete.

DeleteSessionResponse

Bases: Response

Response to session/delete.

Source code in src/aclientp/schema/agent_responses.py
class DeleteSessionResponse(Response):
    """Response to ``session/delete``."""

DeniedOutcome

Bases: Schema

The prompt turn was cancelled before the user responded.

When a client sends a session/cancel notification to cancel an ongoing prompt turn, it MUST respond to all pending session/request_permission requests with this Cancelled outcome. See protocol docs: Cancellation

Source code in src/aclientp/schema/tool_call.py
class DeniedOutcome(Schema):
    """The prompt turn was cancelled before the user responded.

    When a client sends a `session/cancel` notification to cancel an ongoing
    prompt turn, it MUST respond to all pending `session/request_permission`
    requests with this `Cancelled` outcome.
    See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)
    """

    outcome: Literal["cancelled"] = Field(default="cancelled", init=False)

ElicitationCapabilities

Bases: AnnotatedObject

Elicitation capabilities supported by the client.

Source code in src/aclientp/schema/elicitation.py
class ElicitationCapabilities(AnnotatedObject):
    """Elicitation capabilities supported by the client."""

    form: ElicitationFormCapabilities | None = None
    """Whether the client supports form-based elicitation."""

    url: ElicitationUrlCapabilities | None = None
    """Whether the client supports URL-based elicitation."""

form class-attribute instance-attribute

form: ElicitationFormCapabilities | None = None

Whether the client supports form-based elicitation.

url class-attribute instance-attribute

url: ElicitationUrlCapabilities | None = None

Whether the client supports URL-based elicitation.

ElicitationCompleteNotification

Bases: AnnotatedObject

Notification sent by the agent when a URL-based elicitation is complete.

Source code in src/aclientp/schema/elicitation.py
class ElicitationCompleteNotification(AnnotatedObject):
    """Notification sent by the agent when a URL-based elicitation is complete."""

    elicitation_id: str
    """The ID of the elicitation that completed."""

elicitation_id instance-attribute

elicitation_id: str

The ID of the elicitation that completed.

ElicitationFormCapabilities

Bases: AnnotatedObject

Form-based elicitation capabilities.

Source code in src/aclientp/schema/elicitation.py
class ElicitationFormCapabilities(AnnotatedObject):
    """Form-based elicitation capabilities."""

ElicitationRequest

Bases: Request

Request from the agent to elicit structured user input (elicitation/create).

The agent sends this to the client to request information from the user, either via a form or by directing them to a URL.

Mode and scope fields are flattened into the request on the wire:

  • mode: "form" carries requested_schema.
  • mode: "url" carries elicitation_id and url.
  • Session scope sets session_id (and optionally tool_call_id), request scope sets request_id (e.g. during auth before any session exists).
Source code in src/aclientp/schema/elicitation.py
class ElicitationRequest(Request):
    """Request from the agent to elicit structured user input (``elicitation/create``).

    The agent sends this to the client to request information from the user,
    either via a form or by directing them to a URL.

    Mode and scope fields are flattened into the request on the wire:

    - ``mode: "form"`` carries ``requested_schema``.
    - ``mode: "url"`` carries ``elicitation_id`` and ``url``.
    - Session scope sets ``session_id`` (and optionally ``tool_call_id``),
      request scope sets ``request_id`` (e.g. during auth before any session exists).
    """

    message: str
    """A human-readable message describing what input is needed."""

    mode: ElicitationModeType
    """The elicitation mode."""

    requested_schema: ElicitationSchema | None = None
    """Form mode: a JSON Schema describing the form fields to present to the user."""

    elicitation_id: str | None = None
    """URL mode: the unique identifier for this elicitation."""

    url: str | None = None
    """URL mode: the URL to direct the user to."""

    session_id: str | None = None
    """Session scope: the session this elicitation is tied to."""

    tool_call_id: str | None = None
    """Session scope: optional tool call within the session."""

    request_id: int | str | None = None
    """Request scope: the JSON-RPC request this elicitation is tied to."""

    @classmethod
    def form(
        cls,
        message: str,
        schema: ElicitationSchema,
        *,
        session_id: str | None = None,
        tool_call_id: str | None = None,
        request_id: int | str | None = None,
    ) -> Self:
        """Create a form-based elicitation request."""
        return cls(
            message=message,
            mode="form",
            requested_schema=schema,
            session_id=session_id,
            tool_call_id=tool_call_id,
            request_id=request_id,
        )

    @classmethod
    def url_based(
        cls,
        message: str,
        elicitation_id: str,
        url: str,
        *,
        session_id: str | None = None,
        tool_call_id: str | None = None,
        request_id: int | str | None = None,
    ) -> Self:
        """Create a URL-based elicitation request."""
        return cls(
            message=message,
            mode="url",
            elicitation_id=elicitation_id,
            url=url,
            session_id=session_id,
            tool_call_id=tool_call_id,
            request_id=request_id,
        )

elicitation_id class-attribute instance-attribute

elicitation_id: str | None = None

URL mode: the unique identifier for this elicitation.

message instance-attribute

message: str

A human-readable message describing what input is needed.

mode instance-attribute

The elicitation mode.

request_id class-attribute instance-attribute

request_id: int | str | None = None

Request scope: the JSON-RPC request this elicitation is tied to.

requested_schema class-attribute instance-attribute

requested_schema: ElicitationSchema | None = None

Form mode: a JSON Schema describing the form fields to present to the user.

session_id class-attribute instance-attribute

session_id: str | None = None

Session scope: the session this elicitation is tied to.

tool_call_id class-attribute instance-attribute

tool_call_id: str | None = None

Session scope: optional tool call within the session.

url class-attribute instance-attribute

url: str | None = None

URL mode: the URL to direct the user to.

form classmethod

form(
    message: str,
    schema: ElicitationSchema,
    *,
    session_id: str | None = None,
    tool_call_id: str | None = None,
    request_id: int | str | None = None,
) -> Self

Create a form-based elicitation request.

Source code in src/aclientp/schema/elicitation.py
@classmethod
def form(
    cls,
    message: str,
    schema: ElicitationSchema,
    *,
    session_id: str | None = None,
    tool_call_id: str | None = None,
    request_id: int | str | None = None,
) -> Self:
    """Create a form-based elicitation request."""
    return cls(
        message=message,
        mode="form",
        requested_schema=schema,
        session_id=session_id,
        tool_call_id=tool_call_id,
        request_id=request_id,
    )

url_based classmethod

url_based(
    message: str,
    elicitation_id: str,
    url: str,
    *,
    session_id: str | None = None,
    tool_call_id: str | None = None,
    request_id: int | str | None = None,
) -> Self

Create a URL-based elicitation request.

Source code in src/aclientp/schema/elicitation.py
@classmethod
def url_based(
    cls,
    message: str,
    elicitation_id: str,
    url: str,
    *,
    session_id: str | None = None,
    tool_call_id: str | None = None,
    request_id: int | str | None = None,
) -> Self:
    """Create a URL-based elicitation request."""
    return cls(
        message=message,
        mode="url",
        elicitation_id=elicitation_id,
        url=url,
        session_id=session_id,
        tool_call_id=tool_call_id,
        request_id=request_id,
    )

ElicitationResponse

Bases: Response

Response from the client to an elicitation request.

Source code in src/aclientp/schema/elicitation.py
class ElicitationResponse(Response):
    """Response from the client to an elicitation request."""

    action: ElicitationActionType
    """The user's action."""

    content: dict[str, ElicitationContentValue] | None = None
    """For ``accept``: the user-provided content, as an object matching the requested schema."""

    @classmethod
    def accept(cls, content: dict[str, ElicitationContentValue] | None = None) -> Self:
        return cls(action="accept", content=content)

    @classmethod
    def decline(cls) -> Self:
        return cls(action="decline")

    @classmethod
    def cancel(cls) -> Self:
        return cls(action="cancel")

action instance-attribute

The user's action.

content class-attribute instance-attribute

content: dict[str, ElicitationContentValue] | None = None

For accept: the user-provided content, as an object matching the requested schema.

ElicitationSchema

Bases: AnnotatedObject

Type-safe elicitation schema for requesting structured user input.

This represents a JSON Schema object with primitive-typed properties, as required by the elicitation specification.

Source code in src/aclientp/schema/elicitation.py
class ElicitationSchema(AnnotatedObject):
    """Type-safe elicitation schema for requesting structured user input.

    This represents a JSON Schema object with primitive-typed properties,
    as required by the elicitation specification.
    """

    type: Literal["object"] = "object"
    """Type discriminator. Always ``"object"``."""

    title: str | None = None
    """Optional title for the schema."""

    description: str | None = None
    """Optional description of what this schema represents."""

    properties: dict[str, ElicitationPropertySchema] = Field(default_factory=dict)
    """Property definitions (must be primitive types)."""

    required: Sequence[str] | None = None
    """List of required property names."""

description class-attribute instance-attribute

description: str | None = None

Optional description of what this schema represents.

properties class-attribute instance-attribute

properties: dict[str, ElicitationPropertySchema] = Field(default_factory=dict)

Property definitions (must be primitive types).

required class-attribute instance-attribute

required: Sequence[str] | None = None

List of required property names.

title class-attribute instance-attribute

title: str | None = None

Optional title for the schema.

type class-attribute instance-attribute

type: Literal['object'] = 'object'

Type discriminator. Always "object".

ElicitationUrlCapabilities

Bases: AnnotatedObject

URL-based elicitation capabilities.

Source code in src/aclientp/schema/elicitation.py
class ElicitationUrlCapabilities(AnnotatedObject):
    """URL-based elicitation capabilities."""

EnumOption

Bases: AnnotatedObject

A titled enum option with a const value, human-readable title and optional description.

Source code in src/aclientp/schema/elicitation.py
class EnumOption(AnnotatedObject):
    """A titled enum option with a const value, human-readable title and optional description."""

    const: str
    """The constant value for this option."""

    title: str
    """Human-readable title for this option."""

    description: str | None = None
    """Human-readable description."""

const instance-attribute

const: str

The constant value for this option.

description class-attribute instance-attribute

description: str | None = None

Human-readable description.

title instance-attribute

title: str

Human-readable title for this option.

EnvVariable

Bases: AnnotatedObject

An environment variable to set when launching an MCP server.

Source code in src/aclientp/schema/common.py
class EnvVariable(AnnotatedObject):
    """An environment variable to set when launching an MCP server."""

    name: str
    """The name of the environment variable."""

    value: str
    """The value to set for the environment variable."""

name instance-attribute

name: str

The name of the environment variable.

value instance-attribute

value: str

The value to set for the environment variable.

FileSystemCapabilities

Bases: AnnotatedObject

File system capabilities that a client may support.

See protocol docs: FileSystem

Source code in src/aclientp/schema/capabilities.py
class FileSystemCapabilities(AnnotatedObject):
    """File system capabilities that a client may support.

    See protocol docs: [FileSystem](https://agentclientprotocol.com/protocol/initialization#filesystem)
    """

    read_text_file: bool | None = False
    """Whether the Client supports `fs/read_text_file` requests."""

    write_text_file: bool | None = False
    """Whether the Client supports `fs/write_text_file` requests."""

read_text_file class-attribute instance-attribute

read_text_file: bool | None = False

Whether the Client supports fs/read_text_file requests.

write_text_file class-attribute instance-attribute

write_text_file: bool | None = False

Whether the Client supports fs/write_text_file requests.

ForkSessionRequest

Bases: SessionSetupRequest

UNSTABLE: Request parameters for forking an existing session.

Creates a new, active session based on the context of an existing one.

Only available if the Agent supports the session.fork capability.

Source code in src/aclientp/schema/client_requests.py
class ForkSessionRequest(SessionSetupRequest):
    """**UNSTABLE**: Request parameters for forking an existing session.

    Creates a new, active session based on the context of an existing one.

    Only available if the Agent supports the `session.fork` capability.
    """

    session_id: str
    """The ID of the session to fork."""

    cursor_id: str | None = None
    """**UNSTABLE**: Fork at this session cursor instead of the end of the session.

    The new session's history is the source history before the cursor. Only IDs of
    cursors announced on the source session that currently advertise
    ``capabilities.fork`` are valid; Agents reject others with ``-32602``.
    """

cursor_id class-attribute instance-attribute

cursor_id: str | None = None

UNSTABLE: Fork at this session cursor instead of the end of the session.

The new session's history is the source history before the cursor. Only IDs of cursors announced on the source session that currently advertise capabilities.fork are valid; Agents reject others with -32602.

session_id instance-attribute

session_id: str

The ID of the session to fork.

ForkSessionResponse

Bases: Response

UNSTABLE: Response from forking an existing session.

Source code in src/aclientp/schema/agent_responses.py
class ForkSessionResponse(Response):
    """**UNSTABLE**: Response from forking an existing session."""

    modes: SessionModeState | None = None
    """Initial mode state if supported by the Agent

    See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
    """

    session_id: str
    """Unique identifier for the newly created forked session."""

    config_options: Sequence[SessionConfigOption] | None = None
    """The full list of config options with updated values."""

    @classmethod
    def create(
        cls,
        session_id: str,
        config_options: Sequence[SessionConfigOption] | None = None,
        modes: Sequence[SessionMode] | None = None,
        current_mode: str | None = None,
    ) -> Self:
        """Create a response with the given session ID and config options."""
        return cls(
            session_id=session_id,
            config_options=config_options or [],
            modes=_mode_state(modes, current_mode),
        )

config_options class-attribute instance-attribute

config_options: Sequence[SessionConfigOption] | None = None

The full list of config options with updated values.

modes class-attribute instance-attribute

modes: SessionModeState | None = None

Initial mode state if supported by the Agent

See protocol docs: Session Modes

session_id instance-attribute

session_id: str

Unique identifier for the newly created forked session.

create classmethod

create(
    session_id: str,
    config_options: Sequence[SessionConfigOption] | None = None,
    modes: Sequence[SessionMode] | None = None,
    current_mode: str | None = None,
) -> Self

Create a response with the given session ID and config options.

Source code in src/aclientp/schema/agent_responses.py
@classmethod
def create(
    cls,
    session_id: str,
    config_options: Sequence[SessionConfigOption] | None = None,
    modes: Sequence[SessionMode] | None = None,
    current_mode: str | None = None,
) -> Self:
    """Create a response with the given session ID and config options."""
    return cls(
        session_id=session_id,
        config_options=config_options or [],
        modes=_mode_state(modes, current_mode),
    )

HeadlessACPClient

Bases: Client

Headless ACP client with real filesystem and terminal operations.

This client implementation: - Performs real filesystem operations - Uses ProcessManager for actual terminal/command execution - Automatically grants permissions for testing - Suitable for testing and standalone usage

Source code in src/aclientp/client/implementations/headless_client.py
class HeadlessACPClient(Client):
    """Headless ACP client with real filesystem and terminal operations.

    This client implementation:
    - Performs real filesystem operations
    - Uses ProcessManager for actual terminal/command execution
    - Automatically grants permissions for testing
    - Suitable for testing and standalone usage
    """

    def __init__(
        self,
        *,
        working_dir: Path | str | None = None,
        allow_file_operations: bool = True,
        auto_grant_permissions: bool = True,
    ) -> None:
        """Initialize headless ACP client.

        Args:
            working_dir: Default working directory for operations
            allow_file_operations: Whether to allow file read/write operations
            auto_grant_permissions: Whether to automatically grant all permissions
        """
        self.working_dir = Path(working_dir) if working_dir else Path.cwd()
        self.allow_file_operations = allow_file_operations
        self.auto_grant_permissions = auto_grant_permissions
        # Process management for terminals
        self.process_manager = ProcessManager()
        self.terminals: dict[str, str] = {}  # terminal_id -> process_id
        # Tracking for testing/debugging
        self.notifications: list[SessionNotification] = []
        self.permission_requests: list[RequestPermissionRequest] = []

    async def request_permission(
        self, params: RequestPermissionRequest
    ) -> RequestPermissionResponse:
        """Handle permission requests. Grants if auto_grant_permissions is True."""
        self.permission_requests.append(params)
        tool_name = params.tool_call.title or "operation"
        logger.info("Permission requested", tool_name=tool_name)
        if self.auto_grant_permissions and params.options:
            # Grant permission using first available option
            option_id = params.options[0].option_id
            logger.debug("Auto-granting permission", tool_name=tool_name)
            return RequestPermissionResponse.allowed(option_id)
        logger.debug("Denying permission", tool_name=tool_name)
        return RequestPermissionResponse.denied()

    async def session_update(self, params: SessionNotification) -> None:
        """Handle session update notifications."""
        typ = type(params.update).__name__
        logger.debug("Session update", session_id=params.session_id, update_type=typ)
        self.notifications.append(params)

    async def read_text_file(self, params: ReadTextFileRequest) -> ReadTextFileResponse:
        """Read text from file."""
        if not self.allow_file_operations:
            raise RuntimeError("File operations not allowed")
        path = Path(params.path)
        if not path.exists():
            raise FileNotFoundError(f"File not found: {params.path}")
        try:
            content = path.read_text(encoding="utf-8")
            # Apply line filtering if requested
            if params.line is not None or params.limit is not None:
                lines = content.splitlines(keepends=True)
                start_line = (params.line - 1) if params.line else 0
                end_line = start_line + params.limit if params.limit else len(lines)
                content = "".join(lines[start_line:end_line])
            logger.debug("Read file", path=params.path, num_chars=len(content))
            return ReadTextFileResponse(content=content)

        except Exception:
            logger.exception("Failed to read file", path=params.path)
            raise

    async def write_text_file(self, params: WriteTextFileRequest) -> WriteTextFileResponse:
        """Write text to file."""
        if not self.allow_file_operations:
            raise RuntimeError("File operations not allowed")
        path = Path(params.path)
        try:
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_text(params.content, encoding="utf-8")
            logger.debug("Wrote file", path=params.path, num_chars=len(params.content))
            return WriteTextFileResponse()
        except Exception:
            logger.exception("Failed to write file", path=params.path)
            raise

    async def create_terminal(self, params: CreateTerminalRequest) -> CreateTerminalResponse:
        """Create a new terminal session using ProcessManager."""
        try:
            process_id = await self.process_manager.start_process(
                command=params.command,
                args=list(params.args) if params.args else None,
                cwd=params.cwd or str(self.working_dir),
                env={var.name: var.value for var in (params.env or [])},
                output_limit=params.output_byte_limit,
            )
            terminal_id = f"term_{uuid.uuid4().hex[:8]}"
            self.terminals[terminal_id] = process_id
            msg = "Created terminal"
            logger.info(msg, terminal_id=terminal_id, command=params.command, args=params.args)

            return CreateTerminalResponse(terminal_id=terminal_id)

        except Exception:
            logger.exception("Failed to create terminal", command=params.command)
            raise

    async def terminal_output(self, params: TerminalOutputRequest) -> TerminalOutputResponse:
        """Get output from terminal."""
        terminal_id = params.terminal_id
        if terminal_id not in self.terminals:
            raise ValueError(f"Terminal {terminal_id} not found")
        try:
            process_id = self.terminals[terminal_id]
            output = await self.process_manager.get_output(process_id)
            return TerminalOutputResponse(output=output.combined, truncated=output.truncated)
        except Exception:
            logger.exception("Failed to get output", terminal_id=terminal_id)
            raise

    async def wait_for_terminal_exit(
        self, params: WaitForTerminalExitRequest
    ) -> WaitForTerminalExitResponse:
        """Wait for terminal process to exit."""
        terminal_id = params.terminal_id
        if terminal_id not in self.terminals:
            raise ValueError(f"Terminal {terminal_id} not found")
        try:
            process_id = self.terminals[terminal_id]
            exit_code = await self.process_manager.wait_for_exit(process_id)
            logger.debug("Terminal exited", terminal_id=terminal_id, exit_code=exit_code)
            return WaitForTerminalExitResponse(exit_code=exit_code)
        except Exception:
            logger.exception("Failed to wait", terminal_id=terminal_id)
            raise

    async def kill_terminal(self, params: KillTerminalRequest) -> KillTerminalResponse | None:
        """Kill terminal process."""
        terminal_id = params.terminal_id
        if terminal_id not in self.terminals:
            raise ValueError(f"Terminal {terminal_id} not found")
        try:
            process_id = self.terminals[terminal_id]
            await self.process_manager.kill_process(process_id)
            logger.info("Killed terminal", terminal_id=terminal_id)
            return KillTerminalResponse()
        except Exception:
            logger.exception("Failed to kill terminal", terminal_id=terminal_id)
            raise

    async def release_terminal(
        self, params: ReleaseTerminalRequest
    ) -> ReleaseTerminalResponse | None:
        """Release terminal resources."""
        terminal_id = params.terminal_id
        if terminal_id not in self.terminals:
            raise ValueError(f"Terminal {terminal_id} not found")
        try:
            process_id = self.terminals[terminal_id]
            await self.process_manager.release_process(process_id)
            del self.terminals[terminal_id]  # Remove from our tracking
            logger.info("Released terminal", terminal_id=terminal_id)
            return ReleaseTerminalResponse()
        except Exception:
            logger.exception("Failed to release terminal", terminal_id=terminal_id)
            raise

    async def cleanup(self) -> None:
        """Clean up all resources."""
        logger.info("Cleaning up headless client resources")
        for terminal_id, process_id in self.terminals.items():
            try:
                await self.process_manager.release_process(process_id)
            except Exception:
                logger.exception("Error cleaning up terminal", terminal_id=terminal_id)

        self.terminals.clear()
        await self.process_manager.cleanup()
        logger.info("Headless client cleanup completed")

    # Testing/debugging helpers

    def get_session_updates(self) -> list[SessionNotification]:
        """Get all received session updates."""
        return self.notifications.copy()

    def clear_session_updates(self) -> None:
        """Clear all stored session updates."""
        self.notifications.clear()

    def get_permission_requests(self) -> list[RequestPermissionRequest]:
        """Get all permission requests."""
        return self.permission_requests.copy()

    def clear_permission_requests(self) -> None:
        """Clear all stored permission requests."""
        self.permission_requests.clear()

    def list_active_terminals(self) -> list[str]:
        """List all active terminal IDs."""
        return list(self.terminals.keys())

    async def ext_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
        """Handle extension method calls."""
        logger.debug("Extension method called", method=method)
        return {"ok": True, "method": method, "params": params}

    async def elicitation(self, params: ElicitationRequest) -> ElicitationResponse:
        """Decline elicitation by default."""
        from aclientp.schema.elicitation import ElicitationResponse

        return ElicitationResponse.decline()

    async def elicitation_complete(self, params: ElicitationCompleteNotification) -> None:
        """Ignore elicitation complete notifications."""

    async def ext_notification(self, method: str, params: dict[str, Any]) -> None:
        """Handle extension notifications."""
        logger.debug("Extension notification", method=method)

__init__

__init__(
    *,
    working_dir: Path | str | None = None,
    allow_file_operations: bool = True,
    auto_grant_permissions: bool = True,
) -> None

Initialize headless ACP client.

Parameters:

Name Type Description Default
working_dir Path | str | None

Default working directory for operations

None
allow_file_operations bool

Whether to allow file read/write operations

True
auto_grant_permissions bool

Whether to automatically grant all permissions

True
Source code in src/aclientp/client/implementations/headless_client.py
def __init__(
    self,
    *,
    working_dir: Path | str | None = None,
    allow_file_operations: bool = True,
    auto_grant_permissions: bool = True,
) -> None:
    """Initialize headless ACP client.

    Args:
        working_dir: Default working directory for operations
        allow_file_operations: Whether to allow file read/write operations
        auto_grant_permissions: Whether to automatically grant all permissions
    """
    self.working_dir = Path(working_dir) if working_dir else Path.cwd()
    self.allow_file_operations = allow_file_operations
    self.auto_grant_permissions = auto_grant_permissions
    # Process management for terminals
    self.process_manager = ProcessManager()
    self.terminals: dict[str, str] = {}  # terminal_id -> process_id
    # Tracking for testing/debugging
    self.notifications: list[SessionNotification] = []
    self.permission_requests: list[RequestPermissionRequest] = []

cleanup async

cleanup() -> None

Clean up all resources.

Source code in src/aclientp/client/implementations/headless_client.py
async def cleanup(self) -> None:
    """Clean up all resources."""
    logger.info("Cleaning up headless client resources")
    for terminal_id, process_id in self.terminals.items():
        try:
            await self.process_manager.release_process(process_id)
        except Exception:
            logger.exception("Error cleaning up terminal", terminal_id=terminal_id)

    self.terminals.clear()
    await self.process_manager.cleanup()
    logger.info("Headless client cleanup completed")

clear_permission_requests

clear_permission_requests() -> None

Clear all stored permission requests.

Source code in src/aclientp/client/implementations/headless_client.py
def clear_permission_requests(self) -> None:
    """Clear all stored permission requests."""
    self.permission_requests.clear()

clear_session_updates

clear_session_updates() -> None

Clear all stored session updates.

Source code in src/aclientp/client/implementations/headless_client.py
def clear_session_updates(self) -> None:
    """Clear all stored session updates."""
    self.notifications.clear()

create_terminal async

create_terminal(params: CreateTerminalRequest) -> CreateTerminalResponse

Create a new terminal session using ProcessManager.

Source code in src/aclientp/client/implementations/headless_client.py
async def create_terminal(self, params: CreateTerminalRequest) -> CreateTerminalResponse:
    """Create a new terminal session using ProcessManager."""
    try:
        process_id = await self.process_manager.start_process(
            command=params.command,
            args=list(params.args) if params.args else None,
            cwd=params.cwd or str(self.working_dir),
            env={var.name: var.value for var in (params.env or [])},
            output_limit=params.output_byte_limit,
        )
        terminal_id = f"term_{uuid.uuid4().hex[:8]}"
        self.terminals[terminal_id] = process_id
        msg = "Created terminal"
        logger.info(msg, terminal_id=terminal_id, command=params.command, args=params.args)

        return CreateTerminalResponse(terminal_id=terminal_id)

    except Exception:
        logger.exception("Failed to create terminal", command=params.command)
        raise

elicitation async

elicitation(params: ElicitationRequest) -> ElicitationResponse

Decline elicitation by default.

Source code in src/aclientp/client/implementations/headless_client.py
async def elicitation(self, params: ElicitationRequest) -> ElicitationResponse:
    """Decline elicitation by default."""
    from aclientp.schema.elicitation import ElicitationResponse

    return ElicitationResponse.decline()

elicitation_complete async

elicitation_complete(params: ElicitationCompleteNotification) -> None

Ignore elicitation complete notifications.

Source code in src/aclientp/client/implementations/headless_client.py
async def elicitation_complete(self, params: ElicitationCompleteNotification) -> None:
    """Ignore elicitation complete notifications."""

ext_method async

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

Handle extension method calls.

Source code in src/aclientp/client/implementations/headless_client.py
async def ext_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
    """Handle extension method calls."""
    logger.debug("Extension method called", method=method)
    return {"ok": True, "method": method, "params": params}

ext_notification async

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

Handle extension notifications.

Source code in src/aclientp/client/implementations/headless_client.py
async def ext_notification(self, method: str, params: dict[str, Any]) -> None:
    """Handle extension notifications."""
    logger.debug("Extension notification", method=method)

get_permission_requests

get_permission_requests() -> list[RequestPermissionRequest]

Get all permission requests.

Source code in src/aclientp/client/implementations/headless_client.py
def get_permission_requests(self) -> list[RequestPermissionRequest]:
    """Get all permission requests."""
    return self.permission_requests.copy()

get_session_updates

get_session_updates() -> list[SessionNotification]

Get all received session updates.

Source code in src/aclientp/client/implementations/headless_client.py
def get_session_updates(self) -> list[SessionNotification]:
    """Get all received session updates."""
    return self.notifications.copy()

kill_terminal async

kill_terminal(params: KillTerminalRequest) -> KillTerminalResponse | None

Kill terminal process.

Source code in src/aclientp/client/implementations/headless_client.py
async def kill_terminal(self, params: KillTerminalRequest) -> KillTerminalResponse | None:
    """Kill terminal process."""
    terminal_id = params.terminal_id
    if terminal_id not in self.terminals:
        raise ValueError(f"Terminal {terminal_id} not found")
    try:
        process_id = self.terminals[terminal_id]
        await self.process_manager.kill_process(process_id)
        logger.info("Killed terminal", terminal_id=terminal_id)
        return KillTerminalResponse()
    except Exception:
        logger.exception("Failed to kill terminal", terminal_id=terminal_id)
        raise

list_active_terminals

list_active_terminals() -> list[str]

List all active terminal IDs.

Source code in src/aclientp/client/implementations/headless_client.py
def list_active_terminals(self) -> list[str]:
    """List all active terminal IDs."""
    return list(self.terminals.keys())

read_text_file async

read_text_file(params: ReadTextFileRequest) -> ReadTextFileResponse

Read text from file.

Source code in src/aclientp/client/implementations/headless_client.py
async def read_text_file(self, params: ReadTextFileRequest) -> ReadTextFileResponse:
    """Read text from file."""
    if not self.allow_file_operations:
        raise RuntimeError("File operations not allowed")
    path = Path(params.path)
    if not path.exists():
        raise FileNotFoundError(f"File not found: {params.path}")
    try:
        content = path.read_text(encoding="utf-8")
        # Apply line filtering if requested
        if params.line is not None or params.limit is not None:
            lines = content.splitlines(keepends=True)
            start_line = (params.line - 1) if params.line else 0
            end_line = start_line + params.limit if params.limit else len(lines)
            content = "".join(lines[start_line:end_line])
        logger.debug("Read file", path=params.path, num_chars=len(content))
        return ReadTextFileResponse(content=content)

    except Exception:
        logger.exception("Failed to read file", path=params.path)
        raise

release_terminal async

release_terminal(params: ReleaseTerminalRequest) -> ReleaseTerminalResponse | None

Release terminal resources.

Source code in src/aclientp/client/implementations/headless_client.py
async def release_terminal(
    self, params: ReleaseTerminalRequest
) -> ReleaseTerminalResponse | None:
    """Release terminal resources."""
    terminal_id = params.terminal_id
    if terminal_id not in self.terminals:
        raise ValueError(f"Terminal {terminal_id} not found")
    try:
        process_id = self.terminals[terminal_id]
        await self.process_manager.release_process(process_id)
        del self.terminals[terminal_id]  # Remove from our tracking
        logger.info("Released terminal", terminal_id=terminal_id)
        return ReleaseTerminalResponse()
    except Exception:
        logger.exception("Failed to release terminal", terminal_id=terminal_id)
        raise

request_permission async

request_permission(params: RequestPermissionRequest) -> RequestPermissionResponse

Handle permission requests. Grants if auto_grant_permissions is True.

Source code in src/aclientp/client/implementations/headless_client.py
async def request_permission(
    self, params: RequestPermissionRequest
) -> RequestPermissionResponse:
    """Handle permission requests. Grants if auto_grant_permissions is True."""
    self.permission_requests.append(params)
    tool_name = params.tool_call.title or "operation"
    logger.info("Permission requested", tool_name=tool_name)
    if self.auto_grant_permissions and params.options:
        # Grant permission using first available option
        option_id = params.options[0].option_id
        logger.debug("Auto-granting permission", tool_name=tool_name)
        return RequestPermissionResponse.allowed(option_id)
    logger.debug("Denying permission", tool_name=tool_name)
    return RequestPermissionResponse.denied()

session_update async

session_update(params: SessionNotification) -> None

Handle session update notifications.

Source code in src/aclientp/client/implementations/headless_client.py
async def session_update(self, params: SessionNotification) -> None:
    """Handle session update notifications."""
    typ = type(params.update).__name__
    logger.debug("Session update", session_id=params.session_id, update_type=typ)
    self.notifications.append(params)

terminal_output async

terminal_output(params: TerminalOutputRequest) -> TerminalOutputResponse

Get output from terminal.

Source code in src/aclientp/client/implementations/headless_client.py
async def terminal_output(self, params: TerminalOutputRequest) -> TerminalOutputResponse:
    """Get output from terminal."""
    terminal_id = params.terminal_id
    if terminal_id not in self.terminals:
        raise ValueError(f"Terminal {terminal_id} not found")
    try:
        process_id = self.terminals[terminal_id]
        output = await self.process_manager.get_output(process_id)
        return TerminalOutputResponse(output=output.combined, truncated=output.truncated)
    except Exception:
        logger.exception("Failed to get output", terminal_id=terminal_id)
        raise

wait_for_terminal_exit async

wait_for_terminal_exit(params: WaitForTerminalExitRequest) -> WaitForTerminalExitResponse

Wait for terminal process to exit.

Source code in src/aclientp/client/implementations/headless_client.py
async def wait_for_terminal_exit(
    self, params: WaitForTerminalExitRequest
) -> WaitForTerminalExitResponse:
    """Wait for terminal process to exit."""
    terminal_id = params.terminal_id
    if terminal_id not in self.terminals:
        raise ValueError(f"Terminal {terminal_id} not found")
    try:
        process_id = self.terminals[terminal_id]
        exit_code = await self.process_manager.wait_for_exit(process_id)
        logger.debug("Terminal exited", terminal_id=terminal_id, exit_code=exit_code)
        return WaitForTerminalExitResponse(exit_code=exit_code)
    except Exception:
        logger.exception("Failed to wait", terminal_id=terminal_id)
        raise

write_text_file async

write_text_file(params: WriteTextFileRequest) -> WriteTextFileResponse

Write text to file.

Source code in src/aclientp/client/implementations/headless_client.py
async def write_text_file(self, params: WriteTextFileRequest) -> WriteTextFileResponse:
    """Write text to file."""
    if not self.allow_file_operations:
        raise RuntimeError("File operations not allowed")
    path = Path(params.path)
    try:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(params.content, encoding="utf-8")
        logger.debug("Wrote file", path=params.path, num_chars=len(params.content))
        return WriteTextFileResponse()
    except Exception:
        logger.exception("Failed to write file", path=params.path)
        raise

HttpMcpServer

Bases: BaseMcpServer

HTTP transport configuration.

Only available when the Agent capabilities indicate mcp_capabilities.http is true.

Source code in src/aclientp/schema/mcp.py
class HttpMcpServer(BaseMcpServer):
    """HTTP transport configuration.

    Only available when the Agent capabilities indicate `mcp_capabilities.http` is `true`.
    """

    headers: Sequence[HttpHeader] = Field(default_factory=list)
    """HTTP headers to set when making requests to the MCP server."""

    type: Literal["http"] = Field(default="http", init=False)
    """HTTP transport type."""

    url: HttpUrl
    """URL to the MCP server."""

    def get_headers_dict(self) -> dict[str, str]:
        return {header.name: header.value for header in self.headers}

headers class-attribute instance-attribute

headers: Sequence[HttpHeader] = Field(default_factory=list)

HTTP headers to set when making requests to the MCP server.

type class-attribute instance-attribute

type: Literal['http'] = Field(default='http', init=False)

HTTP transport type.

url instance-attribute

url: HttpUrl

URL to the MCP server.

HttpTransport dataclass

Configuration for the Streamable HTTP & WebSocket server transport (experimental).

Serves ACP on one endpoint per the transport RFD: Streamable HTTP (POST/GET/DELETE) and WebSocket upgrade. Each client connection gets its own agent instance. Requires the bridge extra (starlette, uvicorn).

Attributes:

Name Type Description
host str

Host to bind to.

port int

Port to listen on.

path str

Endpoint path.

authenticate Authenticate | None

Identifies callers (None rejects with 401); connections belong to their creator. None accepts every caller, for local use only.

allow_origins list[str]

CORS origins for browser clients.

max_buffered_bytes int

Output a connection may hold for its client before the agent's writes wait.

max_output_stall float

Seconds a client may take no output while over that limit before its connection is closed.

Source code in src/aclientp/transports.py
@dataclass
class HttpTransport:
    """Configuration for the Streamable HTTP & WebSocket server transport (experimental).

    Serves ACP on one endpoint per the transport RFD: Streamable HTTP (POST/GET/DELETE)
    and WebSocket upgrade. Each client connection gets its own agent instance. Requires
    the ``bridge`` extra (starlette, uvicorn).

    Attributes:
        host: Host to bind to.
        port: Port to listen on.
        path: Endpoint path.
        authenticate: Identifies callers (None rejects with 401); connections belong to
            their creator. None accepts every caller, for local use only.
        allow_origins: CORS origins for browser clients.
        max_buffered_bytes: Output a connection may hold for its client before the agent's
            writes wait.
        max_output_stall: Seconds a client may take no output while over that limit
            before its connection is closed.
    """

    host: str = "localhost"
    port: int = 8765
    path: str = "/acp"
    authenticate: Authenticate | None = None
    allow_origins: list[str] = field(default_factory=list)
    max_buffered_bytes: int = 64 * 1024 * 1024
    max_output_stall: float = 60.0

HttpTransportError

Bases: ConnectionError

The ACP server rejected the connection or became unreachable.

Source code in src/aclientp/http_transport.py
class HttpTransportError(ConnectionError):
    """The ACP server rejected the connection or became unreachable."""

Implementation

Bases: AnnotatedObject

Describes the name and version of an ACP implementation.

Includes an optional title for UI representation.

Source code in src/aclientp/schema/common.py
class Implementation(AnnotatedObject):
    """Describes the name and version of an ACP implementation.

    Includes an optional title for UI representation.
    """

    name: str
    """Intended for programmatic or logical use.

    Can be used as a display name fallback if title isn't present."""

    title: str | None = None
    """Intended for UI and end-user contexts.

    Optimized to be human-readable and easily understood.
    If not provided, the name should be used for display."""

    version: str
    """Version of the implementation.

    Can be displayed to the user or used for debugging or metrics purposes."""

name instance-attribute

name: str

Intended for programmatic or logical use.

Can be used as a display name fallback if title isn't present.

title class-attribute instance-attribute

title: str | None = None

Intended for UI and end-user contexts.

Optimized to be human-readable and easily understood. If not provided, the name should be used for display.

version instance-attribute

version: str

Version of the implementation.

Can be displayed to the user or used for debugging or metrics purposes.

InitializeRequest

Bases: Request

Request parameters for the initialize method.

Sent by the client to establish connection and negotiate capabilities.

See protocol docs: Initialization

Source code in src/aclientp/schema/client_requests.py
class InitializeRequest(Request):
    """Request parameters for the initialize method.

    Sent by the client to establish connection and negotiate capabilities.

    See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
    """

    client_capabilities: ClientCapabilities | None = Field(default_factory=ClientCapabilities)
    """Capabilities supported by the client."""

    client_info: Implementation | None = None
    """Information about the Client name and version sent to the Agent.

    Note: in future versions of the protocol, this will be required.
    """

    protocol_version: int
    """The latest protocol version supported by the client."""

    @classmethod
    def create(
        cls,
        title: str,
        name: str,
        version: str,
        terminal: bool = True,
        read_text_file: bool = True,
        write_text_file: bool = True,
        protocol_version: int = 1,
        terminal_auth: bool = False,
        prompt_suggestions: bool = False,
        compaction: bool = False,
        notices: bool = False,
        metadata: dict[str, Any] | None = None,
    ) -> Self:
        """Create a new InitializeRequest instance."""
        fs = FileSystemCapabilities(read_text_file=read_text_file, write_text_file=write_text_file)
        auth = AuthCapabilities(terminal=terminal_auth) if terminal_auth else None
        session = ClientSessionCapabilities(
            prompt_suggestions=PromptSuggestionsCapabilities() if prompt_suggestions else None,
            compaction=CompactionCapabilities() if compaction else None,
            notices=NoticeCapabilities() if notices else None,
        )
        caps = ClientCapabilities(terminal=terminal, fs=fs, auth=auth, session=session)
        impl = Implementation(title=title, name=name, version=version)
        return cls(
            client_capabilities=caps,
            client_info=impl,
            protocol_version=protocol_version,
            field_meta=metadata,
        )

    @classmethod
    def create_for_package(
        cls,
        package_name: str,
        allow_terminal: bool = True,
        allow_file_operations: bool = True,
        terminal_auth: bool = False,
        prompt_suggestions: bool = False,
        compaction: bool = False,
        notices: bool = False,
        metadata: dict[str, Any] | None = None,
    ) -> InitializeRequest:
        """Create ACP initialize request for app with given name (based on pkg metadata)."""
        from importlib.metadata import metadata as _metadata

        pkg_meta = _metadata(package_name)
        return cls.create(
            title=pkg_meta["Name"],
            version=pkg_meta["Version"],
            name=package_name,
            protocol_version=1,
            terminal=allow_terminal,
            read_text_file=allow_file_operations,
            write_text_file=allow_file_operations,
            terminal_auth=terminal_auth,
            prompt_suggestions=prompt_suggestions,
            compaction=compaction,
            notices=notices,
            metadata=metadata,
        )

client_capabilities class-attribute instance-attribute

client_capabilities: ClientCapabilities | None = Field(default_factory=ClientCapabilities)

Capabilities supported by the client.

client_info class-attribute instance-attribute

client_info: Implementation | None = None

Information about the Client name and version sent to the Agent.

Note: in future versions of the protocol, this will be required.

protocol_version instance-attribute

protocol_version: int

The latest protocol version supported by the client.

create classmethod

create(
    title: str,
    name: str,
    version: str,
    terminal: bool = True,
    read_text_file: bool = True,
    write_text_file: bool = True,
    protocol_version: int = 1,
    terminal_auth: bool = False,
    prompt_suggestions: bool = False,
    compaction: bool = False,
    notices: bool = False,
    metadata: dict[str, Any] | None = None,
) -> Self

Create a new InitializeRequest instance.

Source code in src/aclientp/schema/client_requests.py
@classmethod
def create(
    cls,
    title: str,
    name: str,
    version: str,
    terminal: bool = True,
    read_text_file: bool = True,
    write_text_file: bool = True,
    protocol_version: int = 1,
    terminal_auth: bool = False,
    prompt_suggestions: bool = False,
    compaction: bool = False,
    notices: bool = False,
    metadata: dict[str, Any] | None = None,
) -> Self:
    """Create a new InitializeRequest instance."""
    fs = FileSystemCapabilities(read_text_file=read_text_file, write_text_file=write_text_file)
    auth = AuthCapabilities(terminal=terminal_auth) if terminal_auth else None
    session = ClientSessionCapabilities(
        prompt_suggestions=PromptSuggestionsCapabilities() if prompt_suggestions else None,
        compaction=CompactionCapabilities() if compaction else None,
        notices=NoticeCapabilities() if notices else None,
    )
    caps = ClientCapabilities(terminal=terminal, fs=fs, auth=auth, session=session)
    impl = Implementation(title=title, name=name, version=version)
    return cls(
        client_capabilities=caps,
        client_info=impl,
        protocol_version=protocol_version,
        field_meta=metadata,
    )

create_for_package classmethod

create_for_package(
    package_name: str,
    allow_terminal: bool = True,
    allow_file_operations: bool = True,
    terminal_auth: bool = False,
    prompt_suggestions: bool = False,
    compaction: bool = False,
    notices: bool = False,
    metadata: dict[str, Any] | None = None,
) -> InitializeRequest

Create ACP initialize request for app with given name (based on pkg metadata).

Source code in src/aclientp/schema/client_requests.py
@classmethod
def create_for_package(
    cls,
    package_name: str,
    allow_terminal: bool = True,
    allow_file_operations: bool = True,
    terminal_auth: bool = False,
    prompt_suggestions: bool = False,
    compaction: bool = False,
    notices: bool = False,
    metadata: dict[str, Any] | None = None,
) -> InitializeRequest:
    """Create ACP initialize request for app with given name (based on pkg metadata)."""
    from importlib.metadata import metadata as _metadata

    pkg_meta = _metadata(package_name)
    return cls.create(
        title=pkg_meta["Name"],
        version=pkg_meta["Version"],
        name=package_name,
        protocol_version=1,
        terminal=allow_terminal,
        read_text_file=allow_file_operations,
        write_text_file=allow_file_operations,
        terminal_auth=terminal_auth,
        prompt_suggestions=prompt_suggestions,
        compaction=compaction,
        notices=notices,
        metadata=metadata,
    )

InitializeResponse

Bases: Response

Response from the initialize method.

Contains the negotiated protocol version and agent capabilities.

See protocol docs: Initialization

Source code in src/aclientp/schema/agent_responses.py
class InitializeResponse(Response):
    """Response from the initialize method.

    Contains the negotiated protocol version and agent capabilities.

    See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
    """

    agent_capabilities: AgentCapabilities | None = Field(default_factory=AgentCapabilities)
    """Capabilities supported by the agent."""

    agent_info: Implementation | None = None
    """Information about the Agent name and version sent to the Client.


    Note: in future versions of the protocol, this will be required."""

    auth_methods: Sequence[AuthMethod] | None = Field(default_factory=list)
    """Authentication methods supported by the agent."""

    protocol_version: int = Field(ge=0, le=65535)
    """The protocol version the client specified if supported by the agent.

    Or the latest protocol version supported by the agent.
    The client should disconnect, if it doesn't support this version.
    """

    @classmethod
    def create(
        cls,
        name: str,
        title: str,
        version: str,
        protocol_version: int,
        load_session: bool | None = False,
        http_mcp_servers: bool = False,
        sse_mcp_servers: bool = False,
        audio_prompts: bool = False,
        embedded_context_prompts: bool = False,
        image_prompts: bool = False,
        list_sessions: bool = False,
        resume_session: bool = False,
        close_session: bool = False,
        auth_methods: Sequence[AuthMethod] | None = None,
    ) -> Self:
        """Create an instance of AgentCapabilities.

        Args:
            name: The name of the agent.
            title: The title of the agent.
            version: The version of the agent.
            protocol_version: The protocol version of the agent.
            load_session: Whether the agent supports `session/load`.
            http_mcp_servers: Whether the agent supports HTTP MCP servers.
            sse_mcp_servers: Whether the agent supports SSE MCP servers.
            audio_prompts: Whether the agent supports audio prompts.
            embedded_context_prompts: Whether the agent supports embedded context prompts.
            image_prompts: Whether the agent supports image prompts.
            list_sessions: Whether the agent supports `session/list`.
            resume_session: Whether the agent supports `session/resume`.
            close_session: Whether the agent supports `session/close`.
            auth_methods: The authentication methods supported by the agent.
        """
        caps = AgentCapabilities.create(
            load_session=load_session,
            http_mcp_servers=http_mcp_servers,
            sse_mcp_servers=sse_mcp_servers,
            audio_prompts=audio_prompts,
            embedded_context_prompts=embedded_context_prompts,
            image_prompts=image_prompts,
            list_sessions=list_sessions,
            resume_session=resume_session,
            close_session=close_session,
        )
        return cls(
            agent_info=Implementation(name=name, title=title, version=version),
            protocol_version=protocol_version,
            agent_capabilities=caps,
            auth_methods=auth_methods,
        )

agent_capabilities class-attribute instance-attribute

agent_capabilities: AgentCapabilities | None = Field(default_factory=AgentCapabilities)

Capabilities supported by the agent.

agent_info class-attribute instance-attribute

agent_info: Implementation | None = None

Information about the Agent name and version sent to the Client.

Note: in future versions of the protocol, this will be required.

auth_methods class-attribute instance-attribute

auth_methods: Sequence[AuthMethod] | None = Field(default_factory=list)

Authentication methods supported by the agent.

protocol_version class-attribute instance-attribute

protocol_version: int = Field(ge=0, le=65535)

The protocol version the client specified if supported by the agent.

Or the latest protocol version supported by the agent. The client should disconnect, if it doesn't support this version.

create classmethod

create(
    name: str,
    title: str,
    version: str,
    protocol_version: int,
    load_session: bool | None = False,
    http_mcp_servers: bool = False,
    sse_mcp_servers: bool = False,
    audio_prompts: bool = False,
    embedded_context_prompts: bool = False,
    image_prompts: bool = False,
    list_sessions: bool = False,
    resume_session: bool = False,
    close_session: bool = False,
    auth_methods: Sequence[AuthMethod] | None = None,
) -> Self

Create an instance of AgentCapabilities.

Parameters:

Name Type Description Default
name str

The name of the agent.

required
title str

The title of the agent.

required
version str

The version of the agent.

required
protocol_version int

The protocol version of the agent.

required
load_session bool | None

Whether the agent supports session/load.

False
http_mcp_servers bool

Whether the agent supports HTTP MCP servers.

False
sse_mcp_servers bool

Whether the agent supports SSE MCP servers.

False
audio_prompts bool

Whether the agent supports audio prompts.

False
embedded_context_prompts bool

Whether the agent supports embedded context prompts.

False
image_prompts bool

Whether the agent supports image prompts.

False
list_sessions bool

Whether the agent supports session/list.

False
resume_session bool

Whether the agent supports session/resume.

False
close_session bool

Whether the agent supports session/close.

False
auth_methods Sequence[AuthMethod] | None

The authentication methods supported by the agent.

None
Source code in src/aclientp/schema/agent_responses.py
@classmethod
def create(
    cls,
    name: str,
    title: str,
    version: str,
    protocol_version: int,
    load_session: bool | None = False,
    http_mcp_servers: bool = False,
    sse_mcp_servers: bool = False,
    audio_prompts: bool = False,
    embedded_context_prompts: bool = False,
    image_prompts: bool = False,
    list_sessions: bool = False,
    resume_session: bool = False,
    close_session: bool = False,
    auth_methods: Sequence[AuthMethod] | None = None,
) -> Self:
    """Create an instance of AgentCapabilities.

    Args:
        name: The name of the agent.
        title: The title of the agent.
        version: The version of the agent.
        protocol_version: The protocol version of the agent.
        load_session: Whether the agent supports `session/load`.
        http_mcp_servers: Whether the agent supports HTTP MCP servers.
        sse_mcp_servers: Whether the agent supports SSE MCP servers.
        audio_prompts: Whether the agent supports audio prompts.
        embedded_context_prompts: Whether the agent supports embedded context prompts.
        image_prompts: Whether the agent supports image prompts.
        list_sessions: Whether the agent supports `session/list`.
        resume_session: Whether the agent supports `session/resume`.
        close_session: Whether the agent supports `session/close`.
        auth_methods: The authentication methods supported by the agent.
    """
    caps = AgentCapabilities.create(
        load_session=load_session,
        http_mcp_servers=http_mcp_servers,
        sse_mcp_servers=sse_mcp_servers,
        audio_prompts=audio_prompts,
        embedded_context_prompts=embedded_context_prompts,
        image_prompts=image_prompts,
        list_sessions=list_sessions,
        resume_session=resume_session,
        close_session=close_session,
    )
    return cls(
        agent_info=Implementation(name=name, title=title, version=version),
        protocol_version=protocol_version,
        agent_capabilities=caps,
        auth_methods=auth_methods,
    )

IntegerPropertySchema

Bases: AnnotatedObject

Schema for integer properties in an elicitation form.

Source code in src/aclientp/schema/elicitation.py
class IntegerPropertySchema(AnnotatedObject):
    """Schema for integer properties in an elicitation form."""

    type: Literal["integer"] = "integer"
    """Type discriminator."""

    title: str | None = None
    """Optional title for the property."""

    description: str | None = None
    """Human-readable description."""

    minimum: int | None = None
    """Minimum value (inclusive)."""

    maximum: int | None = None
    """Maximum value (inclusive)."""

    default: int | None = None
    """Default value."""

default class-attribute instance-attribute

default: int | None = None

Default value.

description class-attribute instance-attribute

description: str | None = None

Human-readable description.

maximum class-attribute instance-attribute

maximum: int | None = None

Maximum value (inclusive).

minimum class-attribute instance-attribute

minimum: int | None = None

Minimum value (inclusive).

title class-attribute instance-attribute

title: str | None = None

Optional title for the property.

type class-attribute instance-attribute

type: Literal['integer'] = 'integer'

Type discriminator.

KillTerminalRequest

Bases: BaseAgentRequest

Request to kill a terminal command without releasing the terminal.

Source code in src/aclientp/schema/agent_requests.py
class KillTerminalRequest(BaseAgentRequest):
    """Request to kill a terminal command without releasing the terminal."""

    terminal_id: str
    """The ID of the terminal to kill."""

terminal_id instance-attribute

terminal_id: str

The ID of the terminal to kill.

KillTerminalResponse

Bases: Response

Response to the terminal/kill method.

Source code in src/aclientp/schema/client_responses.py
class KillTerminalResponse(Response):
    """Response to the ``terminal/kill`` method."""

ListSessionsRequest

Bases: Request

Request parameters for listing existing sessions.

Only available if the Agent supports the session.list capability.

Source code in src/aclientp/schema/client_requests.py
class ListSessionsRequest(Request):
    """Request parameters for listing existing sessions.

    Only available if the Agent supports the `session.list` capability.
    """

    cursor: str | None = None
    """Opaque cursor token from a previous response's nextCursor field for pagination."""

    cwd: str | None = None
    """Filter sessions by working directory. Must be an absolute path."""

    archived: SessionArchiveFilter | None = None
    """**UNSTABLE**: Which sessions to return by archive state. Defaults to ``exclude``."""

archived class-attribute instance-attribute

archived: SessionArchiveFilter | None = None

UNSTABLE: Which sessions to return by archive state. Defaults to exclude.

cursor class-attribute instance-attribute

cursor: str | None = None

Opaque cursor token from a previous response's nextCursor field for pagination.

cwd class-attribute instance-attribute

cwd: str | None = None

Filter sessions by working directory. Must be an absolute path.

ListSessionsResponse

Bases: Response

Response from listing sessions.

Source code in src/aclientp/schema/agent_responses.py
class ListSessionsResponse(Response):
    """Response from listing sessions."""

    next_cursor: str | None = None
    """Opaque cursor token. If present, pass this in the next request's cursor parameter
    to fetch the next page. If absent, there are no more results."""

    sessions: Sequence[SessionInfo] = Field(default_factory=list)
    """Array of session information objects."""

next_cursor class-attribute instance-attribute

next_cursor: str | None = None

Opaque cursor token. If present, pass this in the next request's cursor parameter to fetch the next page. If absent, there are no more results.

sessions class-attribute instance-attribute

sessions: Sequence[SessionInfo] = Field(default_factory=list)

Array of session information objects.

LoadSessionRequest

Bases: SessionSetupRequest

Request parameters for loading an existing session.

Only available if the Agent supports the loadSession capability.

See protocol docs: Loading Sessions

Source code in src/aclientp/schema/client_requests.py
class LoadSessionRequest(SessionSetupRequest):
    """Request parameters for loading an existing session.

    Only available if the Agent supports the `loadSession` capability.

    See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)
    """

    session_id: str
    """The ID of the session to load."""

session_id instance-attribute

session_id: str

The ID of the session to load.

LoadSessionResponse

Bases: Response

Response from loading an existing session.

Source code in src/aclientp/schema/agent_responses.py
class LoadSessionResponse(Response):
    """Response from loading an existing session."""

    modes: SessionModeState | None = None
    """Initial mode state if supported by the Agent

    See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
    """

    config_options: Sequence[SessionConfigOption] | None = None
    """The full list of config options with updated values."""

config_options class-attribute instance-attribute

config_options: Sequence[SessionConfigOption] | None = None

The full list of config options with updated values.

modes class-attribute instance-attribute

modes: SessionModeState | None = None

Initial mode state if supported by the Agent

See protocol docs: Session Modes

LogoutCapabilities

Bases: AnnotatedObject

Logout capabilities supported by the agent.

By supplying {} it means that the agent supports the logout method.

Source code in src/aclientp/schema/capabilities.py
class LogoutCapabilities(AnnotatedObject):
    """Logout capabilities supported by the agent.

    By supplying ``{}`` it means that the agent supports the logout method.
    """

LogoutRequest

Bases: Request

Request parameters for the logout method.

Terminates the current authenticated session.

After a successful logout, all new sessions will require authentication. There is no guarantee about the behavior of already running sessions.

Source code in src/aclientp/schema/client_requests.py
class LogoutRequest(Request):
    """Request parameters for the logout method.

    Terminates the current authenticated session.

    After a successful logout, all new sessions will require authentication.
    There is no guarantee about the behavior of already running sessions.
    """

LogoutResponse

Bases: Response

Response to the logout method.

Source code in src/aclientp/schema/agent_responses.py
class LogoutResponse(Response):
    """Response to the ``logout`` method."""

MessageMcpNotification

Bases: AnnotatedObject

UNSTABLE: An inner MCP notification tied to an active inner MCP request.

Source code in src/aclientp/schema/mcp.py
class MessageMcpNotification(AnnotatedObject):
    """**UNSTABLE**: An inner MCP notification tied to an active inner MCP request."""

    server_id: McpServerAcpId
    """The declared ACP MCP server handling the associated request."""

    request_id: McpRequestId
    """The identifier of the active inner MCP request."""

    method: str
    """The inner MCP method name."""

    params: dict[str, Any] | None = None
    """Optional inner MCP params."""

method instance-attribute

method: str

The inner MCP method name.

params class-attribute instance-attribute

params: dict[str, Any] | None = None

Optional inner MCP params.

request_id instance-attribute

request_id: McpRequestId

The identifier of the active inner MCP request.

server_id instance-attribute

server_id: McpServerAcpId

The declared ACP MCP server handling the associated request.

MessageMcpRequest

Bases: Request

UNSTABLE: An inner MCP request sent to an acp MCP server via mcp/message.

Either side may send it, to the side that declared the server.

Source code in src/aclientp/schema/mcp.py
class MessageMcpRequest(Request):
    """**UNSTABLE**: An inner MCP request sent to an ``acp`` MCP server via ``mcp/message``.

    Either side may send it, to the side that declared the server.
    """

    server_id: McpServerAcpId
    """The declared ACP MCP server receiving this request."""

    request_id: McpRequestId
    """The caller-generated identifier for the inner MCP request."""

    method: str
    """The inner MCP method name."""

    params: dict[str, Any] | None = None
    """Optional inner MCP params."""

method instance-attribute

method: str

The inner MCP method name.

params class-attribute instance-attribute

params: dict[str, Any] | None = None

Optional inner MCP params.

request_id instance-attribute

request_id: McpRequestId

The caller-generated identifier for the inner MCP request.

server_id instance-attribute

server_id: McpServerAcpId

The declared ACP MCP server receiving this request.

MessageMcpResponse

Bases: Response

UNSTABLE: Response to mcp/message: exactly one inner MCP outcome.

Either an opaque result (which may be JSON null) or an error. Receivers prefer result if both are present.

Source code in src/aclientp/schema/mcp.py
class MessageMcpResponse(Response):
    """**UNSTABLE**: Response to ``mcp/message``: exactly one inner MCP outcome.

    Either an opaque ``result`` (which may be JSON null) or an ``error``.
    Receivers prefer ``result`` if both are present.
    """

    result: Any = None
    """The opaque inner MCP result."""

    error: McpError | None = None
    """The inner MCP error."""

error class-attribute instance-attribute

error: McpError | None = None

The inner MCP error.

result class-attribute instance-attribute

result: Any = None

The opaque inner MCP result.

MultiSelectPropertySchema

Bases: AnnotatedObject

Schema for multi-select (array) properties in an elicitation form.

Source code in src/aclientp/schema/elicitation.py
class MultiSelectPropertySchema(AnnotatedObject):
    """Schema for multi-select (array) properties in an elicitation form."""

    type: Literal["array"] = "array"
    """Type discriminator."""

    title: str | None = None
    """Optional title for the property."""

    description: str | None = None
    """Human-readable description."""

    min_items: int | None = Field(default=None, ge=0)
    """Minimum number of items to select."""

    max_items: int | None = Field(default=None, ge=0)
    """Maximum number of items to select."""

    items: MultiSelectItems
    """The items definition describing allowed values."""

    default: Sequence[str] | None = None
    """Default selected values."""

default class-attribute instance-attribute

default: Sequence[str] | None = None

Default selected values.

description class-attribute instance-attribute

description: str | None = None

Human-readable description.

items instance-attribute

The items definition describing allowed values.

max_items class-attribute instance-attribute

max_items: int | None = Field(default=None, ge=0)

Maximum number of items to select.

min_items class-attribute instance-attribute

min_items: int | None = Field(default=None, ge=0)

Minimum number of items to select.

title class-attribute instance-attribute

title: str | None = None

Optional title for the property.

type class-attribute instance-attribute

type: Literal['array'] = 'array'

Type discriminator.

NewSessionRequest

Bases: SessionSetupRequest

Request parameters for creating a new session.

See protocol docs: Creating a Session

Source code in src/aclientp/schema/client_requests.py
class NewSessionRequest(SessionSetupRequest):
    """Request parameters for creating a new session.

    See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)
    """

NewSessionResponse

Bases: Response

Response from creating a new session.

See protocol docs: Creating a Session

Source code in src/aclientp/schema/agent_responses.py
class NewSessionResponse(Response):
    """Response from creating a new session.

    See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)
    """

    modes: SessionModeState | None = None
    """Initial mode state if supported by the Agent

    See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
    """

    config_options: Sequence[SessionConfigOption] | None = None
    """**Configuration options for this session."""

    session_id: str
    """Unique identifier for the created session.

    Used in all subsequent requests for this conversation.
    """

config_options class-attribute instance-attribute

config_options: Sequence[SessionConfigOption] | None = None

**Configuration options for this session.

modes class-attribute instance-attribute

modes: SessionModeState | None = None

Initial mode state if supported by the Agent

See protocol docs: Session Modes

session_id instance-attribute

session_id: str

Unique identifier for the created session.

Used in all subsequent requests for this conversation.

NoOpClient

Bases: Client

Minimal client that returns default responses for all operations.

This client is useful for bridging scenarios where you need a Client implementation but don't actually need to handle client-side operations. All methods return minimal valid responses.

Source code in src/aclientp/client/implementations/noop_client.py
class NoOpClient(Client):
    """Minimal client that returns default responses for all operations.

    This client is useful for bridging scenarios where you need a Client
    implementation but don't actually need to handle client-side operations.
    All methods return minimal valid responses.
    """

    async def request_permission(
        self, params: RequestPermissionRequest
    ) -> RequestPermissionResponse:
        """Grant permission using first available option."""
        from aclientp.schema import AllowedOutcome, RequestPermissionResponse

        return RequestPermissionResponse(outcome=AllowedOutcome(option_id="allow"))

    async def session_update(self, params: SessionNotification) -> None:
        """Ignore session updates."""

    async def write_text_file(self, params: WriteTextFileRequest) -> WriteTextFileResponse:
        """Return empty write response."""
        from aclientp.schema import WriteTextFileResponse

        return WriteTextFileResponse()

    async def read_text_file(self, params: ReadTextFileRequest) -> ReadTextFileResponse:
        """Return empty file content."""
        from aclientp.schema import ReadTextFileResponse

        return ReadTextFileResponse(content="")

    async def create_terminal(self, params: CreateTerminalRequest) -> CreateTerminalResponse:
        """Return dummy terminal ID."""
        from aclientp.schema import CreateTerminalResponse

        return CreateTerminalResponse(terminal_id="noop-terminal")

    async def terminal_output(self, params: TerminalOutputRequest) -> TerminalOutputResponse:
        """Return empty terminal output."""
        from aclientp.schema import TerminalOutputResponse

        return TerminalOutputResponse(output="", truncated=False)

    async def release_terminal(
        self, params: ReleaseTerminalRequest
    ) -> ReleaseTerminalResponse | None:
        """Return empty release response."""
        from aclientp.schema import ReleaseTerminalResponse

        return ReleaseTerminalResponse()

    async def wait_for_terminal_exit(
        self, params: WaitForTerminalExitRequest
    ) -> WaitForTerminalExitResponse:
        """Return immediate exit with code 0."""
        from aclientp.schema import WaitForTerminalExitResponse

        return WaitForTerminalExitResponse(exit_code=0)

    async def kill_terminal(self, params: KillTerminalRequest) -> KillTerminalResponse | None:
        """Return empty kill response."""
        from aclientp.schema import KillTerminalResponse

        return KillTerminalResponse()

    async def ext_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
        """Return empty dict for extension methods."""
        return {}

    async def elicitation(self, params: ElicitationRequest) -> ElicitationResponse:
        """Decline elicitation by default."""
        from aclientp.schema.elicitation import ElicitationResponse

        return ElicitationResponse.decline()

    async def elicitation_complete(self, params: ElicitationCompleteNotification) -> None:
        """Ignore elicitation complete notifications."""

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

create_terminal async

create_terminal(params: CreateTerminalRequest) -> CreateTerminalResponse

Return dummy terminal ID.

Source code in src/aclientp/client/implementations/noop_client.py
async def create_terminal(self, params: CreateTerminalRequest) -> CreateTerminalResponse:
    """Return dummy terminal ID."""
    from aclientp.schema import CreateTerminalResponse

    return CreateTerminalResponse(terminal_id="noop-terminal")

elicitation async

elicitation(params: ElicitationRequest) -> ElicitationResponse

Decline elicitation by default.

Source code in src/aclientp/client/implementations/noop_client.py
async def elicitation(self, params: ElicitationRequest) -> ElicitationResponse:
    """Decline elicitation by default."""
    from aclientp.schema.elicitation import ElicitationResponse

    return ElicitationResponse.decline()

elicitation_complete async

elicitation_complete(params: ElicitationCompleteNotification) -> None

Ignore elicitation complete notifications.

Source code in src/aclientp/client/implementations/noop_client.py
async def elicitation_complete(self, params: ElicitationCompleteNotification) -> None:
    """Ignore elicitation complete notifications."""

ext_method async

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

Return empty dict for extension methods.

Source code in src/aclientp/client/implementations/noop_client.py
async def ext_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
    """Return empty dict for extension methods."""
    return {}

ext_notification async

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

Ignore extension notifications.

Source code in src/aclientp/client/implementations/noop_client.py
async def ext_notification(self, method: str, params: dict[str, Any]) -> None:
    """Ignore extension notifications."""

kill_terminal async

kill_terminal(params: KillTerminalRequest) -> KillTerminalResponse | None

Return empty kill response.

Source code in src/aclientp/client/implementations/noop_client.py
async def kill_terminal(self, params: KillTerminalRequest) -> KillTerminalResponse | None:
    """Return empty kill response."""
    from aclientp.schema import KillTerminalResponse

    return KillTerminalResponse()

read_text_file async

read_text_file(params: ReadTextFileRequest) -> ReadTextFileResponse

Return empty file content.

Source code in src/aclientp/client/implementations/noop_client.py
async def read_text_file(self, params: ReadTextFileRequest) -> ReadTextFileResponse:
    """Return empty file content."""
    from aclientp.schema import ReadTextFileResponse

    return ReadTextFileResponse(content="")

release_terminal async

release_terminal(params: ReleaseTerminalRequest) -> ReleaseTerminalResponse | None

Return empty release response.

Source code in src/aclientp/client/implementations/noop_client.py
async def release_terminal(
    self, params: ReleaseTerminalRequest
) -> ReleaseTerminalResponse | None:
    """Return empty release response."""
    from aclientp.schema import ReleaseTerminalResponse

    return ReleaseTerminalResponse()

request_permission async

request_permission(params: RequestPermissionRequest) -> RequestPermissionResponse

Grant permission using first available option.

Source code in src/aclientp/client/implementations/noop_client.py
async def request_permission(
    self, params: RequestPermissionRequest
) -> RequestPermissionResponse:
    """Grant permission using first available option."""
    from aclientp.schema import AllowedOutcome, RequestPermissionResponse

    return RequestPermissionResponse(outcome=AllowedOutcome(option_id="allow"))

session_update async

session_update(params: SessionNotification) -> None

Ignore session updates.

Source code in src/aclientp/client/implementations/noop_client.py
async def session_update(self, params: SessionNotification) -> None:
    """Ignore session updates."""

terminal_output async

terminal_output(params: TerminalOutputRequest) -> TerminalOutputResponse

Return empty terminal output.

Source code in src/aclientp/client/implementations/noop_client.py
async def terminal_output(self, params: TerminalOutputRequest) -> TerminalOutputResponse:
    """Return empty terminal output."""
    from aclientp.schema import TerminalOutputResponse

    return TerminalOutputResponse(output="", truncated=False)

wait_for_terminal_exit async

wait_for_terminal_exit(params: WaitForTerminalExitRequest) -> WaitForTerminalExitResponse

Return immediate exit with code 0.

Source code in src/aclientp/client/implementations/noop_client.py
async def wait_for_terminal_exit(
    self, params: WaitForTerminalExitRequest
) -> WaitForTerminalExitResponse:
    """Return immediate exit with code 0."""
    from aclientp.schema import WaitForTerminalExitResponse

    return WaitForTerminalExitResponse(exit_code=0)

write_text_file async

write_text_file(params: WriteTextFileRequest) -> WriteTextFileResponse

Return empty write response.

Source code in src/aclientp/client/implementations/noop_client.py
async def write_text_file(self, params: WriteTextFileRequest) -> WriteTextFileResponse:
    """Return empty write response."""
    from aclientp.schema import WriteTextFileResponse

    return WriteTextFileResponse()

NumberPropertySchema

Bases: AnnotatedObject

Schema for number (floating-point) properties in an elicitation form.

Source code in src/aclientp/schema/elicitation.py
class NumberPropertySchema(AnnotatedObject):
    """Schema for number (floating-point) properties in an elicitation form."""

    type: Literal["number"] = "number"
    """Type discriminator."""

    title: str | None = None
    """Optional title for the property."""

    description: str | None = None
    """Human-readable description."""

    minimum: float | None = None
    """Minimum value (inclusive)."""

    maximum: float | None = None
    """Maximum value (inclusive)."""

    default: float | None = None
    """Default value."""

default class-attribute instance-attribute

default: float | None = None

Default value.

description class-attribute instance-attribute

description: str | None = None

Human-readable description.

maximum class-attribute instance-attribute

maximum: float | None = None

Maximum value (inclusive).

minimum class-attribute instance-attribute

minimum: float | None = None

Minimum value (inclusive).

title class-attribute instance-attribute

title: str | None = None

Optional title for the property.

type class-attribute instance-attribute

type: Literal['number'] = 'number'

Type discriminator.

PermissionOption

Bases: AnnotatedObject

An option presented to the user when requesting permission.

Source code in src/aclientp/schema/tool_call.py
class PermissionOption(AnnotatedObject):
    """An option presented to the user when requesting permission."""

    kind: PermissionKind
    """Hint about the nature of this permission option."""

    name: str
    """Human-readable label to display to the user."""

    option_id: str
    """Unique identifier for this permission option."""

kind instance-attribute

kind: PermissionKind

Hint about the nature of this permission option.

name instance-attribute

name: str

Human-readable label to display to the user.

option_id instance-attribute

option_id: str

Unique identifier for this permission option.

PlanEntry

Bases: AnnotatedObject

A single entry in the execution plan.

Represents a task or goal that the assistant intends to accomplish as part of fulfilling the user's request. See protocol docs: Plan Entries

Source code in src/aclientp/schema/agent_plan.py
class PlanEntry(AnnotatedObject):
    """A single entry in the execution plan.

    Represents a task or goal that the assistant intends to accomplish
    as part of fulfilling the user's request.
    See protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/agent-plan#plan-entries)
    """

    content: str
    """Human-readable description of what this task aims to accomplish."""

    priority: PlanEntryPriority
    """The relative importance of this task.

    Used to indicate which tasks are most critical to the overall goal.
    """

    status: PlanEntryStatus
    """Current execution status of this task."""

content instance-attribute

content: str

Human-readable description of what this task aims to accomplish.

priority instance-attribute

priority: PlanEntryPriority

The relative importance of this task.

Used to indicate which tasks are most critical to the overall goal.

status instance-attribute

status: PlanEntryStatus

Current execution status of this task.

PromptRequest

Bases: Request

Request parameters for sending a user prompt to the agent.

Contains the user's message and any additional context.

See protocol docs: User Message

Source code in src/aclientp/schema/client_requests.py
class PromptRequest(Request):
    """Request parameters for sending a user prompt to the agent.

    Contains the user's message and any additional context.

    See protocol docs: [User Message](https://agentclientprotocol.com/protocol/prompt-turn#1-user-message)
    """

    prompt: Sequence[ContentBlock]
    """The blocks of content that compose the user's message.

    As a baseline, the Agent MUST support [`ContentBlock::Text`] and
    [`ContentBlock::ResourceContentBlock`],
    while other variants are optionally enabled via [`PromptCapabilities`].

    The Client MUST adapt its interface according to [`PromptCapabilities`].

    The client MAY include referenced pieces of context as either
    [`ContentBlock::Resource`] or [`ContentBlock::ResourceContentBlock`].

    When available, [`ContentBlock::Resource`] is preferred
    as it avoids extra round-trips and allows the message to include
    pieces of context from sources the agent may not have access to.
    """

    session_id: str
    """The ID of the session to send this user message to."""

prompt instance-attribute

prompt: Sequence[ContentBlock]

The blocks of content that compose the user's message.

As a baseline, the Agent MUST support [ContentBlock::Text] and [ContentBlock::ResourceContentBlock], while other variants are optionally enabled via [PromptCapabilities].

The Client MUST adapt its interface according to [PromptCapabilities].

The client MAY include referenced pieces of context as either [ContentBlock::Resource] or [ContentBlock::ResourceContentBlock].

When available, [ContentBlock::Resource] is preferred as it avoids extra round-trips and allows the message to include pieces of context from sources the agent may not have access to.

session_id instance-attribute

session_id: str

The ID of the session to send this user message to.

PromptResponse

Bases: Response

Response from processing a user prompt.

See protocol docs: Check for Completion

Source code in src/aclientp/schema/agent_responses.py
class PromptResponse(Response):
    """Response from processing a user prompt.

    See protocol docs: [Check for Completion](https://agentclientprotocol.com/protocol/prompt-turn#4-check-for-completion)
    """

    stop_reason: StopReason
    """Indicates why the agent stopped processing the turn."""

    usage: Usage | None = None
    """**UNSTABLE**: Token usage for this turn (optional)."""

stop_reason instance-attribute

stop_reason: StopReason

Indicates why the agent stopped processing the turn.

usage class-attribute instance-attribute

usage: Usage | None = None

UNSTABLE: Token usage for this turn (optional).

ProtocolVersionError

Bases: RequestError

The peer answered initialize with a protocol version this side does not speak.

Raised by clients before the rest of the response is validated, so an agent that only speaks another version (e.g. a v1 agent answering a v2 client) is reported as such instead of as a malformed response.

Source code in src/aclientp/exceptions.py
class ProtocolVersionError(RequestError):
    """The peer answered ``initialize`` with a protocol version this side does not speak.

    Raised by clients before the rest of the response is validated, so an agent that
    only speaks another version (e.g. a v1 agent answering a v2 client) is reported
    as such instead of as a malformed response.
    """

    def __init__(self, expected: int, received: Any, result: Any = None) -> None:
        super().__init__(-32600, "Invalid request", {"expected": expected, "received": received})
        self.expected = expected
        """The protocol version this side speaks."""
        self.received = received
        """The ``protocolVersion`` of the response (any JSON value, as sent by the peer)."""
        self.result = result
        """The raw ``initialize`` result, e.g. to show the peer's name."""

expected instance-attribute

expected = expected

The protocol version this side speaks.

received instance-attribute

received = received

The protocolVersion of the response (any JSON value, as sent by the peer).

result instance-attribute

result = result

The raw initialize result, e.g. to show the peer's name.

ReadTextFileRequest

Bases: BaseAgentRequest

Request to read content from a text file.

Only available if the client supports the fs.readTextFile capability.

Source code in src/aclientp/schema/agent_requests.py
class ReadTextFileRequest(BaseAgentRequest):
    """Request to read content from a text file.

    Only available if the client supports the `fs.readTextFile` capability.
    """

    limit: int | None = Field(default=None, ge=0)
    """Maximum number of lines to read."""

    line: int | None = Field(default=None, ge=0)
    """Line number to start reading from (1-based)."""

    path: str
    """Absolute path to the file to read."""

limit class-attribute instance-attribute

limit: int | None = Field(default=None, ge=0)

Maximum number of lines to read.

line class-attribute instance-attribute

line: int | None = Field(default=None, ge=0)

Line number to start reading from (1-based).

path instance-attribute

path: str

Absolute path to the file to read.

ReadTextFileResponse

Bases: Response

Response containing the contents of a text file.

Source code in src/aclientp/schema/client_responses.py
class ReadTextFileResponse(Response):
    """Response containing the contents of a text file."""

    content: str
    """The contents of the text file."""

content instance-attribute

content: str

The contents of the text file.

ReleaseTerminalRequest

Bases: BaseAgentRequest

Request to release a terminal and free its resources.

Source code in src/aclientp/schema/agent_requests.py
class ReleaseTerminalRequest(BaseAgentRequest):
    """Request to release a terminal and free its resources."""

    terminal_id: str
    """The ID of the terminal to release."""

terminal_id instance-attribute

terminal_id: str

The ID of the terminal to release.

ReleaseTerminalResponse

Bases: Response

Response to terminal/release method.

Source code in src/aclientp/schema/client_responses.py
class ReleaseTerminalResponse(Response):
    """Response to terminal/release method."""

RequestError

Bases: Exception

Raised when a JSON-RPC request fails.

Source code in src/aclientp/exceptions.py
class RequestError(Exception):
    """Raised when a JSON-RPC request fails."""

    def __init__(self, code: int, message: str, data: Any | None = None) -> None:
        super().__init__(message)
        self.code = code
        self.data = data

    @classmethod
    def parse_error(cls, data: dict[str, Any] | None = None) -> Self:
        return cls(-32700, "Parse error", data)

    @classmethod
    def invalid_request(cls, data: dict[str, Any] | None = None) -> Self:
        return cls(-32600, "Invalid request", data)

    @classmethod
    def method_not_found(cls, method: str) -> Self:
        return cls(-32601, "Method not found", {"method": method})

    @classmethod
    def invalid_params(cls, data: dict[str, Any] | None = None) -> Self:
        return cls(-32602, "Invalid params", data)

    @classmethod
    def internal_error(cls, data: dict[str, Any] | None = None) -> Self:
        return cls(-32603, "Internal error", data)

    @classmethod
    def request_cancelled(cls, data: dict[str, Any] | None = None) -> Self:
        return cls(-32800, "Request cancelled", data)

    @classmethod
    def resource_not_found(cls, uri: str | None = None) -> Self:
        data = {"uri": uri} if uri is not None else None
        return cls(-32002, "Resource not found", data)

    @classmethod
    def auth_required(cls, data: dict[str, Any] | None = None) -> Self:
        return cls(-32000, "Authentication required", data)

    @classmethod
    def session_not_found(cls, session_id: str) -> Self:
        """``-32002`` for a request naming a session that does not exist or is not active."""
        return cls(-32002, "Resource not found", {"sessionId": session_id})

    @classmethod
    def unsupported_protocol_version(cls, requested: int, supported: list[int]) -> Self:
        """``-32022``: no supported protocol version is at or below the requested one."""
        data = {"requested": requested, "supported": supported}
        return cls(-32022, "Unsupported protocol version", data)

    @classmethod
    def from_error_obj(cls, error: Any) -> Self:
        """Build an error from a peer's JSON-RPC error object.

        Peers are not trusted to send a well-formed object: ``data`` is optional per
        JSON-RPC 2.0 and ``code`` / ``message`` may be missing or have the wrong type.
        """
        if not isinstance(error, dict):
            return cls.internal_error({"details": "Malformed error response", "error": error})
        code = error.get("code")
        message = error.get("message")
        return cls(
            code if isinstance(code, int) and not isinstance(code, bool) else -32603,
            message if isinstance(message, str) and message else "Error",
            error.get("data"),
        )

    def to_error_obj(self) -> dict[str, Any]:
        return {"code": self.code, "message": str(self), "data": self.data}

from_error_obj classmethod

from_error_obj(error: Any) -> Self

Build an error from a peer's JSON-RPC error object.

Peers are not trusted to send a well-formed object: data is optional per JSON-RPC 2.0 and code / message may be missing or have the wrong type.

Source code in src/aclientp/exceptions.py
@classmethod
def from_error_obj(cls, error: Any) -> Self:
    """Build an error from a peer's JSON-RPC error object.

    Peers are not trusted to send a well-formed object: ``data`` is optional per
    JSON-RPC 2.0 and ``code`` / ``message`` may be missing or have the wrong type.
    """
    if not isinstance(error, dict):
        return cls.internal_error({"details": "Malformed error response", "error": error})
    code = error.get("code")
    message = error.get("message")
    return cls(
        code if isinstance(code, int) and not isinstance(code, bool) else -32603,
        message if isinstance(message, str) and message else "Error",
        error.get("data"),
    )

session_not_found classmethod

session_not_found(session_id: str) -> Self

-32002 for a request naming a session that does not exist or is not active.

Source code in src/aclientp/exceptions.py
@classmethod
def session_not_found(cls, session_id: str) -> Self:
    """``-32002`` for a request naming a session that does not exist or is not active."""
    return cls(-32002, "Resource not found", {"sessionId": session_id})

unsupported_protocol_version classmethod

unsupported_protocol_version(requested: int, supported: list[int]) -> Self

-32022: no supported protocol version is at or below the requested one.

Source code in src/aclientp/exceptions.py
@classmethod
def unsupported_protocol_version(cls, requested: int, supported: list[int]) -> Self:
    """``-32022``: no supported protocol version is at or below the requested one."""
    data = {"requested": requested, "supported": supported}
    return cls(-32022, "Unsupported protocol version", data)

RequestPermissionRequest

Bases: BaseAgentRequest

Request for user permission to execute a tool call.

Sent when the agent needs authorization before performing a sensitive operation.

See protocol docs: Requesting Permission

Source code in src/aclientp/schema/agent_requests.py
class RequestPermissionRequest(BaseAgentRequest):
    """Request for user permission to execute a tool call.

    Sent when the agent needs authorization before performing a sensitive operation.

    See protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/tool-calls#requesting-permission)
    """

    options: Sequence[PermissionOption]
    """Available permission options for the user to choose from."""

    tool_call: ToolCallUpdate
    """Details about the tool call requiring permission."""

options instance-attribute

options: Sequence[PermissionOption]

Available permission options for the user to choose from.

tool_call instance-attribute

tool_call: ToolCallUpdate

Details about the tool call requiring permission.

RequestPermissionResponse

Bases: Response

Response to a permission request.

Source code in src/aclientp/schema/client_responses.py
class RequestPermissionResponse(Response):
    """Response to a permission request."""

    outcome: RequestPermissionOutcome
    """The user's decision on the permission request."""

    @classmethod
    def denied(cls, metadata: dict[str, Any] | None = None) -> Self:
        """Create a response indicating that the permission request was denied."""
        return cls(outcome=DeniedOutcome(), field_meta=metadata)

    @classmethod
    def allowed(cls, option_id: str, metadata: dict[str, Any] | None = None) -> Self:
        """Create a response indicating that the permission request was allowed."""
        return cls(outcome=AllowedOutcome(option_id=option_id), field_meta=metadata)

outcome instance-attribute

The user's decision on the permission request.

allowed classmethod

allowed(option_id: str, metadata: dict[str, Any] | None = None) -> Self

Create a response indicating that the permission request was allowed.

Source code in src/aclientp/schema/client_responses.py
@classmethod
def allowed(cls, option_id: str, metadata: dict[str, Any] | None = None) -> Self:
    """Create a response indicating that the permission request was allowed."""
    return cls(outcome=AllowedOutcome(option_id=option_id), field_meta=metadata)

denied classmethod

denied(metadata: dict[str, Any] | None = None) -> Self

Create a response indicating that the permission request was denied.

Source code in src/aclientp/schema/client_responses.py
@classmethod
def denied(cls, metadata: dict[str, Any] | None = None) -> Self:
    """Create a response indicating that the permission request was denied."""
    return cls(outcome=DeniedOutcome(), field_meta=metadata)

ResumeSessionRequest

Bases: SessionSetupRequest

Request parameters for resuming an existing session.

Resumes an existing session without returning previous messages (unlike session/load). mcp_servers is the complete client-provided set.

Only available if the Agent supports the session.resume capability.

Source code in src/aclientp/schema/client_requests.py
class ResumeSessionRequest(SessionSetupRequest):
    """Request parameters for resuming an existing session.

    Resumes an existing session without returning previous messages (unlike `session/load`).
    ``mcp_servers`` is the complete client-provided set.

    Only available if the Agent supports the `session.resume` capability.
    """

    session_id: str
    """The ID of the session to resume."""

session_id instance-attribute

session_id: str

The ID of the session to resume.

ResumeSessionResponse

Bases: Response

Response from resuming an existing session.

Source code in src/aclientp/schema/agent_responses.py
class ResumeSessionResponse(Response):
    """Response from resuming an existing session."""

    modes: SessionModeState | None = None
    """Initial mode state if supported by the Agent

    See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
    """

    config_options: Sequence[SessionConfigOption] | None = None
    """The full list of config options with updated values."""

    @classmethod
    def create(
        cls,
        config_options: Sequence[SessionConfigOption] | None = None,
        modes: Sequence[SessionMode] | None = None,
        current_mode: str | None = None,
    ) -> Self:
        """Create a response with the given config options and modes."""
        return cls(config_options=config_options or [], modes=_mode_state(modes, current_mode))

config_options class-attribute instance-attribute

config_options: Sequence[SessionConfigOption] | None = None

The full list of config options with updated values.

modes class-attribute instance-attribute

modes: SessionModeState | None = None

Initial mode state if supported by the Agent

See protocol docs: Session Modes

create classmethod

create(
    config_options: Sequence[SessionConfigOption] | None = None,
    modes: Sequence[SessionMode] | None = None,
    current_mode: str | None = None,
) -> Self

Create a response with the given config options and modes.

Source code in src/aclientp/schema/agent_responses.py
@classmethod
def create(
    cls,
    config_options: Sequence[SessionConfigOption] | None = None,
    modes: Sequence[SessionMode] | None = None,
    current_mode: str | None = None,
) -> Self:
    """Create a response with the given config options and modes."""
    return cls(config_options=config_options or [], modes=_mode_state(modes, current_mode))

SessionMode

Bases: AnnotatedObject

A mode the agent can operate in.

See protocol docs: Session Modes

Source code in src/aclientp/schema/session_state.py
class SessionMode(AnnotatedObject):
    """A mode the agent can operate in.

    See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
    """

    description: str | None = None
    """Optional description of the mode."""

    id: str
    """Unique identifier for the mode."""

    name: str
    """Human-readable name of the mode."""

description class-attribute instance-attribute

description: str | None = None

Optional description of the mode.

id instance-attribute

id: str

Unique identifier for the mode.

name instance-attribute

name: str

Human-readable name of the mode.

SessionModeState

Bases: AnnotatedObject

The set of modes and the one currently active.

Source code in src/aclientp/schema/session_state.py
class SessionModeState(AnnotatedObject):
    """The set of modes and the one currently active."""

    available_modes: Sequence[SessionMode]
    """The set of modes that the Agent can operate in."""

    current_mode_id: str
    """The current mode the Agent is in."""

available_modes instance-attribute

available_modes: Sequence[SessionMode]

The set of modes that the Agent can operate in.

current_mode_id instance-attribute

current_mode_id: str

The current mode the Agent is in.

SessionNotification

Bases: AnnotatedObject

Notification containing a session update from the agent.

Used to stream real-time progress and results during prompt processing.

See protocol docs: Agent Reports Output

Source code in src/aclientp/schema/notifications.py
class SessionNotification(AnnotatedObject):
    """Notification containing a session update from the agent.

    Used to stream real-time progress and results during prompt processing.

    See protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)
    """

    session_id: str
    """The ID of the session this update pertains to."""

    update: SessionUpdate
    """The session update data."""

session_id instance-attribute

session_id: str

The ID of the session this update pertains to.

update instance-attribute

update: SessionUpdate

The session update data.

SessionOptionsRequest

Bases: Request

UNSTABLE: Request the modes and config options a session would start with.

Only available if the Agent supports the session.options capability.

Source code in src/aclientp/schema/client_requests.py
class SessionOptionsRequest(Request):
    """**UNSTABLE**: Request the modes and config options a session would start with.

    Only available if the Agent supports the ``session.options`` capability.
    """

    cwd: str
    """The working directory to resolve options for. Must be an absolute path."""

    additional_directories: Sequence[str] = Field(default_factory=list)
    """Additional workspace roots to resolve options for. Each path must be absolute."""

    session_id: str | None = None
    """The session to resolve options for."""

additional_directories class-attribute instance-attribute

additional_directories: Sequence[str] = Field(default_factory=list)

Additional workspace roots to resolve options for. Each path must be absolute.

cwd instance-attribute

cwd: str

The working directory to resolve options for. Must be an absolute path.

session_id class-attribute instance-attribute

session_id: str | None = None

The session to resolve options for.

SessionOptionsResponse

Bases: Response

UNSTABLE: The modes and config options a session would start with.

Source code in src/aclientp/schema/agent_responses.py
class SessionOptionsResponse(Response):
    """**UNSTABLE**: The modes and config options a session would start with."""

    modes: SessionModeState | None = None
    """The mode state the session would start with, if the Agent supports modes."""

    config_options: Sequence[SessionConfigOption] | None = None
    """The config options the session would start with."""

config_options class-attribute instance-attribute

config_options: Sequence[SessionConfigOption] | None = None

The config options the session would start with.

modes class-attribute instance-attribute

modes: SessionModeState | None = None

The mode state the session would start with, if the Agent supports modes.

SessionStatusRequest

Bases: Request

UNSTABLE: Request parameters for checking whether the Agent has a session in memory.

Only available if the Agent supports the session.status capability.

Source code in src/aclientp/schema/client_requests.py
class SessionStatusRequest(Request):
    """**UNSTABLE**: Request parameters for checking whether the Agent has a session in memory.

    Only available if the Agent supports the ``session.status`` capability.
    """

    session_id: str
    """The ID of the session to check."""

session_id instance-attribute

session_id: str

The ID of the session to check.

SessionStatusResponse

Bases: Response

UNSTABLE: Response to session/status.

Source code in src/aclientp/schema/agent_responses.py
class SessionStatusResponse(Response):
    """**UNSTABLE**: Response to ``session/status``."""

    status: SessionStatus
    """Whether the Agent has the session in memory."""

status instance-attribute

status: SessionStatus

Whether the Agent has the session in memory.

SetSessionConfigOptionRequest

Bases: Request

Request parameters for setting a session configuration option.

Supports both select (string value ID) and boolean config options. When type is "boolean", value is a bool. When type is absent or "value_id", value is a string.

See protocol docs: Session Config Options

Source code in src/aclientp/schema/client_requests.py
class SetSessionConfigOptionRequest(Request):
    """Request parameters for setting a session configuration option.

    Supports both select (string value ID) and boolean config options.
    When ``type`` is ``"boolean"``, ``value`` is a bool.
    When ``type`` is absent or ``"value_id"``, ``value`` is a string.

    See protocol docs: [Session Config Options](https://agentclientprotocol.com/protocol/session-config-options)
    """

    config_id: str
    """The ID of the configuration option to set."""

    session_id: str
    """The ID of the session to set the config option for."""

    type: str | None = None
    """The value type discriminator. ``"boolean"`` for bool values, absent for string value IDs."""

    value: str | bool
    """The value to set. String for select options, bool for boolean options."""

config_id instance-attribute

config_id: str

The ID of the configuration option to set.

session_id instance-attribute

session_id: str

The ID of the session to set the config option for.

type class-attribute instance-attribute

type: str | None = None

The value type discriminator. "boolean" for bool values, absent for string value IDs.

value instance-attribute

value: str | bool

The value to set. String for select options, bool for boolean options.

SetSessionConfigOptionResponse

Bases: Response

Response to session/set_config_option method.

Source code in src/aclientp/schema/agent_responses.py
class SetSessionConfigOptionResponse(Response):
    """Response to `session/set_config_option` method."""

    config_options: Sequence[SessionConfigOption] = []
    """The full list of config options with updated values."""

config_options class-attribute instance-attribute

config_options: Sequence[SessionConfigOption] = []

The full list of config options with updated values.

SetSessionModeRequest

Bases: Request

Request parameters for setting a session mode.

Source code in src/aclientp/schema/client_requests.py
class SetSessionModeRequest(Request):
    """Request parameters for setting a session mode."""

    mode_id: str
    """The ID of the mode to set."""

    session_id: str
    """The ID of the session to set the mode for."""

mode_id instance-attribute

mode_id: str

The ID of the mode to set.

session_id instance-attribute

session_id: str

The ID of the session to set the mode for.

SetSessionModeResponse

Bases: Response

Response to session/set_mode method.

Source code in src/aclientp/schema/agent_responses.py
class SetSessionModeResponse(Response):
    """Response to `session/set_mode` method."""

SetSessionTitleRequest

Bases: Request

UNSTABLE: Request parameters for renaming a session.

Only available if the Agent supports the session.title capability.

Source code in src/aclientp/schema/client_requests.py
class SetSessionTitleRequest(Request):
    """**UNSTABLE**: Request parameters for renaming a session.

    Only available if the Agent supports the ``session.title`` capability.
    """

    session_id: str
    """The ID of the session to retitle."""

    title: str
    """The new title for the session."""

session_id instance-attribute

session_id: str

The ID of the session to retitle.

title instance-attribute

title: str

The new title for the session.

SetSessionTitleResponse

Bases: Response

UNSTABLE: Response to session/set_title.

Source code in src/aclientp/schema/agent_responses.py
class SetSessionTitleResponse(Response):
    """**UNSTABLE**: Response to ``session/set_title``."""

    title: str
    """The title the Agent stored."""

title instance-attribute

title: str

The title the Agent stored.

SseMcpServer

Bases: BaseMcpServer

SSE transport configuration.

Only available when the Agent capabilities indicate mcp_capabilities.sse is true.

Source code in src/aclientp/schema/mcp.py
class SseMcpServer(BaseMcpServer):
    """SSE transport configuration.

    Only available when the Agent capabilities indicate `mcp_capabilities.sse` is `true`.
    """

    headers: Sequence[HttpHeader]
    """HTTP headers to set when making requests to the MCP server."""

    type: Literal["sse"] = Field(default="sse", init=False)
    """SSE transport type."""

    url: HttpUrl
    """URL to the MCP server."""

    def get_headers_dict(self) -> dict[str, str]:
        return {header.name: header.value for header in self.headers}

headers instance-attribute

headers: Sequence[HttpHeader]

HTTP headers to set when making requests to the MCP server.

type class-attribute instance-attribute

type: Literal['sse'] = Field(default='sse', init=False)

SSE transport type.

url instance-attribute

url: HttpUrl

URL to the MCP server.

StdioMcpServer

Bases: BaseMcpServer

Stdio transport configuration.

All Agents MUST support this transport.

Source code in src/aclientp/schema/mcp.py
class StdioMcpServer(BaseMcpServer):
    """Stdio transport configuration.

    All Agents MUST support this transport.
    """

    args: Sequence[str]
    """Command-line arguments to pass to the MCP server."""

    # typ: Literal["stdio"] = Field(default="stdio", init=False)
    # """Stdio transport type."""

    command: str
    """Path to the MCP server executable."""

    env: Sequence[EnvVariable]
    """Environment variables to set when launching the MCP server."""

    def get_env_dict(self) -> dict[str, str]:
        return {env.name: env.value for env in self.env}

args instance-attribute

args: Sequence[str]

Command-line arguments to pass to the MCP server.

command instance-attribute

command: str

Path to the MCP server executable.

env instance-attribute

env: Sequence[EnvVariable]

Environment variables to set when launching the MCP server.

StdioTransport dataclass

Configuration for stdio transport.

This is the default transport for ACP agents, communicating over stdin/stdout streams.

Source code in src/aclientp/transports.py
@dataclass
class StdioTransport:
    """Configuration for stdio transport.

    This is the default transport for ACP agents, communicating over
    stdin/stdout streams.
    """

StreamTransport dataclass

Configuration for custom stream transport.

Allows passing pre-created streams for the agent to use.

Attributes:

Name Type Description
reader ByteReceiveStream

Stream to read incoming messages from.

writer ByteSendStream

Stream to write outgoing messages to.

Source code in src/aclientp/transports.py
@dataclass
class StreamTransport:
    """Configuration for custom stream transport.

    Allows passing pre-created streams for the agent to use.

    Attributes:
        reader: Stream to read incoming messages from.
        writer: Stream to write outgoing messages to.
    """

    reader: ByteReceiveStream
    writer: ByteSendStream

StringPropertySchema

Bases: AnnotatedObject

Schema for string properties in an elicitation form.

When enum_values or one_of is set, this represents a single-select enum.

Source code in src/aclientp/schema/elicitation.py
class StringPropertySchema(AnnotatedObject):
    """Schema for string properties in an elicitation form.

    When ``enum_values`` or ``one_of`` is set, this represents a single-select enum.
    """

    type: Literal["string"] = "string"
    """Type discriminator."""

    title: str | None = None
    """Optional title for the property."""

    description: str | None = None
    """Human-readable description."""

    min_length: int | None = Field(default=None, ge=0)
    """Minimum string length."""

    max_length: int | None = Field(default=None, ge=0)
    """Maximum string length."""

    pattern: str | None = None
    """Pattern the string must match."""

    format: StringFormatLiteral | None = None
    """String format."""

    default: str | None = None
    """Default value."""

    enum: Sequence[str] | None = None
    """Enum values for untitled single-select enums."""

    one_of: Sequence[EnumOption] | None = None
    """Titled enum options for titled single-select enums."""

default class-attribute instance-attribute

default: str | None = None

Default value.

description class-attribute instance-attribute

description: str | None = None

Human-readable description.

enum class-attribute instance-attribute

enum: Sequence[str] | None = None

Enum values for untitled single-select enums.

format class-attribute instance-attribute

format: StringFormatLiteral | None = None

String format.

max_length class-attribute instance-attribute

max_length: int | None = Field(default=None, ge=0)

Maximum string length.

min_length class-attribute instance-attribute

min_length: int | None = Field(default=None, ge=0)

Minimum string length.

one_of class-attribute instance-attribute

one_of: Sequence[EnumOption] | None = None

Titled enum options for titled single-select enums.

pattern class-attribute instance-attribute

pattern: str | None = None

Pattern the string must match.

title class-attribute instance-attribute

title: str | None = None

Optional title for the property.

type class-attribute instance-attribute

type: Literal['string'] = 'string'

Type discriminator.

SystemPrompt

Bases: AnnotatedObject

Client-provided system-level instructions for a session.

Only allowed if the Agent advertises session_capabilities.system_prompt.

Source code in src/aclientp/schema/client_requests.py
class SystemPrompt(AnnotatedObject):
    """Client-provided system-level instructions for a session.

    Only allowed if the Agent advertises ``session_capabilities.system_prompt``.
    """

    mode: SystemPromptMode
    """How the Agent combines ``content`` with its own instructions."""

    content: Sequence[ContentBlock]
    """The system prompt content."""

content instance-attribute

content: Sequence[ContentBlock]

The system prompt content.

mode instance-attribute

How the Agent combines content with its own instructions.

TerminalHandle

Handle for a terminal session.

Source code in src/aclientp/terminal_handle.py
class TerminalHandle:
    """Handle for a terminal session."""

    def __init__(self, terminal_id: str, requests: ACPRequests) -> None:
        self.terminal_id = terminal_id
        self._requests = requests

    async def current_output(self) -> TerminalOutputResponse:
        return await self._requests.terminal_output(self.terminal_id)

    async def wait_for_exit(self) -> WaitForTerminalExitResponse:
        return await self._requests.wait_for_terminal_exit(self.terminal_id)

    async def kill(self) -> None:
        return await self._requests.kill_terminal(self.terminal_id)

    async def release(self) -> None:
        return await self._requests.release_terminal(self.terminal_id)

TerminalOutputRequest

Bases: BaseAgentRequest

Request to get the current output and status of a terminal.

Source code in src/aclientp/schema/agent_requests.py
class TerminalOutputRequest(BaseAgentRequest):
    """Request to get the current output and status of a terminal."""

    terminal_id: str
    """The ID of the terminal to get output from."""

terminal_id instance-attribute

terminal_id: str

The ID of the terminal to get output from.

TerminalOutputResponse

Bases: Response

Response containing the terminal output and exit status.

Source code in src/aclientp/schema/client_responses.py
class TerminalOutputResponse(Response):
    """Response containing the terminal output and exit status."""

    exit_status: TerminalExitStatus | None = None
    """Exit status if the command has completed."""

    output: str
    """The terminal output captured so far."""

    truncated: bool
    """Whether the output was truncated due to byte limits."""

exit_status class-attribute instance-attribute

exit_status: TerminalExitStatus | None = None

Exit status if the command has completed.

output instance-attribute

output: str

The terminal output captured so far.

truncated instance-attribute

truncated: bool

Whether the output was truncated due to byte limits.

TextContentBlock

Bases: BaseContentBlock

Text content.

May be plain text or formatted with Markdown.

All agents MUST support text content blocks in prompts. Clients SHOULD render this text as Markdown.

Source code in src/aclientp/schema/content_blocks.py
class TextContentBlock(BaseContentBlock):
    """Text content.

    May be plain text or formatted with Markdown.

    All agents MUST support text content blocks in prompts.
    Clients SHOULD render this text as Markdown.
    """

    type: Literal["text"] = Field(default="text", init=False)

    text: str
    """Text content of the block."""

text instance-attribute

text: str

Text content of the block.

TitledMultiSelectItems

Bases: AnnotatedObject

Items definition for titled multi-select enum properties.

Source code in src/aclientp/schema/elicitation.py
class TitledMultiSelectItems(AnnotatedObject):
    """Items definition for titled multi-select enum properties."""

    any_of: Sequence[EnumOption]
    """Titled enum options."""

any_of instance-attribute

any_of: Sequence[EnumOption]

Titled enum options.

ToolCallLocation

Bases: AnnotatedObject

A file location being accessed or modified by a tool.

Enables clients to implement "follow-along" features that track which files the agent is working with in real-time. See protocol docs: Following the Agent

Source code in src/aclientp/schema/tool_call.py
class ToolCallLocation(AnnotatedObject):
    """A file location being accessed or modified by a tool.

    Enables clients to implement "follow-along" features that track
    which files the agent is working with in real-time.
    See protocol docs: [Following the Agent](https://agentclientprotocol.com/protocol/tool-calls#following-the-agent)
    """

    line: int | None = Field(default=0, ge=0)
    """Optional 1-based line number within the file.

    Defaults to 0 (unspecified) rather than None: some clients only render
    clickable paths when the field is present.
    """

    path: str
    """The absolute file path being accessed or modified."""

line class-attribute instance-attribute

line: int | None = Field(default=0, ge=0)

Optional 1-based line number within the file.

Defaults to 0 (unspecified) rather than None: some clients only render clickable paths when the field is present.

path instance-attribute

path: str

The absolute file path being accessed or modified.

ToolCallState

Tracks tool call state and sends delta updates.

Instead of accumulating all state and sending everything on each update, this class tracks whether we've started and sends only the fields that are explicitly provided in each update call.

The ACP protocol spec states: "All fields except toolCallId are optional in updates. Only the fields being changed need to be included."

Example flow
  1. Tool call starts → state.start() sends initial notification
  2. Progress event → state.update(title="Running...") sends just title
  3. More progress → state.update(content=[...]) sends just content
  4. Tool completes → state.complete(raw_output=result) sends status + output
Source code in src/aclientp/tool_call_state.py
class ToolCallState:
    """Tracks tool call state and sends delta updates.

    Instead of accumulating all state and sending everything on each update,
    this class tracks whether we've started and sends only the fields that
    are explicitly provided in each update call.

    The ACP protocol spec states:
    "All fields except toolCallId are optional in updates.
     Only the fields being changed need to be included."

    Example flow:
        1. Tool call starts → state.start() sends initial notification
        2. Progress event → state.update(title="Running...") sends just title
        3. More progress → state.update(content=[...]) sends just content
        4. Tool completes → state.complete(raw_output=result) sends status + output
    """

    def __init__(
        self,
        notifications: ACPNotifications,
        tool_call_id: str,
        tool_name: str,
        title: str,
        kind: ToolCallKind,
        raw_input: dict[str, Any],
    ) -> None:
        """Initialize tool call state.

        Args:
            notifications: ACPNotifications instance for sending updates
            tool_call_id: Unique identifier for this tool call
            tool_name: Name of the tool being called
            title: Initial human-readable title
            kind: Category of tool (read, edit, execute, etc.)
            raw_input: Input parameters passed to the tool
        """
        self._notifications = notifications
        self.tool_call_id = tool_call_id
        self.tool_name = tool_name
        self._initial_title = title
        self._initial_kind: ToolCallKind = kind
        self._raw_input = raw_input
        self._started = False
        self._has_content = False  # Track if content has been sent

    @property
    def has_content(self) -> bool:
        """Whether content has been sent for this tool call."""
        return self._has_content

    async def start(self) -> None:
        """Send initial tool_call notification.

        This creates the tool call entry in the client UI. Subsequent calls
        to update() will send tool_call_update notifications with only
        the changed fields.
        """
        if self._started:
            return

        await self._notifications.tool_call_start(
            tool_call_id=self.tool_call_id,
            title=self._initial_title,
            kind=self._initial_kind,
            raw_input=self._raw_input,
        )
        self._started = True

    async def update(
        self,
        *,
        title: str | None = None,
        status: ToolCallStatus | None = None,
        kind: ToolCallKind | None = None,
        content: Sequence[ToolCallContent] | None = None,
        locations: Sequence[ToolCallLocation | str] | None = None,
        raw_output: Any = None,
    ) -> None:
        """Send an update with only the provided fields.

        Args:
            title: Update the human-readable title
            status: Update execution status
            kind: Update tool kind
            content: Content items (terminals, diffs, text) - replaces previous
            locations: File locations - replaces previous
            raw_output: Update raw output data

        Note:
            Only fields that are truthy (not None/empty) will be included
            in the notification. This follows the ACP spec which states
            that only changed fields need to be sent.
        """
        from aclientp.schema.tool_call import ToolCallLocation

        if not self._started:
            await self.start()
        # Build kwargs with only the provided fields
        kwargs: dict[str, Any] = {}
        if title is not None:
            kwargs["title"] = title
        if status is not None:
            kwargs["status"] = status
        if kind is not None:
            kwargs["kind"] = kind
        if content:
            kwargs["content"] = content
            self._has_content = True
        if locations:
            # Normalize string paths to ToolCallLocation
            kwargs["locations"] = [
                ToolCallLocation(path=loc) if isinstance(loc, str) else loc for loc in locations
            ]
        if raw_output is not None:
            kwargs["raw_output"] = raw_output

        # Only send if there's something to update
        if kwargs:
            await self._notifications.tool_call_update(tool_call_id=self.tool_call_id, **kwargs)

    async def complete(
        self,
        raw_output: Any = None,
        *,
        content: Sequence[ToolCallContent] | None = None,
        title: str | None = None,
    ) -> None:
        """Mark tool call as completed.

        Args:
            raw_output: Final output data
            content: Optional final content
            title: Optional final title
        """
        await self.update(status="completed", raw_output=raw_output, content=content, title=title)

    async def fail(self, error: str | None = None, *, raw_output: Any = None) -> None:
        """Mark tool call as failed.

        Args:
            error: Error message to display
            raw_output: Optional error details
        """
        from aclientp.schema import ContentToolCallContent

        content = None
        if error:
            error_content = ContentToolCallContent.text(f"Error: {error}")
            content = [error_content]

        await self.update(status="failed", content=content, raw_output=raw_output)

has_content property

has_content: bool

Whether content has been sent for this tool call.

__init__

__init__(
    notifications: ACPNotifications,
    tool_call_id: str,
    tool_name: str,
    title: str,
    kind: ToolCallKind,
    raw_input: dict[str, Any],
) -> None

Initialize tool call state.

Parameters:

Name Type Description Default
notifications ACPNotifications

ACPNotifications instance for sending updates

required
tool_call_id str

Unique identifier for this tool call

required
tool_name str

Name of the tool being called

required
title str

Initial human-readable title

required
kind ToolCallKind

Category of tool (read, edit, execute, etc.)

required
raw_input dict[str, Any]

Input parameters passed to the tool

required
Source code in src/aclientp/tool_call_state.py
def __init__(
    self,
    notifications: ACPNotifications,
    tool_call_id: str,
    tool_name: str,
    title: str,
    kind: ToolCallKind,
    raw_input: dict[str, Any],
) -> None:
    """Initialize tool call state.

    Args:
        notifications: ACPNotifications instance for sending updates
        tool_call_id: Unique identifier for this tool call
        tool_name: Name of the tool being called
        title: Initial human-readable title
        kind: Category of tool (read, edit, execute, etc.)
        raw_input: Input parameters passed to the tool
    """
    self._notifications = notifications
    self.tool_call_id = tool_call_id
    self.tool_name = tool_name
    self._initial_title = title
    self._initial_kind: ToolCallKind = kind
    self._raw_input = raw_input
    self._started = False
    self._has_content = False  # Track if content has been sent

complete async

complete(
    raw_output: Any = None,
    *,
    content: Sequence[ToolCallContent] | None = None,
    title: str | None = None,
) -> None

Mark tool call as completed.

Parameters:

Name Type Description Default
raw_output Any

Final output data

None
content Sequence[ToolCallContent] | None

Optional final content

None
title str | None

Optional final title

None
Source code in src/aclientp/tool_call_state.py
async def complete(
    self,
    raw_output: Any = None,
    *,
    content: Sequence[ToolCallContent] | None = None,
    title: str | None = None,
) -> None:
    """Mark tool call as completed.

    Args:
        raw_output: Final output data
        content: Optional final content
        title: Optional final title
    """
    await self.update(status="completed", raw_output=raw_output, content=content, title=title)

fail async

fail(error: str | None = None, *, raw_output: Any = None) -> None

Mark tool call as failed.

Parameters:

Name Type Description Default
error str | None

Error message to display

None
raw_output Any

Optional error details

None
Source code in src/aclientp/tool_call_state.py
async def fail(self, error: str | None = None, *, raw_output: Any = None) -> None:
    """Mark tool call as failed.

    Args:
        error: Error message to display
        raw_output: Optional error details
    """
    from aclientp.schema import ContentToolCallContent

    content = None
    if error:
        error_content = ContentToolCallContent.text(f"Error: {error}")
        content = [error_content]

    await self.update(status="failed", content=content, raw_output=raw_output)

start async

start() -> None

Send initial tool_call notification.

This creates the tool call entry in the client UI. Subsequent calls to update() will send tool_call_update notifications with only the changed fields.

Source code in src/aclientp/tool_call_state.py
async def start(self) -> None:
    """Send initial tool_call notification.

    This creates the tool call entry in the client UI. Subsequent calls
    to update() will send tool_call_update notifications with only
    the changed fields.
    """
    if self._started:
        return

    await self._notifications.tool_call_start(
        tool_call_id=self.tool_call_id,
        title=self._initial_title,
        kind=self._initial_kind,
        raw_input=self._raw_input,
    )
    self._started = True

update async

update(
    *,
    title: str | None = None,
    status: ToolCallStatus | None = None,
    kind: ToolCallKind | None = None,
    content: Sequence[ToolCallContent] | None = None,
    locations: Sequence[ToolCallLocation | str] | None = None,
    raw_output: Any = None,
) -> None

Send an update with only the provided fields.

Parameters:

Name Type Description Default
title str | None

Update the human-readable title

None
status ToolCallStatus | None

Update execution status

None
kind ToolCallKind | None

Update tool kind

None
content Sequence[ToolCallContent] | None

Content items (terminals, diffs, text) - replaces previous

None
locations Sequence[ToolCallLocation | str] | None

File locations - replaces previous

None
raw_output Any

Update raw output data

None
Note

Only fields that are truthy (not None/empty) will be included in the notification. This follows the ACP spec which states that only changed fields need to be sent.

Source code in src/aclientp/tool_call_state.py
async def update(
    self,
    *,
    title: str | None = None,
    status: ToolCallStatus | None = None,
    kind: ToolCallKind | None = None,
    content: Sequence[ToolCallContent] | None = None,
    locations: Sequence[ToolCallLocation | str] | None = None,
    raw_output: Any = None,
) -> None:
    """Send an update with only the provided fields.

    Args:
        title: Update the human-readable title
        status: Update execution status
        kind: Update tool kind
        content: Content items (terminals, diffs, text) - replaces previous
        locations: File locations - replaces previous
        raw_output: Update raw output data

    Note:
        Only fields that are truthy (not None/empty) will be included
        in the notification. This follows the ACP spec which states
        that only changed fields need to be sent.
    """
    from aclientp.schema.tool_call import ToolCallLocation

    if not self._started:
        await self.start()
    # Build kwargs with only the provided fields
    kwargs: dict[str, Any] = {}
    if title is not None:
        kwargs["title"] = title
    if status is not None:
        kwargs["status"] = status
    if kind is not None:
        kwargs["kind"] = kind
    if content:
        kwargs["content"] = content
        self._has_content = True
    if locations:
        # Normalize string paths to ToolCallLocation
        kwargs["locations"] = [
            ToolCallLocation(path=loc) if isinstance(loc, str) else loc for loc in locations
        ]
    if raw_output is not None:
        kwargs["raw_output"] = raw_output

    # Only send if there's something to update
    if kwargs:
        await self._notifications.tool_call_update(tool_call_id=self.tool_call_id, **kwargs)

ToolCallUpdate

Bases: AnnotatedObject

Details about the tool call requiring permission.

Source code in src/aclientp/schema/tool_call.py
class ToolCallUpdate(AnnotatedObject):
    """Details about the tool call requiring permission."""

    content: Sequence[ToolCallContent] | None = None
    """Replace the content collection."""

    kind: ToolCallKind | None = None
    """Update the tool kind."""

    locations: Sequence[ToolCallLocation] | None = None
    """Replace the locations collection."""

    raw_input: Any | None = None
    """Update the raw input."""

    raw_output: Any | None = None
    """Update the raw output."""

    status: ToolCallStatus | None = None
    """Update the execution status."""

    title: str | None = None
    """Update the human-readable title."""

    name: str | None = None
    """Programmatic name of the tool being invoked."""

    tool_call_id: str
    """The ID of the tool call being updated."""

content class-attribute instance-attribute

content: Sequence[ToolCallContent] | None = None

Replace the content collection.

kind class-attribute instance-attribute

kind: ToolCallKind | None = None

Update the tool kind.

locations class-attribute instance-attribute

locations: Sequence[ToolCallLocation] | None = None

Replace the locations collection.

name class-attribute instance-attribute

name: str | None = None

Programmatic name of the tool being invoked.

raw_input class-attribute instance-attribute

raw_input: Any | None = None

Update the raw input.

raw_output class-attribute instance-attribute

raw_output: Any | None = None

Update the raw output.

status class-attribute instance-attribute

status: ToolCallStatus | None = None

Update the execution status.

title class-attribute instance-attribute

title: str | None = None

Update the human-readable title.

tool_call_id instance-attribute

tool_call_id: str

The ID of the tool call being updated.

UnarchiveSessionRequest

Bases: Request

UNSTABLE: Request parameters for unarchiving a session.

Only available if the Agent supports the session.archive capability.

Source code in src/aclientp/schema/client_requests.py
class UnarchiveSessionRequest(Request):
    """**UNSTABLE**: Request parameters for unarchiving a session.

    Only available if the Agent supports the ``session.archive`` capability.
    """

    session_id: str
    """The ID of the session to unarchive."""

session_id instance-attribute

session_id: str

The ID of the session to unarchive.

UnarchiveSessionResponse

Bases: Response

UNSTABLE: Response to session/unarchive.

Source code in src/aclientp/schema/agent_responses.py
class UnarchiveSessionResponse(Response):
    """**UNSTABLE**: Response to ``session/unarchive``."""

UntitledMultiSelectItems

Bases: AnnotatedObject

Items definition for untitled multi-select enum properties.

Source code in src/aclientp/schema/elicitation.py
class UntitledMultiSelectItems(AnnotatedObject):
    """Items definition for untitled multi-select enum properties."""

    type: Literal["string"] = "string"
    """Item type discriminator. Must be ``"string"``."""

    enum: Sequence[str]
    """Allowed enum values."""

enum instance-attribute

enum: Sequence[str]

Allowed enum values.

type class-attribute instance-attribute

type: Literal['string'] = 'string'

Item type discriminator. Must be "string".

UserMessageChunk

Bases: BaseChunk

A chunk of the user's message being streamed.

Source code in src/aclientp/schema/session_updates.py
class UserMessageChunk(BaseChunk):
    """A chunk of the user's message being streamed."""

    session_update: Literal["user_message_chunk"] = Field(default="user_message_chunk", init=False)
    """User message chunk."""

session_update class-attribute instance-attribute

session_update: Literal['user_message_chunk'] = Field(default='user_message_chunk', init=False)

User message chunk.

WaitForTerminalExitRequest

Bases: BaseAgentRequest

Request to wait for a terminal command to exit.

Source code in src/aclientp/schema/agent_requests.py
class WaitForTerminalExitRequest(BaseAgentRequest):
    """Request to wait for a terminal command to exit."""

    terminal_id: str
    """The ID of the terminal to wait for."""

terminal_id instance-attribute

terminal_id: str

The ID of the terminal to wait for.

WaitForTerminalExitResponse

Bases: Response

Response containing the exit status of a terminal command.

Source code in src/aclientp/schema/client_responses.py
class WaitForTerminalExitResponse(Response):
    """Response containing the exit status of a terminal command."""

    exit_code: int | None = None
    """The process exit code (may be null if terminated by signal)."""

    signal: str | None = None
    """The signal that terminated the process (may be null if exited normally)."""

exit_code class-attribute instance-attribute

exit_code: int | None = None

The process exit code (may be null if terminated by signal).

signal class-attribute instance-attribute

signal: str | None = None

The signal that terminated the process (may be null if exited normally).

WebSocketTransport dataclass

Configuration for WebSocket server transport.

Runs an ACP agent as a WebSocket server that accepts client connections. Each client connection gets its own agent instance.

Attributes:

Name Type Description
host str

Host to bind the WebSocket server to.

port int

Port for the WebSocket server.

Source code in src/aclientp/transports.py
@dataclass
class WebSocketTransport:
    """Configuration for WebSocket server transport.

    Runs an ACP agent as a WebSocket server that accepts client connections.
    Each client connection gets its own agent instance.

    Attributes:
        host: Host to bind the WebSocket server to.
        port: Port for the WebSocket server.
    """

    host: str = "localhost"
    port: int = 8765

WebSocketTransportError

Bases: ConnectionError

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

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

WriteTextFileRequest

Bases: BaseAgentRequest

Request to write content to a text file.

Only available if the client supports the fs.writeTextFile capability.

Source code in src/aclientp/schema/agent_requests.py
class WriteTextFileRequest(BaseAgentRequest):
    """Request to write content to a text file.

    Only available if the client supports the `fs.writeTextFile` capability.
    """

    content: str
    """The text content to write to the file."""

    path: str
    """Absolute path to the file to write."""

content instance-attribute

content: str

The text content to write to the file.

path instance-attribute

path: str

Absolute path to the file to write.

WriteTextFileResponse

Bases: Response

Response to fs/write_text_file.

Source code in src/aclientp/schema/client_responses.py
class WriteTextFileResponse(Response):
    """Response to `fs/write_text_file`."""

connect_http_transport async

connect_http_transport(
    url: str,
    *,
    headers: Mapping[str, str] | None = None,
    client: AsyncClient | None = None,
    timeout: float = 30.0,
) -> AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream]]

Connect to an ACP server's Streamable HTTP endpoint.

The streams carry newline-delimited JSON-RPC, like a stdio agent's. The first message written must be initialize.

Parameters:

Name Type Description Default
url str

The /acp endpoint.

required
headers Mapping[str, str] | None

Extra headers for every request (e.g. authentication).

None
client AsyncClient | None

HTTP client to use (its cookies and settings apply). By default a client is created, using HTTP/2 when the h2 package is installed.

None
timeout float

Timeout for connecting and for POSTs (SSE streams have no read timeout).

30.0

Yields:

Type Description
AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream]]

(reader, writer) byte streams.

Source code in src/aclientp/http_transport.py
@asynccontextmanager
async def connect_http_transport(
    url: str,
    *,
    headers: Mapping[str, str] | None = None,
    client: httpx2.AsyncClient | None = None,
    timeout: float = 30.0,
) -> AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream]]:
    """Connect to an ACP server's Streamable HTTP endpoint.

    The streams carry newline-delimited JSON-RPC, like a stdio agent's. The first message
    written must be ``initialize``.

    Args:
        url: The ``/acp`` endpoint.
        headers: Extra headers for every request (e.g. authentication).
        client: HTTP client to use (its cookies and settings apply). By default a client
            is created, using HTTP/2 when the ``h2`` package is installed.
        timeout: Timeout for connecting and for POSTs (SSE streams have no read timeout).

    Yields:
        (reader, writer) byte streams.
    """
    owned = client is None
    if client is None:
        client = httpx2.AsyncClient(
            http2=_http2_available(),
            headers=dict(headers or {}),
            timeout=httpx2.Timeout(timeout, read=None),
        )
    elif headers:
        client.headers.update(headers)
    send_inbox, receive_inbox = anyio.create_memory_object_stream[bytes](max_buffer_size=1024)
    try:
        async with anyio.create_task_group() as tg:
            connection = _HttpConnection(url, client, tg, send_inbox)
            try:
                yield _InboxReader(receive_inbox), _PostWriter(connection)
            finally:
                await connection.close_inbox()
                await connection.terminate()
                tg.cancel_scope.cancel()
    finally:
        if owned:
            await client.aclose()

connect_remote_transport async

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

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

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

Raises:

Type Description
ValueError

The URL has another scheme.

Source code in src/aclientp/ws_transport.py
@asynccontextmanager
async def connect_remote_transport(
    url: str, *, headers: Mapping[str, str] | None = None
) -> AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream]]:
    """Connect to a remote agent, choosing the transport by URL scheme.

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

    Raises:
        ValueError: The URL has another scheme.
    """
    from aclientp.http_transport import connect_http_transport

    scheme = url.split("://", 1)[0].lower() if "://" in url else ""
    match scheme:
        case "ws" | "wss":
            async with connect_websocket_transport(url, headers=headers) as streams:
                yield streams
        case "http" | "https":
            async with connect_http_transport(url, headers=headers) as streams:
                yield streams
        case _:
            msg = f"Unsupported ACP URL {url!r}: use http(s):// or ws(s)://"
            raise ValueError(msg)

connect_to_agent

connect_to_agent(
    client: Client,
    input_stream: ByteSendStream,
    output_stream: ByteReceiveStream,
    **connection_kwargs: Any,
) -> ClientSideConnection

Create a ClientSideConnection to an ACP agent.

This is the recommended entry point for client-side connections.

Parameters:

Name Type Description Default
client Client

The client implementation.

required
input_stream ByteSendStream

ByteSendStream for sending to the agent.

required
output_stream ByteReceiveStream

ByteReceiveStream for receiving from the agent.

required
**connection_kwargs Any

Additional keyword arguments for ClientSideConnection.

{}

Returns:

Type Description
ClientSideConnection

A ClientSideConnection connected to the agent.

Source code in src/aclientp/stdio.py
def connect_to_agent(
    client: Client,
    input_stream: ByteSendStream,
    output_stream: ByteReceiveStream,
    **connection_kwargs: Any,
) -> ClientSideConnection:
    """Create a ClientSideConnection to an ACP agent.

    This is the recommended entry point for client-side connections.

    Args:
        client: The client implementation.
        input_stream: ByteSendStream for sending to the agent.
        output_stream: ByteReceiveStream for receiving from the agent.
        **connection_kwargs: Additional keyword arguments for ClientSideConnection.

    Returns:
        A ClientSideConnection connected to the agent.
    """

    # Create a factory that ignores the connection parameter
    def client_factory(connection: Agent) -> Client:
        return client

    return ClientSideConnection(client_factory, input_stream, output_stream, **connection_kwargs)

connect_websocket_transport async

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

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

Parameters:

Name Type Description Default
url str

The /acp endpoint.

required
headers Mapping[str, str] | None

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

None
open_timeout float

Timeout for the opening handshake.

30.0

Yields:

Type Description
AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream]]

(reader, writer) byte streams.

Raises:

Type Description
WebSocketTransportError

The server rejected the upgrade or is unreachable.

Source code in src/aclientp/ws_transport.py
@asynccontextmanager
async def connect_websocket_transport(
    url: str,
    *,
    headers: Mapping[str, str] | None = None,
    open_timeout: float = 30.0,
) -> AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream]]:
    """Connect to an ACP server's WebSocket endpoint (``ws://`` or ``wss://``).

    Args:
        url: The ``/acp`` endpoint.
        headers: Extra headers for the upgrade request (e.g. authentication).
        open_timeout: Timeout for the opening handshake.

    Yields:
        (reader, writer) byte streams.

    Raises:
        WebSocketTransportError: The server rejected the upgrade or is unreachable.
    """
    from websockets.asyncio.client import connect
    from websockets.exceptions import InvalidHandshake, InvalidStatus

    try:
        websocket = await connect(
            url,
            additional_headers=dict(headers or {}),
            open_timeout=open_timeout,
            max_size=MAX_MESSAGE_BYTES,
        )
    except InvalidStatus as exc:
        response = exc.response
        body = response.body.decode(errors="replace")[:200] if response.body else ""
        msg = f"ACP WebSocket upgrade rejected ({response.status_code}): {body}".rstrip(": ")
        raise WebSocketTransportError(msg) from exc
    except (InvalidHandshake, OSError, TimeoutError) as exc:
        raise WebSocketTransportError(f"ACP WebSocket connection failed: {exc}") from exc
    if websocket.response is not None:
        connection_id = websocket.response.headers.get(HEADER_CONNECTION_ID)
        logger.debug("ACP WebSocket connected (%s)", connection_id or "no connection ID")
    try:
        yield _FrameReader(websocket), _FrameWriter(websocket)
    finally:
        await websocket.close()

run_agent async

run_agent(
    agent: Agent | Callable[[AgentSideConnection], Agent],
    input_stream: ByteSendStream | None = None,
    output_stream: ByteReceiveStream | None = None,
    **connection_kwargs: Any,
) -> None

Run an ACP agent over stdio or provided streams.

This is the recommended entry point for running agents. It handles stream setup and connection lifecycle automatically, and returns once the client disconnects (or raises when cancelled).

Parameters:

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

An Agent implementation or a factory callable that takes an AgentSideConnection and returns an Agent. Using a factory allows the agent to access the connection for client communication.

required
input_stream ByteSendStream | None

ByteSendStream the agent writes to (defaults to stdout).

None
output_stream ByteReceiveStream | None

ByteReceiveStream the agent reads from (defaults to stdin).

None
**connection_kwargs Any

Additional keyword arguments for AgentSideConnection.

{}
Example with direct agent
class MyAgent(Agent):
    async def initialize(self, params: InitializeRequest) -> InitializeResponse:
        return InitializeResponse(protocol_version=params.protocol_version)
    # ... implement protocol methods ...

await run_agent(MyAgent())
Example with factory
class MyAgent(Agent):
    def __init__(self, connection: AgentSideConnection):
        self.connection = connection
    # ... implement protocol methods ...

def create_agent(conn: AgentSideConnection) -> MyAgent:
    return MyAgent(conn)

await run_agent(create_agent)
Source code in src/aclientp/stdio.py
async def run_agent(
    agent: Agent | Callable[[AgentSideConnection], Agent],
    input_stream: ByteSendStream | None = None,
    output_stream: ByteReceiveStream | None = None,
    **connection_kwargs: Any,
) -> None:
    """Run an ACP agent over stdio or provided streams.

    This is the recommended entry point for running agents. It handles stream
    setup and connection lifecycle automatically, and returns once the client
    disconnects (or raises when cancelled).

    Args:
        agent: An Agent implementation or a factory callable that takes
            an AgentSideConnection and returns an Agent. Using a factory allows
            the agent to access the connection for client communication.
        input_stream: ByteSendStream the agent writes to (defaults to stdout).
        output_stream: ByteReceiveStream the agent reads from (defaults to stdin).
        **connection_kwargs: Additional keyword arguments for AgentSideConnection.

    Example with direct agent:
        ```python
        class MyAgent(Agent):
            async def initialize(self, params: InitializeRequest) -> InitializeResponse:
                return InitializeResponse(protocol_version=params.protocol_version)
            # ... implement protocol methods ...

        await run_agent(MyAgent())
        ```

    Example with factory:
        ```python
        class MyAgent(Agent):
            def __init__(self, connection: AgentSideConnection):
                self.connection = connection
            # ... implement protocol methods ...

        def create_agent(conn: AgentSideConnection) -> MyAgent:
            return MyAgent(conn)

        await run_agent(create_agent)
        ```
    """
    if (input_stream is None) != (output_stream is None):
        msg = "Pass both input_stream and output_stream, or neither to use stdio"
        raise ValueError(msg)
    if input_stream is None or output_stream is None:
        output_stream, input_stream = await stdio_streams()

    conn = AgentSideConnection(agent, input_stream, output_stream, **connection_kwargs)
    try:
        await conn.wait_closed()
    finally:
        await conn.close()

serve async

serve(
    agent: V1AgentSource | None = None,
    transport: Transport = "stdio",
    *,
    v2_agent: V2AgentSource | None = None,
    shutdown_event: Event | None = None,
    debug_file: str | None = None,
    observers: list[StreamObserver] | None = None,
) -> None

Run an ACP agent with the specified transport.

This is the main entry point for running ACP agents. It handles transport setup and lifecycle management automatically.

With only agent, every client is served by that v1 agent. With v2_agent, each client connection is routed on initialize (:class:~aclientp.router.RoutedAgentConnection): clients asking for v2 or later get the v2 agent, others the v1 agent (if given).

Parameters:

Name Type Description Default
agent V1AgentSource | None

The v1 agent, or a factory that takes an AgentSideConnection and returns one.

None
transport Transport

Transport configuration. Can be: - "stdio" or StdioTransport(): Use stdin/stdout - "websocket" or WebSocketTransport(...): Run WebSocket server - StreamTransport(...): Use custom streams

'stdio'
v2_agent V2AgentSource | None

The v2 agent, or a factory that takes a v2 AgentSideConnection and returns one.

None
shutdown_event Event | None

Optional event to signal shutdown. If not provided, runs until cancelled.

None
debug_file str | None

Optional file path for debug message logging.

None
observers list[StreamObserver] | None

Observers of the raw messages of each connection.

None
Example
# Stdio (default)
await serve(MyAgent())

# WebSocket server
await serve(MyAgent(), WebSocketTransport(host="0.0.0.0", port=9000))

# v1 and v2 clients on one endpoint
await serve(MyAgent(), v2_agent=MyV2Agent)

# With shutdown control
shutdown = asyncio.Event()
task = asyncio.create_task(serve(MyAgent(), shutdown_event=shutdown))
# ... later ...
shutdown.set()
await task
Source code in src/aclientp/transports.py
async def serve(
    agent: V1AgentSource | None = None,
    transport: Transport = "stdio",
    *,
    v2_agent: V2AgentSource | None = None,
    shutdown_event: asyncio.Event | None = None,
    debug_file: str | None = None,
    observers: list[StreamObserver] | None = None,
) -> None:
    """Run an ACP agent with the specified transport.

    This is the main entry point for running ACP agents. It handles transport
    setup and lifecycle management automatically.

    With only ``agent``, every client is served by that v1 agent. With ``v2_agent``,
    each client connection is routed on ``initialize``
    (:class:`~aclientp.router.RoutedAgentConnection`): clients asking for v2 or later
    get the v2 agent, others the v1 agent (if given).

    Args:
        agent: The v1 agent, or a factory that takes an AgentSideConnection and
            returns one.
        transport: Transport configuration. Can be:
            - "stdio" or StdioTransport(): Use stdin/stdout
            - "websocket" or WebSocketTransport(...): Run WebSocket server
            - StreamTransport(...): Use custom streams
        v2_agent: The v2 agent, or a factory that takes a v2 AgentSideConnection and
            returns one.
        shutdown_event: Optional event to signal shutdown. If not provided,
            runs until cancelled.
        debug_file: Optional file path for debug message logging.
        observers: Observers of the raw messages of each connection.

    Example:
        ```python
        # Stdio (default)
        await serve(MyAgent())

        # WebSocket server
        await serve(MyAgent(), WebSocketTransport(host="0.0.0.0", port=9000))

        # v1 and v2 clients on one endpoint
        await serve(MyAgent(), v2_agent=MyV2Agent)

        # With shutdown control
        shutdown = asyncio.Event()
        task = asyncio.create_task(serve(MyAgent(), shutdown_event=shutdown))
        # ... later ...
        shutdown.set()
        await task
        ```
    """
    if agent is None and v2_agent is None:
        msg = "serve() needs a v1 agent, a v2 agent, or both"
        raise ValueError(msg)
    spec = _AgentSpec(v1=agent, v2=v2_agent, debug_file=debug_file, observers=observers)
    # Normalize string shortcuts to config objects
    match transport:
        case "stdio":
            transport = StdioTransport()
        case "websocket":
            transport = WebSocketTransport()
        case "http":
            transport = HttpTransport()

    # Dispatch to appropriate runner
    match transport:
        case StdioTransport():
            await _serve_stdio(spec, shutdown_event)
        case WebSocketTransport(host=host, port=port):
            await _serve_websocket(spec, host, port, shutdown_event)
        case HttpTransport():
            await _serve_http(spec, transport, shutdown_event)
        case StreamTransport(reader=reader, writer=writer):
            await _serve_streams(spec, reader, writer, shutdown_event)
        case _ as unreachable:
            assert_never(unreachable)

stdio_streams async

stdio_streams() -> tuple[StdinStream, StdoutStream]

Create stdio anyio-compatible streams (cross-platform).

Returns (stdin, stdout) as byte stream wrappers compatible with ByteReceiveStream and ByteSendStream interfaces.

Source code in src/aclientp/stdio.py
async def stdio_streams() -> tuple[StdinStream, StdoutStream]:
    """Create stdio anyio-compatible streams (cross-platform).

    Returns (stdin, stdout) as byte stream wrappers compatible with
    ByteReceiveStream and ByteSendStream interfaces.
    """
    return StdinStream(), StdoutStream()