Skip to content

transports

Class info

Classes

Name Children Inherits
HttpTransport
aclientp.transports
Configuration for the Streamable HTTP & WebSocket server transport (experimental).
    StdioTransport
    aclientp.transports
    Configuration for stdio transport.
      StreamTransport
      aclientp.transports
      Configuration for custom stream transport.
        WebSocketTransport
        aclientp.transports
        Configuration for WebSocket server transport.

          🛈 DocStrings

          Transport abstractions for ACP agents.

          This module provides transport configuration classes and utilities for running ACP agents over different transports (stdio, WebSocket, etc.).

          V1AgentSource

          V1AgentSource = Agent | Callable[[AgentSideConnection], Agent]
          

          A v1 agent, or a factory receiving its connection.

          V2AgentSource

          V2AgentSource = Agent | Callable[[AgentSideConnection], Agent]
          

          A v2 agent, or a factory receiving its connection.

          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
          

          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
          

          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
          

          default_environment

          default_environment() -> dict[str, str]
          

          Return a trimmed environment based on MCP best practices.

          Source code in src/aclientp/transports.py
          def default_environment() -> dict[str, str]:
              """Return a trimmed environment based on MCP best practices."""
              env: dict[str, str] = {}
              for key in DEFAULT_INHERITED_ENV_VARS:
                  value = os.environ.get(key)
                  if value is None:
                      continue
                  # Skip function-style env vars on some shells (see MCP reference)
                  if value.startswith("()"):
                      continue
                  env[key] = value
              return env
          

          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)
          

          spawn_stdio_transport async

          spawn_stdio_transport(
              command: str,
              *args: str,
              env: Mapping[str, str] | None = None,
              cwd: str | Path | None = None,
              stderr: int | None = PIPE,
              shutdown_timeout: float = 2.0,
              log_stderr: bool = False,
              stderr_log_level: int = WARNING,
              on_stderr: Callable[[str], object] | None = None,
          ) -> AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream, Process]]
          

          Launch a subprocess and expose its stdio streams as anyio streams.

          This mirrors the defensive shutdown behaviour used by the MCP Python SDK: close stdin first, wait for graceful exit, then escalate to terminate/kill.

          Parameters:

          Name Type Description Default
          command str

          The command to execute.

          required
          *args str

          Arguments for the command.

          ()
          env Mapping[str, str] | None

          Environment variables (merged with defaults).

          None
          cwd str | Path | None

          Working directory for the subprocess.

          None
          stderr int | None

          How to handle stderr (default: subprocess.PIPE).

          PIPE
          shutdown_timeout float

          Timeout for graceful shutdown.

          2.0
          log_stderr bool

          If True, read stderr in background and log each line.

          False
          stderr_log_level int

          Log level for stderr output (default WARNING).

          WARNING
          on_stderr Callable[[str], object] | None

          Called with each stderr line (read in background), e.g. to show it in a UI.

          None

          With stderr=PIPE (the default), stderr is always read in the background, so an agent writing a lot to it can never block on a full pipe: lines go to on_stderr and / or the log, and are discarded otherwise. To read process.stderr yourself, pass another stderr (e.g. a file) instead.

          Source code in src/aclientp/transports.py
          @asynccontextmanager
          async def spawn_stdio_transport(
              command: str,
              *args: str,
              env: Mapping[str, str] | None = None,
              cwd: str | Path | None = None,
              stderr: int | None = subprocess.PIPE,
              shutdown_timeout: float = 2.0,
              log_stderr: bool = False,
              stderr_log_level: int = logging.WARNING,
              on_stderr: Callable[[str], object] | None = None,
          ) -> AsyncGenerator[tuple[ByteReceiveStream, ByteSendStream, Process]]:
              """Launch a subprocess and expose its stdio streams as anyio streams.
          
              This mirrors the defensive shutdown behaviour used by the MCP Python SDK:
              close stdin first, wait for graceful exit, then escalate to terminate/kill.
          
              Args:
                  command: The command to execute.
                  *args: Arguments for the command.
                  env: Environment variables (merged with defaults).
                  cwd: Working directory for the subprocess.
                  stderr: How to handle stderr (default: subprocess.PIPE).
                  shutdown_timeout: Timeout for graceful shutdown.
                  log_stderr: If True, read stderr in background and log each line.
                  stderr_log_level: Log level for stderr output (default WARNING).
                  on_stderr: Called with each stderr line (read in background), e.g. to show
                      it in a UI.
          
              With ``stderr=PIPE`` (the default), stderr is always read in the background, so
              an agent writing a lot to it can never block on a full pipe: lines go to
              ``on_stderr`` and / or the log, and are discarded otherwise. To read
              ``process.stderr`` yourself, pass another ``stderr`` (e.g. a file) instead.
              """
              merged_env = default_environment()
              if env:
                  merged_env.update(env)
          
              process = await anyio.open_process(
                  [command, *args],
                  stdin=subprocess.PIPE,
                  stdout=subprocess.PIPE,
                  stderr=stderr,
                  env=merged_env,
                  cwd=str(cwd) if cwd is not None else None,
              )
          
              if process.stdout is None or process.stdin is None:
                  process.kill()
                  await process.wait()
                  raise RuntimeError("spawn_stdio_transport requires stdout/stdin pipes")
          
              stderr_task: asyncio.Task[None] | None = None
              if process.stderr is not None and stderr == subprocess.PIPE:
                  stderr_task = asyncio.create_task(
                      _drain_stderr_to_log(
                          process, command, stderr_log_level, log=log_stderr, on_stderr=on_stderr
                      )
                  )
          
              try:
                  yield process.stdout, process.stdin, process
              finally:
                  await _shutdown_process(process, shutdown_timeout)
                  # The process is gone: read what is left of stderr (e.g. a crash message)
                  # before stopping the reader.
                  if stderr_task is not None:
                      with contextlib.suppress(TimeoutError, asyncio.CancelledError):
                          await asyncio.wait_for(asyncio.shield(stderr_task), shutdown_timeout)
                      stderr_task.cancel()
                      with contextlib.suppress(asyncio.CancelledError):
                          await stderr_task