@dataclass
class AcpHttpServer:
"""ASGI app serving ACP over Streamable HTTP and WebSocket on one endpoint."""
serve_connection: ServeConnection
"""Runs the agent for one connection."""
path: str = "/acp"
authenticate: Authenticate | None = None
"""Caller identification; None accepts everyone (local use only)."""
allow_origins: list[str] = field(default_factory=list)
"""CORS origins for browser clients."""
max_buffered_bytes: int = DEFAULT_MAX_BUFFERED_BYTES
"""Output a connection may hold for its client before the agent has to wait."""
max_output_stall: float = DEFAULT_MAX_OUTPUT_STALL_SECONDS
"""Seconds a client may take nothing while over the limit before it is dropped."""
connections: dict[str, _Connection] = field(default_factory=dict)
def app(self) -> Starlette:
"""The Starlette application."""
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.routing import Route as HttpRoute, WebSocketRoute
routes = [
HttpRoute(self.path, self._http, methods=["POST", "GET", "DELETE"]),
WebSocketRoute(self.path, self._websocket),
]
middleware = []
if self.allow_origins:
middleware.append(
Middleware(
CORSMiddleware,
allow_origins=self.allow_origins,
allow_methods=["GET", "POST", "DELETE"],
allow_headers=["*"],
expose_headers=["Acp-Connection-Id"],
)
)
@contextlib.asynccontextmanager
async def lifespan(_app: Starlette) -> AsyncGenerator[None]:
try:
yield
finally:
await self.close()
return Starlette(routes=routes, middleware=middleware, lifespan=lifespan)
async def close(self) -> None:
"""End all connections."""
for connection in list(self.connections.values()):
await self._remove(connection)
# --- connections ------------------------------------------------------------------
def _open(self, owner: str) -> tuple[_Connection, MemoryObjectReceiveStream[bytes]]:
send, receive = anyio.create_memory_object_stream[bytes](max_buffer_size=1024)
backlog = _Backlog(self.max_buffered_bytes, self.max_output_stall)
connection = _Connection(
connection_id=str(uuid.uuid4()), owner=owner, to_agent=send, backlog=backlog
)
self.connections[connection.connection_id] = connection
return connection, receive
def _output(
self, connection: _Connection, deliver: Callable[[JsonMessage], None]
) -> _AgentOutput:
"""The agent's output for a connection; a stalled client drops the connection."""
def on_stall() -> None:
logger.warning(
"Closing ACP connection %s: the client took no output for %ss",
connection.connection_id,
self.max_output_stall,
)
asyncio.get_running_loop().create_task(self._remove(connection))
return _AgentOutput(deliver, connection.backlog, on_stall)
def _start(
self, connection: _Connection, agent_input: ByteReceiveStream, output: ByteSendStream
) -> None:
async def run() -> None:
try:
await self.serve_connection(agent_input, output)
except Exception:
logger.exception("ACP connection %s failed", connection.connection_id)
finally:
connection.finish()
self.connections.pop(connection.connection_id, None)
connection.task = asyncio.create_task(run(), name=f"acp-http-{connection.connection_id}")
async def _remove(self, connection: _Connection) -> None:
self.connections.pop(connection.connection_id, None)
connection.finish()
await connection.to_agent.aclose() # EOF: the agent connection closes
if (task := connection.task) is not None:
try:
async with asyncio.timeout(5):
await asyncio.shield(task)
except TimeoutError:
task.cancel()
async def _caller(self, conn: HTTPConnection) -> str | None:
if self.authenticate is None:
return "anonymous"
return await self.authenticate(conn)
def _owned(self, connection_id: str | None, owner: str) -> _Connection | None:
"""The caller's connection (other callers' connections look unknown)."""
if connection_id is None:
return None
connection = self.connections.get(connection_id)
return connection if connection is not None and connection.owner == owner else None
# --- HTTP -------------------------------------------------------------------------
async def _http(self, request: Request) -> Response:
owner = await self._caller(request)
if owner is None:
return _text("Unauthorized", 401)
match request.method:
case "POST":
return await self._post(request, owner)
case "GET":
return self._get(request, owner)
case "DELETE":
connection = self._owned(request.headers.get(HEADER_CONNECTION_ID), owner)
if connection is None:
return _text("Unknown Acp-Connection-Id", 404)
await self._remove(connection)
return _text("", 202)
case _:
return _text("Method Not Allowed", 405)
@staticmethod
async def _read_message(request: Request) -> JsonMessage | Response:
"""The POSTed JSON-RPC message, or the error response for an invalid body."""
from starlette.responses import JSONResponse
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if content_type != JSON_MIME_TYPE:
return _text("Unsupported Media Type", 415)
try:
message = anyenv.load_json(await request.body())
except anyenv.JsonLoadError:
return _text("Invalid JSON", 400)
if isinstance(message, list):
error = {"code": -32600, "message": "JSON-RPC batches are not supported"}
return JSONResponse({"jsonrpc": "2.0", "id": None, "error": error}, status_code=400)
if not isinstance(message, dict):
return _text("Invalid JSON-RPC message", 400)
return message
async def _post(self, request: Request, owner: str) -> Response:
message = await self._read_message(request)
if not isinstance(message, dict):
return message
connection_id = request.headers.get(HEADER_CONNECTION_ID)
if message.get("method") == "initialize" and _is_request(message):
if connection_id is not None:
return _text("Initialize not allowed on existing connection", 400)
return await self._initialize(message, owner)
return await self._forward(request, message, owner, connection_id)
async def _forward(
self, request: Request, message: JsonMessage, owner: str, connection_id: str | None
) -> Response:
"""Pass a message of an existing connection to its agent (202)."""
if connection_id is None:
return _text("Missing Acp-Connection-Id", 400)
connection = self._owned(connection_id, owner)
if connection is None or connection.closed:
return _text("Unknown Acp-Connection-Id", 404)
header_session = request.headers.get(HEADER_SESSION_ID)
if _is_response(message):
error = self._route_client_response(connection, message, header_session)
else:
error = self._route_client_message(connection, message, header_session)
if error is not None:
return _text(error, 400)
await connection.send_to_agent(message)
return _text("", 202)
@staticmethod
def _route_client_message(
connection: _Connection, message: JsonMessage, header_session: str | None
) -> str | None:
params_session = _params_session_id(message)
method = message.get("method")
needs_header = method in SESSION_SCOPED_METHODS or params_session is not None
if needs_header and header_session is None:
return "Missing Acp-Session-Id"
if (
header_session is not None
and params_session is not None
and header_session != params_session
):
return "Mismatched Acp-Session-Id"
route = header_session or params_session
if route is not None:
connection.known_sessions.add(route)
if _is_request(message) and (key := _id_key(message.get("id"))) is not None:
connection.pending_routes[key] = None if method == "session/load" else route
return None
@staticmethod
def _route_client_response(
connection: _Connection, message: JsonMessage, header_session: str | None
) -> str | None:
key = _id_key(message.get("id"))
if key is None or key not in connection.client_response_routes:
return None
route = connection.client_response_routes[key]
if route is not None and header_session is None:
return "Missing Acp-Session-Id"
if route is not None and header_session != route:
return "Mismatched Acp-Session-Id"
del connection.client_response_routes[key]
return None
async def _initialize(self, message: JsonMessage, owner: str) -> Response:
from starlette.responses import JSONResponse
connection, agent_input = self._open(owner)
connection.initial_response = asyncio.get_running_loop().create_future()
output = self._output(connection, connection.deliver)
self._start(connection, _AgentInput(agent_input), output)
try:
await connection.send_to_agent(message)
async with asyncio.timeout(INITIALIZE_TIMEOUT_SECONDS):
response = await connection.initial_response
except (TimeoutError, ConnectionError) as exc:
await self._remove(connection)
error = {"code": -32603, "message": "Initialize failed", "data": str(exc)}
body = {"jsonrpc": "2.0", "id": message.get("id"), "error": error}
return JSONResponse(body, status_code=500)
connection.initial_response = None
if "error" in response:
await self._remove(connection)
return JSONResponse(response, status_code=200)
headers = {"Acp-Connection-Id": connection.connection_id}
return JSONResponse(response, status_code=200, headers=headers)
def _get(self, request: Request, owner: str) -> Response:
from starlette.responses import StreamingResponse
if EVENT_STREAM_MIME_TYPE not in request.headers.get("accept", "").lower():
return _text("Not Acceptable", 406)
connection_id = request.headers.get(HEADER_CONNECTION_ID)
if connection_id is None:
return _text("Missing Acp-Connection-Id", 400)
connection = self._owned(connection_id, owner)
if connection is None:
return _text("Unknown Acp-Connection-Id", 404)
session_id = request.headers.get(HEADER_SESSION_ID)
if session_id is not None:
connection.known_sessions.add(session_id)
stream = (
connection.connection_stream
if session_id is None
else connection.session_stream(session_id)
)
if stream.has_receiver:
return _text("Outbound stream already has an active receiver", 409)
stream.has_receiver = True
async def events() -> AsyncIterator[bytes]:
try:
yield b":\n\n"
while (text := await stream.receive(KEEPALIVE_SECONDS)) is not None:
yield f"data: {text}\n\n".encode() if text else b":\n\n"
finally:
stream.has_receiver = False
headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}
return StreamingResponse(events(), media_type=EVENT_STREAM_MIME_TYPE, headers=headers)
# --- WebSocket --------------------------------------------------------------------
async def _websocket(self, websocket: WebSocket) -> None:
from starlette.websockets import WebSocketDisconnect
owner = await self._caller(websocket)
if owner is None:
# A real 401 where the server supports denial responses (uvicorn does)
if "websocket.http.response" in websocket.scope.get("extensions", {}):
await websocket.send_denial_response(_text("Unauthorized", 401))
else:
await websocket.close(code=1008, reason="Unauthorized")
return
connection, agent_input = self._open(owner)
# Everything goes out on the socket in order; using the connection stream means
# ending the connection (agent gone, client stalled) also closes the socket.
outbox = connection.connection_stream
def deliver(message: JsonMessage) -> None:
outbox.push(anyenv.dump_json(message))
self._start(connection, _AgentInput(agent_input), self._output(connection, deliver))
await websocket.accept(headers=[(b"acp-connection-id", connection.connection_id.encode())])
async def pump_out() -> None:
while (text := await outbox.receive(KEEPALIVE_SECONDS)) is not None:
if text: # "" is a keep-alive tick; the socket pings by itself
await websocket.send_text(text)
await websocket.close()
sender = asyncio.create_task(pump_out())
try:
while True:
frame = await websocket.receive()
if frame["type"] == "websocket.disconnect":
break
text = frame.get("text")
if text is None:
continue # Binary frames are ignored
try:
message = anyenv.load_json(text)
except anyenv.JsonLoadError:
continue
if isinstance(message, list):
error = {"code": -32600, "message": "JSON-RPC batches are not supported"}
outbox.push(anyenv.dump_json({"jsonrpc": "2.0", "id": None, "error": error}))
continue
if isinstance(message, dict):
await connection.send_to_agent(message)
except WebSocketDisconnect:
pass
finally:
outbox.finish()
sender.cancel()
with contextlib.suppress(asyncio.CancelledError, Exception):
await sender
await self._remove(connection)