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(canvas): make context reads reliable and expose run failures (#101398)

posthog[bot]de921ca7ab45
diff --git a/docs/internal/canvas-collaboration.md b/docs/internal/canvas-collaboration.md
index 237c584b4b3e..d65cffa693c0 100644
--- a/docs/internal/canvas-collaboration.md
+++ b/docs/internal/canvas-collaboration.md
@@ -42,6 +42,31 @@ to the earlier task. Each new edit starts a new task and session.
## Release checks
+### Agent reads and run health
+
+The canvas runtime still reads complete state when it omits read options.
+The `canvas-state-retrieve` MCP tool defaults to a paged key inventory (`keys_only=true`).
+Keep `scope`, `key`, and `key_prefix` unchanged when following `next_offset`.
+Set `keys_only=false` to read small selected values.
+Use `canvas-state-value-retrieve` for long values: join `value_json` chunks, then parse the complete JSON.
+Pass the first chunk's `revision` on each continuation; restart from zero after HTTP 409.
+Inventory pages are not a snapshot, so re-read the inventory if another writer changes keys during traversal.
+
+Context wiki MCP reads also return bounded chunks.
+Follow `next_offset` with the same `head_sha` and `limit` until `complete` is true.
+Join every content chunk before editing or proposing a replacement page.
+Restart after HTTP 409 rather than joining content from different revisions.
+The ordinary page API remains a full read when `limit` is absent.
+
+Run health comes from task records, not saved canvas labels.
+Use `tasks-list` with the space's `channel`, `status=failed`, `internal=all`, and `archived=all`.
+For workflow-backed loops, add `hog_flow_id`.
+Results include the latest run's error and completion time even if the agent could not write canvas state.
+Read `tasks-runs-list` for earlier runs, or use `loops-runs-retrieve` with `status=failed` for a loop's paged failure history.
+These reads do not change task states or grant additional permissions.
+
+### Validation
+
The desktop changes use existing endpoints and version fields. They can ship before
or after the backend changes. The backend still controls write access. An older
backend continues to reject shared edits until the new permissions reach it.
diff --git a/products/canvas/backend/facade/api.py b/products/canvas/backend/facade/api.py
index 69d8fc858eab..f1f817747148 100644
--- a/products/canvas/backend/facade/api.py
+++ b/products/canvas/backend/facade/api.py
@@ -18,6 +18,7 @@ from products.canvas.backend.layout import (
validate_layout as validate_layout,
validate_layout_references as validate_layout_references,
)
+from products.canvas.backend.state_reads import CanvasStateReader as CanvasStateReader
from products.canvas.backend.teaching import (
RESERVED_TEMPLATE_IDS as RESERVED_TEMPLATE_IDS,
TEACHING_CANVAS_NAME as TEACHING_CANVAS_NAME,
diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.py
index 1fc7a8756a35..9b1f87f05c0f 100644
--- a/products/canvas/backend/presentation/serializers.py
+++ b/products/canvas/backend/presentation/serializers.py
@@ -1167,6 +1167,75 @@ class CanvasConnectorCallResultSerializer(serializers.Serializer):
)
+class CanvasStateQuerySerializer(serializers.Serializer):
+ scope = serializers.ChoiceField(choices=CanvasState.SCOPES, required=False, help_text="Only read this scope.")
+ key = serializers.CharField(required=False, max_length=200, help_text="Only read this exact key.")
+ key_prefix = serializers.CharField(
+ required=False,
+ max_length=200,
+ allow_blank=True,
+ trim_whitespace=False,
+ help_text="Only read entries whose key starts with this prefix.",
+ )
+ keys_only = serializers.BooleanField(
+ required=False, default=False, help_text="True returns a key inventory without stored values."
+ )
+ offset = serializers.IntegerField(
+ required=False,
+ default=0,
+ min_value=0,
+ help_text="Entry offset from next_offset. Keep filters unchanged between pages.",
+ )
+ limit = serializers.IntegerField(
+ required=False,
+ min_value=1,
+ max_value=100,
+ help_text="Maximum entries per page. Omit for the full state. Prefer an inventory and state/value for large values.",
+ )
+
+
+class CanvasStateValueQuerySerializer(serializers.Serializer):
+ scope = serializers.ChoiceField(choices=CanvasState.SCOPES, help_text="Scope of the value to read.")
+ key = serializers.CharField(max_length=200, help_text="Exact key to read.")
+ offset = serializers.IntegerField(
+ required=False, default=0, min_value=0, help_text="Character offset from next_offset."
+ )
+ limit = serializers.IntegerField(
+ required=False,
+ default=12000,
+ min_value=1,
+ max_value=12000,
+ help_text="Maximum JSON characters in this response.",
+ )
+ revision = serializers.CharField(
+ required=False,
+ max_length=64,
+ help_text="Revision from the first chunk. Required when offset is greater than zero.",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ if attrs["offset"] and not attrs.get("revision"):
+ raise serializers.ValidationError({"revision": "Read the first chunk and pass its revision to continue."})
+ return attrs
+
+
+class CanvasStateValueResponseSerializer(serializers.Serializer):
+ scope = serializers.ChoiceField(choices=CanvasState.SCOPES, help_text="Scope of this value.")
+ key = serializers.CharField(help_text="Key of this value.")
+ value_json = serializers.CharField(
+ allow_blank=True, help_text="A chunk of JSON text. Join all chunks in order, then parse the complete JSON."
+ )
+ revision = serializers.CharField(
+ help_text="Content revision. Pass it on subsequent reads; a changed value returns 409."
+ )
+ offset = serializers.IntegerField(help_text="Character offset of this chunk.")
+ total_length = serializers.IntegerField(help_text="Character length of the complete JSON text.")
+ next_offset = serializers.IntegerField(allow_null=True, help_text="Next character offset, or null when complete.")
+ complete = serializers.BooleanField(
+ help_text="True when no further chunks remain. Earlier chunks are still needed when offset is nonzero."
+ )
+
+
class CanvasStateEntrySerializer(serializers.Serializer):
"""One key of a canvas's runtime key-value state (the ph.state store)."""
@@ -1175,7 +1244,7 @@ class CanvasStateEntrySerializer(serializers.Serializer):
help_text="user: private to the viewer who wrote it. shared: one value per canvas, visible to every viewer.",
)
key = serializers.CharField(max_length=200, help_text="The entry's key, unique within its scope.")
- value = serializers.JSONField(help_text="The stored JSON value.")
+ value = serializers.JSONField(required=False, help_text="The stored JSON value. Omitted from a key inventory.")
updated_at = serializers.DateTimeField(help_text="When the entry was last written.")
@@ -1186,6 +1255,8 @@ class CanvasStateResponseSerializer(serializers.Serializer):
many=True,
help_text="The canvas's shared entries plus the caller's own user-scoped entries.",
)
+ next_offset = serializers.IntegerField(allow_null=True, help_text="Next entry offset, or null when complete.")
+ complete = serializers.BooleanField(help_text="True when no further entries remain for this selection.")
class CanvasStateSetSerializer(serializers.Serializer):
diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.py
index 4cb6e054e4cd..c63e76c6b1d2 100644
--- a/products/canvas/backend/presentation/views.py
+++ b/products/canvas/backend/presentation/views.py
@@ -35,6 +35,7 @@ from products.canvas.backend.actions import CANVAS_ACTIONS, CanvasActionDenied,
from products.canvas.backend.capabilities import declared_actions, declared_connectors, declared_state_scopes
from products.canvas.backend.contract import contract_limits
from products.canvas.backend.facade.api import (
+ CanvasStateReader,
apply_layout_ops,
call_connector_tool,
canvas_connectors_enabled,
@@ -83,8 +84,11 @@ from products.canvas.backend.presentation.serializers import (
CanvasSourcePublishSerializer,
CanvasSourceResponseSerializer,
CanvasStateEntrySerializer,
+ CanvasStateQuerySerializer,
CanvasStateResponseSerializer,
CanvasStateSetSerializer,
+ CanvasStateValueQuerySerializer,
+ CanvasStateValueResponseSerializer,
CanvasSummarySerializer,
CanvasUpdateSerializer,
CanvasValidateRequestSerializer,
@@ -443,6 +447,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
"builds",
"validate",
"state",
+ "state_value",
"layout",
"connectors",
"view",
@@ -2115,17 +2120,15 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
)
return Response(CanvasConnectorCallResultSerializer(instance=result).data)
+ def _readable_state_entries(self, canvas: Canvas, user: User) -> QuerySet[CanvasState]:
+ version = canvas.current_source_version
+ declared = declared_state_scopes(version.capabilities if version else None)
+ readable = Q(scope=CanvasState.SCOPE_SHARED, user__isnull=True) | Q(scope=CanvasState.SCOPE_USER, user=user)
+ return CanvasState.objects.for_team(self.team_id).filter(readable, canvas=canvas, scope__in=declared)
+
@extend_schema(
operation_id="canvases_state_retrieve",
- parameters=[
- OpenApiParameter(
- "scope",
- OpenApiTypes.STR,
- required=False,
- enum=CanvasState.SCOPES,
- description="Only return entries in this scope.",
- )
- ],
+ parameters=[CanvasStateQuerySerializer],
responses={
200: CanvasStateResponseSerializer,
403: OpenApiResponse(description="Canvas state requires an authenticated user."),
@@ -2145,18 +2148,44 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
# Reads honor the same reviewed boundary as writes: a canvas only sees
# the scopes its head version declares, so narrowing capabilities also
# stops reads of previously written entries.
- version = canvas.current_source_version
- declared = declared_state_scopes(version.capabilities if version else None)
- readable_entries = Q(scope=CanvasState.SCOPE_SHARED, user__isnull=True) | Q(
- scope=CanvasState.SCOPE_USER, user=user
- )
- entries = CanvasState.objects.for_team(self.team_id).filter(readable_entries, canvas=canvas, scope__in=declared)
- scope = request.query_params.get("scope")
- if scope:
- if scope not in CanvasState.SCOPES:
- return Response({"detail": "scope must be 'user' or 'shared'."}, status=status.HTTP_400_BAD_REQUEST)
- entries = entries.filter(scope=scope)
- return Response(CanvasStateResponseSerializer(instance={"entries": entries.order_by("scope", "key")}).data)
+ query = CanvasStateQuerySerializer(data=request.query_params)
+ query.is_valid(raise_exception=True)
+ result = CanvasStateReader.entries(self._readable_state_entries(canvas, user), **query.validated_data)
+ return Response(CanvasStateResponseSerializer(result).data)
+
+ @extend_schema(
+ operation_id="canvases_state_value_retrieve",
+ parameters=[CanvasStateValueQuerySerializer],
+ responses={
+ 200: CanvasStateValueResponseSerializer,
+ 400: OpenApiResponse(description="Invalid query, or the offset exceeds the value length."),
+ 404: OpenApiResponse(description="No readable value for this scope and key."),
+ 409: OpenApiResponse(description="The value changed. Restart from offset zero."),
+ },
+ )
+ @action(methods=["GET"], detail=True, url_path="state/value")
+ def state_value(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ canvas = self.get_object()
+ user = self._state_actor(request)
+ if user is None:
+ return _state_rejection()
+ query = CanvasStateValueQuerySerializer(data=request.query_params)
+ query.is_valid(raise_exception=True)
+ params = query.validated_data
+ entry = self._readable_state_entries(canvas, user).filter(scope=params["scope"], key=params["key"]).first()
+ if entry is None:
+ raise NotFound("No readable value for this scope and key. Read the key inventory first.")
+ result = CanvasStateReader.value(entry, offset=params["offset"], limit=params["limit"])
+ if params.get("revision") and params["revision"] != result["revision"]:
+ return Response(
+ {"detail": "The value changed. Read again from offset zero."}, status=status.HTTP_409_CONFLICT
+ )
+ if params["offset"] > result["total_length"]:
+ return Response(
+ {"detail": "Offset exceeds the value length. Read again from offset zero."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ return Response(CanvasStateValueResponseSerializer(result).data)
@extend_schema(
operation_id="canvases_state_set",
diff --git a/products/canvas/backend/state_reads.py b/products/canvas/backend/state_reads.py
new file mode 100644
index 000000000000..8a5578809a2b
--- /dev/null
+++ b/products/canvas/backend/state_reads.py
@@ -0,0 +1,54 @@
+import json
+import hashlib
+from typing import Any
+
+from django.db.models import QuerySet
+
+from products.canvas.backend.models import CanvasState
+
+
+class CanvasStateReader:
+ @staticmethod
+ def entries(
+ queryset: QuerySet[CanvasState],
+ *,
+ scope: str | None = None,
+ key: str | None = None,
+ key_prefix: str | None = None,
+ keys_only: bool = False,
+ offset: int = 0,
+ limit: int | None = None,
+ ) -> dict[str, Any]:
+ if scope:
+ queryset = queryset.filter(scope=scope)
+ if key is not None:
+ queryset = queryset.filter(key=key)
+ if key_prefix:
+ queryset = queryset.filter(key__startswith=key_prefix)
+ # A scope holds up to 256 keys of 64 KB, so a whole-scope read can exceed what the caller can hold.
+ fields = ["scope", "key", "updated_at"]
+ if not keys_only:
+ fields.append("value")
+ selected = queryset.order_by("scope", "key").values(*fields)
+ rows = list(selected[offset : offset + limit + 1] if limit is not None else selected[offset:])
+ has_more = limit is not None and len(rows) > limit
+ return {
+ "entries": rows[:limit] if limit is not None else rows,
+ "next_offset": offset + limit if has_more and limit is not None else None,
+ "complete": not has_more,
+ }
+
+ @staticmethod
+ def value(entry: CanvasState, *, offset: int, limit: int) -> dict[str, Any]:
+ encoded = json.dumps(entry.value, ensure_ascii=True, separators=(",", ":"), sort_keys=True)
+ next_offset = offset + limit if offset + limit < len(encoded) else None
+ return {
+ "scope": entry.scope,
+ "key": entry.key,
+ "value_json": encoded[offset : offset + limit],
+ "revision": hashlib.sha256(encoded.encode()).hexdigest(),
+ "offset": offset,
+ "total_length": len(encoded),
+ "next_offset": next_offset,
+ "complete": next_offset is None,
+ }
diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.py
index 2c4c72063c03..f21a23608a5a 100644
--- a/products/canvas/backend/tests/test_canvas_api.py
+++ b/products/canvas/backend/tests/test_canvas_api.py
@@ -1,3 +1,4 @@
+import json
from datetime import timedelta
from types import SimpleNamespace
from typing import Any, cast
@@ -1546,8 +1547,8 @@ class TestCanvasState(CanvasAPIBaseTest):
format="json",
)
- def _entries(self, canvas_id: str) -> list[dict[str, Any]]:
- response = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/")
+ def _entries(self, canvas_id: str, **params: Any) -> list[dict[str, Any]]:
+ response = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/", params)
assert response.status_code == status.HTTP_200_OK, response.json()
return response.json()["entries"]
@@ -1565,6 +1566,29 @@ class TestCanvasState(CanvasAPIBaseTest):
self.client.force_login(self.user)
own_view = {(e["scope"], e["key"]): e["value"] for e in self._entries(canvas_id)}
assert own_view == {("shared", "board"): {"columns": 3}, ("user", "draft"): "mine"}
+ value_url = f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/value/"
+ own_value = self.client.get(value_url, {"scope": "user", "key": "draft"})
+ assert json.loads(own_value.json()["value_json"]) == "mine"
+ self.client.force_login(teammate)
+ peer_value = self.client.get(value_url, {"scope": "user", "key": "draft"})
+ assert json.loads(peer_value.json()["value_json"]) == "theirs"
+
+ def test_state_reads_can_be_bounded_by_prefix_and_to_keys_only(self):
+ canvas_id = self._state_canvas()
+ assert self._set_state(canvas_id, "shared", "todo:1", {"title": "first"}).status_code == status.HTTP_200_OK
+ assert self._set_state(canvas_id, "shared", "todo:2", {"title": "second"}).status_code == status.HTTP_200_OK
+ assert self._set_state(canvas_id, "shared", "history", "x" * 1000).status_code == status.HTTP_200_OK
+
+ assert [e["key"] for e in self._entries(canvas_id, key_prefix="todo:")] == ["todo:1", "todo:2"]
+
+ rejected = self.client.get(
+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/", {"key_prefix": "todo:\x00"}
+ )
+ assert rejected.status_code == status.HTTP_400_BAD_REQUEST
+
+ inventory = self._entries(canvas_id, keys_only="true")
+ assert [e["key"] for e in inventory] == ["history", "todo:1", "todo:2"]
+ assert all("value" not in e for e in inventory)
def test_state_reads_only_declared_scopes(self):
canvas_id = self._state_canvas()
@@ -1580,6 +1604,49 @@ class TestCanvasState(CanvasAPIBaseTest):
assert self._publish(canvas_id, project=self._project(capabilities=narrowed)).status_code == status.HTTP_200_OK
assert [(e["scope"], e["key"]) for e in self._entries(canvas_id)] == [("shared", "board")]
+ hidden = self.client.get(
+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/value/", {"scope": "user", "key": "draft"}
+ )
+ assert hidden.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_state_inventory_is_paged_and_can_select_keys(self):
+ canvas_id = self._state_canvas()
+ self._set_state(canvas_id, "shared", "board", {"columns": 3})
+ self._set_state(canvas_id, "shared", "policy", "a long policy")
+ url = f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/"
+
+ first = self.client.get(url, {"keys_only": "true", "limit": "1"}).json()
+ assert [entry["key"] for entry in first["entries"]] == ["board"]
+ assert "value" not in first["entries"][0]
+ assert first["next_offset"] == 1
+ assert first["complete"] is False
+ second = self.client.get(url, {"keys_only": "true", "limit": "1", "offset": "1"}).json()
+ assert [entry["key"] for entry in second["entries"]] == ["policy"]
+ assert second["next_offset"] is None
+ assert second["complete"] is True
+ selected = self.client.get(url, {"key": "policy"}).json()
+ assert [(entry["key"], entry["value"]) for entry in selected["entries"]] == [("policy", "a long policy")]
+
+ def test_state_value_chunks_detect_changes(self):
+ canvas_id = self._state_canvas()
+ value = {"text": "é\\n" * 30}
+ self._set_state(canvas_id, "shared", "policy", value)
+ url = f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/value/"
+ params = {"scope": "shared", "key": "policy", "limit": "17"}
+ first = self.client.get(url, params)
+ assert first.status_code == status.HTTP_200_OK, first.content
+ page = first.json()
+ chunks = [page["value_json"]]
+ while page["next_offset"] is not None:
+ page = self.client.get(url, {**params, "offset": page["next_offset"], "revision": page["revision"]}).json()
+ chunks.append(page["value_json"])
+ assert json.loads("".join(chunks)) == value
+ assert page["complete"] is True
+
+ self._set_state(canvas_id, "shared", "policy", {"text": "changed"})
+ conflict = self.client.get(url, {**params, "offset": "17", "revision": first.json()["revision"]})
+ assert conflict.status_code == status.HTTP_409_CONFLICT
+ assert self.client.get(url, {**params, "offset": "17"}).status_code == status.HTTP_400_BAD_REQUEST
def test_set_state_requires_the_scope_to_be_declared(self):
canvas_id = self._state_canvas(scopes=("user",))
@@ -1657,6 +1724,21 @@ class TestCanvasState(CanvasAPIBaseTest):
assert write_shared.status_code == status.HTTP_200_OK
assert write_user.status_code == status.HTTP_200_OK
+ inventory = client.get(
+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/",
+ {"keys_only": "true", "limit": "1"},
+ HTTP_X_POSTHOG_TASK_ID=str(task.id),
+ )
+ assert inventory.status_code == status.HTTP_200_OK, inventory.content
+ assert "value" not in inventory.json()["entries"][0]
+ chunk = client.get(
+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/value/",
+ {"scope": "shared", "key": "progress", "limit": "5"},
+ HTTP_X_POSTHOG_TASK_ID=str(task.id),
+ )
+ assert chunk.status_code == status.HTTP_200_OK, chunk.content
+ assert chunk.json()["complete"] is False
+
class TestCanvasErrorReports(CanvasAPIBaseTest):
def setUp(self):
diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.ts
index 0df392ff72f0..5da40a0a133d 100644
--- a/products/canvas/frontend/generated/api.schemas.ts
+++ b/products/canvas/frontend/generated/api.schemas.ts
@@ -1434,8 +1434,8 @@ export interface CanvasStateEntryApi {
* @maxLength 200
*/
key: string
- /** The stored JSON value. */
- value: unknown
+ /** The stored JSON value. Omitted from a key inventory. */
+ value?: unknown
/** When the entry was last written. */
updated_at: string
}
@@ -1446,6 +1446,13 @@ export interface CanvasStateEntryApi {
export interface CanvasStateResponseApi {
/** The canvas's shared entries plus the caller's own user-scoped entries. */
entries: CanvasStateEntryApi[]
+ /**
+ * Next entry offset, or null when complete.
+ * @nullable
+ */
+ next_offset: number | null
+ /** True when no further entries remain for this selection. */
+ complete: boolean
}
/**
@@ -1466,6 +1473,31 @@ export interface CanvasStateSetApi {
value: unknown
}
+export interface CanvasStateValueResponseApi {
+ /** Scope of this value.
+ *
+ * * `user` - user
+ * * `shared` - shared */
+ scope: CanvasStateScopeEnumApi
+ /** Key of this value. */
+ key: string
+ /** A chunk of JSON text. Join all chunks in order, then parse the complete JSON. */
+ value_json: string
+ /** Content revision. Pass it on subsequent reads; a changed value returns 409. */
+ revision: string
+ /** Character offset of this chunk. */
+ offset: number
+ /** Character length of the complete JSON text. */
+ total_length: number
+ /**
+ * Next character offset, or null when complete.
+ * @nullable
+ */
+ next_offset: number | null
+ /** True when no further chunks remain. Earlier chunks are still needed when offset is nonzero. */
+ complete: boolean
+}
+
/**
* Payload for validating a candidate source project without publishing it.
*/
@@ -1709,7 +1741,37 @@ export type CanvasesSourceRetrieveParams = {
export type CanvasesStateRetrieveParams = {
/**
- * Only return entries in this scope.
+ * Only read this exact key.
+ * @minLength 1
+ * @maxLength 200
+ */
+ key?: string
+ /**
+ * Only read entries whose key starts with this prefix.
+ * @maxLength 200
+ */
+ key_prefix?: string
+ /**
+ * True returns a key inventory without stored values.
+ */
+ keys_only?: boolean
+ /**
+ * Maximum entries per page. Omit for the full state. Prefer an inventory and state/value for large values.
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number
+ /**
+ * Entry offset from next_offset. Keep filters unchanged between pages.
+ * @minimum 0
+ */
+ offset?: number
+ /**
+ * Only read this scope.
+ *
+ * * `user` - user
+ * * `shared` - shared
+ * @minLength 1
*/
scope?: CanvasesStateRetrieveScope
}
@@ -1717,8 +1779,50 @@ export type CanvasesStateRetrieveParams = {
export type CanvasesStateRetrieveScope = (typeof CanvasesStateRetrieveScope)[keyof typeof CanvasesStateRetrieveScope]
export const CanvasesStateRetrieveScope = {
+ User: 'user',
Shared: 'shared',
+} as const
+
+export type CanvasesStateValueRetrieveParams = {
+ /**
+ * Exact key to read.
+ * @minLength 1
+ * @maxLength 200
+ */
+ key: string
+ /**
+ * Maximum JSON characters in this response.
+ * @minimum 1
+ * @maximum 12000
+ */
+ limit?: number
+ /**
+ * Character offset from next_offset.
+ * @minimum 0
+ */
+ offset?: number
+ /**
+ * Revision from the first chunk. Required when offset is greater than zero.
+ * @minLength 1
+ * @maxLength 64
+ */
+ revision?: string
+ /**
+ * Scope of the value to read.
+ *
+ * * `user` - user
+ * * `shared` - shared
+ * @minLength 1
+ */
+ scope: CanvasesStateValueRetrieveScope
+}
+
+export type CanvasesStateValueRetrieveScope =
+ (typeof CanvasesStateValueRetrieveScope)[keyof typeof CanvasesStateValueRetrieveScope]
+
+export const CanvasesStateValueRetrieveScope = {
User: 'user',
+ Shared: 'shared',
} as const
export type CanvasesVersionsRetrieveParams = {
diff --git a/products/canvas/frontend/generated/api.ts b/products/canvas/frontend/generated/api.ts
index ad820f0da477..73fa45edf999 100644
--- a/products/canvas/frontend/generated/api.ts
+++ b/products/canvas/frontend/generated/api.ts
@@ -42,6 +42,7 @@ import type {
CanvasStateEntryApi,
CanvasStateResponseApi,
CanvasStateSetApi,
+ CanvasStateValueResponseApi,
CanvasValidateRequestApi,
CanvasValidateResponseApi,
CanvasViewResponseApi,
@@ -52,6 +53,7 @@ import type {
CanvasesListParams,
CanvasesSourceRetrieveParams,
CanvasesStateRetrieveParams,
+ CanvasesStateValueRetrieveParams,
CanvasesVersionsRetrieveParams,
PaginatedCanvasDraftListApi,
PaginatedCanvasListApi,
@@ -707,6 +709,44 @@ export const canvasesStateSet = async (
})
}
+export const getCanvasesStateValueRetrieveUrl = (
+ projectId: string,
+ id: string,
+ params: CanvasesStateValueRetrieveParams
+) => {
+ 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}/canvases/${id}/state/value/?${stringifiedParams}`
+ : `/api/projects/${projectId}/canvases/${id}/state/value/`
+}
+
+/**
+ * Canvases: agent-built sandboxed browser apps, filed into channels.
+ *
+ * Source is versioned per publish and built server-side; the canvas app
+ * renders the published build's artifact from the isolated artifact origin.
+ */
+export const canvasesStateValueRetrieve = async (
+ projectId: string,
+ id: string,
+ params: CanvasesStateValueRetrieveParams,
+ options?: RequestInit
+): Promise<CanvasStateValueResponseApi> => {
+ return apiMutator<CanvasStateValueResponseApi>(getCanvasesStateValueRetrieveUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getCanvasesValidateCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/canvases/${id}/validate/`
}
diff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yaml
index 4438bcd4882f..345fdc4d323c 100644
--- a/products/canvas/mcp/tools.yaml
+++ b/products/canvas/mcp/tools.yaml
@@ -363,6 +363,14 @@ tools:
own user-scoped entries, never another user's. Use this with canvas-source-retrieve when collaborative
progress, checklist selections, filters, or other runtime values live outside the source. Only scopes
declared by the live canvas version are readable. Optionally filter to `user` or `shared` with `scope`.
+ Returns a key inventory by default. Keep filters unchanged and follow next_offset until complete is true.
+ Set key or key_prefix and keys_only=false for small selected values. Use canvas-state-value-retrieve for
+ long values. This reads persisted state directly; no composition storage tool is needed.
+ param_overrides:
+ limit:
+ input_schema: CanvasStateReadLimitSchema
+ keys_only:
+ input_schema: CanvasStateKeysOnlySchema
canvas-state-set:
operation: canvases_state_set
enabled: true
@@ -378,6 +386,24 @@ tools:
only the authenticated user's private state; `shared` updates the state every viewer sees. The scope must be
declared by the live canvas version. Read the current entries with canvas-state-retrieve before changing
progress or other existing values.
+ canvas-state-value-retrieve:
+ operation: canvases_state_value_retrieve
+ enabled: true
+ scopes:
+ - canvas:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Read a canvas state value
+ description: >
+ Read one exact scope and key as bounded JSON text chunks. Start at offset zero, then pass next_offset and
+ revision until complete is true. Join value_json chunks in order before parsing the JSON. If the value
+ changes, the read returns 409; discard earlier chunks and restart at zero. On a 404, read the error detail:
+ "No readable value for this scope and key" means the entry is absent and broader permissions would not help,
+ while any other 404 means the canvas is not available to this caller.
+ validators:
+ - validateCanvasStateValueContinuation
canvas-validate-create:
operation: canvases_validate_create
enabled: true
diff --git a/products/context_layer/backend/presentation/serializers.py b/products/context_layer/backend/presentation/serializers.py
index 51a310bad821..8f92d0e43eb1 100644
--- a/products/context_layer/backend/presentation/serializers.py
+++ b/products/context_layer/backend/presentation/serializers.py
@@ -1,3 +1,5 @@
+from typing import Any
+
from rest_framework import serializers
from products.context_layer.backend.facade.api import DREAM_BRANCH_RE, PAGE_MAX_BYTES
@@ -22,6 +24,26 @@ class WikiTreeSerializer(serializers.Serializer):
)
+class WikiPageQuerySerializer(serializers.Serializer):
+ path = serializers.CharField(help_text="Repo-relative Markdown path of the page to read.")
+ offset = serializers.IntegerField(
+ required=False, default=0, min_value=0, help_text="Character offset from next_offset."
+ )
+ limit = serializers.IntegerField(
+ required=False, min_value=1, max_value=12000, help_text="Maximum characters to read. Omit for the full page."
+ )
+ head_sha = serializers.CharField(
+ required=False,
+ max_length=64,
+ help_text="Head from the first chunk. Required for continuation. A changed head returns 409.",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ if attrs["offset"] and (not attrs.get("head_sha") or not attrs.get("limit")):
+ raise serializers.ValidationError("To continue, pass the head_sha and limit from the first read.")
+ return attrs
+
+
class WikiPageSerializer(serializers.Serializer):
"""Response shape for one wiki page."""
@@ -31,6 +53,12 @@ class WikiPageSerializer(serializers.Serializer):
help_text="Commit sha the content was read at; pass back as `base_head` on writes."
)
updated_at = serializers.DateTimeField(help_text="When this page was last changed in the wiki history.")
+ offset = serializers.IntegerField(help_text="Character offset of this chunk.")
+ total_length = serializers.IntegerField(help_text="Character length of the complete page.")
+ next_offset = serializers.IntegerField(allow_null=True, help_text="Next character offset, or null when complete.")
+ complete = serializers.BooleanField(
+ help_text="True when no further chunks remain. Do not write a page until all chunks are read."
+ )
class DreamRunSerializer(serializers.Serializer):
diff --git a/products/context_layer/backend/presentation/views.py b/products/context_layer/backend/presentation/views.py
index 08a11cd436d7..ea6bc561ab5a 100644
--- a/products/context_layer/backend/presentation/views.py
+++ b/products/context_layer/backend/presentation/views.py
@@ -1,7 +1,7 @@
from typing import Literal, cast
from uuid import UUID
-from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, PermissionDenied, Throttled, ValidationError
@@ -30,6 +30,7 @@ from products.context_layer.backend.presentation.serializers import (
WikiHealthReportSerializer,
WikiPageProposalSerializer,
WikiPageProposalWriteSerializer,
+ WikiPageQuerySerializer,
WikiPageSerializer,
WikiPageWriteSerializer,
WikiTreeSerializer,
@@ -119,12 +120,53 @@ def _store_error_response(error: facade.ContextLayerStoreError) -> Response:
raise error
+_read_page_schema = extend_schema(
+ parameters=[WikiPageQuerySerializer],
+ responses={
+ 200: WikiPageSerializer,
+ 400: OpenApiResponse(description="Invalid query, or the offset exceeds the page length."),
+ 404: OpenApiResponse(description="No page at this path."),
+ 409: OpenApiResponse(description="The wiki changed. Restart from offset zero."),
+ },
+ summary="Read a wiki page",
+)
+
+
def _read_page(organization_id, request: Request) -> Response: # noqa: ANN001
+ query = WikiPageQuerySerializer(data=request.query_params)
+ query.is_valid(raise_exception=True)
+ params = query.validated_data
try:
- wiki_page = facade.get_page(organization_id, request.query_params.get("path", ""))
+ wiki_page = facade.get_page(organization_id, params["path"])
except facade.ContextLayerStoreError as error:
return _store_error_response(error)
- return Response(WikiPageSerializer(wiki_page).data)
+ if params.get("head_sha") and params["head_sha"] != wiki_page.head_sha:
+ return Response(
+ {"detail": "The wiki changed. Read again from offset zero.", "head_sha": wiki_page.head_sha},
+ status=status.HTTP_409_CONFLICT,
+ )
+ offset = params["offset"]
+ length = len(wiki_page.content)
+ if offset > length:
+ return Response(
+ {"detail": "Offset exceeds the page length. Read again from offset zero."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ end = offset + params["limit"] if "limit" in params else length
+ next_offset = end if end < length else None
+ page = WikiPageSerializer(
+ {
+ "path": wiki_page.path,
+ "content": wiki_page.content[offset:end],
+ "head_sha": wiki_page.head_sha,
+ "updated_at": wiki_page.updated_at,
+ "offset": offset,
+ "total_length": length,
+ "next_offset": next_offset,
+ "complete": next_offset is None,
+ }
+ )
+ return Response(page.data)
def _assert_run_write_in_scope(organization_id, team_id, request: Request, path: str, content: str) -> None: # noqa: ANN001
@@ -419,15 +461,7 @@ class ContextLayerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return _store_error_response(error)
return Response(WikiHealthReportSerializer(report).data)
- @extend_schema(
- parameters=[
- OpenApiParameter(
- name="path", type=str, required=True, description="Repo-relative Markdown path of the page to read."
- )
- ],
- responses={200: WikiPageSerializer, 404: OpenApiResponse(description="No page at this path.")},
- summary="Read a wiki page",
- )
+ @_read_page_schema
@action(methods=["GET"], detail=False, url_path="pages", url_name="pages")
def page(self, request: Request, **kwargs) -> Response:
return _read_page(self.organization.id, request)
@@ -621,15 +655,7 @@ class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return ["organization:read"]
return None
- @extend_schema(
- parameters=[
- OpenApiParameter(
- name="path", type=str, required=True, description="Repo-relative Markdown path of the page to read."
- )
- ],
- responses={200: WikiPageSerializer, 404: OpenApiResponse(description="No page at this path.")},
- summary="Read a wiki page",
- )
+ @_read_page_schema
@action(methods=["GET"], detail=False, url_path="pages", url_name="pages")
def page(self, request: Request, **kwargs) -> Response:
return _read_page(self.organization.id, request)
diff --git a/products/context_layer/backend/test/test_api.py b/products/context_layer/backend/test/test_api.py
index 6091e6487e72..0ea6da786c89 100644
--- a/products/context_layer/backend/test/test_api.py
+++ b/products/context_layer/backend/test/test_api.py
@@ -737,6 +737,27 @@ class TestContextLayerAPI(APIBaseTest):
)
assert read.status_code == 200, read.content
+ content = read.json()["content"]
+ params = {"path": f"projects/{self.team.id}/spaces/growth.md", "limit": "23"}
+ chunks: list[str] = []
+ while True:
+ response = self.client.get(f"{self.agent_url}/pages/", params, HTTP_AUTHORIZATION=f"Bearer {token}")
+ assert response.status_code == 200, response.content
+ page = response.json()
+ chunks.append(page["content"])
+ assert len(page["content"]) <= 23
+ if page["next_offset"] is None:
+ assert page["complete"] is True
+ break
+ params.update(offset=page["next_offset"], head_sha=page["head_sha"])
+ assert "".join(chunks) == content
+ stale = self.client.get(
+ f"{self.agent_url}/pages/",
+ {**params, "head_sha": "0" * 40},
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert stale.status_code == 409, stale.content
+
updated = self.client.put(
f"{self.agent_url}/pages/",
{
diff --git a/products/context_layer/frontend/generated/api.schemas.ts b/products/context_layer/frontend/generated/api.schemas.ts
index e74be6215694..5978fff32a99 100644
--- a/products/context_layer/frontend/generated/api.schemas.ts
+++ b/products/context_layer/frontend/generated/api.schemas.ts
@@ -176,6 +176,17 @@ export interface WikiPageApi {
head_sha: string
/** When this page was last changed in the wiki history. */
updated_at: string
+ /** Character offset of this chunk. */
+ offset: number
+ /** Character length of the complete page. */
+ total_length: number
+ /**
+ * Next character offset, or null when complete.
+ * @nullable
+ */
+ next_offset: number | null
+ /** True when no further chunks remain. Do not write a page until all chunks are read. */
+ complete: boolean
}
/**
@@ -283,8 +294,26 @@ export interface WikiPageProposalWriteApi {
}
export type ContextLayerPagesRetrieveParams = {
+ /**
+ * Head from the first chunk. Required for continuation. A changed head returns 409.
+ * @minLength 1
+ * @maxLength 64
+ */
+ head_sha?: string
+ /**
+ * Maximum characters to read. Omit for the full page.
+ * @minimum 1
+ * @maximum 12000
+ */
+ limit?: number
+ /**
+ * Character offset from next_offset.
+ * @minimum 0
+ */
+ offset?: number
/**
* Repo-relative Markdown path of the page to read.
+ * @minLength 1
*/
path: string
}
@@ -301,8 +330,26 @@ export type ContextLayerProposalsListParams = {
}
export type ContextLayerAgentPagesRetrieveParams = {
+ /**
+ * Head from the first chunk. Required for continuation. A changed head returns 409.
+ * @minLength 1
+ * @maxLength 64
+ */
+ head_sha?: string
+ /**
+ * Maximum characters to read. Omit for the full page.
+ * @minimum 1
+ * @maximum 12000
+ */
+ limit?: number
+ /**
+ * Character offset from next_offset.
+ * @minimum 0
+ */
+ offset?: number
/**
* Repo-relative Markdown path of the page to read.
+ * @minLength 1
*/
path: string
}
diff --git a/products/context_layer/mcp/tools.yaml b/products/context_layer/mcp/tools.yaml
index 7ab1f6ec5bee..703437e18550 100644
--- a/products/context_layer/mcp/tools.yaml
+++ b/products/context_layer/mcp/tools.yaml
@@ -77,7 +77,12 @@ tools:
title: Read a context wiki page
description: >
Read one repo-relative Markdown page from the organization context wiki. Returns its content and head_sha;
- pass that head_sha as base_head when updating the page.
+ pass that head_sha as base_head when updating the page. Reads are bounded. Follow next_offset with the same
+ head_sha and limit until complete is true. Join content chunks in order before editing. On 409, discard the
+ chunks and restart at offset zero.
+ param_overrides:
+ limit:
+ input_schema: WikiPageReadLimitSchema
feature_flag: context-layer
context-wiki-page-update:
operation: context_layer_agent_pages_update
@@ -117,7 +122,13 @@ tools:
destructive: false
idempotent: true
title: Read a loop context wiki page
- description: Read a context wiki page and its head_sha for an unattended loop run.
+ description: >
+ Read a bounded context wiki page chunk and its head_sha for an unattended loop run. Follow next_offset with
+ the same head_sha and limit until complete is true. Join all content chunks before editing. On 409, discard
+ the chunks and restart at offset zero.
+ param_overrides:
+ limit:
+ input_schema: WikiPageReadLimitSchema
feature_flag: context-layer
loop-context-wiki-page-update:
operation: context_layer_agent_pages_update
@@ -174,7 +185,13 @@ tools:
destructive: false
idempotent: true
title: Read this task's context wiki page
- description: Read a context wiki page and its head_sha for an unattended task run.
+ description: >
+ Read a bounded context wiki page chunk and its head_sha for an unattended task run. Follow next_offset with
+ the same head_sha and limit until complete is true. Join all content chunks before editing. On 409, discard
+ the chunks and restart at offset zero.
+ param_overrides:
+ limit:
+ input_schema: WikiPageReadLimitSchema
feature_flag: context-layer
task-context-wiki-page-update:
operation: context_layer_agent_pages_update
diff --git a/products/tasks/backend/facade/loops.py b/products/tasks/backend/facade/loops.py
index 760d6a57683c..809773b89b19 100644
--- a/products/tasks/backend/facade/loops.py
+++ b/products/tasks/backend/facade/loops.py
@@ -1472,6 +1472,7 @@ def list_loop_runs(
*,
cursor: str | None = None,
limit: int = DEFAULT_LOOP_RUN_PAGE_SIZE,
+ status: str | None = None,
) -> LoopRunPageDTO | None:
"""TaskRun rows spawned by this loop's firings, newest first, cursor-paginated.
@@ -1484,7 +1485,7 @@ def list_loop_runs(
loop = _visible_loop_queryset(team_id, user_id).select_related("team").filter(pk=loop_id).first()
if loop is None or _rbac_denied(loop, user, "viewer"):
return None
- return _loop_runs_page(loop, team_id, cursor=cursor, limit=limit)
+ return _loop_runs_page(loop, team_id, cursor=cursor, limit=limit, status=status)
def list_loop_runs_for_service(
@@ -1493,16 +1494,19 @@ def list_loop_runs_for_service(
*,
cursor: str | None = None,
limit: int = DEFAULT_LOOP_RUN_PAGE_SIZE,
+ status: str | None = None,
) -> LoopRunPageDTO | None:
"""Run history for a PSAK-authenticated service caller: project-wide, no personal/team
visibility filter (a PSAK can already trigger any loop in the project — see `fire_loop_api`)."""
loop = Loop.objects.filter(team_id=team_id, deleted=False, internal=False, pk=loop_id).first()
if loop is None:
return None
- return _loop_runs_page(loop, team_id, cursor=cursor, limit=limit)
+ return _loop_runs_page(loop, team_id, cursor=cursor, limit=limit, status=status)
-def _loop_runs_page(loop: Loop, team_id: int, *, cursor: str | None, limit: int) -> LoopRunPageDTO:
+def _loop_runs_page(
+ loop: Loop, team_id: int, *, cursor: str | None, limit: int, status: str | None = None
+) -> LoopRunPageDTO:
page_size = max(1, min(limit, MAX_LOOP_RUN_PAGE_SIZE))
queryset = (
TaskRun.objects.filter(team_id=team_id)
@@ -1510,6 +1514,9 @@ def _loop_runs_page(loop: Loop, team_id: int, *, cursor: str | None, limit: int)
.order_by("-created_at", "-id")
)
+ if status is not None:
+ queryset = queryset.filter(status=status)
+
if cursor:
decoded = _decode_run_cursor(cursor)
if decoded is not None:
diff --git a/products/tasks/backend/logic/services/loop_runs.py b/products/tasks/backend/logic/services/loop_runs.py
index 153569d1b573..c5f4647a5e10 100644
--- a/products/tasks/backend/logic/services/loop_runs.py
+++ b/products/tasks/backend/logic/services/loop_runs.py
@@ -131,7 +131,7 @@ def _context_outputs(context_target: dict | None) -> dict:
}
-def render_context_target_block(context_target: dict | None) -> str:
+def render_context_target_block(context_target: dict | None, *, loop_id: str) -> str:
"""The publish contract appended to a loop's prompt when it maintains a context's deliverables.
Empty for an unattached loop or a feed-only attachment — filing the run into the feed needs no
@@ -161,6 +161,8 @@ def render_context_target_block(context_target: dict | None) -> str:
f"`loop-channel-instructions-retrieve` and "
f"`loop-channel-instructions-update` with the version you just read as base_version. Edit in place, "
f"carrying forward anything still true instead of rewriting from scratch."
+ " If a page read returns next_offset, continue with that offset, the same head_sha, and the same limit "
+ "until complete is true. Join all content chunks before editing. On a revision conflict, restart the read."
)
if outputs["canvas_id"]:
lines.append(
@@ -168,7 +170,21 @@ def render_context_target_block(context_target: dict | None) -> str:
f"`current_version_id` with `canvas-source-retrieve`, then publish the "
f"complete project with `canvas-publish-create`, passing the version you "
f"read as `expected_current_version_id`. Follow the `building-canvases` skill."
+ " Read runtime state with `canvas-state-retrieve`: list keys without values, follow next_offset, "
+ "and select only the keys needed. Read long values with `canvas-state-value-retrieve`, keeping "
+ "the revision fixed across chunks. Discover these tools through MCP search and info; do not assume "
+ "a composition storage tool is available. Missing tools, denied access, missing values, and incomplete "
+ "reads are different conditions. Report the actual condition instead of requesting broader permissions."
)
+ # A context-only target has no canvas, and the run holds no canvas scopes for one.
+ destination = "canvas" if outputs["canvas_id"] else "context page"
+ lines.append(
+ f"- Read failures with `tasks-list`, channel={channel_id}, status=failed, internal=all, and archived=all. "
+ "Use hog_flow_id for workflow-backed loops and `tasks-runs-list` for earlier runs of a task. "
+ f"When available, `loops-runs-retrieve` with id={loop_id} also accepts status=failed and next_cursor. "
+ f"Show task/run links and stored errors in the {destination}, not a saved Enabled label. If a read fails, "
+ "report the failure in the task response; do not mark the work complete."
+ )
return "\n".join(lines)
@@ -700,7 +716,7 @@ def _create_loop_task_and_run(loop: Loop, trigger: LoopTrigger | None, trigger_c
raise ValueError("The loop's context canvas is no longer available.")
title = f"{loop.name} ({django_timezone.now().isoformat()})"
- context_block = render_context_target_block(context_target)
+ context_block = render_context_target_block(context_target, loop_id=str(loop.id))
execution_context = "\n\n".join(part for part in [LOOP_FRAMING_BLOCK, context_block, trigger_context] if part)
pending_user_message = render_loop_run_message(loop.instructions, execution_context)
diff --git a/products/tasks/backend/presentation/serializers_loops.py b/products/tasks/backend/presentation/serializers_loops.py
index 2eccc4dd879c..932f9437d15f 100644
--- a/products/tasks/backend/presentation/serializers_loops.py
+++ b/products/tasks/backend/presentation/serializers_loops.py
@@ -23,6 +23,7 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.models.integration import Integration
from products.tasks.backend.facade import loops as loops_facade
+from products.tasks.backend.facade.api import TaskRunStatus
from products.tasks.backend.facade.run_config import (
PUBLIC_REASONING_EFFORTS,
RuntimeAdapter,
@@ -733,6 +734,11 @@ class LoopRunPageSerializer(serializers.Serializer):
class LoopRunsQuerySerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ choices=TaskRunStatus.choices,
+ required=False,
+ help_text="Only return runs with this status. Use failed to read errors even when canvas state is unavailable.",
+ )
cursor = serializers.CharField(
required=False, help_text="Opaque pagination cursor from a previous response's `next_cursor`."
)
diff --git a/products/tasks/backend/presentation/views/loops.py b/products/tasks/backend/presentation/views/loops.py
index dd3277db112a..24075b396e81 100644
--- a/products/tasks/backend/presentation/views/loops.py
+++ b/products/tasks/backend/presentation/views/loops.py
@@ -433,9 +433,13 @@ class LoopViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
if is_authenticated_via_project_secret_api_key(request):
# PSAK is project-wide (it can already trigger any loop), so its readback skips the
# personal/team visibility split, same as the trigger path.
- page = loops_facade.list_loop_runs_for_service(pk, self.team_id, cursor=cursor, limit=limit)
+ page = loops_facade.list_loop_runs_for_service(
+ pk, self.team_id, cursor=cursor, limit=limit, status=query.get("status")
+ )
else:
- page = loops_facade.list_loop_runs(pk, self.team_id, request.user, cursor=cursor, limit=limit)
+ page = loops_facade.list_loop_runs(
+ pk, self.team_id, request.user, cursor=cursor, limit=limit, status=query.get("status")
+ )
if page is None:
raise NotFound()
return Response(LoopRunPageSerializer({"results": page.runs, "next_cursor": page.next_cursor}).data)
diff --git a/products/tasks/backend/tests/test_loop_runs.py b/products/tasks/backend/tests/test_loop_runs.py
index e6293a5e5e49..8e1bf0275f1f 100644
--- a/products/tasks/backend/tests/test_loop_runs.py
+++ b/products/tasks/backend/tests/test_loop_runs.py
@@ -22,6 +22,7 @@ from products.tasks.backend.logic.services.loop_runs import (
TRIGGER_CONTEXT_MAX_BYTES,
fire_loop,
handle_loop_run_terminal,
+ render_context_target_block,
render_trigger_context,
)
from products.tasks.backend.models import (
@@ -84,6 +85,33 @@ class TestRenderTriggerContext(SimpleTestCase):
self.assertIn(f"[truncated: payload exceeded {TRIGGER_CONTEXT_MAX_BYTES} bytes]", context)
+class TestRenderContextTargetBlock(SimpleTestCase):
+ CHANNEL_ID = "0199c0de-0000-4000-8000-000000000001"
+ CANVAS_ID = "0199c0de-0000-4000-8000-000000000002"
+ LOOP_ID = "0199c0de-0000-4000-8000-000000000003"
+
+ @parameterized.expand(
+ [
+ ("context only", {"update_context": True}, "context page"),
+ ("canvas only", {"canvas_id": CANVAS_ID}, "canvas"),
+ ("both", {"update_context": True, "canvas_id": CANVAS_ID}, "canvas"),
+ ]
+ )
+ def test_failures_are_published_to_a_deliverable_the_target_has(self, _name, outputs, destination):
+ block = render_context_target_block(
+ {"channel_id": self.CHANNEL_ID, "name": "Growth", "outputs": outputs}, loop_id=self.LOOP_ID
+ )
+
+ self.assertIn(f"stored errors in the {destination}", block)
+
+ def test_failure_history_names_the_firing_loop(self):
+ block = render_context_target_block(
+ {"channel_id": self.CHANNEL_ID, "outputs": {"update_context": True}}, loop_id=self.LOOP_ID
+ )
+
+ self.assertIn(f"`loops-runs-retrieve` with id={self.LOOP_ID}", block)
+
+
class LoopRunsTestCase(TestCase):
def setUp(self):
self.organization = Organization.objects.create(name="Test Org")
diff --git a/products/tasks/backend/tests/test_loops_api.py b/products/tasks/backend/tests/test_loops_api.py
index 7b60f96dc1cd..e07b63feb302 100644
--- a/products/tasks/backend/tests/test_loops_api.py
+++ b/products/tasks/backend/tests/test_loops_api.py
@@ -1196,6 +1196,24 @@ class LoopRunsAPITest(LoopsAPITestCase):
self.assertEqual(collected_ids, list(reversed(created_run_ids)))
+ failed_ids = created_run_ids[::2]
+ TaskRun.objects.filter(id__in=failed_ids).update(status=TaskRun.Status.FAILED, error_message="Read failed")
+ failures = []
+ cursor = None
+ for _ in range(len(failed_ids) + 1):
+ response = self.owner_client.get(
+ runs_url, {"status": "failed", "limit": "2", **({"cursor": cursor} if cursor else {})}
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ page = response.json()
+ failures.extend(page["results"])
+ cursor = page["next_cursor"]
+ if cursor is None:
+ break
+ self.assertEqual([run["id"] for run in failures], list(reversed(failed_ids)))
+ self.assertTrue(all(run["error_message"] == "Read failed" for run in failures))
+ self.assertEqual(self.owner_client.get(runs_url, {"status": "unknown"}).status_code, 400)
+
def test_runs_listing_is_invisible_for_personal_loop_of_another_member(self):
loop_id = self._create_loop(self.owner_client, visibility="personal")["id"]
response = self.peer_client.get(f"{self._loop_url(loop_id)}runs/")
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 9a26bc7870f0..8ecbcfbb73ec 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -5320,8 +5320,31 @@ export type LoopsRunsRetrieveParams = {
* @maximum 100
*/
limit?: number
+ /**
+ * Only return runs with this status. Use failed to read errors even when canvas state is unavailable.
+ *
+ * * `not_started` - Not Started
+ * * `queued` - Queued
+ * * `in_progress` - In Progress
+ * * `completed` - Completed
+ * * `failed` - Failed
+ * * `cancelled` - Cancelled
+ * @minLength 1
+ */
+ status?: LoopsRunsRetrieveStatus
}
+export type LoopsRunsRetrieveStatus = (typeof LoopsRunsRetrieveStatus)[keyof typeof LoopsRunsRetrieveStatus]
+
+export const LoopsRunsRetrieveStatus = {
+ NotStarted: 'not_started',
+ Queued: 'queued',
+ InProgress: 'in_progress',
+ Completed: 'completed',
+ Failed: 'failed',
+ Cancelled: 'cancelled',
+} as const
+
export type LoopsTriggerCreateBodyOne = { [key: string]: unknown }
export type LoopsTriggerCreateBodyTwo = { [key: string]: unknown }
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index 181907ccb3ae..fc9d2d967e92 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -277,7 +277,9 @@ tools:
description: >
List a loop's run history, newest first, cursor-paginated. Each entry carries the run's status, branch,
error message and output (including any PR URL), so an agent can check whether a loop's runs succeeded and
- what they produced.
+ what they produced. Set status=failed to find failure records without reading canvas state. Keep the status
+ filter unchanged when following next_cursor. Use these records and the loop's last_run_status, last_error,
+ and consecutive_failures for current health; an enabled schedule alone does not show successful work.
feature_flag: loops
loops-skill-bundles-update:
operation: loops_skill_bundles_update
@@ -516,7 +518,10 @@ tools:
Search agent tasks before starting related work. Use `search` to match task titles and descriptions, and
`channel` to limit results to the current space. The results identify who created each task and whether its
latest run is active. Supports additional filtering by status, repository, creator, origin product, and
- archived or internal state. Requires the calling token's organization to have Tasks access enabled.
+ archived or internal state. Requires the calling token's organization to have Tasks access enabled. To
+ inspect failures in a space, set channel, status=failed, internal=all, and archived=all. For workflow-backed
+ loops, also set hog_flow_id. The latest_run includes the stored error and completion time even if the run
+ stopped before writing canvas state. Use tasks-runs-list for earlier runs of a task.
feature_flag: tasks
response:
include:
@@ -532,6 +537,9 @@ tools:
- created_by.last_name
- latest_run.id
- latest_run.status
+ - latest_run.error_message
+ - latest_run.created_at
+ - latest_run.completed_at
- created_at
- updated_at
tasks-me-config-create:
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index efc7f57fa248..cd2c8b3171e3 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1460,7 +1460,7 @@
}
},
"canvas-state-retrieve": {
- "description": "Read persisted `ph.state` entries for a visible canvas. Returns shared entries and the authenticated user's own user-scoped entries, never another user's. Use this with canvas-source-retrieve when collaborative progress, checklist selections, filters, or other runtime values live outside the source. Only scopes declared by the live canvas version are readable. Optionally filter to `user` or `shared` with `scope`.",
+ "description": "Read persisted `ph.state` entries for a visible canvas. Returns shared entries and the authenticated user's own user-scoped entries, never another user's. Use this with canvas-source-retrieve when collaborative progress, checklist selections, filters, or other runtime values live outside the source. Only scopes declared by the live canvas version are readable. Optionally filter to `user` or `shared` with `scope`. Returns a key inventory by default. Keep filters unchanged and follow next_offset until complete is true. Set key or key_prefix and keys_only=false for small selected values. Use canvas-state-value-retrieve for long values. This reads persisted state directly; no composition storage tool is needed.",
"category": "Canvas",
"feature": "canvas",
"summary": "Read canvas state",
@@ -1487,6 +1487,20 @@
"readOnlyHint": false
}
},
+ "canvas-state-value-retrieve": {
+ "description": "Read one exact scope and key as bounded JSON text chunks. Start at offset zero, then pass next_offset and revision until complete is true. Join value_json chunks in order before parsing the JSON. If the value changes, the read returns 409; discard earlier chunks and restart at zero. On a 404, read the error detail: \"No readable value for this scope and key\" means the entry is absent and broader permissions would not help, while any other 404 means the canvas is not available to this caller.",
+ "category": "Canvas",
+ "feature": "canvas",
+ "summary": "Read a canvas state value",
+ "title": "Read a canvas state value",
+ "required_scopes": ["canvas:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"canvas-validate-create": {
"description": "Validate a candidate canvas source project without publishing it. Returns structured diagnostics (severity, code, message, file, line); `valid: false` means a publish would be rejected. Side-effect free — call it as often as needed while iterating, and fix every error-severity diagnostic (including undeclared-capability errors) before publishing.",
"category": "Canvas",
@@ -2077,7 +2091,7 @@
"feature_flag": "context-layer"
},
"context-wiki-page-retrieve": {
- "description": "Read one repo-relative Markdown page from the organization context wiki. Returns its content and head_sha; pass that head_sha as base_head when updating the page.",
+ "description": "Read one repo-relative Markdown page from the organization context wiki. Returns its content and head_sha; pass that head_sha as base_head when updating the page. Reads are bounded. Follow next_offset with the same head_sha and limit until complete is true. Join content chunks in order before editing. On 409, discard the chunks and restart at offset zero.",
"category": "Context wiki",
"feature": "context_layer",
"summary": "Read a context wiki page",
@@ -7788,7 +7802,7 @@
"feature_flag": "context-layer"
},
"loop-context-wiki-page-retrieve": {
- "description": "Read a context wiki page and its head_sha for an unattended loop run.",
+ "description": "Read a bounded context wiki page chunk and its head_sha for an unattended loop run. Follow next_offset with the same head_sha and limit until complete is true. Join all content chunks before editing. On 409, discard the chunks and restart at offset zero.",
"category": "Context wiki",
"feature": "context_layer",
"summary": "Read a loop context wiki page",
@@ -7938,7 +7952,7 @@
"feature_flag": "loops"
},
"loops-runs-retrieve": {
- "description": "List a loop's run history, newest first, cursor-paginated. Each entry carries the run's status, branch, error message and output (including any PR URL), so an agent can check whether a loop's runs succeeded and what they produced.",
+ "description": "List a loop's run history, newest first, cursor-paginated. Each entry carries the run's status, branch, error message and output (including any PR URL), so an agent can check whether a loop's runs succeeded and what they produced. Set status=failed to find failure records without reading canvas state. Keep the status filter unchanged when following next_cursor. Use these records and the loop's last_run_status, last_error, and consecutive_failures for current health; an enabled schedule alone does not show successful work.",
"category": "Tasks",
"feature": "tasks",
"summary": "List loop runs",
@@ -11318,7 +11332,7 @@
"feature_flag": "context-layer"
},
"task-context-wiki-page-retrieve": {
- "description": "Read a context wiki page and its head_sha for an unattended task run.",
+ "description": "Read a bounded context wiki page chunk and its head_sha for an unattended task run. Follow next_offset with the same head_sha and limit until complete is true. Join all content chunks before editing. On 409, discard the chunks and restart at offset zero.",
"category": "Context wiki",
"feature": "context_layer",
"summary": "Read this task's context wiki page",
@@ -11408,7 +11422,7 @@
"feature_flag": "tasks-mcp-agent-run-start"
},
"tasks-list": {
- "description": "Search agent tasks before starting related work. Use `search` to match task titles and descriptions, and `channel` to limit results to the current space. The results identify who created each task and whether its latest run is active. Supports additional filtering by status, repository, creator, origin product, and archived or internal state. Requires the calling token's organization to have Tasks access enabled.",
+ "description": "Search agent tasks before starting related work. Use `search` to match task titles and descriptions, and `channel` to limit results to the current space. The results identify who created each task and whether its latest run is active. Supports additional filtering by status, repository, creator, origin product, and archived or internal state. Requires the calling token's organization to have Tasks access enabled. To inspect failures in a space, set channel, status=failed, internal=all, and archived=all. For workflow-backed loops, also set hog_flow_id. The latest_run includes the stored error and completion time even if the run stopped before writing canvas state. Use tasks-runs-list for earlier runs of a task.",
"category": "Tasks",
"feature": "tasks",
"summary": "Search and list tasks",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index dde9a1c167ee..0a65b3a47a40 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1475,7 +1475,7 @@
}
},
"canvas-state-retrieve": {
- "description": "Read persisted `ph.state` entries for a visible canvas. Returns shared entries and the authenticated user's own user-scoped entries, never another user's. Use this with canvas-source-retrieve when collaborative progress, checklist selections, filters, or other runtime values live outside the source. Only scopes declared by the live canvas version are readable. Optionally filter to `user` or `shared` with `scope`.",
+ "description": "Read persisted `ph.state` entries for a visible canvas. Returns shared entries and the authenticated user's own user-scoped entries, never another user's. Use this with canvas-source-retrieve when collaborative progress, checklist selections, filters, or other runtime values live outside the source. Only scopes declared by the live canvas version are readable. Optionally filter to `user` or `shared` with `scope`. Returns a key inventory by default. Keep filters unchanged and follow next_offset until complete is true. Set key or key_prefix and keys_only=false for small selected values. Use canvas-state-value-retrieve for long values. This reads persisted state directly; no composition storage tool is needed.",
"category": "Canvas",
"feature": "canvas",
"summary": "Read canvas state",
@@ -1502,6 +1502,20 @@
"readOnlyHint": false
}
},
+ "canvas-state-value-retrieve": {
+ "description": "Read one exact scope and key as bounded JSON text chunks. Start at offset zero, then pass next_offset and revision until complete is true. Join value_json chunks in order before parsing the JSON. If the value changes, the read returns 409; discard earlier chunks and restart at zero. On a 404, read the error detail: \"No readable value for this scope and key\" means the entry is absent and broader permissions would not help, while any other 404 means the canvas is not available to this caller.",
+ "category": "Canvas",
+ "feature": "canvas",
+ "summary": "Read a canvas state value",
+ "title": "Read a canvas state value",
+ "required_scopes": ["canvas:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"canvas-validate-create": {
"description": "Validate a candidate canvas source project without publishing it. Returns structured diagnostics (severity, code, message, file, line); `valid: false` means a publish would be rejected. Side-effect free — call it as often as needed while iterating, and fix every error-severity diagnostic (including undeclared-capability errors) before publishing.",
"category": "Canvas",
@@ -2092,7 +2106,7 @@
"feature_flag": "context-layer"
},
"context-wiki-page-retrieve": {
- "description": "Read one repo-relative Markdown page from the organization context wiki. Returns its content and head_sha; pass that head_sha as base_head when updating the page.",
+ "description": "Read one repo-relative Markdown page from the organization context wiki. Returns its content and head_sha; pass that head_sha as base_head when updating the page. Reads are bounded. Follow next_offset with the same head_sha and limit until complete is true. Join content chunks in order before editing. On 409, discard the chunks and restart at offset zero.",
"category": "Context wiki",
"feature": "context_layer",
"summary": "Read a context wiki page",
@@ -8167,7 +8181,7 @@
"feature_flag": "context-layer"
},
"loop-context-wiki-page-retrieve": {
- "description": "Read a context wiki page and its head_sha for an unattended loop run.",
+ "description": "Read a bounded context wiki page chunk and its head_sha for an unattended loop run. Follow next_offset with the same head_sha and limit until complete is true. Join all content chunks before editing. On 409, discard the chunks and restart at offset zero.",
"category": "Context wiki",
"feature": "context_layer",
"summary": "Read a loop context wiki page",
@@ -8332,7 +8346,7 @@
"feature_flag": "loops"
},
"loops-runs-retrieve": {
- "description": "List a loop's run history, newest first, cursor-paginated. Each entry carries the run's status, branch, error message and output (including any PR URL), so an agent can check whether a loop's runs succeeded and what they produced.",
+ "description": "List a loop's run history, newest first, cursor-paginated. Each entry carries the run's status, branch, error message and output (including any PR URL), so an agent can check whether a loop's runs succeeded and what they produced. Set status=failed to find failure records without reading canvas state. Keep the status filter unchanged when following next_cursor. Use these records and the loop's last_run_status, last_error, and consecutive_failures for current health; an enabled schedule alone does not show successful work.",
"category": "Tasks",
"feature": "tasks",
"summary": "List loop runs",
@@ -11918,7 +11932,7 @@
"feature_flag": "context-layer"
},
"task-context-wiki-page-retrieve": {
- "description": "Read a context wiki page and its head_sha for an unattended task run.",
+ "description": "Read a bounded context wiki page chunk and its head_sha for an unattended task run. Follow next_offset with the same head_sha and limit until complete is true. Join all content chunks before editing. On 409, discard the chunks and restart at offset zero.",
"category": "Context wiki",
"feature": "context_layer",
"summary": "Read this task's context wiki page",
@@ -12053,7 +12067,7 @@
"feature_flag": "tasks-mcp-agent-run-start"
},
"tasks-list": {
- "description": "Search agent tasks before starting related work. Use `search` to match task titles and descriptions, and `channel` to limit results to the current space. The results identify who created each task and whether its latest run is active. Supports additional filtering by status, repository, creator, origin product, and archived or internal state. Requires the calling token's organization to have Tasks access enabled.",
+ "description": "Search agent tasks before starting related work. Use `search` to match task titles and descriptions, and `channel` to limit results to the current space. The results identify who created each task and whether its latest run is active. Supports additional filtering by status, repository, creator, origin product, and archived or internal state. Requires the calling token's organization to have Tasks access enabled. To inspect failures in a space, set channel, status=failed, internal=all, and archived=all. For workflow-backed loops, also set hog_flow_id. The latest_run includes the stored error and completion time even if the run stopped before writing canvas state. Use tasks-runs-list for earlier runs of a task.",
"category": "Tasks",
"feature": "tasks",
"summary": "Search and list tasks",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 0e23a35333a7..0dce1272d87a 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -110,6 +110,16 @@
},
"required": ["name", "url"]
},
+ "CanvasStateKeysOnlySchema": {
+ "default": true,
+ "type": "boolean"
+ },
+ "CanvasStateReadLimitSchema": {
+ "default": 20,
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 100
+ },
"ChannelInstructionsBaseVersionSchema": {
"type": "integer",
"minimum": 0,
@@ -1446,6 +1456,12 @@
],
"description": "Filter definition. Pick exactly one branch: `data_warehouse` (set `source: \"data_warehouse\"` plus `table_name`/`timestamp_field`/`key_field`) or `events` (HogFunction filter shape with an `events` array)."
},
+ "WikiPageReadLimitSchema": {
+ "default": 12000,
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 12000
+ },
"WorkflowActionEmailPatchSchema": {
"type": "object",
"properties": {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 102227046ecf..5b06744a0b90 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17499,8 +17499,8 @@ export namespace Schemas {
* @maxLength 200
*/
key: string;
- /** The stored JSON value. */
- value: unknown;
+ /** The stored JSON value. Omitted from a key inventory. */
+ value?: unknown;
/** When the entry was last written. */
updated_at: string;
}
@@ -17511,6 +17511,13 @@ export namespace Schemas {
export interface CanvasStateResponse {
/** The canvas's shared entries plus the caller's own user-scoped entries. */
entries: CanvasStateEntry[];
+ /**
+ * Next entry offset, or null when complete.
+ * @nullable
+ */
+ next_offset: number | null;
+ /** True when no further entries remain for this selection. */
+ complete: boolean;
}
/**
@@ -17531,6 +17538,31 @@ export namespace Schemas {
value: unknown;
}
+ export interface CanvasStateValueResponse {
+ /** Scope of this value.
+ *
+ * * `user` - user
+ * * `shared` - shared */
+ scope: CanvasStateScopeEnum;
+ /** Key of this value. */
+ key: string;
+ /** A chunk of JSON text. Join all chunks in order, then parse the complete JSON. */
+ value_json: string;
+ /** Content revision. Pass it on subsequent reads; a changed value returns 409. */
+ revision: string;
+ /** Character offset of this chunk. */
+ offset: number;
+ /** Character length of the complete JSON text. */
+ total_length: number;
+ /**
+ * Next character offset, or null when complete.
+ * @nullable
+ */
+ next_offset: number | null;
+ /** True when no further chunks remain. Earlier chunks are still needed when offset is nonzero. */
+ complete: boolean;
+ }
+
/**
* Payload for validating a candidate source project without publishing it.
*/
@@ -93426,6 +93458,17 @@ export namespace Schemas {
head_sha: string;
/** When this page was last changed in the wiki history. */
updated_at: string;
+ /** Character offset of this chunk. */
+ offset: number;
+ /** Character length of the complete page. */
+ total_length: number;
+ /**
+ * Next character offset, or null when complete.
+ * @nullable
+ */
+ next_offset: number | null;
+ /** True when no further chunks remain. Do not write a page until all chunks are read. */
+ complete: boolean;
}
/**
@@ -96586,8 +96629,26 @@ export namespace Schemas {
};
export type ContextLayerPagesRetrieveParams = {
+ /**
+ * Head from the first chunk. Required for continuation. A changed head returns 409.
+ * @minLength 1
+ * @maxLength 64
+ */
+ head_sha?: string;
+ /**
+ * Maximum characters to read. Omit for the full page.
+ * @minimum 1
+ * @maximum 12000
+ */
+ limit?: number;
+ /**
+ * Character offset from next_offset.
+ * @minimum 0
+ */
+ offset?: number;
/**
* Repo-relative Markdown path of the page to read.
+ * @minLength 1
*/
path: string;
};
@@ -98133,7 +98194,37 @@ export namespace Schemas {
export type CanvasesStateRetrieveParams = {
/**
- * Only return entries in this scope.
+ * Only read this exact key.
+ * @minLength 1
+ * @maxLength 200
+ */
+ key?: string;
+ /**
+ * Only read entries whose key starts with this prefix.
+ * @maxLength 200
+ */
+ key_prefix?: string;
+ /**
+ * True returns a key inventory without stored values.
+ */
+ keys_only?: boolean;
+ /**
+ * Maximum entries per page. Omit for the full state. Prefer an inventory and state/value for large values.
+ * @minimum 1
+ * @maximum 100
+ */
+ limit?: number;
+ /**
+ * Entry offset from next_offset. Keep filters unchanged between pages.
+ * @minimum 0
+ */
+ offset?: number;
+ /**
+ * Only read this scope.
+ *
+ * * `user` - user
+ * * `shared` - shared
+ * @minLength 1
*/
scope?: CanvasesStateRetrieveScope;
};
@@ -98142,8 +98233,50 @@ export namespace Schemas {
export const CanvasesStateRetrieveScope = {
+ User: 'user',
Shared: 'shared',
+ } as const;
+
+ export type CanvasesStateValueRetrieveParams = {
+ /**
+ * Exact key to read.
+ * @minLength 1
+ * @maxLength 200
+ */
+ key: string;
+ /**
+ * Maximum JSON characters in this response.
+ * @minimum 1
+ * @maximum 12000
+ */
+ limit?: number;
+ /**
+ * Character offset from next_offset.
+ * @minimum 0
+ */
+ offset?: number;
+ /**
+ * Revision from the first chunk. Required when offset is greater than zero.
+ * @minLength 1
+ * @maxLength 64
+ */
+ revision?: string;
+ /**
+ * Scope of the value to read.
+ *
+ * * `user` - user
+ * * `shared` - shared
+ * @minLength 1
+ */
+ scope: CanvasesStateValueRetrieveScope;
+ };
+
+ export type CanvasesStateValueRetrieveScope = typeof CanvasesStateValueRetrieveScope[keyof typeof CanvasesStateValueRetrieveScope];
+
+
+ export const CanvasesStateValueRetrieveScope = {
User: 'user',
+ Shared: 'shared',
} as const;
export type CanvasesVersionsRetrieveParams = {
@@ -98367,8 +98500,26 @@ export namespace Schemas {
} as const;
export type ContextLayerAgentPagesRetrieveParams = {
+ /**
+ * Head from the first chunk. Required for continuation. A changed head returns 409.
+ * @minLength 1
+ * @maxLength 64
+ */
+ head_sha?: string;
+ /**
+ * Maximum characters to read. Omit for the full page.
+ * @minimum 1
+ * @maximum 12000
+ */
+ limit?: number;
+ /**
+ * Character offset from next_offset.
+ * @minimum 0
+ */
+ offset?: number;
/**
* Repo-relative Markdown path of the page to read.
+ * @minLength 1
*/
path: string;
};
@@ -104047,8 +104198,32 @@ export namespace Schemas {
* @maximum 100
*/
limit?: number;
+ /**
+ * Only return runs with this status. Use failed to read errors even when canvas state is unavailable.
+ *
+ * * `not_started` - Not Started
+ * * `queued` - Queued
+ * * `in_progress` - In Progress
+ * * `completed` - Completed
+ * * `failed` - Failed
+ * * `cancelled` - Cancelled
+ * @minLength 1
+ */
+ status?: LoopsRunsRetrieveStatus;
};
+ export type LoopsRunsRetrieveStatus = typeof LoopsRunsRetrieveStatus[keyof typeof LoopsRunsRetrieveStatus];
+
+
+ export const LoopsRunsRetrieveStatus = {
+ NotStarted: 'not_started',
+ Queued: 'queued',
+ InProgress: 'in_progress',
+ Completed: 'completed',
+ Failed: 'failed',
+ Cancelled: 'cancelled',
+ } as const;
+
export type LoopsTriggerCreateBodyOne = { [key: string]: unknown };
export type LoopsTriggerCreateBodyTwo = { [key: string]: unknown };
diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.ts
index 3412e3e222d0..a82067ab2181 100644
--- a/services/mcp/src/generated/canvas/api.ts
+++ b/services/mcp/src/generated/canvas/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 18 enabled ops
+ * PostHog API - MCP 19 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1228,8 +1228,44 @@ export const CanvasesStateRetrieveParams = () => zod.object({
),
})
+export const canvasesStateRetrieveQueryKeyMax = 200
+
+export const canvasesStateRetrieveQueryKeyPrefixMax = 200
+
+export const canvasesStateRetrieveQueryKeysOnlyDefault = false
+export const canvasesStateRetrieveQueryLimitMax = 100
+
+export const canvasesStateRetrieveQueryOffsetDefault = 0
+export const canvasesStateRetrieveQueryOffsetMin = 0
+
export const CanvasesStateRetrieveQueryParams = () => zod.object({
- scope: zod.enum(['shared', 'user']).optional().describe('Only return entries in this scope.'),
+ key: zod.string().min(1).max(canvasesStateRetrieveQueryKeyMax).optional().describe('Only read this exact key.'),
+ key_prefix: zod
+ .string()
+ .max(canvasesStateRetrieveQueryKeyPrefixMax)
+ .optional()
+ .describe('Only read entries whose key starts with this prefix.'),
+ keys_only: zod
+ .boolean()
+ .default(canvasesStateRetrieveQueryKeysOnlyDefault)
+ .describe('True returns a key inventory without stored values.'),
+ limit: zod
+ .number()
+ .min(1)
+ .max(canvasesStateRetrieveQueryLimitMax)
+ .optional()
+ .describe(
+ 'Maximum entries per page. Omit for the full state. Prefer an inventory and state\/value for large values.'
+ ),
+ offset: zod
+ .number()
+ .min(canvasesStateRetrieveQueryOffsetMin)
+ .default(canvasesStateRetrieveQueryOffsetDefault)
+ .describe('Entry offset from next_offset. Keep filters unchanged between pages.'),
+ scope: zod
+ .enum(['user', 'shared'])
+ .optional()
+ .describe('Only read this scope.\n\n\* `user` - user\n\* `shared` - shared'),
})
/**
@@ -1259,6 +1295,55 @@ export const CanvasesStateSetBody = () => zod
})
.describe("Payload for writing (or deleting) one key of a canvas's runtime state.")
+/**
+ * Canvases: agent-built sandboxed browser apps, filed into channels.
+ *
+ * Source is versioned per publish and built server-side; the canvas app
+ * renders the published build's artifact from the isolated artifact origin.
+ */
+export const CanvasesStateValueRetrieveParams = () => zod.object({
+ id: zod.string().describe('A UUID string identifying this canvas.'),
+ 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 canvasesStateValueRetrieveQueryKeyMax = 200
+
+export const canvasesStateValueRetrieveQueryLimitDefault = 12000
+export const canvasesStateValueRetrieveQueryLimitMax = 12000
+
+export const canvasesStateValueRetrieveQueryOffsetDefault = 0
+export const canvasesStateValueRetrieveQueryOffsetMin = 0
+
+export const canvasesStateValueRetrieveQueryRevisionMax = 64
+
+export const CanvasesStateValueRetrieveQueryParams = () => zod.object({
+ key: zod.string().min(1).max(canvasesStateValueRetrieveQueryKeyMax).describe('Exact key to read.'),
+ limit: zod
+ .number()
+ .min(1)
+ .max(canvasesStateValueRetrieveQueryLimitMax)
+ .default(canvasesStateValueRetrieveQueryLimitDefault)
+ .describe('Maximum JSON characters in this response.'),
+ offset: zod
+ .number()
+ .min(canvasesStateValueRetrieveQueryOffsetMin)
+ .default(canvasesStateValueRetrieveQueryOffsetDefault)
+ .describe('Character offset from next_offset.'),
+ revision: zod
+ .string()
+ .min(1)
+ .max(canvasesStateValueRetrieveQueryRevisionMax)
+ .optional()
+ .describe('Revision from the first chunk. Required when offset is greater than zero.'),
+ scope: zod
+ .enum(['user', 'shared'])
+ .describe('Scope of the value to read.\n\n\* `user` - user\n\* `shared` - shared'),
+})
+
/**
* Validate a candidate source project without publishing it. Side-effect free.
*/
diff --git a/services/mcp/src/generated/context_layer/api.ts b/services/mcp/src/generated/context_layer/api.ts
index 137825fac875..bb07968e15b6 100644
--- a/services/mcp/src/generated/context_layer/api.ts
+++ b/services/mcp/src/generated/context_layer/api.ts
@@ -40,8 +40,32 @@ export const ContextLayerAgentPagesRetrieveParams = () => zod.object({
),
})
+export const contextLayerAgentPagesRetrieveQueryHeadShaMax = 64
+
+export const contextLayerAgentPagesRetrieveQueryLimitMax = 12000
+
+export const contextLayerAgentPagesRetrieveQueryOffsetDefault = 0
+export const contextLayerAgentPagesRetrieveQueryOffsetMin = 0
+
export const ContextLayerAgentPagesRetrieveQueryParams = () => zod.object({
- path: zod.string().describe('Repo-relative Markdown path of the page to read.'),
+ head_sha: zod
+ .string()
+ .min(1)
+ .max(contextLayerAgentPagesRetrieveQueryHeadShaMax)
+ .optional()
+ .describe('Head from the first chunk. Required for continuation. A changed head returns 409.'),
+ limit: zod
+ .number()
+ .min(1)
+ .max(contextLayerAgentPagesRetrieveQueryLimitMax)
+ .optional()
+ .describe('Maximum characters to read. Omit for the full page.'),
+ offset: zod
+ .number()
+ .min(contextLayerAgentPagesRetrieveQueryOffsetMin)
+ .default(contextLayerAgentPagesRetrieveQueryOffsetDefault)
+ .describe('Character offset from next_offset.'),
+ path: zod.string().min(1).describe('Repo-relative Markdown path of the page to read.'),
})
/**
diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.ts
index d9469a335398..8c2d9401181b 100644
--- a/services/mcp/src/generated/tasks/api.ts
+++ b/services/mcp/src/generated/tasks/api.ts
@@ -732,6 +732,12 @@ export const LoopsRunsRetrieveQueryParams = () => zod.object({
.max(loopsRunsRetrieveQueryLimitMax)
.default(loopsRunsRetrieveQueryLimitDefault)
.describe('Max results per page (default 50, max 100).'),
+ status: zod
+ .enum(['not_started', 'queued', 'in_progress', 'completed', 'failed', 'cancelled'])
+ .optional()
+ .describe(
+ 'Only return runs with this status. Use failed to read errors even when canvas state is unavailable.\n\n\* `not_started` - Not Started\n\* `queued` - Queued\n\* `in_progress` - In Progress\n\* `completed` - Completed\n\* `failed` - Failed\n\* `cancelled` - Cancelled'
+ ),
})
/**
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 315394d523bd..f93fa9e5d72e 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -4,6 +4,25 @@ import { z } from 'zod'
// script, and both modules are pure constants/functions — no `.md` imports to choke on.
import { castStringToInt, normalizeParamAliases } from '../tools/cast-helpers'
+export const CanvasStateReadLimitSchema = z.number().int().min(1).max(100).default(20)
+export const CanvasStateKeysOnlySchema = z.boolean().default(true)
+export const WikiPageReadLimitSchema = z.number().int().min(1).max(12000).default(12000)
+
+// Mirrors the Django serializer's `validate` rule so a continuation without the revision
+// fails here instead of at the API with a 400.
+export function validateCanvasStateValueContinuation(
+ data: { offset?: number | undefined; revision?: string | undefined },
+ ctx: z.RefinementCtx
+): void {
+ if ((data.offset ?? 0) > 0 && !data.revision) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['revision'],
+ message: 'Read the first chunk and pass its revision to continue.',
+ })
+ }
+}
+
export const ChannelInstructionsBaseVersionSchema = z
.number()
.int()
diff --git a/services/mcp/src/tools/generated/canvas.ts b/services/mcp/src/tools/generated/canvas.ts
index c5b9dea62ca0..1e0fabb282c3 100644
--- a/services/mcp/src/tools/generated/canvas.ts
+++ b/services/mcp/src/tools/generated/canvas.ts
@@ -3,6 +3,11 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/canvas/api'
+import {
+ CanvasStateKeysOnlySchema,
+ CanvasStateReadLimitSchema,
+ validateCanvasStateValueContinuation,
+} from '@/schema/tool-inputs'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
const CanvasBuildsRetrieveSchema = () => {
@@ -505,7 +510,9 @@ const canvasSourceRetrieve = (): ToolBase<
const CanvasStateRetrieveSchema = () => {
const CanvasesStateRetrieveParams = orvalSchemas.CanvasesStateRetrieveParams()
const CanvasesStateRetrieveQueryParams = orvalSchemas.CanvasesStateRetrieveQueryParams()
- return CanvasesStateRetrieveParams.omit({ project_id: true }).extend(CanvasesStateRetrieveQueryParams.shape)
+ return CanvasesStateRetrieveParams.omit({ project_id: true })
+ .extend(CanvasesStateRetrieveQueryParams.shape)
+ .extend({ limit: CanvasStateReadLimitSchema, keys_only: CanvasStateKeysOnlySchema })
}
const canvasStateRetrieve = (): ToolBase<
@@ -520,6 +527,11 @@ const canvasStateRetrieve = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/canvases/${encodeURIComponent(String(params.id))}/state/`,
query: {
+ key: params.key,
+ key_prefix: params.key_prefix,
+ keys_only: params.keys_only,
+ limit: params.limit,
+ offset: params.offset,
scope: params.scope,
},
})
@@ -557,6 +569,37 @@ const canvasStateSet = (): ToolBase<ReturnType<typeof CanvasStateSetSchema>, Sch
},
})
+const CanvasStateValueRetrieveSchema = () => {
+ const CanvasesStateValueRetrieveParams = orvalSchemas.CanvasesStateValueRetrieveParams()
+ const CanvasesStateValueRetrieveQueryParams = orvalSchemas.CanvasesStateValueRetrieveQueryParams()
+ return CanvasesStateValueRetrieveParams.omit({ project_id: true })
+ .extend(CanvasesStateValueRetrieveQueryParams.shape)
+ .superRefine(validateCanvasStateValueContinuation)
+}
+
+const canvasStateValueRetrieve = (): ToolBase<
+ ReturnType<typeof CanvasStateValueRetrieveSchema>,
+ Schemas.CanvasStateValueResponse
+> => ({
+ name: 'canvas-state-value-retrieve',
+ schema: CanvasStateValueRetrieveSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof CanvasStateValueRetrieveSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.CanvasStateValueResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/canvases/${encodeURIComponent(String(params.id))}/state/value/`,
+ query: {
+ key: params.key,
+ limit: params.limit,
+ offset: params.offset,
+ revision: params.revision,
+ scope: params.scope,
+ },
+ })
+ return result
+ },
+})
+
const CanvasValidateCreateSchema = () => {
const CanvasesValidateCreateBody = orvalSchemas.CanvasesValidateCreateBody()
const CanvasesValidateCreateParams = orvalSchemas.CanvasesValidateCreateParams()
@@ -604,5 +647,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'canvas-source-retrieve': canvasSourceRetrieve,
'canvas-state-retrieve': canvasStateRetrieve,
'canvas-state-set': canvasStateSet,
+ 'canvas-state-value-retrieve': canvasStateValueRetrieve,
'canvas-validate-create': canvasValidateCreate,
}
diff --git a/services/mcp/src/tools/generated/context_layer.ts b/services/mcp/src/tools/generated/context_layer.ts
index ca35782f8c11..c4cefc20b252 100644
--- a/services/mcp/src/tools/generated/context_layer.ts
+++ b/services/mcp/src/tools/generated/context_layer.ts
@@ -3,6 +3,7 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/context_layer/api'
+import { WikiPageReadLimitSchema } from '@/schema/tool-inputs'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
const ContextWikiChannelResolveSchema = () => {
@@ -28,7 +29,7 @@ const contextWikiChannelResolve = (): ToolBase<
const ContextWikiPageRetrieveSchema = () => {
const ContextLayerAgentPagesRetrieveQueryParams = orvalSchemas.ContextLayerAgentPagesRetrieveQueryParams()
- return ContextLayerAgentPagesRetrieveQueryParams
+ return ContextLayerAgentPagesRetrieveQueryParams.extend({ limit: WikiPageReadLimitSchema })
}
const contextWikiPageRetrieve = (): ToolBase<ReturnType<typeof ContextWikiPageRetrieveSchema>, Schemas.WikiPage> => ({
@@ -40,6 +41,9 @@ const contextWikiPageRetrieve = (): ToolBase<ReturnType<typeof ContextWikiPageRe
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/context_layer/agent/pages/`,
query: {
+ head_sha: params.head_sha,
+ limit: params.limit,
+ offset: params.offset,
path: params.path,
},
})
@@ -102,7 +106,7 @@ const loopContextWikiChannelResolve = (): ToolBase<
const LoopContextWikiPageRetrieveSchema = () => {
const ContextLayerAgentPagesRetrieveQueryParams = orvalSchemas.ContextLayerAgentPagesRetrieveQueryParams()
- return ContextLayerAgentPagesRetrieveQueryParams
+ return ContextLayerAgentPagesRetrieveQueryParams.extend({ limit: WikiPageReadLimitSchema })
}
const loopContextWikiPageRetrieve = (): ToolBase<
@@ -117,6 +121,9 @@ const loopContextWikiPageRetrieve = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/context_layer/agent/pages/`,
query: {
+ head_sha: params.head_sha,
+ limit: params.limit,
+ offset: params.offset,
path: params.path,
},
})
@@ -211,7 +218,7 @@ const taskContextWikiPagePropose = (): ToolBase<
const TaskContextWikiPageRetrieveSchema = () => {
const ContextLayerAgentPagesRetrieveQueryParams = orvalSchemas.ContextLayerAgentPagesRetrieveQueryParams()
- return ContextLayerAgentPagesRetrieveQueryParams
+ return ContextLayerAgentPagesRetrieveQueryParams.extend({ limit: WikiPageReadLimitSchema })
}
const taskContextWikiPageRetrieve = (): ToolBase<
@@ -226,6 +233,9 @@ const taskContextWikiPageRetrieve = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/context_layer/agent/pages/`,
query: {
+ head_sha: params.head_sha,
+ limit: params.limit,
+ offset: params.offset,
path: params.path,
},
})
diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.ts
index df3ebb59e003..9a19bd6c9479 100644
--- a/services/mcp/src/tools/generated/tasks.ts
+++ b/services/mcp/src/tools/generated/tasks.ts
@@ -517,6 +517,7 @@ const loopsRunsRetrieve = (): ToolBase<
query: {
cursor: params.cursor,
limit: params.limit,
+ status: params.status,
},
})
return await withPostHogUrl(
@@ -751,6 +752,9 @@ const tasksList = (): ToolBase<
'created_by.last_name',
'latest_run.id',
'latest_run.status',
+ 'latest_run.error_message',
+ 'latest_run.created_at',
+ 'latest_run.completed_at',
'created_at',
'updated_at',
])
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-state-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-state-retrieve.json
index 032837db1a0f..3998f8e33776 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-state-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-state-retrieve.json
@@ -5,9 +5,36 @@
"description": "A UUID string identifying this canvas.",
"type": "string"
},
+ "key": {
+ "description": "Only read this exact key.",
+ "maxLength": 200,
+ "minLength": 1,
+ "type": "string"
+ },
+ "key_prefix": {
+ "description": "Only read entries whose key starts with this prefix.",
+ "maxLength": 200,
+ "type": "string"
+ },
+ "keys_only": {
+ "default": true,
+ "type": "boolean"
+ },
+ "limit": {
+ "default": 20,
+ "maximum": 100,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "offset": {
+ "default": 0,
+ "description": "Entry offset from next_offset. Keep filters unchanged between pages.",
+ "minimum": 0,
+ "type": "number"
+ },
"scope": {
- "description": "Only return entries in this scope.",
- "enum": ["shared", "user"],
+ "description": "Only read this scope.\n\n* `user` - user\n* `shared` - shared",
+ "enum": ["user", "shared"],
"type": "string"
}
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-state-value-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-state-value-retrieve.json
new file mode 100644
index 000000000000..82bd64f0d86e
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-state-value-retrieve.json
@@ -0,0 +1,41 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this canvas.",
+ "type": "string"
+ },
+ "key": {
+ "description": "Exact key to read.",
+ "maxLength": 200,
+ "minLength": 1,
+ "type": "string"
+ },
+ "limit": {
+ "default": 12000,
+ "description": "Maximum JSON characters in this response.",
+ "maximum": 12000,
+ "minimum": 1,
+ "type": "number"
+ },
+ "offset": {
+ "default": 0,
+ "description": "Character offset from next_offset.",
+ "minimum": 0,
+ "type": "number"
+ },
+ "revision": {
+ "description": "Revision from the first chunk. Required when offset is greater than zero.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ },
+ "scope": {
+ "description": "Scope of the value to read.\n\n* `user` - user\n* `shared` - shared",
+ "enum": ["user", "shared"],
+ "type": "string"
+ }
+ },
+ "required": ["id", "key", "scope"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/loops-runs-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/loops-runs-retrieve.json
index a3716f7276d5..3defa07014a6 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/loops-runs-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/loops-runs-retrieve.json
@@ -15,6 +15,11 @@
"maximum": 100,
"minimum": 1,
"type": "number"
+ },
+ "status": {
+ "description": "Only return runs with this status. Use failed to read errors even when canvas state is unavailable.\n\n* `not_started` - Not Started\n* `queued` - Queued\n* `in_progress` - In Progress\n* `completed` - Completed\n* `failed` - Failed\n* `cancelled` - Cancelled",
+ "enum": ["not_started", "queued", "in_progress", "completed", "failed", "cancelled"],
+ "type": "string"
}
},
"required": ["id"],
diff --git a/services/mcp/tests/unit/canvas-state-value-tool.test.ts b/services/mcp/tests/unit/canvas-state-value-tool.test.ts
new file mode 100644
index 000000000000..360429f3589a
--- /dev/null
+++ b/services/mcp/tests/unit/canvas-state-value-tool.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest'
+
+import { GENERATED_TOOL_MAP } from '@/tools/generated'
+
+describe('canvas-state-value-retrieve tool', () => {
+ const firstChunk = { id: 'canvas-1', scope: 'shared', key: 'notes' }
+
+ it('rejects a continuation that omits the revision', () => {
+ const result = GENERATED_TOOL_MAP['canvas-state-value-retrieve']!().schema.safeParse({
+ ...firstChunk,
+ offset: 12000,
+ })
+
+ expect(result.success).toBe(false)
+ expect(result.error?.issues.map((issue) => issue.path)).toEqual([['revision']])
+ })
+
+ it.each([
+ { label: 'the first chunk', input: firstChunk },
+ { label: 'a continuation carrying the revision', input: { ...firstChunk, offset: 12000, revision: 'rev-1' } },
+ ])('accepts $label', ({ input }) => {
+ expect(GENERATED_TOOL_MAP['canvas-state-value-retrieve']!().schema.safeParse(input).success).toBe(true)
+ })
+})
diff --git a/services/mcp/tests/unit/context-wiki-generated.test.ts b/services/mcp/tests/unit/context-wiki-generated.test.ts
index 6b510a75a145..f5dce896c6b3 100644
--- a/services/mcp/tests/unit/context-wiki-generated.test.ts
+++ b/services/mcp/tests/unit/context-wiki-generated.test.ts
@@ -4,6 +4,7 @@ import { ApiClient } from '@/api/client'
import { MemoryCache } from '@/lib/cache/MemoryCache'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
+import { GENERATED_TOOLS as CANVAS_TOOLS } from '@/tools/generated/canvas'
import { GENERATED_TOOLS } from '@/tools/generated/context_layer'
import type { Context, State } from '@/tools/types'
@@ -33,7 +34,47 @@ function createMockContext(): Context {
}
}
-describe('context wiki generated tools', () => {
+describe('generated context read tools', () => {
+ it.each(['context-wiki-page-retrieve', 'loop-context-wiki-page-retrieve', 'task-context-wiki-page-retrieve'])(
+ '%s forwards bounded reads and the revision',
+ async (name) => {
+ const context = createMockContext()
+ const request = vi.spyOn(context.api, 'request').mockResolvedValue({})
+ const tool = GENERATED_TOOLS[name]!()
+ const params = tool.schema.parse({ path: 'areas/analytics.md', offset: 12, head_sha: 'a'.repeat(40) })
+
+ await tool.handler(context, params)
+
+ expect(request).toHaveBeenCalledWith({
+ method: 'GET',
+ path: '/api/projects/42/context_layer/agent/pages/',
+ query: { path: 'areas/analytics.md', offset: 12, head_sha: 'a'.repeat(40), limit: 12000 },
+ })
+ }
+ )
+
+ it('defaults canvas reads to a bounded key inventory', async () => {
+ const context = createMockContext()
+ const request = vi
+ .spyOn(context.api, 'request')
+ .mockResolvedValue({ entries: [], complete: true, next_offset: null })
+ const tool = CANVAS_TOOLS['canvas-state-retrieve']!()
+ const params = tool.schema.parse({ id: '00000000-0000-4000-8000-000000000001' })
+
+ await tool.handler(context, params)
+
+ expect(request).toHaveBeenCalledWith(
+ expect.objectContaining({
+ method: 'GET',
+ query: expect.objectContaining({ keys_only: true, limit: 20 }),
+ })
+ )
+ expect(tool.schema.parse({ ...params, key: 'policy', keys_only: false })).toMatchObject({
+ key: 'policy',
+ keys_only: false,
+ })
+ })
+
it('uses the project-nested route for ordinary task tokens', async () => {
const context = createMockContext()
const request = vi.spyOn(context.api, 'request').mockResolvedValue({
diff --git a/services/mcp/tests/unit/tasks-generated.test.ts b/services/mcp/tests/unit/tasks-generated.test.ts
index d7edecb768d1..e488e74b86be 100644
--- a/services/mcp/tests/unit/tasks-generated.test.ts
+++ b/services/mcp/tests/unit/tasks-generated.test.ts
@@ -1,8 +1,40 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import { GENERATED_TOOL_MAP } from '@/tools/generated'
+import type { Context } from '@/tools/types'
describe('Generated task tools', () => {
+ it('preserves failure details when listing tasks in a space', async () => {
+ const latestRun = {
+ id: 'run-id',
+ status: 'failed',
+ error_message: 'Read failed',
+ created_at: '2026-01-01T00:00:00Z',
+ completed_at: '2026-01-01T00:01:00Z',
+ }
+ const request = vi.fn().mockResolvedValue({ results: [{ id: 'task-id', latest_run: latestRun }], next: null })
+ const context = {
+ api: { request, getProjectBaseUrl: () => 'https://example.com/project/42' },
+ stateManager: { getProjectId: async () => '42' },
+ } as unknown as Context
+ const tool = GENERATED_TOOL_MAP['tasks-list']!()
+ const params = tool.schema.parse({
+ channel: '00000000-0000-4000-8000-000000000001',
+ status: 'failed',
+ internal: 'all',
+ archived: 'all',
+ })
+
+ const result = await tool.handler(context, params)
+
+ expect(result).toMatchObject({ results: [{ id: 'task-id', latest_run: latestRun }] })
+ expect(request).toHaveBeenCalledWith(
+ expect.objectContaining({
+ query: expect.objectContaining({ status: 'failed', internal: 'all', archived: 'all' }),
+ })
+ )
+ })
+
it('does not expose run inputs on tasks-create', () => {
const schema = GENERATED_TOOL_MAP['tasks-create']!().schema