Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(agent-platform): agent-applications invoke/send/listen MCP tools (#69846)

Aidan Zarski7f10e49690c3
diff --git a/products/agent_platform/backend/logic/ingress_client.py b/products/agent_platform/backend/logic/ingress_client.py
new file mode 100644
index 000000000000..d522af81892f
--- /dev/null
+++ b/products/agent_platform/backend/logic/ingress_client.py
@@ -0,0 +1,120 @@
+"""
+Thin HTTP client for the agent-ingress service — the LIVE (promoted-revision)
+runtime surface behind the `agent-invoke` / `agent-send` / `agent-listen` MCP
+tools. Two auth stances:
+
+ - run() / send() forward the CALLER's PAT (`Authorization: Bearer …`) so the
+ ingress `posthog` auth mode re-introspects it and the session principal is
+ the real caller — preserving ACL on later send/listen. See
+ services/agent-ingress/src/enqueue/auth.ts.
+ - session_digest() is an internal read RPC: a short-lived aud=`agent-ingress.rpc`
+ JWT sent as `x-internal-secret`, the same idiom the janitor client uses.
+
+Base URL comes from the `AGENT_INGRESS_URL` env var (default
+http://localhost:3030), matching the preview-proxy in presentation/views.py.
+"""
+
+from __future__ import annotations
+
+import os
+import logging
+from datetime import timedelta
+from typing import Any
+
+from django.conf import settings
+
+import requests
+
+from posthog.security.outbound_proxy import internal_requests
+
+from .internal_jwt import AgentInternalAudience, encode_agent_internal_jwt
+
+logger = logging.getLogger(__name__)
+
+
+class IngressClientError(Exception):
+ """Wraps non-2xx ingress responses + transport failures so view code can
+ map them to DRF responses with a single except clause (mirrors
+ JanitorClientError)."""
+
+ def __init__(self, status_code: int, message: str, body: Any | None = None) -> None:
+ super().__init__(message)
+ self.status_code = status_code
+ self.message = message
+ self.body = body
+
+
+class IngressClient:
+ def __init__(self, base_url: str | None = None, timeout: float = 30.0) -> None:
+ # Same source as the preview-proxy (presentation/views.py): the
+ # `AGENT_INGRESS_URL` env var, default http://localhost:3030.
+ self.base_url = (base_url or os.environ.get("AGENT_INGRESS_URL", "http://localhost:3030")).rstrip("/")
+ self.timeout = timeout
+
+ def _call(self, method: str, path: str, *, headers: dict[str, str], **kwargs: Any) -> Any:
+ url = f"{self.base_url}{path}"
+ try:
+ # In-cluster service — the internal session bypasses HTTP(S)_PROXY
+ # (smokescreen blocks private IPs → 407), same as janitor_client.
+ resp = internal_requests.request(method, url, headers=headers, timeout=self.timeout, **kwargs)
+ except requests.RequestException as e:
+ logger.exception("ingress request failed")
+ raise IngressClientError(502, f"ingress unreachable: {e}") from e
+ if resp.status_code >= 400:
+ try:
+ body = resp.json()
+ except ValueError:
+ body = None
+ raise IngressClientError(resp.status_code, f"ingress returned {resp.status_code}", body=body)
+ if not resp.content:
+ return {}
+ return resp.json()
+
+ @staticmethod
+ def _forward_headers(authorization: str | None) -> dict[str, str]:
+ # Forward the caller's PAT verbatim: ingress's `posthog` auth mode
+ # re-introspects it so the session principal is the real caller.
+ h = {"content-type": "application/json"}
+ if authorization:
+ h["authorization"] = authorization
+ return h
+
+ @staticmethod
+ def _internal_headers() -> dict[str, str]:
+ h = {"content-type": "application/json"}
+ if settings.AGENT_INTERNAL_SIGNING_KEY:
+ token = encode_agent_internal_jwt(
+ {"sub": "django"},
+ timedelta(seconds=60),
+ AgentInternalAudience.INGRESS_RPC,
+ )
+ h["x-internal-secret"] = token
+ return h
+
+ # ── LIVE public routes: forward the caller PAT ───────────────────────────
+
+ def run(self, slug: str, *, message: str, external_key: str | None, authorization: str | None) -> dict:
+ body: dict[str, Any] = {"message": message}
+ if external_key:
+ body["external_key"] = external_key
+ return self._call("POST", f"/agents/{slug}/run", headers=self._forward_headers(authorization), json=body)
+
+ def send(self, slug: str, *, session_id: str, message: str, authorization: str | None) -> dict:
+ return self._call(
+ "POST",
+ f"/agents/{slug}/send",
+ headers=self._forward_headers(authorization),
+ json={"session_id": session_id, "message": message},
+ )
+
+ # ── internal read RPC: session digest ────────────────────────────────────
+
+ def session_digest(
+ self, *, application_id: str, session_id: str, cursor: int | None, max_chars: int | None
+ ) -> dict:
+ body: dict[str, Any] = {"application_id": application_id, "session_id": session_id}
+ if cursor is not None:
+ body["cursor"] = cursor
+ if max_chars is not None:
+ body["max_chars"] = max_chars
+ return self._call("POST", "/internal/session-digest", headers=self._internal_headers(), json=body)
diff --git a/products/agent_platform/backend/logic/internal_jwt.py b/products/agent_platform/backend/logic/internal_jwt.py
index af9a69fb858d..002f0f732238 100644
--- a/products/agent_platform/backend/logic/internal_jwt.py
+++ b/products/agent_platform/backend/logic/internal_jwt.py
@@ -20,6 +20,7 @@ class AgentInternalAudience(Enum):
"""
INGRESS_PREVIEW = "agent-ingress.preview"
+ INGRESS_RPC = "agent-ingress.rpc"
JANITOR_RPC = "agent-janitor.rpc"
diff --git a/products/agent_platform/backend/presentation/serializers.py b/products/agent_platform/backend/presentation/serializers.py
index 48b77e2ede31..8b39ceb28ad0 100644
--- a/products/agent_platform/backend/presentation/serializers.py
+++ b/products/agent_platform/backend/presentation/serializers.py
@@ -701,3 +701,28 @@ class PreviewProxyInvokeRequestSerializer(serializers.Serializer):
required=False,
help_text="Target session id for `send` — the running session to append the message to. Omit for `run` (a fresh session is created).",
)
+
+
+class AgentInvokeRequestSerializer(serializers.Serializer):
+ """Body for `agent-applications-invoke` — start a new session on the agent's live (promoted) revision."""
+
+ message = serializers.CharField(
+ trim_whitespace=False,
+ help_text="The user message that starts the session. Required, non-empty.",
+ )
+ external_key = serializers.CharField(
+ required=False,
+ help_text="Optional idempotency / threading key. A repeat invoke with the same external_key resumes the existing session instead of starting a new one.",
+ )
+
+
+class AgentSendRequestSerializer(serializers.Serializer):
+ """Body for `agent-applications-send` — append a message to an existing live session."""
+
+ session_id = serializers.UUIDField(
+ help_text="The session to append to (returned by agent-applications-invoke). Must belong to this agent.",
+ )
+ message = serializers.CharField(
+ trim_whitespace=False,
+ help_text="The user message to append. Required, non-empty.",
+ )
diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.py
index 7575edf606fd..5c9d9ece58e3 100644
--- a/products/agent_platform/backend/presentation/views.py
+++ b/products/agent_platform/backend/presentation/views.py
@@ -53,7 +53,7 @@ from rest_framework import (
viewsets,
)
from rest_framework.decorators import action
-from rest_framework.exceptions import APIException, NotFound, ValidationError
+from rest_framework.exceptions import APIException, AuthenticationFailed, NotFound, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.settings import api_settings
@@ -73,6 +73,7 @@ from posthog.security.outbound_proxy import internal_requests
from ..db import WRITER_DB
from ..logic.generated import APPROVAL_REQUEST_STATES, ASSISTANT_STOP_REASONS, TRIGGER_ROUTES
+from ..logic.ingress_client import IngressClient, IngressClientError
from ..logic.internal_jwt import AgentInternalAudience, encode_agent_internal_jwt
from ..logic.janitor_client import JanitorClient, JanitorClientError, default_client
from ..logic.kernel_skills import all_kernel_skill_ids, kernel_skills_for
@@ -92,7 +93,9 @@ from ..models import AgentApplication, AgentIdentityCredential, AgentRevision
from .serializers import (
MAX_SKILL_REFS,
AgentApplicationSerializer,
+ AgentInvokeRequestSerializer,
AgentRevisionSerializer,
+ AgentSendRequestSerializer,
CloneFromRequestSerializer,
DecideApprovalRequestSerializer,
DryRunToolRequestSerializer,
@@ -140,6 +143,23 @@ def _janitor() -> JanitorClient:
return default_client()
+def _ingress() -> IngressClient:
+ """Indirection so tests can monkey-patch. The client is stateless, so (unlike
+ `_janitor()`'s singleton) this news up a fresh instance per call."""
+ return IngressClient()
+
+
+def _require_ingress_bearer(request: Request) -> str:
+ authorization = request.headers.get("Authorization")
+ if isinstance(request.successful_authenticator, SessionAuthentication) or not authorization:
+ raise AuthenticationFailed(
+ "Authenticate with a personal API key in the Authorization header to invoke or send messages to an agent."
+ )
+ if re.fullmatch(r"Bearer\s+\S+", authorization) is None:
+ raise AuthenticationFailed("The Authorization header must contain a bearer token.")
+ return authorization
+
+
# Mirrors `RESOURCE_ID_REGEX` in
# services/agent-shared/src/storage/typed-bundle.ts. The janitor enforces this
# regex on every PUT /skills/<id>; pre-checking on the Django side turns a
@@ -249,6 +269,108 @@ class JanitorUpstreamError(APIException):
super().__init__(detail=detail_str)
+class IngressUpstreamError(APIException):
+ """DRF-friendly wrapper for non-2xx ingress responses. Preserves 4xx (so a
+ caller sees a clean 401/403/404/422), clamps 5xx to a single 502. Mirrors
+ JanitorUpstreamError, minus the janitor's structured sub-error flattening —
+ ingress error bodies are the flat `{ "error": <code>, ... }` shape."""
+
+ status_code: int = status.HTTP_502_BAD_GATEWAY
+ default_detail = "Upstream ingress service error"
+ default_code = "ingress_upstream"
+
+ def __init__(self, e: IngressClientError) -> None:
+ if 400 <= e.status_code < 500:
+ self.status_code = e.status_code
+ # A preserved upstream 4xx is a CLIENT error — label it as such (exceptions_hog
+ # keys `type` off the exception class, and a bare APIException defaults to
+ # `server_error`, which would page on-call and pollute error monitoring). A
+ # clamped 5xx (502) keeps the default `server_error` — that one really is ours.
+ self.exception_type = "invalid_request"
+ if isinstance(e.body, dict):
+ detail_str: str = e.body.get("error") or e.body.get("detail") or e.body.get("message") or json.dumps(e.body)
+ elif isinstance(e.body, str):
+ detail_str = e.body
+ else:
+ detail_str = e.message
+ super().__init__(detail=detail_str)
+
+
+class ElevationRequiredError(APIException):
+ """A non-owner tried to act on someone else's session and must run the elevation
+ flow first. This is an EXPECTED client condition, so it renders a clean
+ `authentication_error`/`elevation_required` (like DRF's own PermissionDenied) rather
+ than the bare-APIException `server_error`/`error` that pages on-call. The actionable
+ fields (which approval request, which session) are carried in the detail message."""
+
+ status_code = status.HTTP_403_FORBIDDEN
+ default_detail = "You are not the owner of this session; elevation is required to act on it."
+ default_code = "elevation_required"
+ default_type = "authentication_error"
+
+
+class SessionGoneError(APIException):
+ """The target session is terminal (failed / cancelled / closed-without-restart) and
+ can't accept more messages. A 410 is an EXPECTED client condition, so it renders a
+ clean `invalid_request`/`session_gone` instead of the bare-APIException
+ `server_error`/`error`. Preserves the terminal state in the detail message."""
+
+ status_code = status.HTTP_410_GONE
+ default_detail = "This session is terminal and can't accept more messages."
+ default_code = "session_gone"
+ default_type = "invalid_request"
+
+
+def _map_ingress_error(
+ e: IngressClientError, *, not_found_detail: str = "Session not found in this application"
+) -> APIException:
+ """Map an ingress failure to a clean DRF exception — never a bare 500.
+
+ The slack/cron-only "no chat trigger" 404 is reframed as a 400 (it isn't a
+ missing agent), and the 403 `elevation_required` keeps its actionable fields.
+ The terminal-session 410 passes THROUGH as 410 (preserve 4xx doctrine), and
+ everything else preserves the upstream 4xx or clamps 5xx to 502.
+ `not_found_detail` lets each action phrase a plain 404 for its own context
+ (invoke has no session).
+ """
+ body = e.body if isinstance(e.body, dict) else {}
+ code = body.get("error")
+ # slack/cron-only agent → chat routes 404 `no_chat_trigger` (ingress mount.ts).
+ # Reframe so it doesn't read as "agent not found".
+ if e.status_code == 404 and code == "no_chat_trigger":
+ return ValidationError(
+ "This agent has no chat trigger, so it can't be invoked over run/send/listen. "
+ "It only runs via its configured slack / cron / webhook surfaces."
+ )
+ if e.status_code == 404:
+ return NotFound(not_found_detail)
+ if e.status_code == 410:
+ # Pass the terminal-session 410 THROUGH as 410 (doctrine: preserve 4xx —
+ # 404 stays 404, 409 stays 409). Only truly-terminal states reach here:
+ # ingress re-queues `completed`/`queued`/`running` sessions and 410s only
+ # on failed / cancelled / closed-without-restart, so a 410 means "really
+ # done", not "idle between turns" — surfacing it as 400 would mislabel it.
+ # SessionGoneError carries the client-error type/code (not a bare APIException,
+ # which renders `server_error`/`error` and pages on-call for a normal 410).
+ return SessionGoneError(
+ f"Session is terminal (state={body.get('state', 'unknown')}) and can't accept more messages."
+ )
+ if e.status_code == 403 and code == "elevation_required":
+ # Preserve the actionable elevation fields (which approval request to act
+ # on, which session) instead of collapsing to the opaque code — the
+ # approval flow the agentic caller must follow needs them. Shapes:
+ # buildElevationResponse / runHandler in agent-ingress (chat.ts).
+ # ElevationRequiredError carries the client-error type/code so a normal
+ # non-owner 403 doesn't render as `server_error`/`error`.
+ parts = ["You are not the owner of this session; elevation is required to act on it."]
+ if body.get("elevation_request_id"):
+ parts.append(f"Elevation request: {body['elevation_request_id']}.")
+ if body.get("session_id"):
+ parts.append(f"Session: {body['session_id']}.")
+ return ElevationRequiredError(" ".join(parts))
+ return IngressUpstreamError(e)
+
+
def _is_sealed_bundle_conflict(e: JanitorClientError) -> bool:
"""True when a janitor edit was refused because the bundle is already sealed.
@@ -599,6 +721,11 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# never hand it back, so the GET `preview_proxy_get` stays read-scoped.)
"preview_token_mint",
"preview_token",
+ # `agent_invoke` starts a new LIVE session and `agent_send` appends a
+ # turn — both drive the agent's tools and incur inference cost, so they
+ # are write-class (the read-only `agent_listen` poll is below).
+ "agent_invoke",
+ "agent_send",
]
scope_object_read_actions = [
"list",
@@ -617,6 +744,10 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# this read-scoped GET can't leak a usable credential (unlike
# `preview_token`, which is write-scoped above).
"preview_proxy_get",
+ # `agent_listen` is a read-only digest poll of a live session — it never
+ # mutates, so it is read-scoped (its `agent_invoke`/`agent_send` siblings
+ # are write actions above).
+ "agent_listen",
"approvals_list",
"approvals_retrieve",
]
@@ -828,6 +959,255 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# `@action`-decorated method confuses mypy about the bound-method signature.
return self.preview_proxy(request, rest=rest, **kwargs) # type: ignore[arg-type]
+ # ── Live-agent invocation (invoke / send / listen) ────────────────
+ # Runtime counterparts to the authoring surface: talk to a LIVE (promoted)
+ # agent over the ingress runtime endpoints, so an authoring AI can iterate
+ # end-to-end without leaving MCP. invoke/send bridge to the public ingress
+ # run/send routes forwarding the caller's PAT (so the session principal is
+ # the real caller); listen bridges to an internal digest RPC. Draft/non-live
+ # invokes stay on `preview_proxy`.
+ # Tool names use the `agent-applications-` prefix (agent-applications-invoke /
+ # -send / -listen) for consistency with the rest of the surface — the ~60 sibling
+ # tools on this viewset all share it (cf. `agent_applications_preview_proxy`). An
+ # earlier gap doc advertised the short `agent-invoke/send/listen` form, but we chose
+ # namespace consistency over that shorthand — hence the explicit `operation_id=`
+ # overrides pinning the `agent_applications_*` operation ids the codegen derives from.
+
+ def _assert_session_in_application(self, session_id: str, application: AgentApplication) -> None:
+ """Tenant/ownership check run BEFORE any ingress bridge. Django gates
+ tenancy first so the internal read endpoint stays internal-only and a
+ buggy/compromised ingress can't leak cross-tenant; the ingress read
+ re-scopes by `application_id` as an authoritative backstop. `last_n=1`
+ keeps this cheap — we only compare `application_id`, not the transcript."""
+ try:
+ session = _janitor().get_session(session_id, last_n=1)
+ except JanitorClientError as e:
+ # A plain not-found from the janitor IS a not-found for the caller —
+ # surface it as a clean 404 (`invalid_request`/`not_found`), not the
+ # internal `janitor_upstream` label, matching the sibling clean paths.
+ # Everything else (incl. 5xx → 502) still flows through JanitorUpstreamError.
+ if e.status_code == 404:
+ raise NotFound("Session not found in this application") from e
+ raise JanitorUpstreamError(e) from e
+ if session.get("application_id") != str(application.id):
+ raise NotFound("Session not found in this application")
+
+ @extend_schema(
+ operation_id="agent_applications_invoke",
+ request=AgentInvokeRequestSerializer,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentInvokeResponse",
+ fields={
+ "session_id": drf_serializers.UUIDField(
+ help_text="The newly-created (or resumed, if external_key matched) session id. Feed to agent-applications-send / agent-applications-listen.",
+ ),
+ "state": drf_serializers.ChoiceField(
+ choices=_AGENT_SESSION_STATE_VALUES,
+ help_text="Session state right after enqueue — `queued`. Poll agent-applications-listen for progress.",
+ ),
+ "resumed": drf_serializers.BooleanField(
+ help_text="True if an existing session matched `external_key` and was resumed, rather than a new one being created.",
+ ),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["post"], url_path="invoke")
+ def agent_invoke(self, request: Request, **kwargs) -> Response:
+ """Start a new session on this agent's LIVE (promoted) revision.
+
+ Bridges to ingress `POST /agents/<slug>/run`, forwarding the caller's PAT
+ so the session principal is the real caller. Returns the new `session_id`;
+ drive the conversation with `agent-applications-send` and read progress with
+ `agent-applications-listen`. For non-live / draft revisions use `preview_proxy` instead.
+ """
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ if not application.live_revision_id:
+ raise ValidationError("This agent has no live revision. Freeze + promote a revision before invoking it.")
+ if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,61}[a-z0-9]?", application.slug):
+ raise ValidationError("Application slug contains unsafe characters")
+
+ payload = AgentInvokeRequestSerializer(data=request.data)
+ payload.is_valid(raise_exception=True)
+ authorization = _require_ingress_bearer(request)
+ try:
+ result = _ingress().run(
+ application.slug,
+ message=payload.validated_data["message"],
+ external_key=payload.validated_data.get("external_key"),
+ authorization=authorization,
+ )
+ except IngressClientError as e:
+ raise _map_ingress_error(
+ e,
+ not_found_detail="This agent isn't reachable yet — its live revision may still be propagating. Try again shortly.",
+ ) from e
+ return Response(
+ {"session_id": result.get("session_id"), "state": "queued", "resumed": bool(result.get("resumed", False))}
+ )
+
+ @extend_schema(
+ operation_id="agent_applications_send",
+ request=AgentSendRequestSerializer,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentSendResponse",
+ fields={
+ "state": drf_serializers.ChoiceField(
+ choices=_AGENT_SESSION_STATE_VALUES,
+ help_text="Session state after the message was appended — `queued` (a new turn will run).",
+ ),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["post"], url_path="send")
+ def agent_send(self, request: Request, **kwargs) -> Response:
+ """Append a message to an existing LIVE session and re-queue it.
+
+ Bridges to ingress `POST /agents/<slug>/send`, forwarding the caller's PAT
+ so the ACL principal-match passes. A `completed` session is NOT terminal —
+ it's a per-turn idle state for a multi-turn agent, so send re-queues it for
+ another turn; only truly-terminal states (failed / cancelled / closed) 410,
+ which passes through as a 410. A janitor ownership pre-check runs first, but
+ it's redundant defense-in-depth (ingress `/send` already app-scopes the
+ load), kept for a clean early 404.
+ """
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+ if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,61}[a-z0-9]?", application.slug):
+ raise ValidationError("Application slug contains unsafe characters")
+
+ payload = AgentSendRequestSerializer(data=request.data)
+ payload.is_valid(raise_exception=True)
+ session_id = str(payload.validated_data["session_id"])
+ authorization = _require_ingress_bearer(request)
+ self._assert_session_in_application(session_id, application)
+ try:
+ _ingress().send(
+ application.slug,
+ session_id=session_id,
+ message=payload.validated_data["message"],
+ authorization=authorization,
+ )
+ except IngressClientError as e:
+ raise _map_ingress_error(e) from e
+ return Response({"state": "queued"})
+
+ @extend_schema(
+ operation_id="agent_applications_listen",
+ parameters=[
+ OpenApiParameter(
+ "session_id",
+ OpenApiTypes.UUID,
+ OpenApiParameter.QUERY,
+ required=True,
+ description="Session to read (must belong to this agent).",
+ ),
+ OpenApiParameter(
+ "cursor",
+ OpenApiTypes.INT,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="`next_cursor` from the previous call. Omit on the first read; pass it back to summarize only what's new.",
+ ),
+ OpenApiParameter(
+ "max_chars",
+ OpenApiTypes.INT,
+ OpenApiParameter.QUERY,
+ required=False,
+ description="Digest character budget (default 4000, range 1–20000). The digest is clipped to fit and `truncated` is set.",
+ ),
+ ],
+ request=None,
+ responses=OpenApiResponse(
+ response=inline_serializer(
+ name="AgentListenResponse",
+ fields={
+ "session_id": drf_serializers.UUIDField(),
+ "state": drf_serializers.ChoiceField(choices=_AGENT_SESSION_STATE_VALUES),
+ "turns": drf_serializers.IntegerField(help_text="Total messages in the conversation so far."),
+ "next_cursor": drf_serializers.IntegerField(
+ help_text="Pass back as `cursor` on the next call to page forward — high-water mark of messages seen.",
+ ),
+ "digest": drf_serializers.CharField(
+ help_text="Compact, payload-free progress summary: last assistant text, one-line tool activity, state/usage.",
+ ),
+ "truncated": drf_serializers.BooleanField(
+ help_text="True when the digest was clipped to `max_chars` — read the full transcript via `agent-applications-sessions-retrieve`.",
+ ),
+ "done": drf_serializers.BooleanField(
+ help_text="True once the current turn has finished (`completed`) or the session ended (`closed`/`cancelled`/`failed`) — stop polling. A `completed` session is still open: `agent-applications-send` to continue it.",
+ ),
+ },
+ )
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="listen")
+ def agent_listen(self, request: Request, **kwargs) -> Response:
+ """Poll a LIVE session's progress as a single JSON digest (non-streaming,
+ MCP-friendly). Bridges to the internal ingress digest RPC — the digest is
+ built node-side (never in Python). Tenancy is enforced by the team-scoped
+ `get_object()` here plus the ingress digest's `application_id` re-scope;
+ there is no janitor pre-check on this polled path (see the comment below).
+ """
+ application = self.get_object()
+ if application is None:
+ raise NotFound("Application not found")
+
+ session_id = request.query_params.get("session_id")
+ if not session_id:
+ raise ValidationError("session_id query parameter is required")
+ try:
+ UUID(str(session_id))
+ except (ValueError, TypeError):
+ raise ValidationError("session_id must be a valid UUID")
+ cursor_param = request.query_params.get("cursor")
+ try:
+ cursor = int(cursor_param) if cursor_param is not None else None
+ except ValueError:
+ raise ValidationError("cursor must be an integer")
+ if cursor is not None and cursor < 0:
+ raise ValidationError("cursor must be non-negative")
+ max_chars_param = request.query_params.get("max_chars")
+ try:
+ max_chars = int(max_chars_param) if max_chars_param is not None else None
+ except ValueError:
+ raise ValidationError("max_chars must be an integer")
+ # Range-check here (symmetric with the cursor >= 0 check above and the
+ # ingress zod `.positive().max(20_000)`) so a 0 / negative / oversized value
+ # returns a clean field-level 400 instead of the opaque ingress `invalid_body`.
+ if max_chars is not None and not (1 <= max_chars <= 20000):
+ raise ValidationError("max_chars must be between 1 and 20000")
+
+ # No janitor pre-check here (unlike agent_send): tenancy is still decided
+ # in Django — `get_object()` resolves `application` through the team-scoped
+ # queryset (a cross-team caller 404s above, before any bridge) — and the
+ # ingress digest RPC re-scopes the read by this team-checked `application_id`
+ # (`getForApplication ... WHERE application_id = $2`), returning
+ # `session_not_found` for a foreign session, which `_map_ingress_error`
+ # maps to 404. A janitor `get_session` here would just re-evaluate that same
+ # predicate one hop earlier — an extra round-trip on the polled hot path, not
+ # an independent gate. (agent_send keeps its own janitor pre-check, but that
+ # is redundant defense-in-depth, NOT load-bearing: `/send` already app-scopes
+ # in SQL — sendHandler loads via getOwnedSession → getForApplication (WHERE
+ # application_id) and then ACL-matches the principal (agent-ingress chat.ts).
+ # The Django pre-check is kept there for symmetry / a clean early 404.)
+ try:
+ digest = _ingress().session_digest(
+ application_id=str(application.id),
+ session_id=session_id,
+ cursor=cursor,
+ max_chars=max_chars,
+ )
+ except IngressClientError as e:
+ raise _map_ingress_error(e) from e
+ return Response(digest)
+
# ── Preview token (direct-to-ingress flow) ───────────────────────
# Alternative to `preview_proxy`: returns a short-lived JWT the
# browser can attach to direct ingress calls. Console uses this
diff --git a/products/agent_platform/backend/tests/test_agent_runtime_bridge.py b/products/agent_platform/backend/tests/test_agent_runtime_bridge.py
new file mode 100644
index 000000000000..c9c6c4c36a4f
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_agent_runtime_bridge.py
@@ -0,0 +1,406 @@
+"""
+Integration tests: AgentApplicationViewSet runtime bridge actions
+(`agent_invoke` / `agent_send` / `agent_listen`) ↔ the agent-ingress client.
+
+These actions are the LIVE-agent runtime surface behind the `agent-applications-invoke` /
+`agent-applications-send` / `agent-applications-listen` MCP tools. They talk to the ingress over
+`_ingress()` (public run/send + internal digest RPC) and check session
+ownership against the janitor via `_janitor().get_session`. Both boundaries are
+mocked so no live ingress / janitor process is needed — the contract under test
+is Django-side: the pre-flight guards (no live revision, cross-app session), the
+caller-PAT forwarding, and the `_map_ingress_error` mapping that turns ingress
+404 `no_chat_trigger` / terminal 410 / 403 `elevation_required` / 5xx into clean
+responses instead of a bare 500. The runtime side (real PG, real session
+creation) is exercised in the node harness (`services/agent-tests`) and
+`services/agent-ingress/src/routing/*.test.ts`.
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.models import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from ..logic.ingress_client import IngressClientError
+from ..logic.janitor_client import JanitorClientError
+from ..models import AgentApplication, AgentRevision
+
+_SESSION_ID = "33333333-3333-3333-3333-333333333333"
+
+
+def _base_spec() -> dict:
+ return {
+ "model": "test/x",
+ "triggers": [{"type": "chat", "config": {}, "auth": {"modes": [{"type": "posthog", "scopes": []}]}}],
+ }
+
+
+class TestAgentRuntimeBridge(APIBaseTest):
+ databases = {
+ "default",
+ "agent_platform_db_writer",
+ "agent_platform_db_reader",
+ }
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.application = AgentApplication.all_teams.create(
+ team_id=self.team.id,
+ slug="runtime-agent",
+ name="Runtime agent",
+ description="",
+ )
+ self.base = f"/api/projects/{self.team.id}/agent_applications/{self.application.id}"
+ self.personal_api_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="runtime-test",
+ user=self.user,
+ secure_value=hash_key_value(self.personal_api_key),
+ scopes=["agents:read", "agents:write"],
+ )
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.personal_api_key}")
+
+ def _make_live_revision(self) -> AgentRevision:
+ rev = AgentRevision.all_teams.create(
+ application=self.application,
+ state="live",
+ bundle_uri="fs://test/",
+ spec=_base_spec(),
+ )
+ self.application.live_revision = rev
+ self.application.save(update_fields=["live_revision"])
+ return rev
+
+ # ── agent_invoke ─────────────────────────────────────────────────────────
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ def test_invoke_without_live_revision_returns_400(self, mock_ingress: MagicMock) -> None:
+ # No revision promoted → the action rejects before any ingress call.
+ res = self.client.post(f"{self.base}/invoke/", {"message": "hi"}, format="json")
+ self.assertEqual(res.status_code, 400, res.content)
+ self.assertIn("no live revision", res.content.decode().lower())
+ mock_ingress.return_value.run.assert_not_called()
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ def test_invoke_happy_path_returns_session_state_resumed(self, mock_ingress: MagicMock) -> None:
+ self._make_live_revision()
+ mock_ingress.return_value.run.return_value = {"session_id": _SESSION_ID, "resumed": True}
+ res = self.client.post(f"{self.base}/invoke/", {"message": "start it"}, format="json")
+ self.assertEqual(res.status_code, 200, res.content)
+ body = res.json()
+ self.assertEqual(body["session_id"], _SESSION_ID)
+ self.assertEqual(body["state"], "queued")
+ self.assertTrue(body["resumed"]) # external_key matched → resumed surfaced
+ # Forwards message + slug (+ the Authorization kwarg) to the ingress run route.
+ args, kwargs = mock_ingress.return_value.run.call_args
+ self.assertEqual(kwargs["message"], "start it")
+ self.assertEqual(args[0], self.application.slug)
+ self.assertIn("authorization", kwargs)
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ def test_invoke_forwards_caller_pat_to_ingress(self, mock_ingress: MagicMock) -> None:
+ # The central auth decision: the caller's PAT is forwarded verbatim so the
+ # ingress `posthog` mode re-introspects it and the session principal is the
+ # real caller. Authenticate with a real scoped PAT and assert it lands.
+ self._make_live_revision()
+ mock_ingress.return_value.run.return_value = {"session_id": _SESSION_ID}
+ res = self.client.post(
+ f"{self.base}/invoke/",
+ {"message": "hi"},
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {self.personal_api_key}",
+ )
+ self.assertEqual(res.status_code, 200, res.content)
+ _, kwargs = mock_ingress.return_value.run.call_args
+ self.assertEqual(kwargs["authorization"], f"Bearer {self.personal_api_key}")
+
+ @parameterized.expand(
+ [
+ ("invoke", {"message": "hi"}),
+ ("send", {"session_id": _SESSION_ID, "message": "hi"}),
+ ]
+ )
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_session_auth_cannot_call_ingress_without_bearer(
+ self,
+ action: str,
+ payload: dict[str, str],
+ mock_janitor: MagicMock,
+ mock_ingress: MagicMock,
+ ) -> None:
+ if action == "invoke":
+ self._make_live_revision()
+ self.client.credentials()
+
+ res = self.client.post(f"{self.base}/{action}/", payload, format="json")
+
+ self.assertEqual(res.status_code, 401, res.content)
+ self.assertIn("personal api key", res.content.decode().lower())
+ mock_janitor.assert_not_called()
+ mock_ingress.assert_not_called()
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ def test_invoke_no_chat_trigger_maps_to_clean_400(self, mock_ingress: MagicMock) -> None:
+ # A slack/cron-only agent 404s `no_chat_trigger` at the ingress; the view
+ # must reframe that as a 400 (not a 404 "not found" and not a bare 500).
+ self._make_live_revision()
+ mock_ingress.return_value.run.side_effect = IngressClientError(
+ 404, "ingress returned 404", body={"error": "no_chat_trigger"}
+ )
+ res = self.client.post(f"{self.base}/invoke/", {"message": "hi"}, format="json")
+ self.assertEqual(res.status_code, 400, res.content)
+ self.assertIn("no chat trigger", res.content.decode().lower())
+
+ # ── agent_send ───────────────────────────────────────────────────────────
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_send_to_session_from_another_app_returns_404(
+ self, mock_janitor: MagicMock, mock_ingress: MagicMock
+ ) -> None:
+ # The janitor row says this session belongs to a DIFFERENT application →
+ # the ownership pre-flight raises NotFound before any ingress send.
+ mock_janitor.return_value.get_session.return_value = {"application_id": "some-other-app-id"}
+ res = self.client.post(f"{self.base}/send/", {"session_id": _SESSION_ID, "message": "more"}, format="json")
+ self.assertEqual(res.status_code, 404, res.content)
+ mock_ingress.return_value.send.assert_not_called()
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_send_to_terminal_session_passes_410_through(
+ self, mock_janitor: MagicMock, mock_ingress: MagicMock
+ ) -> None:
+ # Ownership passes; the ingress reports the session is truly terminal (410).
+ # The view preserves the 410 verbatim (preserve-4xx doctrine) with an
+ # actionable message — never a bare 500, and no longer remapped to 400.
+ mock_janitor.return_value.get_session.return_value = {"application_id": str(self.application.id)}
+ mock_ingress.return_value.send.side_effect = IngressClientError(
+ 410, "ingress returned 410", body={"state": "closed"}
+ )
+ res = self.client.post(f"{self.base}/send/", {"session_id": _SESSION_ID, "message": "more"}, format="json")
+ self.assertEqual(res.status_code, 410, res.content)
+ self.assertIn("terminal", res.content.decode().lower())
+ # A 410 is an EXPECTED client condition, so it must render a clean client-error
+ # type/code (SessionGoneError), NOT the bare-APIException `server_error`/`error`
+ # that would page on-call and pollute error monitoring.
+ body = res.json()
+ self.assertEqual(body["type"], "invalid_request", res.content)
+ self.assertEqual(body["code"], "session_gone", res.content)
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_send_elevation_required_preserves_request_id(
+ self, mock_janitor: MagicMock, mock_ingress: MagicMock
+ ) -> None:
+ # A non-owner send is denied 403 `elevation_required`; the view must surface
+ # the actionable elevation_request_id, not collapse to the opaque code.
+ mock_janitor.return_value.get_session.return_value = {"application_id": str(self.application.id)}
+ mock_ingress.return_value.send.side_effect = IngressClientError(
+ 403,
+ "ingress returned 403",
+ body={"error": "elevation_required", "elevation_request_id": "elev-123", "session_id": _SESSION_ID},
+ )
+ res = self.client.post(f"{self.base}/send/", {"session_id": _SESSION_ID, "message": "more"}, format="json")
+ self.assertEqual(res.status_code, 403, res.content)
+ self.assertIn("elev-123", res.content.decode())
+ # A non-owner 403 is an EXPECTED client condition (the caller must run the
+ # elevation flow), so it renders a clean auth-error type + the actionable
+ # `elevation_required` code (ElevationRequiredError), NOT `server_error`/`error`.
+ body = res.json()
+ self.assertEqual(body["type"], "authentication_error", res.content)
+ self.assertEqual(body["code"], "elevation_required", res.content)
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_send_ingress_5xx_clamps_to_502(self, mock_janitor: MagicMock, mock_ingress: MagicMock) -> None:
+ # An ingress 5xx must not leak as a 4xx or a bare 500 — it clamps to 502.
+ mock_janitor.return_value.get_session.return_value = {"application_id": str(self.application.id)}
+ mock_ingress.return_value.send.side_effect = IngressClientError(503, "ingress returned 503", body=None)
+ res = self.client.post(f"{self.base}/send/", {"session_id": _SESSION_ID, "message": "more"}, format="json")
+ self.assertEqual(res.status_code, 502, res.content)
+ # A clamped 5xx IS genuinely a server-side failure, so it correctly keeps the
+ # `server_error` type (IngressUpstreamError leaves the default) under the
+ # `ingress_upstream` code — the 4xx path is what must NOT read as server_error.
+ body = res.json()
+ self.assertEqual(body["type"], "server_error", res.content)
+ self.assertEqual(body["code"], "ingress_upstream", res.content)
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_send_happy_path_returns_state(self, mock_janitor: MagicMock, mock_ingress: MagicMock) -> None:
+ mock_janitor.return_value.get_session.return_value = {"application_id": str(self.application.id)}
+ mock_ingress.return_value.send.return_value = {}
+ res = self.client.post(f"{self.base}/send/", {"session_id": _SESSION_ID, "message": "more"}, format="json")
+ self.assertEqual(res.status_code, 200, res.content)
+ self.assertEqual(res.json(), {"state": "queued"})
+ _, kwargs = mock_ingress.return_value.send.call_args
+ self.assertEqual(kwargs["session_id"], _SESSION_ID)
+ self.assertEqual(kwargs["message"], "more")
+ self.assertIn("authorization", kwargs)
+
+ # ── agent_listen ─────────────────────────────────────────────────────────
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ def test_listen_happy_path_passes_through_digest(self, mock_ingress: MagicMock) -> None:
+ # listen does NOT pre-check the janitor (see the action comment) — tenancy is
+ # enforced by the ingress digest's application_id re-scope, so only _ingress
+ # is on the path.
+ digest = {
+ "session_id": _SESSION_ID,
+ "state": "running",
+ "turns": 2,
+ "next_cursor": 2,
+ "digest": "working…\n\nTools: (none)",
+ "truncated": False,
+ "done": False,
+ }
+ mock_ingress.return_value.session_digest.return_value = digest
+ res = self.client.get(f"{self.base}/listen/?session_id={_SESSION_ID}")
+ self.assertEqual(res.status_code, 200, res.content)
+ self.assertEqual(res.json(), digest)
+ _, kwargs = mock_ingress.return_value.session_digest.call_args
+ self.assertEqual(kwargs["application_id"], str(self.application.id))
+ self.assertEqual(kwargs["session_id"], _SESSION_ID)
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ def test_listen_from_another_app_returns_404(self, mock_ingress: MagicMock) -> None:
+ # Cross-tenant listen still 404s end-to-end: the ingress digest re-scopes by
+ # the team-checked application_id and returns session_not_found for a foreign
+ # session, which _map_ingress_error turns into a 404 — the tenancy guarantee
+ # the removed janitor pre-check used to give, now enforced at the ingress read.
+ mock_ingress.return_value.session_digest.side_effect = IngressClientError(
+ 404, "ingress returned 404", body={"error": "session_not_found"}
+ )
+ res = self.client.get(f"{self.base}/listen/?session_id={_SESSION_ID}")
+ self.assertEqual(res.status_code, 404, res.content)
+
+ def test_listen_without_session_id_returns_400(self) -> None:
+ res = self.client.get(f"{self.base}/listen/")
+ self.assertEqual(res.status_code, 400, res.content)
+
+ def test_listen_non_uuid_session_id_returns_400(self) -> None:
+ # A malformed session_id must be a clean 400, not a 502 from a Postgres
+ # "invalid input syntax for type uuid" bubbling up through the janitor.
+ res = self.client.get(f"{self.base}/listen/?session_id=not-a-uuid")
+ self.assertEqual(res.status_code, 400, res.content)
+ self.assertIn("uuid", res.content.decode().lower())
+
+ # ── error mapping + input validation ─────────────────────────────────────
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ def test_invoke_plain_404_maps_to_propagating_message(self, mock_ingress: MagicMock) -> None:
+ # A plain 404 from the ingress (not `no_chat_trigger`) → invoke's own
+ # not_found_detail, phrased as "still propagating" (the agent has no
+ # session context of its own), never a bare 404 "Session not found".
+ self._make_live_revision()
+ mock_ingress.return_value.run.side_effect = IngressClientError(
+ 404, "ingress returned 404", body={"error": "session_not_found"}
+ )
+ res = self.client.post(f"{self.base}/invoke/", {"message": "hi"}, format="json")
+ self.assertEqual(res.status_code, 404, res.content)
+ self.assertIn("propagating", res.content.decode().lower())
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ def test_invoke_blank_message_returns_400(self, mock_ingress: MagicMock) -> None:
+ self._make_live_revision()
+ res = self.client.post(f"{self.base}/invoke/", {"message": ""}, format="json")
+ self.assertEqual(res.status_code, 400, res.content)
+ mock_ingress.return_value.run.assert_not_called()
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ def test_send_blank_message_returns_400(self, mock_ingress: MagicMock) -> None:
+ res = self.client.post(f"{self.base}/send/", {"session_id": _SESSION_ID, "message": ""}, format="json")
+ self.assertEqual(res.status_code, 400, res.content)
+ mock_ingress.return_value.send.assert_not_called()
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ def test_send_non_uuid_session_id_returns_400(self, mock_ingress: MagicMock) -> None:
+ # The serializer's UUIDField rejects a malformed session_id up front.
+ res = self.client.post(f"{self.base}/send/", {"session_id": "not-a-uuid", "message": "hi"}, format="json")
+ self.assertEqual(res.status_code, 400, res.content)
+ mock_ingress.return_value.send.assert_not_called()
+
+ def test_listen_negative_cursor_returns_400(self) -> None:
+ res = self.client.get(f"{self.base}/listen/?session_id={_SESSION_ID}&cursor=-1")
+ self.assertEqual(res.status_code, 400, res.content)
+
+ def test_listen_non_integer_cursor_returns_400(self) -> None:
+ res = self.client.get(f"{self.base}/listen/?session_id={_SESSION_ID}&cursor=abc")
+ self.assertEqual(res.status_code, 400, res.content)
+
+ def test_listen_non_integer_max_chars_returns_400(self) -> None:
+ res = self.client.get(f"{self.base}/listen/?session_id={_SESSION_ID}&max_chars=abc")
+ self.assertEqual(res.status_code, 400, res.content)
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_send_janitor_failure_maps_to_502(self, mock_janitor: MagicMock, mock_ingress: MagicMock) -> None:
+ # send's ownership pre-flight talks to the janitor; a janitor 5xx must clamp
+ # to a clean 502, never bubble as a bare 500 or reach the ingress. (listen
+ # has no janitor pre-check, so this guard lives on send.)
+ mock_janitor.return_value.get_session.side_effect = JanitorClientError(503, "janitor down", body=None)
+ res = self.client.post(f"{self.base}/send/", {"session_id": _SESSION_ID, "message": "hi"}, format="json")
+ self.assertEqual(res.status_code, 502, res.content)
+ mock_ingress.return_value.send.assert_not_called()
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_send_janitor_404_normalizes_to_clean_not_found(
+ self, mock_janitor: MagicMock, mock_ingress: MagicMock
+ ) -> None:
+ # A janitor 404 for a never-existed session is a not-found for the caller —
+ # it must surface as a clean 404 `not_found` (invalid_request), NOT leak the
+ # internal `janitor_upstream` label, matching the sibling clean paths.
+ mock_janitor.return_value.get_session.side_effect = JanitorClientError(404, "no such session", body=None)
+ res = self.client.post(f"{self.base}/send/", {"session_id": _SESSION_ID, "message": "hi"}, format="json")
+ self.assertEqual(res.status_code, 404, res.content)
+ self.assertEqual(res.json().get("code"), "not_found", res.content)
+ self.assertNotIn("janitor_upstream", res.content.decode())
+ mock_ingress.return_value.send.assert_not_called()
+
+ def test_listen_max_chars_out_of_range_returns_400(self) -> None:
+ # max_chars must be in [1, 20000] (symmetric with cursor >= 0 and the ingress
+ # zod ceiling) so a 0 / negative / oversized value is a clean field-level 400,
+ # not the opaque ingress `invalid_body`.
+ for bad in ("0", "-5", "20001"):
+ res = self.client.get(f"{self.base}/listen/?session_id={_SESSION_ID}&max_chars={bad}")
+ self.assertEqual(res.status_code, 400, f"max_chars={bad}: {res.content!r}")
+ self.assertIn("max_chars", res.content.decode())
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_send_non_elevation_403_preserves_status(self, mock_janitor: MagicMock, mock_ingress: MagicMock) -> None:
+ # A 403 that is NOT `elevation_required` falls through to IngressUpstreamError,
+ # which preserves the upstream 4xx status verbatim.
+ mock_janitor.return_value.get_session.return_value = {"application_id": str(self.application.id)}
+ mock_ingress.return_value.send.side_effect = IngressClientError(
+ 403, "ingress returned 403", body={"error": "forbidden"}
+ )
+ res = self.client.post(f"{self.base}/send/", {"session_id": _SESSION_ID, "message": "more"}, format="json")
+ self.assertEqual(res.status_code, 403, res.content)
+ # A preserved (non-elevation) 4xx flows through IngressUpstreamError, which must
+ # label it a client error (`invalid_request`), not the bare `server_error`.
+ body = res.json()
+ self.assertEqual(body["type"], "invalid_request", res.content)
+ self.assertEqual(body["code"], "ingress_upstream", res.content)
+
+ @patch("products.agent_platform.backend.presentation.views._ingress")
+ @patch("products.agent_platform.backend.presentation.views._janitor")
+ def test_send_unmapped_4xx_preserves_status(self, mock_janitor: MagicMock, mock_ingress: MagicMock) -> None:
+ # An unmapped 422 preserves the upstream status through IngressUpstreamError.
+ mock_janitor.return_value.get_session.return_value = {"application_id": str(self.application.id)}
+ mock_ingress.return_value.send.side_effect = IngressClientError(
+ 422, "ingress returned 422", body={"error": "unprocessable"}
+ )
+ res = self.client.post(f"{self.base}/send/", {"session_id": _SESSION_ID, "message": "more"}, format="json")
+ self.assertEqual(res.status_code, 422, res.content)
+ # Same class as the 403 passthrough: a preserved upstream 4xx must render as a
+ # client error, never `server_error`.
+ body = res.json()
+ self.assertEqual(body["type"], "invalid_request", res.content)
+ self.assertEqual(body["code"], "ingress_upstream", res.content)
diff --git a/products/agent_platform/backend/tests/test_ingress_client.py b/products/agent_platform/backend/tests/test_ingress_client.py
new file mode 100644
index 000000000000..c348682dc934
--- /dev/null
+++ b/products/agent_platform/backend/tests/test_ingress_client.py
@@ -0,0 +1,151 @@
+"""
+Unit tests for the agent-ingress HTTP client (logic/ingress_client.py) — the thin
+transport behind the `agent-applications-invoke` / `agent-applications-send` / `agent-applications-listen` MCP tools. The
+viewset bridge is covered in test_agent_runtime_bridge.py against a mocked client;
+here we test the client itself in isolation by stubbing the outbound
+`internal_requests.request`, so no live ingress process is needed. Focus: the
+`_call` error/empty-body mapping, header assembly, and the internal-JWT
+fail-open branch.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase, override_settings
+
+import requests
+
+from ..logic.ingress_client import IngressClient, IngressClientError
+
+_INGRESS = "products.agent_platform.backend.logic.ingress_client.internal_requests"
+
+_SIGNING_KEY = "test-internal-signing-key"
+
+
+def _resp(status_code: int, *, json_body=None, content: bytes = b"{}", raises_value_error: bool = False) -> MagicMock:
+ """Fake requests.Response — only the attributes `_call` touches."""
+ r = MagicMock()
+ r.status_code = status_code
+ r.content = content
+ if raises_value_error:
+ r.json.side_effect = ValueError("no json")
+ else:
+ r.json.return_value = json_body
+ return r
+
+
+class TestIngressClientCall(SimpleTestCase):
+ def setUp(self) -> None:
+ self.ingress_client = IngressClient(base_url="http://ingress.test")
+
+ @patch(_INGRESS)
+ def test_call_raises_with_body_on_4xx_5xx(self, mock_ingress: MagicMock) -> None:
+ # A 503 with a JSON error body → IngressClientError carrying status + body.
+ mock_ingress.request.return_value = _resp(503, json_body={"error": "unavailable"}, content=b'{"error":"x"}')
+ with self.assertRaises(IngressClientError) as ctx:
+ self.ingress_client._call("POST", "/x", headers={})
+ self.assertEqual(ctx.exception.status_code, 503)
+ self.assertEqual(ctx.exception.body, {"error": "unavailable"})
+
+ @patch(_INGRESS)
+ def test_call_maps_transport_failure_to_502(self, mock_ingress: MagicMock) -> None:
+ # A network-level RequestException must clamp to a clean 502, never leak raw.
+ mock_ingress.request.side_effect = requests.RequestException("connection refused")
+ with self.assertRaises(IngressClientError) as ctx:
+ self.ingress_client._call("POST", "/x", headers={})
+ self.assertEqual(ctx.exception.status_code, 502)
+
+ @patch(_INGRESS)
+ def test_call_returns_empty_dict_for_empty_content(self, mock_ingress: MagicMock) -> None:
+ # A 200 with no body (e.g. send's ack) → {} rather than a JSON parse attempt.
+ resp = _resp(200, content=b"")
+ mock_ingress.request.return_value = resp
+ self.assertEqual(self.ingress_client._call("POST", "/x", headers={}), {})
+ resp.json.assert_not_called()
+
+ @patch(_INGRESS)
+ def test_call_error_body_none_when_not_json(self, mock_ingress: MagicMock) -> None:
+ # A non-JSON error body (e.g. an HTML 502 page) → body=None, not a crash.
+ mock_ingress.request.return_value = _resp(500, content=b"<html>oops</html>", raises_value_error=True)
+ with self.assertRaises(IngressClientError) as ctx:
+ self.ingress_client._call("GET", "/x", headers={})
+ self.assertEqual(ctx.exception.status_code, 500)
+ self.assertIsNone(ctx.exception.body)
+
+ @patch(_INGRESS)
+ def test_call_returns_parsed_json_on_2xx(self, mock_ingress: MagicMock) -> None:
+ mock_ingress.request.return_value = _resp(200, json_body={"session_id": "s1"}, content=b'{"session_id":"s1"}')
+ self.assertEqual(self.ingress_client._call("POST", "/x", headers={}), {"session_id": "s1"})
+
+
+class TestIngressClientHeaders(SimpleTestCase):
+ def test_forward_headers_includes_authorization_when_present(self) -> None:
+ h = IngressClient._forward_headers("Bearer x")
+ self.assertEqual(h["authorization"], "Bearer x")
+ self.assertEqual(h["content-type"], "application/json")
+
+ def test_forward_headers_omits_authorization_when_none(self) -> None:
+ h = IngressClient._forward_headers(None)
+ self.assertNotIn("authorization", h)
+
+ @override_settings(AGENT_INTERNAL_SIGNING_KEY=_SIGNING_KEY)
+ def test_internal_headers_signs_when_key_configured(self) -> None:
+ h = IngressClient._internal_headers()
+ self.assertIn("x-internal-secret", h)
+ self.assertTrue(h["x-internal-secret"])
+
+ @override_settings(AGENT_INTERNAL_SIGNING_KEY=None)
+ def test_internal_headers_fail_open_when_no_key(self) -> None:
+ # Dev / harness path: no shared key → no secret header (ingress gate is
+ # also bypassed there), never a crash.
+ h = IngressClient._internal_headers()
+ self.assertNotIn("x-internal-secret", h)
+
+
+class TestIngressClientRoutes(SimpleTestCase):
+ def setUp(self) -> None:
+ self.ingress_client = IngressClient(base_url="http://ingress.test")
+
+ @patch(_INGRESS)
+ def test_run_assembles_method_path_and_omits_external_key_when_none(self, mock_ingress: MagicMock) -> None:
+ mock_ingress.request.return_value = _resp(200, json_body={"session_id": "s1"}, content=b"{}")
+ self.ingress_client.run("my-agent", message="hi", external_key=None, authorization="Bearer x")
+ args, kwargs = mock_ingress.request.call_args
+ self.assertEqual(args[0], "POST")
+ self.assertEqual(args[1], "http://ingress.test/agents/my-agent/run")
+ self.assertEqual(kwargs["json"], {"message": "hi"})
+ self.assertEqual(kwargs["headers"]["authorization"], "Bearer x")
+
+ @patch(_INGRESS)
+ def test_run_includes_external_key_when_present(self, mock_ingress: MagicMock) -> None:
+ mock_ingress.request.return_value = _resp(200, json_body={}, content=b"{}")
+ self.ingress_client.run("my-agent", message="hi", external_key="thread-9", authorization=None)
+ _, kwargs = mock_ingress.request.call_args
+ self.assertEqual(kwargs["json"], {"message": "hi", "external_key": "thread-9"})
+
+ @patch(_INGRESS)
+ def test_send_assembles_body(self, mock_ingress: MagicMock) -> None:
+ mock_ingress.request.return_value = _resp(200, json_body={}, content=b"{}")
+ self.ingress_client.send("my-agent", session_id="s1", message="more", authorization="Bearer x")
+ args, kwargs = mock_ingress.request.call_args
+ self.assertEqual(args[1], "http://ingress.test/agents/my-agent/send")
+ self.assertEqual(kwargs["json"], {"session_id": "s1", "message": "more"})
+
+ @override_settings(AGENT_INTERNAL_SIGNING_KEY=_SIGNING_KEY)
+ @patch(_INGRESS)
+ def test_session_digest_omits_cursor_and_max_chars_when_none(self, mock_ingress: MagicMock) -> None:
+ mock_ingress.request.return_value = _resp(200, json_body={"digest": "x"}, content=b"{}")
+ self.ingress_client.session_digest(application_id="app-1", session_id="s1", cursor=None, max_chars=None)
+ args, kwargs = mock_ingress.request.call_args
+ self.assertEqual(args[1], "http://ingress.test/internal/session-digest")
+ self.assertEqual(kwargs["json"], {"application_id": "app-1", "session_id": "s1"})
+ self.assertIn("x-internal-secret", kwargs["headers"])
+
+ @override_settings(AGENT_INTERNAL_SIGNING_KEY=_SIGNING_KEY)
+ @patch(_INGRESS)
+ def test_session_digest_includes_cursor_and_max_chars_when_set(self, mock_ingress: MagicMock) -> None:
+ mock_ingress.request.return_value = _resp(200, json_body={"digest": "x"}, content=b"{}")
+ self.ingress_client.session_digest(application_id="app-1", session_id="s1", cursor=2, max_chars=500)
+ _, kwargs = mock_ingress.request.call_args
+ self.assertEqual(kwargs["json"], {"application_id": "app-1", "session_id": "s1", "cursor": 2, "max_chars": 500})
diff --git a/products/agent_platform/docs/identity-and-tools.md b/products/agent_platform/docs/identity-and-tools.md
index 6d6f84d34ab5..b2fa1a044a25 100644
--- a/products/agent_platform/docs/identity-and-tools.md
+++ b/products/agent_platform/docs/identity-and-tools.md
@@ -294,5 +294,5 @@ flowchart LR
a single `ask` tool, so an MCP client can talk to a deployed agent.
Separately, the **Django authoring REST API** is generated into MCP tools
(`agent-applications-*`) so an authoring client can create/edit/promote
- agents — that surface is authoring-only (see the gap note in
- [local-dev.md](local-dev.md)).
+ agents, plus `agent-applications-invoke` / `agent-applications-send` /
+ `agent-applications-listen` to talk to a live agent (see [local-dev.md](local-dev.md)).
diff --git a/products/agent_platform/docs/local-dev.md b/products/agent_platform/docs/local-dev.md
index 6160cdc02079..a4e9a2cccd34 100644
--- a/products/agent_platform/docs/local-dev.md
+++ b/products/agent_platform/docs/local-dev.md
@@ -232,25 +232,36 @@ When you change a serializer or viewset under `products/agent_platform/backend/`
**always rerun `hogli build:openapi`** before testing via MCP — the MCP
tool schemas come from the generated OpenAPI and silently drift otherwise.
-### Gap: no MCP tools for invoking a created agent
-
-The `agent_platform` MCP surface today is **authoring-only** — `agent-applications-*`
-and `agent-applications-revisions-*` cover create / edit bundle / freeze /
-promote, but there is no MCP tool that wraps the ingress runtime endpoints
-(`/agents/<slug>/run`, `/send`, `/listen`). After an authoring harness like
-Claude Code creates and promotes an agent via MCP, it has no in-band way to
-then talk to it — the next step ("invoke the thing I just built") is not
-discoverable from the tool list.
-
-Workarounds until invocation tools land:
+### Invoking a created agent: `agent-applications-invoke` / `agent-applications-send` / `agent-applications-listen`
+
+The `agent_platform` MCP surface covers both authoring (`agent-applications-*`
+and `agent-applications-revisions-*` — create / edit bundle / freeze / promote)
+and **invocation** of a live agent, so an authoring harness like Claude Code can
+create, promote, and then talk to an agent without leaving MCP:
+
+- **`agent-applications-invoke`** — start a session on the agent's live (promoted)
+ revision; returns a `session_id`. Bridges to ingress `POST /agents/<slug>/run`,
+ forwarding your PAT so the session runs as you.
+- **`agent-applications-send`** — append a message to an existing session (`POST .../send`).
+- **`agent-applications-listen`** — poll a session's progress as a single JSON digest
+ (non-streaming): last assistant text, a one-line tool-activity summary, and
+ state / usage. Pass the returned `next_cursor` back as `cursor` to get only
+ what's new; stop when `done` is true. (An MCP tool call can't hold an SSE
+ stream open, so cursor polling replaces the `/listen` SSE tail.)
+
+These wrap the ingress runtime via thin Django viewset actions — invoke/send
+forward the caller's PAT (so the session principal is the real caller), listen
+reads a digest over an internal ingress RPC — and regenerate through the same
+`hogli build:openapi` pipeline as the rest of the surface.
+Invoke and send require a bearer PAT; session-cookie authentication is rejected
+instead of silently creating or continuing an anonymous ingress session.
+
+For **non-live / draft** revisions, use `agent-applications-preview-proxy`
+instead. Lower-level manual alternatives remain for debugging:
- `bin/run-agent --slug=<your-slug>` from a terminal pane.
- `curl -XPOST localhost:3030/agents/<slug>/run -d '{"message":"hi"}'` plus
`curl -N localhost:3030/agents/<slug>/listen?session_id=...` for SSE.
-- The [`agent-authoring-flow.md`](../plans/agent-authoring-flow.md) plan
- covers the proper fix: dedicated `agent-invoke` / `agent-send` /
- `agent-listen` MCP tools (and a scripted test-run surface) so the
- authoring AI can iterate end-to-end without leaving MCP.
## E2E tests — `products/agent_platform/services/agent-tests`
diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.ts
index 6c3e4ed74d3d..9429b4c1ae50 100644
--- a/products/agent_platform/frontend/generated/api.schemas.ts
+++ b/products/agent_platform/frontend/generated/api.schemas.ts
@@ -783,6 +783,66 @@ export interface AgentApprovalsDecideResponseApi {
state: string
}
+/**
+ * Body for `agent-applications-invoke` — start a new session on the agent's live (promoted) revision.
+ */
+export interface AgentInvokeRequestApi {
+ /** The user message that starts the session. Required, non-empty. */
+ message: string
+ /** Optional idempotency / threading key. A repeat invoke with the same external_key resumes the existing session instead of starting a new one. */
+ external_key?: string
+}
+
+/**
+ * * `queued` - queued
+ * * `running` - running
+ * * `completed` - completed
+ * * `closed` - closed
+ * * `cancelled` - cancelled
+ * * `failed` - failed
+ */
+export type AgentSessionStateEnumApi = (typeof AgentSessionStateEnumApi)[keyof typeof AgentSessionStateEnumApi]
+
+export const AgentSessionStateEnumApi = {
+ Queued: 'queued',
+ Running: 'running',
+ Completed: 'completed',
+ Closed: 'closed',
+ Cancelled: 'cancelled',
+ Failed: 'failed',
+} as const
+
+export interface AgentInvokeResponseApi {
+ /** The newly-created (or resumed, if external_key matched) session id. Feed to agent-applications-send / agent-applications-listen. */
+ session_id: string
+ /** Session state right after enqueue — `queued`. Poll agent-applications-listen for progress.
+ *
+ * * `queued` - queued
+ * * `running` - running
+ * * `completed` - completed
+ * * `closed` - closed
+ * * `cancelled` - cancelled
+ * * `failed` - failed */
+ state: AgentSessionStateEnumApi
+ /** True if an existing session matched `external_key` and was resumed, rather than a new one being created. */
+ resumed: boolean
+}
+
+export interface AgentListenResponseApi {
+ session_id: string
+ state: AgentSessionStateEnumApi
+ /** Total messages in the conversation so far. */
+ turns: number
+ /** Pass back as `cursor` on the next call to page forward — high-water mark of messages seen. */
+ next_cursor: number
+ /** Compact, payload-free progress summary: last assistant text, one-line tool activity, state/usage. */
+ digest: string
+ /** True when the digest was clipped to `max_chars` — read the full transcript via `agent-applications-sessions-retrieve`. */
+ truncated: boolean
+ /** True once the current turn has finished (`completed`) or the session ended (`closed`/`cancelled`/`failed`) — stop polling. A `completed` session is still open: `agent-applications-send` to continue it. */
+ done: boolean
+}
+
/**
* Body forwarded verbatim to the agent ingress for a *preview* invoke of a
* non-live revision. The meaningful shape depends on the `rest` path segment:
@@ -816,6 +876,28 @@ export interface AgentApplicationPreviewTokenResponseApi {
preview_proxy: unknown
}
+/**
+ * Body for `agent-applications-send` — append a message to an existing live session.
+ */
+export interface AgentSendRequestApi {
+ /** The session to append to (returned by agent-applications-invoke). Must belong to this agent. */
+ session_id: string
+ /** The user message to append. Required, non-empty. */
+ message: string
+}
+
+export interface AgentSendResponseApi {
+ /** Session state after the message was appended — `queued` (a new turn will run).
+ *
+ * * `queued` - queued
+ * * `running` - running
+ * * `completed` - completed
+ * * `closed` - closed
+ * * `cancelled` - cancelled
+ * * `failed` - failed */
+ state: AgentSessionStateEnumApi
+}
+
export interface AgentSessionUsageTotalApi {
tokens_in: number
tokens_out: number
@@ -861,25 +943,6 @@ export interface AgentSessionPrincipalApi {
team_id?: number
}
-/**
- * * `queued` - queued
- * * `running` - running
- * * `completed` - completed
- * * `closed` - closed
- * * `cancelled` - cancelled
- * * `failed` - failed
- */
-export type AgentSessionStateEnumApi = (typeof AgentSessionStateEnumApi)[keyof typeof AgentSessionStateEnumApi]
-
-export const AgentSessionStateEnumApi = {
- Queued: 'queued',
- Running: 'running',
- Completed: 'completed',
- Closed: 'closed',
- Cancelled: 'cancelled',
- Failed: 'failed',
-} as const
-
/**
* Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
@@ -1250,6 +1313,21 @@ export type AgentApplicationsApprovalsListParams = {
state?: string
}
+export type AgentApplicationsListenParams = {
+ /**
+ * `next_cursor` from the previous call. Omit on the first read; pass it back to summarize only what's new.
+ */
+ cursor?: number
+ /**
+ * Digest character budget (default 4000, range 1–20000). The digest is clipped to fit and `truncated` is set.
+ */
+ max_chars?: number
+ /**
+ * Session to read (must belong to this agent).
+ */
+ session_id: string
+}
+
export type AgentApplicationsPreviewProxyGetParams = {
format?: AgentApplicationsPreviewProxyGetFormat
/**
diff --git a/products/agent_platform/frontend/generated/api.ts b/products/agent_platform/frontend/generated/api.ts
index 2d4aa72d3df7..a47061385b77 100644
--- a/products/agent_platform/frontend/generated/api.ts
+++ b/products/agent_platform/frontend/generated/api.ts
@@ -18,6 +18,7 @@ import type {
AgentApplicationSessionsRetrieveResponseApi,
AgentApplicationsApprovalsListParams,
AgentApplicationsListParams,
+ AgentApplicationsListenParams,
AgentApplicationsPreviewProxyGetParams,
AgentApplicationsPreviewProxyParams,
AgentApplicationsPreviewTokenMintParams,
@@ -33,6 +34,9 @@ import type {
AgentFleetLiveSessionsParams,
AgentFleetLiveSessionsResponseApi,
AgentFleetStatsParams,
+ AgentInvokeRequestApi,
+ AgentInvokeResponseApi,
+ AgentListenResponseApi,
AgentMemoryDeleteFileParams,
AgentMemoryFileApi,
AgentMemoryGetFileParams,
@@ -54,6 +58,8 @@ import type {
AgentRevisionSlackManifestResponseApi,
AgentRevisionSystemPromptResponseApi,
AgentRevisionValidateResponseApi,
+ AgentSendRequestApi,
+ AgentSendResponseApi,
AgentTableRowsResponseApi,
AgentTablesListResponseApi,
AgentUsersListApi,
@@ -1699,6 +1705,67 @@ export const agentApplicationsApprovalsDecide = async (
)
}
+export const getAgentApplicationsInvokeUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${id}/invoke/`
+}
+
+/**
+ * Start a new session on this agent's LIVE (promoted) revision.
+ *
+ * Bridges to ingress `POST /agents/<slug>/run`, forwarding the caller's PAT
+ * so the session principal is the real caller. Returns the new `session_id`;
+ * drive the conversation with `agent-applications-send` and read progress with
+ * `agent-applications-listen`. For non-live / draft revisions use `preview_proxy` instead.
+ */
+export const agentApplicationsInvoke = async (
+ projectId: string,
+ id: string,
+ agentInvokeRequestApi: AgentInvokeRequestApi,
+ options?: RequestInit
+): Promise<AgentInvokeResponseApi> => {
+ return apiMutator<AgentInvokeResponseApi>(getAgentApplicationsInvokeUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(agentInvokeRequestApi),
+ })
+}
+
+export const getAgentApplicationsListenUrl = (projectId: string, id: string, params: AgentApplicationsListenParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/agent_applications/${id}/listen/?${stringifiedParams}`
+ : `/api/projects/${projectId}/agent_applications/${id}/listen/`
+}
+
+/**
+ * Poll a LIVE session's progress as a single JSON digest (non-streaming,
+ * MCP-friendly). Bridges to the internal ingress digest RPC — the digest is
+ * built node-side (never in Python). Tenancy is enforced by the team-scoped
+ * `get_object()` here plus the ingress digest's `application_id` re-scope;
+ * there is no janitor pre-check on this polled path (see the comment below).
+ */
+export const agentApplicationsListen = async (
+ projectId: string,
+ id: string,
+ params: AgentApplicationsListenParams,
+ options?: RequestInit
+): Promise<AgentListenResponseApi> => {
+ return apiMutator<AgentListenResponseApi>(getAgentApplicationsListenUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getAgentApplicationsPreviewProxyGetUrl = (
projectId: string,
id: string,
@@ -1883,6 +1950,35 @@ export const agentApplicationsPreviewTokenMint = async (
)
}
+export const getAgentApplicationsSendUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/agent_applications/${id}/send/`
+}
+
+/**
+ * Append a message to an existing LIVE session and re-queue it.
+ *
+ * Bridges to ingress `POST /agents/<slug>/send`, forwarding the caller's PAT
+ * so the ACL principal-match passes. A `completed` session is NOT terminal —
+ * it's a per-turn idle state for a multi-turn agent, so send re-queues it for
+ * another turn; only truly-terminal states (failed / cancelled / closed) 410,
+ * which passes through as a 410. A janitor ownership pre-check runs first, but
+ * it's redundant defense-in-depth (ingress `/send` already app-scopes the
+ * load), kept for a clean early 404.
+ */
+export const agentApplicationsSend = async (
+ projectId: string,
+ id: string,
+ agentSendRequestApi: AgentSendRequestApi,
+ options?: RequestInit
+): Promise<AgentSendResponseApi> => {
+ return apiMutator<AgentSendResponseApi>(getAgentApplicationsSendUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(agentSendRequestApi),
+ })
+}
+
export const getAgentApplicationsSessionsListUrl = (
projectId: string,
id: string,
diff --git a/products/agent_platform/frontend/generated/api.zod.ts b/products/agent_platform/frontend/generated/api.zod.ts
index e334d57fa1ee..eb597a6edbcf 100644
--- a/products/agent_platform/frontend/generated/api.zod.ts
+++ b/products/agent_platform/frontend/generated/api.zod.ts
@@ -637,6 +637,26 @@ export const AgentApplicationsApprovalsDecideBody = /* @__PURE__ */ zod
})
.describe('Body shape for POST \/agent_applications\/<id>\/approvals\/<approval_id>\/decide\/.')
+/**
+ * Start a new session on this agent's LIVE (promoted) revision.
+ *
+ * Bridges to ingress `POST /agents/<slug>/run`, forwarding the caller's PAT
+ * so the session principal is the real caller. Returns the new `session_id`;
+ * drive the conversation with `agent-applications-send` and read progress with
+ * `agent-applications-listen`. For non-live / draft revisions use `preview_proxy` instead.
+ */
+export const AgentApplicationsInvokeBody = /* @__PURE__ */ zod
+ .object({
+ message: zod.string().describe('The user message that starts the session. Required, non-empty.'),
+ external_key: zod
+ .string()
+ .optional()
+ .describe(
+ 'Optional idempotency \/ threading key. A repeat invoke with the same external_key resumes the existing session instead of starting a new one.'
+ ),
+ })
+ .describe("Body for `agent-applications-invoke` — start a new session on the agent's live (promoted) revision.")
+
/**
* Authoring-side proxy for invoking a *draft* (or any non-live) revision.
*
@@ -666,3 +686,23 @@ export const AgentApplicationsPreviewProxyBody = /* @__PURE__ */ zod
.describe(
'Body forwarded verbatim to the agent ingress for a \*preview\* invoke of a\nnon-live revision. The meaningful shape depends on the `rest` path segment:\n\n- `run` — `{ message }`: the user message that starts a new session.\n- `send` — `{ session_id, message }`: append a message to a running session.\n- `cancel` \/ `listen` — no body.\n\nDocuments `message` \/ `session_id` so the generated MCP tool exposes them;\nany extra keys are still forwarded as-is to ingress.'
)
+
+/**
+ * Append a message to an existing LIVE session and re-queue it.
+ *
+ * Bridges to ingress `POST /agents/<slug>/send`, forwarding the caller's PAT
+ * so the ACL principal-match passes. A `completed` session is NOT terminal —
+ * it's a per-turn idle state for a multi-turn agent, so send re-queues it for
+ * another turn; only truly-terminal states (failed / cancelled / closed) 410,
+ * which passes through as a 410. A janitor ownership pre-check runs first, but
+ * it's redundant defense-in-depth (ingress `/send` already app-scopes the
+ * load), kept for a clean early 404.
+ */
+export const AgentApplicationsSendBody = /* @__PURE__ */ zod
+ .object({
+ session_id: zod
+ .uuid()
+ .describe('The session to append to (returned by agent-applications-invoke). Must belong to this agent.'),
+ message: zod.string().describe('The user message to append. Required, non-empty.'),
+ })
+ .describe('Body for `agent-applications-send` — append a message to an existing live session.')
diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.test.ts b/products/agent_platform/services/agent-ingress/src/routing/server.test.ts
index e88ca5a92004..c1ae4e64ee96 100644
--- a/products/agent_platform/services/agent-ingress/src/routing/server.test.ts
+++ b/products/agent_platform/services/agent-ingress/src/routing/server.test.ts
@@ -690,6 +690,56 @@ describe('ingress HTTP server (path mode)', () => {
expect(res.body.snippets.mcp_json.mcpServers['dom-agent'].url).toBe('https://dom-agent.agents.test/mcp')
})
+ it('domain mode serves /run at root and via the path alias for internal hosts', async () => {
+ const { revisions, app } = mk({ routingMode: 'domain', domainSuffix: '.agents.test' })
+ await seedApp(revisions, 'alias-agent')
+ // Public edge shape: slug in Host, route at root.
+ const domainRes = await request(app).post('/run').set('Host', 'alias-agent.agents.test').send({ message: 'hi' })
+ expect(domainRes.status).toBe(200)
+ expect(domainRes.body.session_id).not.toBeUndefined()
+ // In-cluster shape: Django (preview-proxy, IngressClient) addresses the
+ // ingress Service directly, so Host is the Service DNS name and the slug
+ // rides in the path. Before the alias mount this 404ed in domain mode.
+ const pathRes = await request(app)
+ .post('/agents/alias-agent/run')
+ .set('Host', 'agent-ingress.svc.cluster.local:3030')
+ .send({ message: 'hi' })
+ expect(pathRes.status).toBe(200)
+ expect(pathRes.body.session_id).not.toBeUndefined()
+ })
+
+ it('domain mode resolves a non-live revision through the path alias (preview-proxy URL shape)', async () => {
+ const { revisions, queue, app } = mk({ routingMode: 'domain', domainSuffix: '.agents.test' })
+ const { app: agentApp, rev: liveRev } = await seedApp(revisions, 'alias-draft')
+ const draft = await revisions.createRevision({
+ application_id: agentApp.id,
+ parent_revision_id: liveRev.id,
+ created_by_id: null,
+ bundle_uri: 's3://x/',
+ spec: liveRev.spec,
+ })
+ const res = await request(app)
+ .post(`/agents/alias-draft-${draft.id.replace(/-/g, '')}/run`)
+ .set('Host', 'agent-ingress.svc.cluster.local:3030')
+ .send({ message: 'hi' })
+ expect(res.status).toBe(200)
+ const session = await queue.get(res.body.session_id)
+ expect(session!.revision_id).toBe(draft.id)
+ })
+
+ it('domain mode rejects path-form URLs on public *.domainSuffix hosts', async () => {
+ const { revisions, app } = mk({ routingMode: 'domain', domainSuffix: '.agents.test' })
+ await seedApp(revisions, 'fenced-agent')
+ // The alias exists for in-cluster callers only; the public edge keeps
+ // exactly one URL shape per agent (slug in Host, routes at root).
+ const res = await request(app)
+ .post('/agents/fenced-agent/run')
+ .set('Host', 'fenced-agent.agents.test')
+ .send({ message: 'hi' })
+ expect(res.status).toBe(404)
+ expect(res.body.error).toBe('use_host_routing')
+ })
+
it('GET /mcp/connect-info renders Bearer placeholder for a PAT-gated agent', async () => {
const { revisions, app } = mk()
const store = revisions
diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.ts b/products/agent_platform/services/agent-ingress/src/routing/server.ts
index b0a0cb809c32..644daca35bc0 100644
--- a/products/agent_platform/services/agent-ingress/src/routing/server.ts
+++ b/products/agent_platform/services/agent-ingress/src/routing/server.ts
@@ -4,7 +4,7 @@
* mounted at root in domain mode.
*/
-import express, { Express, Request, Response } from 'express'
+import express, { Express, Request, RequestHandler, Response } from 'express'
import { z } from 'zod'
import type {
@@ -22,14 +22,20 @@ import {
applyApprovalDecision,
buildIdentityRegistry,
createLogger,
+ DIGEST_MAX_CHARS_DEFAULT,
effectiveApprovalType,
handleMetricsRequest,
+ INTERNAL_JWT_AUDIENCE,
+ InternalJwtVerifyError,
isDev,
+ renderSessionDigest,
RevisionStore,
serializeApprovalRequest,
type SessionPrincipal,
SessionQueue,
+ TERMINAL_SESSION_STATES,
triggerAuthConfig,
+ verifyInternalJwt,
} from '@posthog/agent-shared'
const log = createLogger('ingress')
@@ -222,6 +228,17 @@ function linkResultPage(message: string): string {
return `<!doctype html><meta charset="utf-8"><title>PostHog agent linking</title><body style="font-family:system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#111"><h2>PostHog agent</h2><p style="font-size:1.05rem">${safe}</p></body>`
}
+// Request body for the internal /internal/session-digest route (below). The pure
+// digest builders (renderSessionDigest et al.) live in @posthog/agent-shared
+// (spec/session-digest.ts) so the janitor / MCP read paths can share them.
+const SessionDigestBodySchema = z.object({
+ application_id: z.string().min(1),
+ session_id: z.string().min(1),
+ /** Exclusive index into conversation[]; the poll returns conversation[cursor:]. */
+ cursor: z.number().int().nonnegative().optional(),
+ max_chars: z.number().int().positive().max(20_000).optional(),
+})
+
export function buildApp(opts: BuildAppOpts): Express {
const app = express()
// Dev only: serve /metrics on the request port (no dedicated scrape server —
@@ -365,7 +382,41 @@ export function buildApp(opts: BuildAppOpts): Express {
envEncryption: opts.envEncryption,
posthogApiBaseUrl: opts.posthogApiBaseUrl,
} as const
- const mount = opts.routingMode === 'path' ? `${opts.pathPrefix ?? '/agents'}/:slug` : ''
+ const pathMount = `${opts.pathPrefix ?? '/agents'}/:slug`
+ // In path mode (dev) agent routes live only under the path mount. In
+ // domain mode (prod) they mount at root, with the slug riding in the Host
+ // header, and the path mount stays registered as an alias: in-cluster
+ // callers that address the ingress Service directly (the Django
+ // preview-proxy and IngressClient) cannot present a public
+ // *.domainSuffix Host, so without the alias every /agents/<slug>/...
+ // call from Django 404s before resolution runs. `resolveAgent` prefers
+ // the mount's `:slug` param over Host parsing, so the alias needs no
+ // resolver changes.
+ //
+ // The alias is for in-cluster callers only: requests arriving with a
+ // public *.domainSuffix Host must keep using host routing, so the public
+ // URL contract stays single-shape per agent.
+ const publicHostGuard: RequestHandler = (req, res, next) => {
+ const host = (req.headers.host ?? '').split(':')[0]
+ if (opts.domainSuffix && host.endsWith(opts.domainSuffix)) {
+ res.status(404).json({ error: 'use_host_routing' })
+ return
+ }
+ next()
+ }
+ const mounts: { mount: string; guards: RequestHandler[] }[] =
+ opts.routingMode === 'path'
+ ? [{ mount: pathMount, guards: [] }]
+ : [
+ { mount: '', guards: [] },
+ { mount: pathMount, guards: [publicHostGuard] },
+ ]
+ // Register one handler (or trigger router) at every active mount.
+ const agentRoute = (method: 'get' | 'post', suffix: string, handler: RequestHandler): void => {
+ for (const { mount, guards } of mounts) {
+ app[method](`${mount}${suffix}`, ...guards, handler)
+ }
+ }
// Principal tool-approval decisions — the lightweight, identity-matched
// counterpart to the Slack interactivity handler, for posthog (PostHog Code)
@@ -382,9 +433,10 @@ export function buildApp(opts: BuildAppOpts): Express {
// same per-agent ingress base it uses for `/send` (PostHog Code does). The
// `:slug` is unused — the row is resolved from the approval id, not the
// slug — but keeping the path under the mount matches how clients address
- // the ingress. In domain mode `mount` is '' so it's `/approvals/:id/decide`.
- app.post(
- `${mount}/approvals/:id/decide`,
+ // the ingress. In domain mode the root mount makes it `/approvals/:id/decide`.
+ agentRoute(
+ 'post',
+ '/approvals/:id/decide',
asyncHandler(async (req: Request, res: Response) => {
if (!opts.approvals) {
res.status(500).json({ error: 'approvals_not_configured' })
@@ -490,7 +542,7 @@ export function buildApp(opts: BuildAppOpts): Express {
}
res.json(serializeApprovalRequest(row))
}
- app.get(`${mount}/approvals/:id`, asyncHandler(respondWithApproval))
+ agentRoute('get', '/approvals/:id', asyncHandler(respondWithApproval))
// Transcript reload, principal-authed: "prove you own the session" lets a
// client rehydrate a session's conversation from any project (the dock on
@@ -537,15 +589,89 @@ export function buildApp(opts: BuildAppOpts): Express {
}
res.json({ ...session, conversation_trimmed: false })
}
- app.get(`${mount}/sessions/:id`, asyncHandler(respondWithSession))
+ agentRoute('get', '/sessions/:id', asyncHandler(respondWithSession))
+
+ // Internal-only session digest — backs the `agent-applications-listen` MCP tool via the
+ // Django bridge. NOT a per-agent public surface: it is a root-level route
+ // (never rendered on `/schemas`) gated by an audience-bound internal JWT
+ // (aud=agent-ingress.rpc, `x-internal-secret`), exactly like the Django↔janitor
+ // RPCs. Django is the sole caller — it enforces the team/app gate on its side,
+ // and `getForApplication` re-scopes at the store layer as a backstop.
+ app.post(
+ '/internal/session-digest',
+ asyncHandler(async (req: Request, res: Response): Promise<void> => {
+ if (!opts.internalSigningKey) {
+ // Fail closed: this route shares the public listener, so a missing
+ // key is a misconfig, never an open door. `requiredInProd` guarantees
+ // the key in prod (config.ts).
+ res.status(500).json({ error: 'internal_auth_not_configured' })
+ return
+ }
+ const rawSecret = req.headers['x-internal-secret']
+ const token = Array.isArray(rawSecret) ? rawSecret[0] : rawSecret
+ if (!token) {
+ res.status(401).json({ error: 'unauthorized', reason: 'missing_token' })
+ return
+ }
+ try {
+ await verifyInternalJwt({
+ token,
+ audience: INTERNAL_JWT_AUDIENCE.INGRESS_RPC,
+ signingKey: opts.internalSigningKey,
+ })
+ } catch (e) {
+ res.status(401).json({ error: 'unauthorized', reason: (e as InternalJwtVerifyError).reason })
+ return
+ }
+
+ const parsed = SessionDigestBodySchema.safeParse(req.body)
+ if (!parsed.success) {
+ res.status(400).json({ error: 'invalid_body', issues: parsed.error.issues })
+ return
+ }
+ const { application_id, session_id, cursor, max_chars } = parsed.data
+
+ // One atomic read: state, conversation and usage_total are columns of
+ // the same `agent_session` row, so `next_cursor` (= conversation.length)
+ // and the slice always come from one consistent snapshot — a turn landing
+ // mid-poll is either fully visible or not yet, never half-served.
+ const session = await opts.queue.getForApplication(session_id, application_id)
+ if (!session) {
+ // Collapses "no such session" and "belongs to another app" — no
+ // cross-tenant existence leak (mirrors getOwnedSession).
+ res.status(404).json({ error: 'session_not_found' })
+ return
+ }
+
+ const total = session.conversation.length
+ const from = Math.min(Math.max(cursor ?? 0, 0), total)
+ const slice = session.conversation.slice(from)
+ const { digest, truncated } = renderSessionDigest(
+ session,
+ slice,
+ total,
+ max_chars ?? DIGEST_MAX_CHARS_DEFAULT
+ )
+ res.json({
+ session_id: session.id,
+ state: session.state,
+ turns: total,
+ next_cursor: total,
+ digest,
+ truncated,
+ done: TERMINAL_SESSION_STATES.has(session.state),
+ })
+ })
+ )
// Self-describing schemas. The response cascades from `spec.triggers` ∩
// `TRIGGER_MODULES`: only modules whose type is configured on this agent
// appear, and each route is rendered with its auth concretely resolved
// against the agent's `spec.auth`. There is no hand-maintained map of
// "which triggers have schemas" — it falls out of the module registry.
- app.get(
- `${mount}/schemas`,
+ agentRoute(
+ 'get',
+ '/schemas',
asyncHandler(async (req: Request, res: Response) => {
const resolved = await resolveAgent(resolver, req, res)
if (!resolved) {
@@ -585,7 +711,10 @@ export function buildApp(opts: BuildAppOpts): Express {
)
for (const m of TRIGGER_MODULES) {
- app.use(mount, mountTrigger(triggerDeps, m))
+ const router = mountTrigger(triggerDeps, m)
+ for (const { mount, guards } of mounts) {
+ app.use(mount, ...guards, router)
+ }
}
// Last in the chain. Catches rejections from `asyncHandler`-wrapped
diff --git a/products/agent_platform/services/agent-ingress/src/routing/session-digest.test.ts b/products/agent_platform/services/agent-ingress/src/routing/session-digest.test.ts
new file mode 100644
index 000000000000..21a5840b2223
--- /dev/null
+++ b/products/agent_platform/services/agent-ingress/src/routing/session-digest.test.ts
@@ -0,0 +1,322 @@
+/**
+ * Unit tests for the internal `POST /internal/session-digest` route (see
+ * server.ts). Unlike the sibling `server.test.ts` (which drives the full
+ * routing surface against a real Postgres queue), this route reads a single
+ * session via `queue.getForApplication` and needs no other store, so we wire
+ * an in-memory fake queue and never touch the DB. That keeps these payload-
+ * safety / cursor / truncation assertions fast and hermetic — exactly the
+ * cases where a real DB adds nothing.
+ */
+
+import request from 'supertest'
+import { describe, expect, it } from 'vitest'
+
+import {
+ type AgentSession,
+ type ConversationMessage,
+ type CredentialBroker,
+ EMPTY_USAGE_TOTAL,
+ type EncryptedFields,
+ type HttpFetcher,
+ type IdentityCredentialStore,
+ type IdentityLinkStateStore,
+ type IdentityStore,
+ INTERNAL_JWT_AUDIENCE,
+ mintInternalJwt,
+ type RevisionStore,
+ type SessionEventBus,
+ type SessionQueue,
+ type TransportBindingStore,
+} from '@posthog/agent-shared'
+
+import { buildApp } from './server'
+
+const SIGNING_KEY = 'test-internal-signing-key'
+const APP_ID = 'app-1111-2222'
+const OTHER_APP_ID = 'app-9999-8888'
+const SESSION_ID = 'sess-aaaa-bbbb'
+
+// A sentinel we plant inside a tool RESULT's content. The digest must never
+// echo tool arguments or result payloads, so this string must not appear in
+// any response body — that's the payload-safety property under test.
+const SECRET_PAYLOAD = 'SUPER_SECRET_TOOL_OUTPUT_a1b2c3d4'
+
+/** Minimal AgentSession fixture. Only the fields the digest route reads
+ * (`id`, `state`, `conversation`, `usage_total`) carry meaning; the rest are
+ * filled to satisfy the type. */
+function makeSession(overrides: Partial<AgentSession> = {}): AgentSession {
+ return {
+ id: SESSION_ID,
+ application_id: APP_ID,
+ revision_id: 'rev-1',
+ team_id: 1,
+ external_key: null,
+ idempotency_key: null,
+ trigger_metadata: null,
+ state: 'running',
+ principal: null,
+ conversation: [],
+ pending_inputs: [],
+ retry_count: 0,
+ usage_total: { ...EMPTY_USAGE_TOTAL },
+ acl: [],
+ pending_elevation_requests: [],
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ ...overrides,
+ } as AgentSession
+}
+
+/** In-memory queue whose `getForApplication` honours the (session_id,
+ * application_id) tenant scope exactly like the Pg store — returning null when
+ * the ids don't both match, so the cross-tenant 404 test is meaningful. */
+function fakeQueue(session: AgentSession | null): SessionQueue {
+ return {
+ async getForApplication(sessionId: string, applicationId: string): Promise<AgentSession | null> {
+ if (!session) {
+ return null
+ }
+ if (sessionId === session.id && applicationId === session.application_id) {
+ return session
+ }
+ return null
+ },
+ } as unknown as SessionQueue
+}
+
+/** Build the ingress app with a fake queue + internal signing key. No other
+ * store is exercised by the digest route, so they're stubbed. */
+function mk(session: AgentSession | null): ReturnType<typeof buildApp> {
+ return buildApp({
+ revisions: {} as unknown as RevisionStore,
+ queue: fakeQueue(session),
+ bus: {} as unknown as SessionEventBus,
+ credentialBroker: {} as unknown as CredentialBroker,
+ identities: {} as unknown as IdentityStore,
+ http: {} as unknown as HttpFetcher,
+ identityCredentials: {} as unknown as IdentityCredentialStore,
+ identityLinks: {} as unknown as IdentityLinkStateStore,
+ transportBindings: {} as unknown as TransportBindingStore,
+ envEncryption: {} as unknown as EncryptedFields,
+ routingMode: 'path',
+ pathPrefix: '/agents',
+ internalSigningKey: SIGNING_KEY,
+ })
+}
+
+/** Same as mk but with NO internal signing key — the route shares the public
+ * listener, so a missing key must fail closed (500), never open the door. */
+function mkNoKey(session: AgentSession | null): ReturnType<typeof buildApp> {
+ return buildApp({
+ revisions: {} as unknown as RevisionStore,
+ queue: fakeQueue(session),
+ bus: {} as unknown as SessionEventBus,
+ credentialBroker: {} as unknown as CredentialBroker,
+ identities: {} as unknown as IdentityStore,
+ http: {} as unknown as HttpFetcher,
+ identityCredentials: {} as unknown as IdentityCredentialStore,
+ identityLinks: {} as unknown as IdentityLinkStateStore,
+ transportBindings: {} as unknown as TransportBindingStore,
+ envEncryption: {} as unknown as EncryptedFields,
+ routingMode: 'path',
+ pathPrefix: '/agents',
+ internalSigningKey: undefined,
+ })
+}
+
+async function ingressToken(): Promise<string> {
+ return mintInternalJwt({ audience: INTERNAL_JWT_AUDIENCE.INGRESS_RPC, signingKey: SIGNING_KEY })
+}
+
+function user(content: string): ConversationMessage {
+ return { role: 'user', content, timestamp: Date.now() }
+}
+
+function assistantText(text: string): ConversationMessage {
+ return { role: 'assistant', content: [{ type: 'text', text }], timestamp: Date.now() }
+}
+
+function assistantToolCall(name: string, args: Record<string, unknown>): ConversationMessage {
+ return {
+ role: 'assistant',
+ content: [{ type: 'toolCall', id: `call-${name}`, name, arguments: args }],
+ timestamp: Date.now(),
+ }
+}
+
+function toolResult(toolName: string, text: string, isError = false): ConversationMessage {
+ return {
+ role: 'toolResult',
+ toolCallId: `call-${toolName}`,
+ toolName,
+ content: [{ type: 'text', text }],
+ isError,
+ timestamp: Date.now(),
+ }
+}
+
+describe('POST /internal/session-digest', () => {
+ it('401s {missing_token} when x-internal-secret is absent', async () => {
+ const app = mk(makeSession())
+ const res = await request(app)
+ .post('/internal/session-digest')
+ .send({ application_id: APP_ID, session_id: SESSION_ID })
+ expect(res.status).toBe(401)
+ expect(res.body).toEqual({ error: 'unauthorized', reason: 'missing_token' })
+ })
+
+ it('500s {internal_auth_not_configured} when no internal signing key is set (fail closed)', async () => {
+ // The route shares the public listener; a missing key is a misconfig, not
+ // an open door — it must 500 before even looking at the token.
+ const app = mkNoKey(makeSession())
+ const token = await ingressToken()
+ const res = await request(app)
+ .post('/internal/session-digest')
+ .set('x-internal-secret', token)
+ .send({ application_id: APP_ID, session_id: SESSION_ID })
+ expect(res.status).toBe(500)
+ expect(res.body).toEqual({ error: 'internal_auth_not_configured' })
+ })
+
+ it('400s {invalid_body} when a required field is missing (valid token)', async () => {
+ // Auth passes, but the body omits session_id → schema rejection, not a 500.
+ const app = mk(makeSession())
+ const token = await ingressToken()
+ const res = await request(app)
+ .post('/internal/session-digest')
+ .set('x-internal-secret', token)
+ .send({ application_id: APP_ID })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('invalid_body')
+ })
+
+ it('401s a wrong-audience JWT (minted for JANITOR_RPC)', async () => {
+ const app = mk(makeSession())
+ const wrongAud = await mintInternalJwt({
+ audience: INTERNAL_JWT_AUDIENCE.JANITOR_RPC,
+ signingKey: SIGNING_KEY,
+ })
+ const res = await request(app)
+ .post('/internal/session-digest')
+ .set('x-internal-secret', wrongAud)
+ .send({ application_id: APP_ID, session_id: SESSION_ID })
+ expect(res.status).toBe(401)
+ expect(res.body.error).toBe('unauthorized')
+ })
+
+ it('404s {session_not_found} when the session belongs to a DIFFERENT application (no cross-tenant leak)', async () => {
+ // The session exists under APP_ID; a caller scoped to OTHER_APP_ID must
+ // get an indistinguishable "not found", never the session's existence.
+ const app = mk(makeSession())
+ const token = await ingressToken()
+ const res = await request(app)
+ .post('/internal/session-digest')
+ .set('x-internal-secret', token)
+ .send({ application_id: OTHER_APP_ID, session_id: SESSION_ID })
+ expect(res.status).toBe(404)
+ expect(res.body).toEqual({ error: 'session_not_found' })
+ })
+
+ it('happy path: digest names the tool + its byte count, never the payload; terminal → done', async () => {
+ const conversation: ConversationMessage[] = [
+ user('run the report'),
+ assistantToolCall('run_query', { sql: 'SELECT * FROM secret_table' }),
+ toolResult('run_query', SECRET_PAYLOAD),
+ assistantText('Here is your report summary.'),
+ ]
+ const app = mk(makeSession({ state: 'completed', conversation }))
+ const token = await ingressToken()
+ const res = await request(app)
+ .post('/internal/session-digest')
+ .set('x-internal-secret', token)
+ .send({ application_id: APP_ID, session_id: SESSION_ID })
+ expect(res.status).toBe(200)
+ expect(res.body.session_id).toBe(SESSION_ID)
+ expect(res.body.next_cursor).toBe(conversation.length)
+ expect(res.body.turns).toBe(conversation.length)
+ // `completed` is terminal → done true.
+ expect(res.body.done).toBe(true)
+ // Digest carries the last assistant text + the tool-activity line.
+ expect(res.body.digest).toContain('Here is your report summary.')
+ expect(res.body.digest).toContain('run_query')
+ // A byte-count marker (`NB`) is present for the tool result.
+ expect(res.body.digest).toMatch(/run_query[^;]*\b\d+B\b/)
+ // Payload safety: neither the tool ARGUMENTS nor the RESULT payload text
+ // leak into any part of the response.
+ const whole = JSON.stringify(res.body)
+ expect(whole).not.toContain(SECRET_PAYLOAD)
+ expect(whole).not.toContain('secret_table')
+ })
+
+ it('non-terminal running session reports done:false', async () => {
+ const app = mk(makeSession({ state: 'running', conversation: [assistantText('working…')] }))
+ const token = await ingressToken()
+ const res = await request(app)
+ .post('/internal/session-digest')
+ .set('x-internal-secret', token)
+ .send({ application_id: APP_ID, session_id: SESSION_ID })
+ expect(res.status).toBe(200)
+ expect(res.body.done).toBe(false)
+ })
+
+ it('cursor: tool activity reflects only conversation[cursor:]; re-poll at next_cursor yields no tool activity', async () => {
+ // First 2 turns hold the tool traffic; a later assistant turn follows.
+ const conversation: ConversationMessage[] = [
+ assistantToolCall('search', {}),
+ toolResult('search', 'first batch of rows'),
+ assistantText('done searching'),
+ ]
+ const app = mk(makeSession({ conversation }))
+ const token = await ingressToken()
+ // cursor=2 → slice is just the trailing assistant text, no tool activity.
+ const res = await request(app)
+ .post('/internal/session-digest')
+ .set('x-internal-secret', token)
+ .send({ application_id: APP_ID, session_id: SESSION_ID, cursor: 2 })
+ expect(res.status).toBe(200)
+ expect(res.body.digest).toContain('Tools: (none)')
+ expect(res.body.digest).not.toContain('search ×')
+ // Re-poll from the returned next_cursor (== length): empty slice, still no
+ // tool activity, no double-serve of the earlier tool traffic.
+ const next = res.body.next_cursor as number
+ expect(next).toBe(conversation.length)
+ const res2 = await request(app)
+ .post('/internal/session-digest')
+ .set('x-internal-secret', token)
+ .send({ application_id: APP_ID, session_id: SESSION_ID, cursor: next })
+ expect(res2.status).toBe(200)
+ expect(res2.body.digest).toContain('Tools: (none)')
+ expect(res2.body.next_cursor).toBe(conversation.length)
+ })
+
+ it('max_chars: a large conversation clips to <= max_chars code points with a re-poll pointer', async () => {
+ const bigText = 'x'.repeat(5_000)
+ const conversation: ConversationMessage[] = [assistantText(bigText)]
+ const app = mk(makeSession({ conversation }))
+ const token = await ingressToken()
+ const MAX = 200
+ const res = await request(app)
+ .post('/internal/session-digest')
+ .set('x-internal-secret', token)
+ .send({ application_id: APP_ID, session_id: SESSION_ID, max_chars: MAX })
+ expect(res.status).toBe(200)
+ expect(res.body.truncated).toBe(true)
+ // Code-point length (not UTF-16 length) is what the route budgets against.
+ expect(Array.from(res.body.digest as string).length).toBeLessThanOrEqual(MAX)
+ expect(res.body.digest).toContain('…[digest clipped; re-poll with cursor=')
+ })
+
+ it('max_chars smaller than the re-poll pointer still never exceeds max_chars', async () => {
+ const conversation: ConversationMessage[] = [assistantText('x'.repeat(5_000))]
+ const app = mk(makeSession({ conversation }))
+ const token = await ingressToken()
+ const MAX = 10 // smaller than the ~40-char pointer — the hard cap must win
+ const res = await request(app)
+ .post('/internal/session-digest')
+ .set('x-internal-secret', token)
+ .send({ application_id: APP_ID, session_id: SESSION_ID, max_chars: MAX })
+ expect(res.status).toBe(200)
+ expect(res.body.truncated).toBe(true)
+ expect(Array.from(res.body.digest as string).length).toBeLessThanOrEqual(MAX)
+ })
+})
diff --git a/products/agent_platform/services/agent-shared/src/index.ts b/products/agent_platform/services/agent-shared/src/index.ts
index 24148f0b0f5c..97cdd4cf053e 100644
--- a/products/agent_platform/services/agent-shared/src/index.ts
+++ b/products/agent_platform/services/agent-shared/src/index.ts
@@ -15,6 +15,7 @@ export * from './spec/spec'
export * from './spec/spec-json-schema'
export * from './spec/slack-manifest'
export * from './spec/summarize-conversation'
+export * from './spec/session-digest'
export * from './spec/tool'
export * from './spec/custom-tool'
export * from './spec/tool-approval'
diff --git a/products/agent_platform/services/agent-shared/src/runtime/internal-jwt.ts b/products/agent_platform/services/agent-shared/src/runtime/internal-jwt.ts
index 7902250dec38..0d0b3bf66517 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/internal-jwt.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/internal-jwt.ts
@@ -8,6 +8,7 @@
*
* Audiences today:
* - INGRESS_PREVIEW — Django → ingress, draft-revision preview invokes
+ * - INGRESS_RPC — Django → ingress, internal read RPCs (session digest)
* - JANITOR_RPC — Django → janitor, bundle CRUD + authoring API
*
* Production minting happens on the Django side (posthog/jwt.py:
@@ -20,6 +21,7 @@ import { jwtVerify, SignJWT } from 'jose'
export const INTERNAL_JWT_AUDIENCE = {
INGRESS_PREVIEW: 'agent-ingress.preview',
+ INGRESS_RPC: 'agent-ingress.rpc',
JANITOR_RPC: 'agent-janitor.rpc',
} as const
diff --git a/products/agent_platform/services/agent-shared/src/spec/session-digest.test.ts b/products/agent_platform/services/agent-shared/src/spec/session-digest.test.ts
new file mode 100644
index 000000000000..9e86bc5a2cda
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/spec/session-digest.test.ts
@@ -0,0 +1,199 @@
+/**
+ * Direct unit tests for the pure session-digest helpers (session-digest.ts) —
+ * the payload-free view behind the `agent-applications-listen` MCP tool. The ingress route
+ * test (services/agent-ingress/src/routing/session-digest.test.ts) drives these
+ * over HTTP; here we exercise the builders in isolation so the byte-count,
+ * error-count, cursor-split and truncation branches each have a focused case.
+ * Fixtures mirror that route test's style (spec types + EMPTY_USAGE_TOTAL).
+ */
+
+import {
+ buildToolActivityLine,
+ DIGEST_MAX_CHARS_DEFAULT,
+ renderSessionDigest,
+ toolResultBytes,
+ usageLine,
+} from './session-digest'
+import {
+ type AgentSession,
+ type ConversationMessage,
+ EMPTY_USAGE_TOTAL,
+ type ImageContent,
+ type SessionUsageTotal,
+ type TextContent,
+} from './spec'
+
+const SESSION_ID = 'sess-aaaa-bbbb'
+const APP_ID = 'app-1111-2222'
+
+/** Minimal AgentSession fixture — only the fields renderSessionDigest reads
+ * (`state`, `conversation`, `usage_total`) carry meaning; the rest satisfy the
+ * type. */
+function makeSession(overrides: Partial<AgentSession> = {}): AgentSession {
+ return {
+ id: SESSION_ID,
+ application_id: APP_ID,
+ revision_id: 'rev-1',
+ team_id: 1,
+ external_key: null,
+ idempotency_key: null,
+ trigger_metadata: null,
+ state: 'running',
+ principal: null,
+ conversation: [],
+ pending_inputs: [],
+ retry_count: 0,
+ usage_total: { ...EMPTY_USAGE_TOTAL },
+ acl: [],
+ pending_elevation_requests: [],
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ ...overrides,
+ } as AgentSession
+}
+
+function assistantText(text: string): ConversationMessage {
+ return { role: 'assistant', content: [{ type: 'text', text }], timestamp: Date.now() }
+}
+
+function assistantToolCall(name: string): ConversationMessage {
+ return {
+ role: 'assistant',
+ content: [{ type: 'toolCall', id: `call-${name}`, name, arguments: {} }],
+ timestamp: Date.now(),
+ }
+}
+
+function toolResult(toolName: string, content: (TextContent | ImageContent)[], isError = false): ConversationMessage {
+ return {
+ role: 'toolResult',
+ toolCallId: `call-${toolName}`,
+ toolName,
+ content,
+ isError,
+ timestamp: Date.now(),
+ }
+}
+
+function text(t: string): TextContent {
+ return { type: 'text', text: t }
+}
+
+describe('buildToolActivityLine', () => {
+ it('summarizes a single tool call + result as `name ×1, <bytes>B`', () => {
+ const slice: ConversationMessage[] = [assistantToolCall('bash'), toolResult('bash', [text('hello')])]
+ const line = buildToolActivityLine(slice)
+ // 'hello' is 5 ASCII bytes.
+ expect(line).toBe('bash ×1, 5B')
+ })
+
+ it('lists TWO distinct tools, joined by `; `', () => {
+ const slice: ConversationMessage[] = [
+ assistantToolCall('bash'),
+ toolResult('bash', [text('ok')]),
+ assistantToolCall('search'),
+ toolResult('search', [text('rows')]),
+ ]
+ const line = buildToolActivityLine(slice)
+ expect(line).toContain('bash ×1, 2B')
+ expect(line).toContain('search ×1, 4B')
+ expect(line).toContain('; ')
+ expect(line.split('; ')).toHaveLength(2)
+ })
+
+ it('counts an errored tool result with `err×1`', () => {
+ const slice: ConversationMessage[] = [assistantToolCall('bash'), toolResult('bash', [text('boom')], true)]
+ const line = buildToolActivityLine(slice)
+ expect(line).toContain('err×1')
+ expect(line).toBe('bash ×1, 4B, err×1')
+ })
+
+ it('reports `name ×0` for a result whose matching call fell before the cursor', () => {
+ // The slice split the call (before cursor) from its result (after) — the
+ // tool still appears, with zero calls counted in this window.
+ const slice: ConversationMessage[] = [toolResult('search', [text('late rows')])]
+ const line = buildToolActivityLine(slice)
+ expect(line).toContain('search ×0')
+ })
+
+ it('returns "" for an empty slice / a slice with no tools', () => {
+ expect(buildToolActivityLine([])).toBe('')
+ expect(buildToolActivityLine([assistantText('just talking')])).toBe('')
+ })
+})
+
+describe('toolResultBytes', () => {
+ it('counts text content as its utf8 byte length', () => {
+ // 'héllo' — the é is 2 bytes in utf8, so 6 bytes for 5 code points.
+ expect(toolResultBytes([text('héllo')])).toBe(Buffer.byteLength('héllo', 'utf8'))
+ expect(toolResultBytes([text('héllo')])).toBe(6)
+ })
+
+ it('counts image content as the base64 data length', () => {
+ const data = 'aGVsbG8='
+ const image: ImageContent = { type: 'image', data, mimeType: 'image/png' }
+ expect(toolResultBytes([image])).toBe(data.length)
+ })
+})
+
+describe('renderSessionDigest', () => {
+ it('renders `(no assistant text yet)` + turns=0 + truncated:false for an empty conversation', () => {
+ const session = makeSession({ conversation: [] })
+ const { digest, truncated } = renderSessionDigest(session, [], 0, DIGEST_MAX_CHARS_DEFAULT)
+ expect(digest).toContain('(no assistant text yet)')
+ expect(digest).toContain('turns=0')
+ expect(truncated).toBe(false)
+ })
+
+ it('falls back to the conversation-wide last assistant text when the slice has only tool traffic', () => {
+ const conversation: ConversationMessage[] = [
+ assistantText('earlier answer'),
+ assistantToolCall('bash'),
+ toolResult('bash', [text('output')]),
+ ]
+ const session = makeSession({ conversation })
+ // Slice is only the tool traffic (cursor past the assistant text).
+ const slice = conversation.slice(1)
+ const { digest } = renderSessionDigest(session, slice, conversation.length, DIGEST_MAX_CHARS_DEFAULT)
+ expect(digest).toContain('earlier answer')
+ })
+
+ it('reports truncated:false for a small digest', () => {
+ const conversation: ConversationMessage[] = [assistantText('short reply')]
+ const session = makeSession({ conversation })
+ const { digest, truncated } = renderSessionDigest(session, conversation, 1, DIGEST_MAX_CHARS_DEFAULT)
+ expect(truncated).toBe(false)
+ expect(digest).toContain('short reply')
+ })
+
+ it('clips a large digest to <= maxChars code points and ends with the re-poll pointer', () => {
+ const conversation: ConversationMessage[] = [assistantText('x'.repeat(5_000))]
+ const session = makeSession({ conversation })
+ const MAX = 200
+ const { digest, truncated } = renderSessionDigest(session, conversation, 1, MAX)
+ expect(truncated).toBe(true)
+ expect(Array.from(digest).length).toBeLessThanOrEqual(MAX)
+ expect(digest).toContain('…[digest clipped; re-poll with cursor=1]')
+ })
+
+ it('never exceeds maxChars even when maxChars is smaller than the pointer', () => {
+ const conversation: ConversationMessage[] = [assistantText('x'.repeat(5_000))]
+ const session = makeSession({ conversation })
+ const MAX = 10 // smaller than the ~40-char pointer — the hard cap must win
+ const { digest, truncated } = renderSessionDigest(session, conversation, 1, MAX)
+ expect(truncated).toBe(true)
+ expect(Array.from(digest).length).toBeLessThanOrEqual(MAX)
+ })
+})
+
+describe('usageLine', () => {
+ it('formats tokens_in / tokens_out / cost_total', () => {
+ const usage: SessionUsageTotal = {
+ ...EMPTY_USAGE_TOTAL,
+ tokens_in: 120,
+ tokens_out: 34,
+ cost_total: 0.5,
+ }
+ expect(usageLine(usage)).toBe('tokens_in=120 tokens_out=34 cost_total=0.5')
+ })
+})
diff --git a/products/agent_platform/services/agent-shared/src/spec/session-digest.ts b/products/agent_platform/services/agent-shared/src/spec/session-digest.ts
new file mode 100644
index 000000000000..196af12241ae
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/spec/session-digest.ts
@@ -0,0 +1,108 @@
+/**
+ * Pure session-digest helpers behind the `agent-applications-listen` MCP tool: a compact,
+ * payload-free view of a session — last assistant text + a one-line tool-activity
+ * summary + state/usage. Lives beside summarize-conversation.ts (whose
+ * `lastAssistantTextPreview` it reuses) so the janitor / MCP read paths can share
+ * it; the ingress `/internal/session-digest` route is the only consumer today.
+ */
+
+import type { AgentSession, ConversationMessage, ImageContent, SessionUsageTotal, TextContent } from './spec'
+import { lastAssistantTextPreview } from './summarize-conversation'
+
+/** Digest text-preview budget — larger than summarize-conversation's PREVIEW_MAX
+ * (120, a list-row length) so the latest assistant text isn't clipped short. */
+const DIGEST_TEXT_MAX = 2_000
+/** Overall digest budget when the caller omits `max_chars`. */
+export const DIGEST_MAX_CHARS_DEFAULT = 4_000
+export const TERMINAL_SESSION_STATES = new Set<string>(['completed', 'closed', 'cancelled', 'failed'])
+
+/** Byte size of a tool result's content — never the content itself. */
+export function toolResultBytes(content: (TextContent | ImageContent)[]): number {
+ let n = 0
+ for (const block of content) {
+ n += block.type === 'text' ? Buffer.byteLength(block.text, 'utf8') : block.data.length
+ }
+ return n
+}
+
+/**
+ * One line summarizing tool activity in a conversation slice: `name ×calls, NB,
+ * err×E` per tool, joined by `; `. Walks assistant `toolCall` blocks and
+ * top-level `toolResult` messages. Never emits arguments or result payloads.
+ */
+export function buildToolActivityLine(slice: ConversationMessage[]): string {
+ const calls = new Map<string, number>()
+ const bytes = new Map<string, number>()
+ const errors = new Map<string, number>()
+ for (const m of slice) {
+ if (m.role === 'assistant') {
+ for (const c of m.content) {
+ if (c.type === 'toolCall') {
+ calls.set(c.name, (calls.get(c.name) ?? 0) + 1)
+ }
+ }
+ } else if (m.role === 'toolResult') {
+ bytes.set(m.toolName, (bytes.get(m.toolName) ?? 0) + toolResultBytes(m.content))
+ if (m.isError) {
+ errors.set(m.toolName, (errors.get(m.toolName) ?? 0) + 1)
+ }
+ }
+ }
+ const names = new Set<string>([...calls.keys(), ...bytes.keys()])
+ if (names.size === 0) {
+ return ''
+ }
+ const parts: string[] = []
+ for (const name of names) {
+ let s = `${name} ×${calls.get(name) ?? 0}`
+ const b = bytes.get(name)
+ if (b !== undefined) {
+ s += `, ${b}B`
+ }
+ const e = errors.get(name)
+ if (e) {
+ s += `, err×${e}`
+ }
+ parts.push(s)
+ }
+ return parts.join('; ')
+}
+
+export function usageLine(u: SessionUsageTotal): string {
+ return `tokens_in=${u.tokens_in} tokens_out=${u.tokens_out} cost_total=${u.cost_total}`
+}
+
+/**
+ * Render the digest for a slice and clip it to `maxChars` (code-point-safe, so
+ * surrogate pairs never split — mirrors summarize-conversation's truncation).
+ * A clipped digest ends in a pointer telling the caller to re-poll for detail.
+ */
+export function renderSessionDigest(
+ session: AgentSession,
+ slice: ConversationMessage[],
+ nextCursor: number,
+ maxChars: number
+): { digest: string; truncated: boolean } {
+ // Prefer the new slice's last assistant text; fall back to the whole
+ // conversation's last text (the slice may hold only tool traffic or a user turn).
+ const text =
+ lastAssistantTextPreview(slice, DIGEST_TEXT_MAX) ??
+ lastAssistantTextPreview(session.conversation, DIGEST_TEXT_MAX)
+ const tools = buildToolActivityLine(slice)
+ const lines = [
+ text ?? '(no assistant text yet)',
+ tools ? `Tools: ${tools}` : 'Tools: (none)',
+ `state=${session.state} turns=${session.conversation.length} ${usageLine(session.usage_total)}`,
+ ]
+ const full = lines.join('\n\n')
+ const chars = Array.from(full)
+ if (chars.length <= maxChars) {
+ return { digest: full, truncated: false }
+ }
+ const pointer = ` …[digest clipped; re-poll with cursor=${nextCursor}]`
+ const budget = Math.max(0, maxChars - Array.from(pointer).length)
+ const clipped = chars.slice(0, budget).join('') + pointer
+ // Hard cap: when maxChars is smaller than the pointer itself, the cap wins
+ // over the pointer so the digest never exceeds the caller's max_chars.
+ return { digest: Array.from(clipped).slice(0, maxChars).join(''), truncated: true }
+}
diff --git a/pyproject.toml b/pyproject.toml
index d26ac131477f..9cd467ca72ec 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -518,6 +518,7 @@ ignore_imports = [
"products.agent_platform.backend.presentation.serializers -> products.agent_platform.backend.models",
"products.agent_platform.backend.presentation.views -> products.agent_platform.backend.db",
"products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.generated",
+ "products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.ingress_client",
"products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.internal_jwt",
"products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.janitor_client",
"products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.kernel_skills",
diff --git a/services/mcp/definitions/agent_platform.yaml b/services/mcp/definitions/agent_platform.yaml
index a69211688e58..4ab2baeb90d0 100644
--- a/services/mcp/definitions/agent_platform.yaml
+++ b/services/mcp/definitions/agent_platform.yaml
@@ -110,6 +110,21 @@ tools:
to deep-link the user into the agent console's secret editor (see the secrets-and-integrations skill for the
URL contract and callback flow); this endpoint exists for CI / scripts that already hold the value
out-of-band.
+ agent-applications-invoke:
+ operation: agent_applications_invoke
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Invoke a live agent (start a session)
+ description: >
+ Start a new session on the agent's LIVE (promoted) revision and return its `session_id`. Requires the agent
+ to have a live revision and a `chat` trigger. Your PAT is forwarded so the session runs as you. Drive the
+ conversation with `agent-applications-send` and read progress with `agent-applications-listen`. For a
+ non-live / draft revision use `agent-applications-preview-proxy` instead.
agent-applications-list:
operation: agent_applications_list
enabled: true
@@ -124,6 +139,20 @@ tools:
List every agent application in the project. Returns id, slug, name, description, live_revision, archived
state. Use the slug to drive subsequent calls — it's stable and human-readable. Playbook: read the
`reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.
+ agent-applications-listen:
+ operation: agent_applications_listen
+ enabled: true
+ scopes:
+ - agents:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Poll a live session's progress
+ description: >
+ Read a live session as a single JSON digest (non-streaming): last assistant text, a one-line tool-activity
+ summary, and state / usage. Pass the returned `next_cursor` back as `cursor` to summarize only what's new,
+ and stop when `done` is true. Use this instead of the SSE `/listen` stream from an MCP client.
agent-applications-models:
operation: agent_applications_models
enabled: true
@@ -568,6 +597,20 @@ tools:
on a draft before calling `agent-applications-revisions-freeze-create`. Playbook: read the
`editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote
workflow.
+ agent-applications-send:
+ operation: agent_applications_send
+ enabled: true
+ scopes:
+ - agents:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Send a message to a live session
+ description: >
+ Append a message to an existing live session (from `agent-applications-invoke`) and re-queue it for another
+ turn. `session_id` must belong to this agent. A `completed` session is still open — send re-queues it for
+ another turn; only truly-terminal sessions (failed / cancelled / closed) fail cleanly with a 410.
agent-applications-session-logs:
operation: agent_applications_session_logs
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index c8c87237b701..03c26878c219 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -459,6 +459,21 @@
},
"feature_flag": "agent-platform"
},
+ "agent-applications-invoke": {
+ "description": "Start a new session on the agent's LIVE (promoted) revision and return its `session_id`. Requires the agent to have a live revision and a `chat` trigger. Your PAT is forwarded so the session runs as you. Drive the conversation with `agent-applications-send` and read progress with `agent-applications-listen`. For a non-live / draft revision use `agent-applications-preview-proxy` instead.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Invoke a live agent (start a session)",
+ "title": "Invoke a live agent (start a session)",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform"
+ },
"agent-applications-list": {
"description": "List every agent application in the project. Returns id, slug, name, description, live_revision, archived state. Use the slug to drive subsequent calls — it's stable and human-readable. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.",
"category": "Agent stack",
@@ -474,6 +489,21 @@
},
"feature_flag": "agent-platform"
},
+ "agent-applications-listen": {
+ "description": "Read a live session as a single JSON digest (non-streaming): last assistant text, a one-line tool-activity summary, and state / usage. Pass the returned `next_cursor` back as `cursor` to summarize only what's new, and stop when `done` is true. Use this instead of the SSE `/listen` stream from an MCP client.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Poll a live session's progress",
+ "title": "Poll a live session's progress",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform"
+ },
"agent-applications-models": {
"description": "Read-only model catalog for `spec.models`. Returns every model the gateway serves (id, provider, display name, per-Mtok input/output cost) plus `levels` — the concrete, priority-ordered model list each `auto` level (`low` / `medium` / `high`) currently resolves to. Use this to answer \"what will auto/medium actually run?\" and to pick ids for a `manual` policy instead of guessing. The level membership is resolved live against the catalog, so it reflects what the runner picks today, not a hardcoded list.",
"category": "Agent stack",
@@ -864,6 +894,21 @@
},
"feature_flag": "agent-platform"
},
+ "agent-applications-send": {
+ "description": "Append a message to an existing live session (from `agent-applications-invoke`) and re-queue it for another turn. `session_id` must belong to this agent. A `completed` session is still open — send re-queues it for another turn; only truly-terminal sessions (failed / cancelled / closed) fail cleanly with a 410.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Send a message to a live session",
+ "title": "Send a message to a live session",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform"
+ },
"agent-applications-session-logs": {
"description": "The append-only event log for one session — the runner's own record of what happened, separate from the conversation transcript. Entries carry a level (info / warn / error), a message, and structured metadata: tool executions + results, MCP open successes / failures (with a coarse failure category), identity resolution decisions (`identity.resolved` — which credential source acted as whom, never the token), approval gates, and errors. Use this to debug WHY a session behaved as it did when the transcript alone isn't enough (e.g. a tool degraded, an MCP failed to open, or an asker's identity resolved unexpectedly). Pair with `agent-applications-sessions-retrieve` for the transcript. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.",
"category": "Agent stack",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 9a409fb59d7f..0de391cb3d48 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -459,6 +459,21 @@
},
"feature_flag": "agent-platform"
},
+ "agent-applications-invoke": {
+ "description": "Start a new session on the agent's LIVE (promoted) revision and return its `session_id`. Requires the agent to have a live revision and a `chat` trigger. Your PAT is forwarded so the session runs as you. Drive the conversation with `agent-applications-send` and read progress with `agent-applications-listen`. For a non-live / draft revision use `agent-applications-preview-proxy` instead.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Invoke a live agent (start a session)",
+ "title": "Invoke a live agent (start a session)",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform"
+ },
"agent-applications-list": {
"description": "List every agent application in the project. Returns id, slug, name, description, live_revision, archived state. Use the slug to drive subsequent calls — it's stable and human-readable. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.",
"category": "Agent stack",
@@ -474,6 +489,21 @@
},
"feature_flag": "agent-platform"
},
+ "agent-applications-listen": {
+ "description": "Read a live session as a single JSON digest (non-streaming): last assistant text, a one-line tool-activity summary, and state / usage. Pass the returned `next_cursor` back as `cursor` to summarize only what's new, and stop when `done` is true. Use this instead of the SSE `/listen` stream from an MCP client.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Poll a live session's progress",
+ "title": "Poll a live session's progress",
+ "required_scopes": ["agents:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "agent-platform"
+ },
"agent-applications-models": {
"description": "Read-only model catalog for `spec.models`. Returns every model the gateway serves (id, provider, display name, per-Mtok input/output cost) plus `levels` — the concrete, priority-ordered model list each `auto` level (`low` / `medium` / `high`) currently resolves to. Use this to answer \"what will auto/medium actually run?\" and to pick ids for a `manual` policy instead of guessing. The level membership is resolved live against the catalog, so it reflects what the runner picks today, not a hardcoded list.",
"category": "Agent stack",
@@ -864,6 +894,21 @@
},
"feature_flag": "agent-platform"
},
+ "agent-applications-send": {
+ "description": "Append a message to an existing live session (from `agent-applications-invoke`) and re-queue it for another turn. `session_id` must belong to this agent. A `completed` session is still open — send re-queues it for another turn; only truly-terminal sessions (failed / cancelled / closed) fail cleanly with a 410.",
+ "category": "Agent stack",
+ "feature": "agent_platform",
+ "summary": "Send a message to a live session",
+ "title": "Send a message to a live session",
+ "required_scopes": ["agents:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "agent-platform"
+ },
"agent-applications-session-logs": {
"description": "The append-only event log for one session — the runner's own record of what happened, separate from the conversation transcript. Entries carry a level (info / warn / error), a message, and structured metadata: tool executions + results, MCP open successes / failures (with a coarse failure category), identity resolution decisions (`identity.resolved` — which credential source acted as whom, never the token), approval gates, and errors. Use this to debug WHY a session behaved as it did when the transcript alone isn't enough (e.g. a tool degraded, an MCP failed to open, or an asker's identity resolved unexpectedly). Pair with `agent-applications-sessions-retrieve` for the transcript. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.",
"category": "Agent stack",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 62e068e1cec4..7abcdc4459a0 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8530,6 +8530,47 @@ export namespace Schemas {
results: AgentFleetLiveSessionSummary[];
}
+ /**
+ * Body for `agent-applications-invoke` — start a new session on the agent's live (promoted) revision.
+ */
+ export interface AgentInvokeRequest {
+ /** The user message that starts the session. Required, non-empty. */
+ message: string;
+ /** Optional idempotency / threading key. A repeat invoke with the same external_key resumes the existing session instead of starting a new one. */
+ external_key?: string;
+ }
+
+ export interface AgentInvokeResponse {
+ /** The newly-created (or resumed, if external_key matched) session id. Feed to agent-applications-send / agent-applications-listen. */
+ session_id: string;
+ /** Session state right after enqueue — `queued`. Poll agent-applications-listen for progress.
+ *
+ * * `queued` - queued
+ * * `running` - running
+ * * `completed` - completed
+ * * `closed` - closed
+ * * `cancelled` - cancelled
+ * * `failed` - failed */
+ state: AgentSessionStateEnum;
+ /** True if an existing session matched `external_key` and was resumed, rather than a new one being created. */
+ resumed: boolean;
+ }
+
+ export interface AgentListenResponse {
+ session_id: string;
+ state: AgentSessionStateEnum;
+ /** Total messages in the conversation so far. */
+ turns: number;
+ /** Pass back as `cursor` on the next call to page forward — high-water mark of messages seen. */
+ next_cursor: number;
+ /** Compact, payload-free progress summary: last assistant text, one-line tool activity, state/usage. */
+ digest: string;
+ /** True when the digest was clipped to `max_chars` — read the full transcript via `agent-applications-sessions-retrieve`. */
+ truncated: boolean;
+ /** True once the current turn has finished (`completed`) or the session ended (`closed`/`cancelled`/`failed`) — stop polling. A `completed` session is still open: `agent-applications-send` to continue it. */
+ done: boolean;
+ }
+
export interface AgentMemoryFile {
/** Full markdown body. */
content: string;
@@ -8831,6 +8872,28 @@ export namespace Schemas {
Sandbox: 'sandbox',
} as const;
+ /**
+ * Body for `agent-applications-send` — append a message to an existing live session.
+ */
+ export interface AgentSendRequest {
+ /** The session to append to (returned by agent-applications-invoke). Must belong to this agent. */
+ session_id: string;
+ /** The user message to append. Required, non-empty. */
+ message: string;
+ }
+
+ export interface AgentSendResponse {
+ /** Session state after the message was appended — `queued` (a new turn will run).
+ *
+ * * `queued` - queued
+ * * `running` - running
+ * * `completed` - completed
+ * * `closed` - closed
+ * * `cancelled` - cancelled
+ * * `failed` - failed */
+ state: AgentSessionStateEnum;
+ }
+
export interface AgentTableHeader {
/** Table name. */
name: string;
@@ -70725,6 +70788,21 @@ export namespace Schemas {
state?: string;
};
+ export type AgentApplicationsListenParams = {
+ /**
+ * `next_cursor` from the previous call. Omit on the first read; pass it back to summarize only what's new.
+ */
+ cursor?: number;
+ /**
+ * Digest character budget (default 4000, range 1–20000). The digest is clipped to fit and `truncated` is set.
+ */
+ max_chars?: number;
+ /**
+ * Session to read (must belong to this agent).
+ */
+ session_id: string;
+ };
+
export type AgentApplicationsPreviewProxyGetParams = {
format?: AgentApplicationsPreviewProxyGetFormat;
/**
diff --git a/services/mcp/src/generated/agent_platform/api.ts b/services/mcp/src/generated/agent_platform/api.ts
index fe4f2b5348ac..e6210866776e 100644
--- a/services/mcp/src/generated/agent_platform/api.ts
+++ b/services/mcp/src/generated/agent_platform/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 37 enabled ops
+ * PostHog API - MCP 40 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -926,6 +926,67 @@ export const AgentApplicationsDestroyParams = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Start a new session on this agent's LIVE (promoted) revision.
+ *
+ * Bridges to ingress `POST /agents/<slug>/run`, forwarding the caller's PAT
+ * so the session principal is the real caller. Returns the new `session_id`;
+ * drive the conversation with `agent-applications-send` and read progress with
+ * `agent-applications-listen`. For non-live / draft revisions use `preview_proxy` instead.
+ */
+export const AgentApplicationsInvokeParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this agent application.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const AgentApplicationsInvokeBody = /* @__PURE__ */ zod
+ .object({
+ message: zod.string().describe('The user message that starts the session. Required, non-empty.'),
+ external_key: zod
+ .string()
+ .optional()
+ .describe(
+ 'Optional idempotency / threading key. A repeat invoke with the same external_key resumes the existing session instead of starting a new one.'
+ ),
+ })
+ .describe("Body for `agent-applications-invoke` — start a new session on the agent's live (promoted) revision.")
+
+/**
+ * Poll a LIVE session's progress as a single JSON digest (non-streaming,
+ * MCP-friendly). Bridges to the internal ingress digest RPC — the digest is
+ * built node-side (never in Python). Tenancy is enforced by the team-scoped
+ * `get_object()` here plus the ingress digest's `application_id` re-scope;
+ * there is no janitor pre-check on this polled path (see the comment below).
+ */
+export const AgentApplicationsListenParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this agent application.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const AgentApplicationsListenQueryParams = /* @__PURE__ */ zod.object({
+ cursor: zod
+ .number()
+ .optional()
+ .describe(
+ "`next_cursor` from the previous call. Omit on the first read; pass it back to summarize only what's new."
+ ),
+ max_chars: zod
+ .number()
+ .optional()
+ .describe(
+ 'Digest character budget (default 4000, range 1–20000). The digest is clipped to fit and `truncated` is set.'
+ ),
+ session_id: zod.string().describe('Session to read (must belong to this agent).'),
+})
+
/**
* Authoring-side proxy for invoking a *draft* (or any non-live) revision.
*
@@ -971,6 +1032,35 @@ export const AgentApplicationsPreviewProxyBody = /* @__PURE__ */ zod
'Body forwarded verbatim to the agent ingress for a *preview* invoke of a\nnon-live revision. The meaningful shape depends on the `rest` path segment:\n\n- `run` — `{ message }`: the user message that starts a new session.\n- `send` — `{ session_id, message }`: append a message to a running session.\n- `cancel` / `listen` — no body.\n\nDocuments `message` / `session_id` so the generated MCP tool exposes them;\nany extra keys are still forwarded as-is to ingress.'
)
+/**
+ * Append a message to an existing LIVE session and re-queue it.
+ *
+ * Bridges to ingress `POST /agents/<slug>/send`, forwarding the caller's PAT
+ * so the ACL principal-match passes. A `completed` session is NOT terminal —
+ * it's a per-turn idle state for a multi-turn agent, so send re-queues it for
+ * another turn; only truly-terminal states (failed / cancelled / closed) 410,
+ * which passes through as a 410. A janitor ownership pre-check runs first, but
+ * it's redundant defense-in-depth (ingress `/send` already app-scopes the
+ * load), kept for a clean early 404.
+ */
+export const AgentApplicationsSendParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this agent application.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const AgentApplicationsSendBody = /* @__PURE__ */ zod
+ .object({
+ session_id: zod
+ .string()
+ .describe('The session to append to (returned by agent-applications-invoke). Must belong to this agent.'),
+ message: zod.string().describe('The user message to append. Required, non-empty.'),
+ })
+ .describe('Body for `agent-applications-send` — append a message to an existing live session.')
+
/**
* List sessions for this application, most recently active first. Strips the
* conversation transcript from each summary, but includes a `preview`
diff --git a/services/mcp/src/tools/generated/agent_platform.ts b/services/mcp/src/tools/generated/agent_platform.ts
index 453bb231b466..67bc289cf2f4 100644
--- a/services/mcp/src/tools/generated/agent_platform.ts
+++ b/services/mcp/src/tools/generated/agent_platform.ts
@@ -5,7 +5,11 @@ import type { Schemas } from '@/api/generated'
import {
AgentApplicationsCreateBody,
AgentApplicationsDestroyParams,
+ AgentApplicationsInvokeBody,
+ AgentApplicationsInvokeParams,
AgentApplicationsListQueryParams,
+ AgentApplicationsListenParams,
+ AgentApplicationsListenQueryParams,
AgentApplicationsPartialUpdateBody,
AgentApplicationsPartialUpdateParams,
AgentApplicationsPreviewProxyBody,
@@ -46,6 +50,8 @@ import {
AgentApplicationsRevisionsToolsUpdateBody,
AgentApplicationsRevisionsToolsUpdateParams,
AgentApplicationsRevisionsValidateCreateParams,
+ AgentApplicationsSendBody,
+ AgentApplicationsSendParams,
AgentApplicationsSessionLogsParams,
AgentApplicationsSessionLogsQueryParams,
AgentApplicationsSessionsListParams,
@@ -154,6 +160,31 @@ const agentApplicationsEnvKeysList = (): ToolBase<
},
})
+const AgentApplicationsInvokeSchema = AgentApplicationsInvokeParams.omit({ project_id: true }).extend(
+ AgentApplicationsInvokeBody.shape
+)
+
+const agentApplicationsInvoke = (): ToolBase<typeof AgentApplicationsInvokeSchema, Schemas.AgentInvokeResponse> => ({
+ name: 'agent-applications-invoke',
+ schema: AgentApplicationsInvokeSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsInvokeSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.message !== undefined) {
+ body['message'] = params.message
+ }
+ if (params.external_key !== undefined) {
+ body['external_key'] = params.external_key
+ }
+ const result = await context.api.request<Schemas.AgentInvokeResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/invoke/`,
+ body,
+ })
+ return result
+ },
+})
+
const AgentApplicationsListSchema = AgentApplicationsListQueryParams
const agentApplicationsList = (): ToolBase<
@@ -176,6 +207,28 @@ const agentApplicationsList = (): ToolBase<
},
})
+const AgentApplicationsListenSchema = AgentApplicationsListenParams.omit({ project_id: true }).extend(
+ AgentApplicationsListenQueryParams.shape
+)
+
+const agentApplicationsListen = (): ToolBase<typeof AgentApplicationsListenSchema, Schemas.AgentListenResponse> => ({
+ name: 'agent-applications-listen',
+ schema: AgentApplicationsListenSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsListenSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AgentListenResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/listen/`,
+ query: {
+ cursor: params.cursor,
+ max_chars: params.max_chars,
+ session_id: params.session_id,
+ },
+ })
+ return result
+ },
+})
+
const AgentApplicationsModelsSchema = z.object({})
const agentApplicationsModels = (): ToolBase<typeof AgentApplicationsModelsSchema, Schemas.AgentApplication> => ({
@@ -799,6 +852,31 @@ const agentApplicationsRevisionsValidateCreate = (): ToolBase<
},
})
+const AgentApplicationsSendSchema = AgentApplicationsSendParams.omit({ project_id: true }).extend(
+ AgentApplicationsSendBody.shape
+)
+
+const agentApplicationsSend = (): ToolBase<typeof AgentApplicationsSendSchema, Schemas.AgentSendResponse> => ({
+ name: 'agent-applications-send',
+ schema: AgentApplicationsSendSchema,
+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsSendSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.session_id !== undefined) {
+ body['session_id'] = params.session_id
+ }
+ if (params.message !== undefined) {
+ body['message'] = params.message
+ }
+ const result = await context.api.request<Schemas.AgentSendResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/send/`,
+ body,
+ })
+ return result
+ },
+})
+
const AgentApplicationsSessionLogsSchema = AgentApplicationsSessionLogsParams.omit({ project_id: true }).extend(
AgentApplicationsSessionLogsQueryParams.shape
)
@@ -924,7 +1002,9 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'agent-applications-env-keys-clear': agentApplicationsEnvKeysClear,
'agent-applications-env-keys-get': agentApplicationsEnvKeysGet,
'agent-applications-env-keys-list': agentApplicationsEnvKeysList,
+ 'agent-applications-invoke': agentApplicationsInvoke,
'agent-applications-list': agentApplicationsList,
+ 'agent-applications-listen': agentApplicationsListen,
'agent-applications-models': agentApplicationsModels,
'agent-applications-partial-update': agentApplicationsPartialUpdate,
'agent-applications-preview-proxy': agentApplicationsPreviewProxy,
@@ -951,6 +1031,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'agent-applications-revisions-tools-dry-run-create': agentApplicationsRevisionsToolsDryRunCreate,
'agent-applications-revisions-tools-update': agentApplicationsRevisionsToolsUpdate,
'agent-applications-revisions-validate-create': agentApplicationsRevisionsValidateCreate,
+ 'agent-applications-send': agentApplicationsSend,
'agent-applications-session-logs': agentApplicationsSessionLogs,
'agent-applications-sessions-list': agentApplicationsSessionsList,
'agent-applications-sessions-retrieve': agentApplicationsSessionsRetrieve,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-invoke.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-invoke.json
new file mode 100644
index 000000000000..638e4090d122
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-invoke.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "external_key": {
+ "description": "Optional idempotency / threading key. A repeat invoke with the same external_key resumes the existing session instead of starting a new one.",
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ },
+ "message": {
+ "description": "The user message that starts the session. Required, non-empty.",
+ "type": "string"
+ }
+ },
+ "required": ["id", "message"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-listen.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-listen.json
new file mode 100644
index 000000000000..d20bf2a496a5
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-listen.json
@@ -0,0 +1,23 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "cursor": {
+ "description": "`next_cursor` from the previous call. Omit on the first read; pass it back to summarize only what's new.",
+ "type": "number"
+ },
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ },
+ "max_chars": {
+ "description": "Digest character budget (default 4000, range 1–20000). The digest is clipped to fit and `truncated` is set.",
+ "type": "number"
+ },
+ "session_id": {
+ "description": "Session to read (must belong to this agent).",
+ "type": "string"
+ }
+ },
+ "required": ["id", "session_id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-send.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-send.json
new file mode 100644
index 000000000000..dc73cc097ddc
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-send.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this agent application.",
+ "type": "string"
+ },
+ "message": {
+ "description": "The user message to append. Required, non-empty.",
+ "type": "string"
+ },
+ "session_id": {
+ "description": "The session to append to (returned by agent-applications-invoke). Must belong to this agent.",
+ "type": "string"
+ }
+ },
+ "required": ["id", "session_id", "message"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/agentInvoke.test.ts b/services/mcp/tests/unit/agentInvoke.test.ts
new file mode 100644
index 000000000000..b31d837ce656
--- /dev/null
+++ b/services/mcp/tests/unit/agentInvoke.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { GENERATED_TOOLS as AGENT_PLATFORM_TOOLS } from '@/tools/generated/agent_platform'
+import type { Context } from '@/tools/types'
+
+// The three agent-platform "runtime" MCP tools (agent-applications-invoke / agent-applications-send /
+// agent-applications-listen) are the caller-facing bridge into a running agent session.
+// These assert the generated handlers issue the exact HTTP call the Django
+// viewset expects — method, project-scoped path, and body/query shape.
+
+function createMockContext(): { context: Context; request: ReturnType<typeof vi.fn> } {
+ const request = vi.fn().mockResolvedValue({})
+ const context = {
+ api: { request } as any,
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') } as any,
+ env: {} as any,
+ sessionManager: {} as any,
+ cache: {} as any,
+ getDistinctId: async () => 'test-distinct-id',
+ trackEvent: async () => {},
+ } as unknown as Context
+ return { context, request }
+}
+
+describe('agent-applications-invoke', () => {
+ it('POSTs to the app invoke endpoint with {message}', async () => {
+ const { context, request } = createMockContext()
+ const tool = AGENT_PLATFORM_TOOLS['agent-applications-invoke']!()
+
+ await tool.handler(context, { id: 'app-123', message: 'kick it off' })
+
+ expect(request).toHaveBeenCalledWith({
+ method: 'POST',
+ path: '/api/projects/42/agent_applications/app-123/invoke/',
+ body: { message: 'kick it off' },
+ })
+ })
+
+ it('includes external_key in the body when provided', async () => {
+ const { context, request } = createMockContext()
+ const tool = AGENT_PLATFORM_TOOLS['agent-applications-invoke']!()
+
+ await tool.handler(context, { id: 'app-123', message: 'hi', external_key: 'ext-abc' })
+
+ expect(request).toHaveBeenCalledWith({
+ method: 'POST',
+ path: '/api/projects/42/agent_applications/app-123/invoke/',
+ body: { message: 'hi', external_key: 'ext-abc' },
+ })
+ })
+
+ it('omits external_key from the body when not provided', async () => {
+ const { context, request } = createMockContext()
+ const tool = AGENT_PLATFORM_TOOLS['agent-applications-invoke']!()
+
+ await tool.handler(context, { id: 'app-123', message: 'hi' })
+
+ const body = request.mock.calls[0]![0].body
+ expect(body).not.toHaveProperty('external_key')
+ })
+})
+
+describe('agent-applications-send', () => {
+ it('POSTs to the app send endpoint with {session_id, message}', async () => {
+ const { context, request } = createMockContext()
+ const tool = AGENT_PLATFORM_TOOLS['agent-applications-send']!()
+
+ await tool.handler(context, { id: 'app-123', session_id: 'sess-9', message: 'more input' })
+
+ expect(request).toHaveBeenCalledWith({
+ method: 'POST',
+ path: '/api/projects/42/agent_applications/app-123/send/',
+ body: { session_id: 'sess-9', message: 'more input' },
+ })
+ })
+})
+
+describe('agent-applications-listen', () => {
+ it('GETs the app listen endpoint with {cursor, max_chars, session_id} query', async () => {
+ const { context, request } = createMockContext()
+ const tool = AGENT_PLATFORM_TOOLS['agent-applications-listen']!()
+
+ await tool.handler(context, {
+ id: 'app-123',
+ session_id: 'sess-9',
+ cursor: 3,
+ max_chars: 1000,
+ })
+
+ expect(request).toHaveBeenCalledWith({
+ method: 'GET',
+ path: '/api/projects/42/agent_applications/app-123/listen/',
+ query: {
+ cursor: 3,
+ max_chars: 1000,
+ session_id: 'sess-9',
+ },
+ })
+ })
+
+ it('is a GET (never mutates) — no request body', async () => {
+ const { context, request } = createMockContext()
+ const tool = AGENT_PLATFORM_TOOLS['agent-applications-listen']!()
+
+ await tool.handler(context, { id: 'app-123', session_id: 'sess-9' })
+
+ const call = request.mock.calls[0]![0]
+ expect(call.method).toBe('GET')
+ expect(call).not.toHaveProperty('body')
+ })
+})