: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(agents): MCP-driven agent authoring from coding agents (#61937)
Danilo Campose4d6ff87c0e5
diff --git a/products/agent_platform/backend/presentation/serializers.py b/products/agent_platform/backend/presentation/serializers.pyindex e7482774e918..b7aae38376de 100644--- a/products/agent_platform/backend/presentation/serializers.py+++ b/products/agent_platform/backend/presentation/serializers.py@@ -300,9 +300,21 @@ class AgentRevisionSerializer(serializers.ModelSerializer):]extra_kwargs = {# The runner / janitor address bundles by revision_id; bundle_uri is- # the storage-prefix metadata. We default it server-side so MCP- # callers (and humans) creating a draft don't need to know about it.- "bundle_uri": {"required": False, "default": ""},+ # the storage-prefix metadata. We default it server-side (the view's+ # perform_create fills `fs://<slug>/` when blank) so MCP callers and+ # humans creating a draft don't need to know about it. `allow_blank`+ # is required because the generated MCP tool ships the `default: ""`+ # value explicitly — without it, callers hit "may not be blank".+ "bundle_uri": {+ "required": False,+ "default": "",+ "allow_blank": True,+ "help_text": (+ "Storage-prefix metadata for the bundle, e.g. `fs://my-agent/`. Optional — leave blank "+ "and the server fills `fs://<application-slug>/`. Bundles are addressed by revision id "+ "regardless, so this is only a prefix hint."+ ),+ },}@@ -438,3 +450,27 @@ class DecideApprovalRequestSerializer(serializers.Serializer):allow_blank=True,help_text="Free-form approver note. Surfaces in the session's synthetic tool_result so the model can communicate the reason back to the user.",)+++class PreviewProxyInvokeRequestSerializer(serializers.Serializer):+ """Body forwarded verbatim to the agent ingress for a *preview* invoke of a+ non-live revision. The meaningful shape depends on the `rest` path segment:++ - `run` — `{ message }`: the user message that starts a new session.+ - `send` — `{ session_id, message }`: append a message to a running session.+ - `cancel` / `listen` — no body.++ Documents `message` / `session_id` so the generated MCP tool exposes them;+ any extra keys are still forwarded as-is to ingress.+ """++ message = serializers.CharField(+ required=False,+ allow_blank=True,+ trim_whitespace=False,+ help_text="User message to deliver to the agent. Required for `run` (starts the session) and `send` (appends to it); ignored for `cancel` / `listen`.",+ )+ session_id = serializers.CharField(+ required=False,+ help_text="Target session id for `send` — the running session to append the message to. Omit for `run` (a fresh session is created).",+ )diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.pyindex da4f15e14b90..edff9570579b 100644--- a/products/agent_platform/backend/presentation/views.py+++ b/products/agent_platform/backend/presentation/views.py@@ -80,6 +80,7 @@ from .serializers import (CloneFromRequestSerializer,DecideApprovalRequestSerializer,NewDraftRevisionRequestSerializer,+ PreviewProxyInvokeRequestSerializer,PromoteRevisionRequestSerializer,SetEnvKeyRequestSerializer,SetEnvRequestSerializer,@@ -512,6 +513,12 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# don't want the scope to drift between methods."env_keys_key","approvals_decide",+ # POST `preview_proxy` forwards `run`/`send`/`cancel` — each starts,+ # feeds, or kills a draft session, driving the agent's configured+ # tools and incurring inference cost. That's a write-class capability,+ # so it lives here even though it targets a non-live revision. The GET+ # `listen` counterpart (read-only SSE tail) stays in read actions.+ "preview_proxy",]scope_object_read_actions = ["list",@@ -521,10 +528,9 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"session_logs","stats","env_keys_list",- # POST → `preview_proxy`, GET (SSE `listen`) → `preview_proxy_get`.- # DRF uses the bound function name as `view.action`, so the GET- # variant is its own entry in the scope-check map.- "preview_proxy",+ # GET (SSE `listen`) → `preview_proxy_get`. DRF uses the bound function+ # name as `view.action`, so the GET variant is its own scope-map entry;+ # the mutating POST sibling (`preview_proxy`) is a write action above."preview_proxy_get","preview_token","approvals_list",@@ -741,7 +747,14 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):@extend_schema(operation_id="agent_applications_preview_proxy",parameters=_PREVIEW_PROXY_PARAMETERS,- request=None,+ # Document the forwarded body (`run`/`send` carry `message`) so the+ # generated MCP tool exposes it — without this the tool had no way to+ # pass a chat message. SCHEMA-ONLY: the action never validates against+ # this serializer; the raw body is forwarded to ingress verbatim (shape+ # varies by `rest`, extra keys pass through). It exists purely to shape+ # the generated tool / OpenAPI. Response is the ingress SSE stream.+ request=PreviewProxyInvokeRequestSerializer,+ responses={(200, "text/event-stream"): OpenApiTypes.STR},)@action(detail=True,@@ -761,7 +774,8 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):this proxy attaches it after authenticating the Django caller.URL: `/api/projects/<team>/agent_applications/<app>/preview-proxy/<rest>`- Auth: standard PAT / session — `agents:read` scope.+ Auth: standard PAT / session — `agents:write` scope (POST run/send/cancel+ is a mutating invoke; the read-only `listen` GET is `agents:read`)."""application = self.get_object()if application is None:@@ -1621,11 +1635,15 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):application = self.get_application()# Fresh revisions start in `draft`. Parent revision is optional — if# set, this revision can later be diff'd against it for review.+ # bundle_uri is optional metadata; fill the `fs://<slug>/` convention+ # when the caller leaves it blank so a no-source create "just works".+ bundle_uri = serializer.validated_data.get("bundle_uri") or f"fs://{application.slug}/"serializer.save(application=application,team_id=application.team_id,state="draft",created_by_id=self.request.user.id,+ bundle_uri=bundle_uri,)def update(self, request: Request, *args, **kwargs) -> Response:diff --git a/products/agent_platform/backend/tests/test_preview_proxy.py b/products/agent_platform/backend/tests/test_preview_proxy.pyindex 65970c64e3e3..15c6e92b66d2 100644--- a/products/agent_platform/backend/tests/test_preview_proxy.py+++ b/products/agent_platform/backend/tests/test_preview_proxy.py@@ -7,8 +7,10 @@ playground flow:* 403 `This action does not support personal API key access` —happened because the GET variant maps to a separate `view.action`name (`preview_proxy_get`) and we only had the POST one- (`preview_proxy`) listed in `scope_object_read_actions`. Both names- must be declared or OAuth/PAT callers get bounced.+ (`preview_proxy`) declared. Both names must appear in a scope list+ or OAuth/PAT callers get bounced. The two now sit in *different*+ lists: POST `preview_proxy` (run/send/cancel) is a mutating invoke+ → `:write`; the GET `listen` tail is read-only → `:read`.* 406 `Could not satisfy the request Accept header` — happenedbecause browser `EventSource` sends `Accept: text/event-stream` and@@ -23,6 +25,7 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterized+from ..presentation.serializers import PreviewProxyInvokeRequestSerializerfrom ..presentation.views import AgentApplicationViewSet, EventStreamRenderer@@ -37,16 +40,17 @@ class TestPreviewProxyScope(APIBaseTest):@parameterized.expand([- # POST verbs (run / send / cancel) route through `preview_proxy`.- ("preview_proxy",),+ # POST verbs (run / send / cancel) route through `preview_proxy` —+ # mutating invokes, so they require `:write`.+ ("preview_proxy", "scope_object_write_actions"),# GET (SSE listen) routes through `preview_proxy_get` —# `view.action` resolves to the bound function name on the- # `@preview_proxy.mapping.get` handler.- ("preview_proxy_get",),+ # `@preview_proxy.mapping.get` handler. Read-only tail → `:read`.+ ("preview_proxy_get", "scope_object_read_actions"),])- def test_action_is_a_declared_read_action(self, action_name: str) -> None:- self.assertIn(action_name, AgentApplicationViewSet.scope_object_read_actions)+ def test_action_is_declared_in_expected_scope_list(self, action_name: str, scope_list: str) -> None:+ self.assertIn(action_name, getattr(AgentApplicationViewSet, scope_list))class TestPreviewProxyRendering(APIBaseTest):@@ -73,3 +77,25 @@ class TestPreviewProxyRendering(APIBaseTest):self.assertIsNotNone(renderer_classes, "preview_proxy action should declare renderer_classes")assert renderer_classes is not None # type narrowing for mypyself.assertIn(EventStreamRenderer, renderer_classes)+++class TestPreviewProxyInvokeBody(APIBaseTest):+ """#4 — the proxy forwards the POST body to ingress (`run`/`send` carry+ `message`), but the action shipped `request=None`, so drf-spectacular+ published an empty body and the generated MCP tool had no way to pass a+ message. The action now declares `PreviewProxyInvokeRequestSerializer`;+ this pins the body shape it documents. (The OpenAPI wiring itself is+ verified by `hogli build:openapi`.)"""++ def test_invoke_serializer_documents_message_and_session_id(self) -> None:+ fields = PreviewProxyInvokeRequestSerializer().fields+ self.assertLessEqual({"message", "session_id"}, set(fields))+ # Optional: `run` needs only `message`; `cancel`/`listen` need neither.+ self.assertFalse(fields["message"].required)+ self.assertFalse(fields["session_id"].required)++ def test_invoke_serializer_validates_run_and_send_bodies(self) -> None:+ self.assertTrue(PreviewProxyInvokeRequestSerializer(data={"message": "tell me a joke"}).is_valid())+ self.assertTrue(+ PreviewProxyInvokeRequestSerializer(data={"session_id": "s-1", "message": "another"}).is_valid()+ )diff --git a/products/agent_platform/backend/tests/test_revision_create.py b/products/agent_platform/backend/tests/test_revision_create.pynew file mode 100644index 000000000000..c1413e77d6ab--- /dev/null+++ b/products/agent_platform/backend/tests/test_revision_create.py@@ -0,0 +1,55 @@+"""+#2 — first-revision create + bundle_uri.++A no-source `revisions-create` is the documented way to mint the first+revision. The serializer advertised `bundle_uri` with `default: ""` but the+field rejected a blank value, so the generated MCP tool (which ships the+default explicitly) hit "may not be blank". `bundle_uri` is now `allow_blank`+and the view fills the `fs://<slug>/` convention when it's left empty.+"""++from __future__ import annotations++from posthog.test.base import APIBaseTest++from rest_framework import status++from ..models import AgentApplication++_SPEC = {"model": "anthropic/claude-haiku-4-5"}+++class TestRevisionCreateBundleUri(APIBaseTest):+ databases = {+ "default",+ "persons_db_writer",+ "persons_db_reader",+ "agent_platform_db_writer",+ "agent_platform_db_reader",+ }++ def setUp(self) -> None:+ super().setUp()+ self.application = AgentApplication.all_teams.create(+ team_id=self.team.id,+ slug="create-bundle-agent",+ name="Create bundle agent",+ description="",+ )+ self.url = f"/api/projects/{self.team.id}/agent_applications/{self.application.id}/revisions/"++ def test_omitted_bundle_uri_autopopulates_fs_slug(self) -> None:+ res = self.client.post(self.url, {"spec": _SPEC}, format="json")+ self.assertEqual(res.status_code, status.HTTP_201_CREATED, res.content)+ self.assertEqual(res.json()["bundle_uri"], "fs://create-bundle-agent/")++ def test_blank_bundle_uri_accepted_and_autopopulated(self) -> None:+ # The exact payload the generated MCP tool sends (default: "").+ res = self.client.post(self.url, {"spec": _SPEC, "bundle_uri": ""}, format="json")+ self.assertEqual(res.status_code, status.HTTP_201_CREATED, res.content)+ self.assertEqual(res.json()["bundle_uri"], "fs://create-bundle-agent/")++ def test_explicit_bundle_uri_preserved(self) -> None:+ res = self.client.post(self.url, {"spec": _SPEC, "bundle_uri": "fs://custom/"}, format="json")+ self.assertEqual(res.status_code, status.HTTP_201_CREATED, res.content)+ self.assertEqual(res.json()["bundle_uri"], "fs://custom/")diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.tsindex 6093c702d6e6..86787cbd9cd5 100644--- a/products/agent_platform/frontend/generated/api.schemas.ts+++ b/products/agent_platform/frontend/generated/api.schemas.ts@@ -556,6 +556,7 @@ export interface AgentRevisionApi {/** @nullable */parent_revision?: string | nullreadonly state: AgentRevisionStateEnumApi+ /** Storage-prefix metadata for the bundle, e.g. `fs://my-agent/`. Optional — leave blank and the server fills `fs://<application-slug>/`. Bundles are addressed by revision id regardless, so this is only a prefix hint. */bundle_uri?: string/** @nullable */readonly bundle_sha256: string | null@@ -937,6 +938,7 @@ export interface PatchedAgentRevisionApi {/** @nullable */parent_revision?: string | nullreadonly state?: AgentRevisionStateEnumApi+ /** Storage-prefix metadata for the bundle, e.g. `fs://my-agent/`. Optional — leave blank and the server fills `fs://<application-slug>/`. Bundles are addressed by revision id regardless, so this is only a prefix hint. */bundle_uri?: string/** @nullable */readonly bundle_sha256?: string | null@@ -1314,6 +1316,24 @@ export interface SetEnvKeyRequestApi {value: string}+/**+ * Body forwarded verbatim to the agent ingress for a *preview* invoke of a+ * non-live revision. The meaningful shape depends on the `rest` path segment:+ *+ * - `run` — `{ message }`: the user message that starts a new session.+ * - `send` — `{ session_id, message }`: append a message to a running session.+ * - `cancel` / `listen` — no body.+ *+ * Documents `message` / `session_id` so the generated MCP tool exposes them;+ * any extra keys are still forwarded as-is to ingress.+ */+export interface PreviewProxyInvokeRequestApi {+ /** User message to deliver to the agent. Required for `run` (starts the session) and `send` (appends to it); ignored for `cancel` / `listen`. */+ message?: string+ /** Target session id for `send` — the running session to append the message to. Omit for `run` (a fresh session is created). */+ session_id?: string+}+export interface AgentApplicationPreviewTokenResponseApi {/** HS256 JWT bound to (app, rev) with a short TTL. Attach as the `x-agent-preview-token` header (POST/DELETE) or `preview_token` query param (GET, including EventSource) when calling ingress directly. */token: stringdiff --git a/products/agent_platform/frontend/generated/api.ts b/products/agent_platform/frontend/generated/api.tsindex ecf7a9f51bc1..f4ac6be99067 100644--- a/products/agent_platform/frontend/generated/api.ts+++ b/products/agent_platform/frontend/generated/api.ts@@ -61,6 +61,7 @@ import type {PatchedAgentApplicationApi,PatchedAgentMemoryUpdateRequestApi,PatchedAgentRevisionApi,+ PreviewProxyInvokeRequestApi,SetEnvKeyRequestApi,SetEnvRequestApi,WriteAgentMdRequestApi,@@ -1686,18 +1687,22 @@ export const getAgentApplicationsPreviewProxyUrl = (* this proxy attaches it after authenticating the Django caller.** URL: `/api/projects/<team>/agent_applications/<app>/preview-proxy/<rest>`- * Auth: standard PAT / session — `agents:read` scope.+ * Auth: standard PAT / session — `agents:write` scope (POST run/send/cancel+ * is a mutating invoke; the read-only `listen` GET is `agents:read`).*/export const agentApplicationsPreviewProxy = async (projectId: string,id: string,rest: string,params: AgentApplicationsPreviewProxyParams,+ previewProxyInvokeRequestApi?: PreviewProxyInvokeRequestApi,options?: RequestInit-): Promise<AgentApplicationApi> => {- return apiMutator<AgentApplicationApi>(getAgentApplicationsPreviewProxyUrl(projectId, id, rest, params), {+): Promise<string> => {+ return apiMutator<string>(getAgentApplicationsPreviewProxyUrl(projectId, id, rest, params), {...options,method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(previewProxyInvokeRequestApi),})}diff --git a/products/agent_platform/frontend/generated/api.zod.ts b/products/agent_platform/frontend/generated/api.zod.tsindex 8a2a0a71f072..101630dd3428 100644--- a/products/agent_platform/frontend/generated/api.zod.ts+++ b/products/agent_platform/frontend/generated/api.zod.ts@@ -211,7 +211,12 @@ export const agentApplicationsRevisionsCreateBodySpecResumeMaxCompletedAgeMsMaxexport const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({parent_revision: zod.uuid().nullish(),- bundle_uri: zod.string().default(agentApplicationsRevisionsCreateBodyBundleUriDefault),+ bundle_uri: zod+ .string()+ .default(agentApplicationsRevisionsCreateBodyBundleUriDefault)+ .describe(+ 'Storage-prefix metadata for the bundle, e.g. `fs:\/\/my-agent\/`. Optional — leave blank and the server fills `fs:\/\/<application-slug>\/`. Bundles are addressed by revision id regardless, so this is only a prefix hint.'+ ),spec: zod.object({model: zod.string().min(1),@@ -789,7 +794,12 @@ export const agentApplicationsRevisionsUpdateBodySpecResumeMaxCompletedAgeMsMaxexport const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({parent_revision: zod.uuid().nullish(),- bundle_uri: zod.string().default(agentApplicationsRevisionsUpdateBodyBundleUriDefault),+ bundle_uri: zod+ .string()+ .default(agentApplicationsRevisionsUpdateBodyBundleUriDefault)+ .describe(+ 'Storage-prefix metadata for the bundle, e.g. `fs:\/\/my-agent\/`. Optional — leave blank and the server fills `fs:\/\/<application-slug>\/`. Bundles are addressed by revision id regardless, so this is only a prefix hint.'+ ),spec: zod.object({model: zod.string().min(1),@@ -1390,7 +1400,12 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecResumeMaxCompletedAgexport const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.object({parent_revision: zod.uuid().nullish(),- bundle_uri: zod.string().default(agentApplicationsRevisionsPartialUpdateBodyBundleUriDefault),+ bundle_uri: zod+ .string()+ .default(agentApplicationsRevisionsPartialUpdateBodyBundleUriDefault)+ .describe(+ 'Storage-prefix metadata for the bundle, e.g. `fs:\/\/my-agent\/`. Optional — leave blank and the server fills `fs:\/\/<application-slug>\/`. Bundles are addressed by revision id regardless, so this is only a prefix hint.'+ ),spec: zod.object({model: zod.string().min(1),@@ -2219,6 +2234,36 @@ export const AgentApplicationsEnvKeysSetBody = /* @__PURE__ */ zod'Body shape for AgentApplicationViewSet.env_keys_set — single secret upsert.\n\nThe view merges `{KEY: value}` into the existing encrypted env block\nwithout touching other keys, so callers can set or rotate one secret\nwithout needing to read the whole block back.')+/**+ * Authoring-side proxy for invoking a *draft* (or any non-live) revision.+ *+ * Closes the anonymous-draft-invoke gap: the public ingress URL refuses+ * non-live invokes that don't carry the `x-agent-preview-secret` header;+ * this proxy attaches it after authenticating the Django caller.+ *+ * URL: `/api/projects/<team>/agent_applications/<app>/preview-proxy/<rest>`+ * Auth: standard PAT / session — `agents:write` scope (POST run/send/cancel+ * is a mutating invoke; the read-only `listen` GET is `agents:read`).+ */+export const AgentApplicationsPreviewProxyBody = /* @__PURE__ */ zod+ .object({+ message: zod+ .string()+ .optional()+ .describe(+ 'User message to deliver to the agent. Required for `run` (starts the session) and `send` (appends to it); ignored for `cancel` \/ `listen`.'+ ),+ session_id: zod+ .string()+ .optional()+ .describe(+ 'Target session id for `send` — the running session to append the message to. Omit for `run` (a fresh session is created).'+ ),+ })+ .describe(+ 'Body forwarded verbatim to the agent ingress for a \*preview\* invoke of a\nnon-live revision. The meaningful shape depends on the `rest` path segment:\n\n- `run` — `{ message }`: the user message that starts a new session.\n- `send` — `{ session_id, message }`: append a message to a running session.\n- `cancel` \/ `listen` — no body.\n\nDocuments `message` \/ `session_id` so the generated MCP tool exposes them;\nany extra keys are still forwarded as-is to ingress.'+ )+/*** Replace the agent's encrypted env block.*diff --git a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.tsindex 9d197abdfd42..7c17e871d969 100644--- a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts+++ b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts@@ -203,7 +203,7 @@ describe('buildAgentTools', () => {it('maps provider-safe names back to original ids', async () => {const rev = makeRev([{ kind: 'native', id: '@posthog/query' }])const built = await buildAgentTools(rev, makeDeps(rev))- expect(built.nameToId.get('_posthog_query')).toBe('@posthog/query')+ expect(built.nameToId.get('posthog_query')).toBe('@posthog/query')// Tools are registered under their original id; the safe form is only// applied on the wire by the driver's streamFn.expect(byId(built, '@posthog/query').name).toBe('@posthog/query')diff --git a/products/agent_platform/services/agent-runner/src/loop/provider-safe-names.test.ts b/products/agent_platform/services/agent-runner/src/loop/provider-safe-names.test.tsnew file mode 100644index 000000000000..1643e545cef9--- /dev/null+++ b/products/agent_platform/services/agent-runner/src/loop/provider-safe-names.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it, vi } from 'vitest'++import { buildToolNameMap, providerSafeName } from './provider-safe-names'++describe('provider-safe-names', () => {+ describe('providerSafeName', () => {+ it('drops the leading underscore a leading `@` would introduce', () => {+ // The regression: the model echoes `posthog_meta-end-turn`, so the+ // safe form (and thus the reverse-map key) must match that — not+ // `_posthog_meta-end-turn`.+ expect(providerSafeName('@posthog/meta-end-turn')).toBe('posthog_meta-end-turn')+ expect(providerSafeName('@posthog/query')).toBe('posthog_query')+ })++ it('is idempotent on already-safe names (MCP `<prefix>__<name>`)', () => {+ expect(providerSafeName('linear__create-issue')).toBe('linear__create-issue')+ })++ it('preserves a legitimately leading underscore', () => {+ // `_` is already in the safe charset, so it was not introduced by+ // sanitization — leave it alone.+ expect(providerSafeName('_foo')).toBe('_foo')+ })++ it('never strips down to an empty name', () => {+ // Pathological all-unsafe id: keep the underscored fallback rather+ // than emit an empty (invalid) tool name.+ expect(providerSafeName('@/')).not.toBe('')+ })++ it('caps length at 128', () => {+ expect(providerSafeName('@' + 'a'.repeat(200)).length).toBe(128)+ })+ })++ describe('buildToolNameMap round-trip', () => {+ it('reverse-resolves the name the model actually emits', () => {+ const map = buildToolNameMap([+ '@posthog/meta-end-turn',+ '@posthog/meta-end-session',+ 'linear__create-issue',+ ])+ // Pre-fix this key was `_posthog_meta-end-turn` and the lookup missed.+ expect(map.get('posthog_meta-end-turn')).toBe('@posthog/meta-end-turn')+ expect(map.get('posthog_meta-end-session')).toBe('@posthog/meta-end-session')+ expect(map.get('linear__create-issue')).toBe('linear__create-issue')+ })++ it('warns when two distinct ids collapse to the same safe name', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ // `a.b` and `a_b` both sanitize to `a_b`; the second wins and the+ // first would be undispatchable, so the collision must be surfaced.+ const map = buildToolNameMap(['a.b', 'a_b'])+ expect(map.get('a_b')).toBe('a_b')+ expect(warn).toHaveBeenCalledOnce()+ warn.mockRestore()+ })+ })+})diff --git a/products/agent_platform/services/agent-runner/src/loop/provider-safe-names.ts b/products/agent_platform/services/agent-runner/src/loop/provider-safe-names.tsindex 9957f0a4b723..48eed7913aa8 100644--- a/products/agent_platform/services/agent-runner/src/loop/provider-safe-names.ts+++ b/products/agent_platform/services/agent-runner/src/loop/provider-safe-names.ts@@ -16,6 +16,20 @@ const MAX_LEN = 128/** Convert a tool id to a provider-safe form. Idempotent on already-safe ids. */export function providerSafeName(id: string): string {let out = id.replace(SAFE_RE, '_')+ // A leading *unsafe* char (the `@` in `@posthog/meta-end-turn`) would become+ // a leading underscore — but models routinely drop it when they echo the+ // name back, calling `posthog_meta-end-turn` for a tool we'd otherwise+ // register as `_posthog_meta-end-turn`. The reverse map then misses and the+ // call dispatches as "not found" (it self-corrects next turn, but burns a+ // turn + emits a spurious tool error every session). Strip the leading+ // underscores that sanitization introduced so the safe name matches the+ // model's natural form. A name that was already a legal `_foo` keeps it.+ if (/^[^a-zA-Z0-9_-]/.test(id)) {+ const stripped = out.replace(/^_+/, '')+ if (stripped.length > 0) {+ out = stripped+ }+ }if (out.length > MAX_LEN) {out = out.slice(0, MAX_LEN)}@@ -34,7 +48,20 @@ export function providerSafeName(id: string): string {export function buildToolNameMap(originalIds: string[]): Map<string, string> {const safeToOriginal = new Map<string, string>()for (const id of originalIds) {- safeToOriginal.set(providerSafeName(id), id)+ const safe = providerSafeName(id)+ const existing = safeToOriginal.get(safe)+ if (existing !== undefined && existing !== id) {+ // Two distinct ids collapsed to the same provider-safe name (e.g. a+ // `.`-vs-`_` clash, or two long ids sharing a 128-char prefix after+ // truncation). The second wins and the first becomes undispatchable.+ // Native ids use a controlled vocab, so this is a custom-tool+ // misconfiguration — warn loudly rather than silently strand a tool.+ // eslint-disable-next-line no-console -- build-time misconfig signal, not a hot path+ console.warn(+ `[provider-safe-names] tool-name collision: "${existing}" and "${id}" both map to "${safe}"; "${id}" wins and the other is undispatchable`+ )+ }+ safeToOriginal.set(safe, id)}return safeToOriginal}diff --git a/products/agent_platform/services/agent-tests/src/cases/control-flow.test.ts b/products/agent_platform/services/agent-tests/src/cases/control-flow.test.tsindex f16267ae63f3..ed512ba26349 100644--- a/products/agent_platform/services/agent-tests/src/cases/control-flow.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/control-flow.test.ts@@ -49,6 +49,27 @@ describe('control flow: real e2e', () => {expect(session!.state).toBe('closed')})+ it('a meta tool call echoed by its provider-safe name (posthog_meta-end-turn) dispatches the real tool', async () => {+ // Real models echo tool calls by the provider-safe name, not the+ // `@posthog/...` original. Pre-fix, providerSafeName turned the leading+ // `@` into a leading underscore (`_posthog_meta-end-turn`), so the+ // model's `posthog_meta-end-turn` missed the reverse map and dispatched+ // as "tool not found" — burning a turn every session before the model+ // self-corrected. Script the sanitized name the real model emits.+ c.setScript([fauxCallTool('posthog_meta-end-turn')])+ await c.deployAgent({ slug: 'meta-safe-name' })+ const res = await request(c.ingress).post('/agents/meta-safe-name/run').send({ message: 'done?' })+ await c.drain()+ const session = await c.queue.get(res.body.session_id)+ // end_turn → completed, with no errored / not-found tool result anywhere.+ expect(session!.state).toBe('completed')+ const hasErroredToolResult = (session!.conversation as Array<{ role: string; isError?: boolean }>).some(+ (m) => m.role === 'toolResult' && m.isError === true+ )+ expect(hasErroredToolResult).toBe(false)+ expect(JSON.stringify(session!.conversation)).not.toContain('not found')+ })+it('max_turns ceiling marks the session failed', async () => {// Script 5 tool calls — but the agent's max_turns is 3.c.setScript(diff --git a/services/mcp/definitions/agent_platform.yaml b/services/mcp/definitions/agent_platform.yamlindex 042ca7dc0f0d..19699addbedf 100644--- a/services/mcp/definitions/agent_platform.yaml+++ b/services/mcp/definitions/agent_platform.yaml@@ -32,7 +32,8 @@ tools:description: >Create a new agent. Requires `name` + `slug` (unique within the team). The fresh application has norevisions; create a draft via `agent-applications-revisions-create`, populate its bundle, then freeze +- promote.+ promote. Playbook: read the `authoring-new-agents` playbook via `agent-resolve-resource` for the end-to-end+ authoring flow.agent-applications-destroy:operation: agent_applications_destroyenabled: true@@ -60,7 +61,8 @@ tools:description: >Remove one key from the encrypted env. No-op when the key wasn't set. Use this when a secret is no longerrequired by the spec or after a credential is known to be compromised. Does NOT trigger session restarts —- in-flight sessions keep the value they resolved at start.+ in-flight sessions keep the value they resolved at start. Playbook: read the `secrets-and-integrations`+ playbook via `agent-resolve-resource` for the credential punch-out flow.agent-applications-env-keys-get:operation: agent_applications_env_keys_getenabled: true@@ -74,7 +76,8 @@ tools:description: >Returns `{ key, is_set }` for one name. The value is never returned. Use as a pre-check before asking theuser to set or rotate a key, and again after the user completes the punch-out flow to confirm the write- landed.+ landed. Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the+ credential punch-out flow.agent-applications-env-keys-list:operation: agent_applications_env_keys_listenabled: true@@ -89,6 +92,8 @@ tools:Returns `{ keys: [name, ...] }` — names only, never values. Use to know which declared secrets are alreadypopulated so you don't ask the user to set something that's already set. Pair with`agent-applications-revisions-retrieve` (`spec.secrets[]`) to spot which declared keys are still unset.+ Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the credential+ punch-out flow.agent-applications-env-keys-set:operation: agent_applications_env_keys_setenabled: false@@ -117,7 +122,8 @@ tools:title: List agent applicationsdescription: >List every agent application in the project. Returns id, slug, name, description, live_revision, archived- state. Use the slug to drive subsequent calls — it's stable and human-readable.+ state. Use the slug to drive subsequent calls — it's stable and human-readable. Playbook: read the+ `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.agent-applications-partial-update:operation: agent_applications_partial_updateenabled: true@@ -135,7 +141,7 @@ tools:operation: agent_applications_preview_proxyenabled: truescopes:- - agents:read+ - agents:writeannotations:readOnly: falsedestructive: false@@ -167,7 +173,8 @@ tools:description: >Fetch one application by id or slug (both unique within the team). Returns metadata only — to inspect therunning spec or bundle, look up the live revision via `agent-applications-revisions-list` then call- `agent-applications-revisions-retrieve` and `agent-applications-revisions-manifest-retrieve`.+ `agent-applications-revisions-retrieve` and `agent-applications-revisions-manifest-retrieve`. Playbook: read+ the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.agent-applications-revisions-agent-md-update:operation: agent_applications_revisions_agent_md_updateenabled: true@@ -180,7 +187,8 @@ tools:title: Replace agent.mddescription: >Body `{ content: "…" }`. Overwrites the agent's system prompt. Use for surgical edits to the prompt; leaves- skills, tools, and spec untouched. Draft-only.+ skills, tools, and spec untouched. Draft-only. Playbook: read the `editing-agents-safely` playbook via+ `agent-resolve-resource` for the branch → validate → freeze → promote workflow.agent-applications-revisions-archive-create:operation: agent_applications_revisions_archive_createenabled: true@@ -193,7 +201,9 @@ tools:title: Archive a revisiondescription: >Mark a revision archived. If it was the live revision, clears the parent application's `live_revision` (the- app has no deployable version until another revision is promoted). Idempotent.+ app has no deployable version until another revision is promoted). Idempotent. Playbook: read the+ `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote+ workflow.agent-applications-revisions-bundle-retrieve:operation: agent_applications_revisions_bundle_retrieveenabled: true@@ -208,7 +218,8 @@ tools:Returns `{ agent_md, skills, tools, spec }` — the typed view of the revision. Use this when you want to editthe whole agent locally (pull, mutate in-memory, push back via the bundle PUT). Skills carry `description`and `body` (stored at `skills/<id>/SKILL.md`). Tools carry `description`, `args_schema`, `source`- (TypeScript). `spec` is the author-facing slice (skills/tools are server-derived at freeze).+ (TypeScript). `spec` is the author-facing slice (skills/tools are server-derived at freeze). Playbook: read+ the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.agent-applications-revisions-bundle-update:operation: agent_applications_revisions_bundle_updateenabled: true@@ -224,6 +235,8 @@ tools:the payload is deleted. For incremental edits use the single-resource PUTs(`agent-applications-revisions-skills-update`, etc.). Each tool source is AST-checked + esbuild-compiledsynchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this.+ Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate →+ freeze → promote workflow.agent-applications-revisions-clone-from-create:operation: agent_applications_revisions_clone_from_createenabled: true@@ -237,7 +250,8 @@ tools:description: >Copy every file in `source_revision_id`'s bundle into this (draft) revision. Use after`agent-applications-revisions-create` if you didn't go through `new-draft` for some reason. Both revisions- must belong to the same team.+ must belong to the same team. Playbook: read the `editing-agents-safely` playbook via+ `agent-resolve-resource` for the branch → validate → freeze → promote workflow.agent-applications-revisions-create:operation: agent_applications_revisions_createenabled: true@@ -252,7 +266,9 @@ tools:Create a new revision in state `draft`. Body shape mirrors the AgentRevision serializer — the only fieldsyou typically set are `spec` (initial JSON) and `parent_revision` (optional, lets the diff UI show whatyou're changing). The bundle starts empty; use `agent-applications-revisions-clone-from-create` or- `agent-applications-revisions-new-draft-create` to seed it from an existing revision.+ `agent-applications-revisions-new-draft-create` to seed it from an existing revision. Playbook: read the+ `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote+ workflow.agent-applications-revisions-cron-fire-create:operation: agent_applications_revisions_cron_fire_createenabled: true@@ -270,7 +286,9 @@ tools:`request_id` — pass a stable id per logical click so repeat fires resolve to the same session instead ofstacking duplicates. Returns `{ ok, session_id, fired_at, idempotency_key }`; track the session via`agent-applications-sessions-retrieve` to read the conversation. Authoring-loop completion piece — without- this, "did my prompt do the right thing?" is unanswerable until the cron actually fires.+ this, "did my prompt do the right thing?" is unanswerable until the cron actually fires. Playbook: read the+ `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the+ logs.agent-applications-revisions-destroy:operation: agent_applications_revisions_destroyenabled: false@@ -287,7 +305,8 @@ tools:description: >Walks the bundle, computes a manifest sha256, stamps it on the row, flips state `draft → ready`. After thisthe bundle is immutable. Idempotent — freezing a `ready` revision is a no-op that returns the existing- sha256.+ sha256. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch →+ validate → freeze → promote workflow.agent-applications-revisions-list:operation: agent_applications_revisions_listenabled: true@@ -300,7 +319,8 @@ tools:title: List revisions of an applicationdescription: >List every revision (draft, ready, live, archived) for one application, newest first. Use to find the- current live revision id or pick a known-good revision to clone for an edit.+ current live revision id or pick a known-good revision to clone for an edit. Playbook: read the+ `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.agent-applications-revisions-manifest-retrieve:operation: agent_applications_revisions_manifest_retrieveenabled: true@@ -314,7 +334,8 @@ tools:description: >Returns `{ revision_id, state, bundle_sha256, files: [{ path, size, sha256 }, …] }`. Use to discover what'sin a bundle without pulling all the bytes — sha256 lets you spot which files have changed since you last- looked.+ looked. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and+ summarize an agent.agent-applications-revisions-new-draft-create:operation: agent_applications_revisions_new_draft_createenabled: true@@ -328,7 +349,9 @@ tools:description: >One-shot helper: creates a draft revision under `application_id` and clones every file from`source_revision_id` into the new bundle in a single round-trip. Use this for the common "edit live"- workflow — branch from the current live revision, mutate files, freeze, promote.+ workflow — branch from the current live revision, mutate files, freeze, promote. Playbook: read the+ `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote+ workflow.agent-applications-revisions-partial-update:operation: agent_applications_revisions_partial_updateenabled: true@@ -342,7 +365,9 @@ tools:description: >Replace `spec` on a draft revision. Only `state=draft` revisions accept spec edits — promote bumps therevision to `ready` which freezes the spec. Validation against the AgentSpec zod schema runs on the runner- side; an invalid spec will surface when the next session starts, not here.+ side; an invalid spec will surface when the next session starts, not here. Playbook: read the+ `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote+ workflow.agent-applications-revisions-promote-create:operation: agent_applications_revisions_promote_createenabled: true@@ -356,7 +381,8 @@ tools:description: >Flips a `ready` revision to `live` and sets the parent application's `live_revision`. The previously liverevision is archived automatically. Requires `state=ready` and `bundle_sha256` set (call `freeze` first).- Idempotent: promoting an already-live revision is a no-op.+ Idempotent: promoting an already-live revision is a no-op. Playbook: read the `editing-agents-safely`+ playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.agent-applications-revisions-retrieve:operation: agent_applications_revisions_retrieveenabled: true@@ -370,7 +396,8 @@ tools:description: >Fetch one revision's metadata: state, spec (the structural JSON), bundle_uri, bundle_sha256, parent revisionid, timestamps. For the bundle contents see `agent-applications-revisions-manifest-retrieve` /- `agent-applications-revisions-bundle-retrieve`.+ `agent-applications-revisions-bundle-retrieve`. Playbook: read the `reading-an-agent` playbook via+ `agent-resolve-resource` for how to inspect and summarize an agent.agent-applications-revisions-skills-destroy:operation: agent_applications_revisions_skills_destroyenabled: true@@ -383,7 +410,8 @@ tools:title: Delete one skilldescription: >Removes the skill folder (`skills/<id>/`, holding its `SKILL.md`). Returns 404 if the skill doesn't exist.- Draft-only.+ Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch+ → validate → freeze → promote workflow.agent-applications-revisions-skills-update:operation: agent_applications_revisions_skills_updateenabled: true@@ -396,7 +424,9 @@ tools:title: Upsert one skilldescription: >Body `{ description, body }`. Creates the skill if it doesn't exist, replaces it if it does. The `body` is- stored at `skills/<skill_id>/SKILL.md`. Skill id comes from the URL. Draft-only.+ stored at `skills/<skill_id>/SKILL.md`. Skill id comes from the URL. Draft-only. Playbook: read the+ `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote+ workflow.agent-applications-revisions-slack-manifest:operation: agent_applications_revisions_slack_manifestenabled: true@@ -427,7 +457,8 @@ tools:description: >Body `{ spec: { … } }`. Replaces the author-writable spec slice (model, triggers, mcps, integrations,secrets, limits, auth, entrypoint, reasoning). `skills[]` and `tools[]` are NOT author-writable — they're- derived at freeze from the typed resources. Draft-only.+ derived at freeze from the typed resources. Draft-only. Playbook: read the `editing-agents-safely` playbook+ via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.agent-applications-revisions-system-prompt:operation: agent_applications_revisions_system_promptenabled: true@@ -443,7 +474,8 @@ tools:preamble + agent.md (or `spec.entrypoint`) + skills index. Use to verify what the model actually sees beforepromoting; particularly useful for confirming `spec.framework_prompt.omit` opt-outs took effect or fordebugging author-vs-framework precedence. Response also includes `framework_prompt_version` so you can tell- whether a pin (`spec.framework_prompt.version_pin`) is in effect. Works on any revision state.+ whether a pin (`spec.framework_prompt.version_pin`) is in effect. Works on any revision state. Playbook:+ read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.agent-applications-revisions-tools-destroy:operation: agent_applications_revisions_tools_destroyenabled: true@@ -456,7 +488,8 @@ tools:title: Delete one custom tooldescription: >Removes source.ts, compiled.js, schema.json from the bundle. Returns 404 if the tool doesn't exist.- Draft-only.+ Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch+ → validate → freeze → promote workflow.agent-applications-revisions-tools-update:operation: agent_applications_revisions_tools_updateenabled: true@@ -471,7 +504,9 @@ tools:Body `{ description, args_schema, source }`. `source` is the TypeScript tool source — the janitor runs anAST shape check + esbuild compile synchronously and rejects a bad shape with structured diagnostics in the422 response. Required shape: `export default { actions: { default: async (args, ctx) => { ... } } }`. Do- NOT include `compiled.js` — it's generated. Tool id comes from the URL. Draft-only.+ NOT include `compiled.js` — it's generated. Tool id comes from the URL. Draft-only. Playbook: read the+ `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote+ workflow.agent-applications-revisions-update:operation: agent_applications_revisions_updateenabled: false@@ -489,7 +524,9 @@ tools:Pre-flight checks before deploying. Returns `{ ok, errors: [...] }`. Catches: missing entrypoint file,unknown native tool ids, custom tools missing `compiled.js` / `schema.json`, skill paths that don't exist inthe bundle, declared secrets that aren't set in the application env. Works on any revision state — use this- on a draft before calling `agent-applications-revisions-freeze-create`.+ on a draft before calling `agent-applications-revisions-freeze-create`. Playbook: read the+ `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote+ workflow.agent-applications-session-logs:operation: agent_applications_session_logsenabled: false@@ -510,7 +547,8 @@ tools:over the whole conversation). The transcript body is omitted — use `agent-applications-sessions-retrieve`for that. Filters: `state` (comma-separated for multiple, e.g. `completed,failed`), `revision_id` (UUID),`created_after` / `created_before` (ISO datetimes). Paging via `limit` (default 100, capped at 500) +- `offset`. Filters AND together.+ `offset`. Filters AND together. Playbook: read the `debugging-sessions` playbook via+ `agent-resolve-resource` for the failure taxonomy and how to read the logs.agent-applications-sessions-retrieve:operation: agent_applications_sessions_retrieveenabled: true@@ -527,7 +565,8 @@ tools:over the entire session. Pass `last_n=<int>` to trim the response to the most recent N messages — useful forlong sessions where you only care about the tail; `conversation_trimmed: true` plus`conversation_total_turns` tells you how much was hidden, and `usage_total` is still computed over the full- untrimmed conversation so cost reporting stays accurate.+ untrimmed conversation so cost reporting stays accurate. Playbook: read the `debugging-sessions` playbook+ via `agent-resolve-resource` for the failure taxonomy and how to read the logs.agent-applications-set-env-create:operation: agent_applications_set_env_createenabled: false@@ -544,6 +583,8 @@ tools:secret entry goes through the agent console's secret editor instead (deep-link flow; see thesecrets-and-integrations skill). Values are encrypted at rest with the team's Fernet keys and never leaveDjango; this endpoint stays available on the REST API for the console / CI that already hold the values.+ Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the credential+ punch-out flow.agent-applications-stats:operation: agent_applications_statsenabled: false@@ -600,4 +641,5 @@ tools:Read-only catalog of every `@posthog/*` native tool an agent can wire into `spec.tools`. Each entry includesthe id, description, args schema (TypeBox-shaped), required integrations + scopes, and a cost hint (`cheap`/ `medium` / `expensive`). Authoring flows use this to validate tool ids before writing them into a- revision's spec.+ revision's spec. Playbook: read the `authoring-new-agents` playbook via `agent-resolve-resource` for the+ end-to-end authoring flow.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 6e62f6e3a755..a5f3a0b92d34 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -247,7 +247,7 @@}},"agent-applications-create": {- "description": "Create a new agent. Requires `name` + `slug` (unique within the team). The fresh application has no revisions; create a draft via `agent-applications-revisions-create`, populate its bundle, then freeze + promote.",+ "description": "Create a new agent. Requires `name` + `slug` (unique within the team). The fresh application has no revisions; create a draft via `agent-applications-revisions-create`, populate its bundle, then freeze + promote. Playbook: read the `authoring-new-agents` playbook via `agent-resolve-resource` for the end-to-end authoring flow.","category": "Agent stack","feature": "agent_platform","summary": "Create an agent application",@@ -277,7 +277,7 @@"feature_flag": "agent-platform"},"agent-applications-env-keys-clear": {- "description": "Remove one key from the encrypted env. No-op when the key wasn't set. Use this when a secret is no longer required by the spec or after a credential is known to be compromised. Does NOT trigger session restarts — in-flight sessions keep the value they resolved at start.",+ "description": "Remove one key from the encrypted env. No-op when the key wasn't set. Use this when a secret is no longer required by the spec or after a credential is known to be compromised. Does NOT trigger session restarts — in-flight sessions keep the value they resolved at start. Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the credential punch-out flow.","category": "Agent stack","feature": "agent_platform","summary": "Clear one secret",@@ -292,7 +292,7 @@"feature_flag": "agent-platform"},"agent-applications-env-keys-get": {- "description": "Returns `{ key, is_set }` for one name. The value is never returned. Use as a pre-check before asking the user to set or rotate a key, and again after the user completes the punch-out flow to confirm the write landed.",+ "description": "Returns `{ key, is_set }` for one name. The value is never returned. Use as a pre-check before asking the user to set or rotate a key, and again after the user completes the punch-out flow to confirm the write landed. Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the credential punch-out flow.","category": "Agent stack","feature": "agent_platform","summary": "Check whether one secret is set",@@ -307,7 +307,7 @@"feature_flag": "agent-platform"},"agent-applications-env-keys-list": {- "description": "Returns `{ keys: [name, ...] }` — names only, never values. Use to know which declared secrets are already populated so you don't ask the user to set something that's already set. Pair with `agent-applications-revisions-retrieve` (`spec.secrets[]`) to spot which declared keys are still unset.",+ "description": "Returns `{ keys: [name, ...] }` — names only, never values. Use to know which declared secrets are already populated so you don't ask the user to set something that's already set. Pair with `agent-applications-revisions-retrieve` (`spec.secrets[]`) to spot which declared keys are still unset. Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the credential punch-out flow.","category": "Agent stack","feature": "agent_platform","summary": "List the names of secrets currently set",@@ -322,7 +322,7 @@"feature_flag": "agent-platform"},"agent-applications-list": {- "description": "List every agent application in the project. Returns id, slug, name, description, live_revision, archived state. Use the slug to drive subsequent calls — it's stable and human-readable.",+ "description": "List every agent application in the project. Returns id, slug, name, description, live_revision, archived state. Use the slug to drive subsequent calls — it's stable and human-readable. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "List agent applications",@@ -357,7 +357,7 @@"feature": "agent_platform","summary": "Invoke a draft revision via the Django preview-proxy","title": "Invoke a draft revision via the Django preview-proxy",- "required_scopes": ["agents:read"],+ "required_scopes": ["agents:write"],"annotations": {"destructiveHint": false,"idempotentHint": false,@@ -367,7 +367,7 @@"feature_flag": "agent-platform"},"agent-applications-retrieve": {- "description": "Fetch one application by id or slug (both unique within the team). Returns metadata only — to inspect the running spec or bundle, look up the live revision via `agent-applications-revisions-list` then call `agent-applications-revisions-retrieve` and `agent-applications-revisions-manifest-retrieve`.",+ "description": "Fetch one application by id or slug (both unique within the team). Returns metadata only — to inspect the running spec or bundle, look up the live revision via `agent-applications-revisions-list` then call `agent-applications-revisions-retrieve` and `agent-applications-revisions-manifest-retrieve`. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "Get an agent application",@@ -382,7 +382,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-agent-md-update": {- "description": "Body `{ content: \"…\" }`. Overwrites the agent's system prompt. Use for surgical edits to the prompt; leaves skills, tools, and spec untouched. Draft-only.",+ "description": "Body `{ content: \"…\" }`. Overwrites the agent's system prompt. Use for surgical edits to the prompt; leaves skills, tools, and spec untouched. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Replace agent.md",@@ -397,7 +397,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-archive-create": {- "description": "Mark a revision archived. If it was the live revision, clears the parent application's `live_revision` (the app has no deployable version until another revision is promoted). Idempotent.",+ "description": "Mark a revision archived. If it was the live revision, clears the parent application's `live_revision` (the app has no deployable version until another revision is promoted). Idempotent. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Archive a revision",@@ -412,7 +412,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-bundle-retrieve": {- "description": "Returns `{ agent_md, skills, tools, spec }` — the typed view of the revision. Use this when you want to edit the whole agent locally (pull, mutate in-memory, push back via the bundle PUT). Skills carry `description` and `body` (stored at `skills/<id>/SKILL.md`). Tools carry `description`, `args_schema`, `source` (TypeScript). `spec` is the author-facing slice (skills/tools are server-derived at freeze).",+ "description": "Returns `{ agent_md, skills, tools, spec }` — the typed view of the revision. Use this when you want to edit the whole agent locally (pull, mutate in-memory, push back via the bundle PUT). Skills carry `description` and `body` (stored at `skills/<id>/SKILL.md`). Tools carry `description`, `args_schema`, `source` (TypeScript). `spec` is the author-facing slice (skills/tools are server-derived at freeze). Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "Get the typed bundle",@@ -427,7 +427,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-bundle-update": {- "description": "Body shape matches the GET response: `{ agent_md, skills, tools, spec }`. **Full replace** — anything not in the payload is deleted. For incremental edits use the single-resource PUTs (`agent-applications-revisions-skills-update`, etc.). Each tool source is AST-checked + esbuild-compiled synchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this.",+ "description": "Body shape matches the GET response: `{ agent_md, skills, tools, spec }`. **Full replace** — anything not in the payload is deleted. For incremental edits use the single-resource PUTs (`agent-applications-revisions-skills-update`, etc.). Each tool source is AST-checked + esbuild-compiled synchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Full-replace the typed bundle",@@ -442,7 +442,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-clone-from-create": {- "description": "Copy every file in `source_revision_id`'s bundle into this (draft) revision. Use after `agent-applications-revisions-create` if you didn't go through `new-draft` for some reason. Both revisions must belong to the same team.",+ "description": "Copy every file in `source_revision_id`'s bundle into this (draft) revision. Use after `agent-applications-revisions-create` if you didn't go through `new-draft` for some reason. Both revisions must belong to the same team. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Clone bundle from another revision",@@ -457,7 +457,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-create": {- "description": "Create a new revision in state `draft`. Body shape mirrors the AgentRevision serializer — the only fields you typically set are `spec` (initial JSON) and `parent_revision` (optional, lets the diff UI show what you're changing). The bundle starts empty; use `agent-applications-revisions-clone-from-create` or `agent-applications-revisions-new-draft-create` to seed it from an existing revision.",+ "description": "Create a new revision in state `draft`. Body shape mirrors the AgentRevision serializer — the only fields you typically set are `spec` (initial JSON) and `parent_revision` (optional, lets the diff UI show what you're changing). The bundle starts empty; use `agent-applications-revisions-clone-from-create` or `agent-applications-revisions-new-draft-create` to seed it from an existing revision. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Create a draft revision",@@ -472,7 +472,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-cron-fire-create": {- "description": "Fire a single cron job out-of-band, bypassing the scheduler's window logic. Use this to iterate on a cron agent's `prompt` (or to debug `external_key` placeholder expansion) without waiting for the next real firing. Required: `cron_name` (matches `spec.triggers[].config.name` on a `type: cron` trigger). Optional: `request_id` — pass a stable id per logical click so repeat fires resolve to the same session instead of stacking duplicates. Returns `{ ok, session_id, fired_at, idempotency_key }`; track the session via `agent-applications-sessions-retrieve` to read the conversation. Authoring-loop completion piece — without this, \"did my prompt do the right thing?\" is unanswerable until the cron actually fires.",+ "description": "Fire a single cron job out-of-band, bypassing the scheduler's window logic. Use this to iterate on a cron agent's `prompt` (or to debug `external_key` placeholder expansion) without waiting for the next real firing. Required: `cron_name` (matches `spec.triggers[].config.name` on a `type: cron` trigger). Optional: `request_id` — pass a stable id per logical click so repeat fires resolve to the same session instead of stacking duplicates. Returns `{ ok, session_id, fired_at, idempotency_key }`; track the session via `agent-applications-sessions-retrieve` to read the conversation. Authoring-loop completion piece — without this, \"did my prompt do the right thing?\" is unanswerable until the cron actually fires. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.","category": "Agent stack","feature": "agent_platform","summary": "Manually fire one cron job",@@ -487,7 +487,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-freeze-create": {- "description": "Walks the bundle, computes a manifest sha256, stamps it on the row, flips state `draft → ready`. After this the bundle is immutable. Idempotent — freezing a `ready` revision is a no-op that returns the existing sha256.",+ "description": "Walks the bundle, computes a manifest sha256, stamps it on the row, flips state `draft → ready`. After this the bundle is immutable. Idempotent — freezing a `ready` revision is a no-op that returns the existing sha256. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Freeze a draft revision",@@ -502,7 +502,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-list": {- "description": "List every revision (draft, ready, live, archived) for one application, newest first. Use to find the current live revision id or pick a known-good revision to clone for an edit.",+ "description": "List every revision (draft, ready, live, archived) for one application, newest first. Use to find the current live revision id or pick a known-good revision to clone for an edit. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "List revisions of an application",@@ -517,7 +517,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-manifest-retrieve": {- "description": "Returns `{ revision_id, state, bundle_sha256, files: [{ path, size, sha256 }, …] }`. Use to discover what's in a bundle without pulling all the bytes — sha256 lets you spot which files have changed since you last looked.",+ "description": "Returns `{ revision_id, state, bundle_sha256, files: [{ path, size, sha256 }, …] }`. Use to discover what's in a bundle without pulling all the bytes — sha256 lets you spot which files have changed since you last looked. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "List files in a revision's bundle",@@ -532,7 +532,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-new-draft-create": {- "description": "One-shot helper: creates a draft revision under `application_id` and clones every file from `source_revision_id` into the new bundle in a single round-trip. Use this for the common \"edit live\" workflow — branch from the current live revision, mutate files, freeze, promote.",+ "description": "One-shot helper: creates a draft revision under `application_id` and clones every file from `source_revision_id` into the new bundle in a single round-trip. Use this for the common \"edit live\" workflow — branch from the current live revision, mutate files, freeze, promote. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Branch a new draft from an existing revision",@@ -547,7 +547,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-partial-update": {- "description": "Replace `spec` on a draft revision. Only `state=draft` revisions accept spec edits — promote bumps the revision to `ready` which freezes the spec. Validation against the AgentSpec zod schema runs on the runner side; an invalid spec will surface when the next session starts, not here.",+ "description": "Replace `spec` on a draft revision. Only `state=draft` revisions accept spec edits — promote bumps the revision to `ready` which freezes the spec. Validation against the AgentSpec zod schema runs on the runner side; an invalid spec will surface when the next session starts, not here. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Update a revision's spec",@@ -562,7 +562,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-promote-create": {- "description": "Flips a `ready` revision to `live` and sets the parent application's `live_revision`. The previously live revision is archived automatically. Requires `state=ready` and `bundle_sha256` set (call `freeze` first). Idempotent: promoting an already-live revision is a no-op.",+ "description": "Flips a `ready` revision to `live` and sets the parent application's `live_revision`. The previously live revision is archived automatically. Requires `state=ready` and `bundle_sha256` set (call `freeze` first). Idempotent: promoting an already-live revision is a no-op. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Promote a revision to live",@@ -577,7 +577,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-retrieve": {- "description": "Fetch one revision's metadata: state, spec (the structural JSON), bundle_uri, bundle_sha256, parent revision id, timestamps. For the bundle contents see `agent-applications-revisions-manifest-retrieve` / `agent-applications-revisions-bundle-retrieve`.",+ "description": "Fetch one revision's metadata: state, spec (the structural JSON), bundle_uri, bundle_sha256, parent revision id, timestamps. For the bundle contents see `agent-applications-revisions-manifest-retrieve` / `agent-applications-revisions-bundle-retrieve`. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "Get a revision",@@ -592,7 +592,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-skills-destroy": {- "description": "Removes the skill folder (`skills/<id>/`, holding its `SKILL.md`). Returns 404 if the skill doesn't exist. Draft-only.",+ "description": "Removes the skill folder (`skills/<id>/`, holding its `SKILL.md`). Returns 404 if the skill doesn't exist. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Delete one skill",@@ -607,7 +607,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-skills-update": {- "description": "Body `{ description, body }`. Creates the skill if it doesn't exist, replaces it if it does. The `body` is stored at `skills/<skill_id>/SKILL.md`. Skill id comes from the URL. Draft-only.",+ "description": "Body `{ description, body }`. Creates the skill if it doesn't exist, replaces it if it does. The `body` is stored at `skills/<skill_id>/SKILL.md`. Skill id comes from the URL. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Upsert one skill",@@ -637,7 +637,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-spec-update": {- "description": "Body `{ spec: { … } }`. Replaces the author-writable spec slice (model, triggers, mcps, integrations, secrets, limits, auth, entrypoint, reasoning). `skills[]` and `tools[]` are NOT author-writable — they're derived at freeze from the typed resources. Draft-only.",+ "description": "Body `{ spec: { … } }`. Replaces the author-writable spec slice (model, triggers, mcps, integrations, secrets, limits, auth, entrypoint, reasoning). `skills[]` and `tools[]` are NOT author-writable — they're derived at freeze from the typed resources. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Replace the author-facing spec",@@ -652,7 +652,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-system-prompt": {- "description": "Returns the fully-assembled system prompt the runner would pass to the model at session start — framework preamble + agent.md (or `spec.entrypoint`) + skills index. Use to verify what the model actually sees before promoting; particularly useful for confirming `spec.framework_prompt.omit` opt-outs took effect or for debugging author-vs-framework precedence. Response also includes `framework_prompt_version` so you can tell whether a pin (`spec.framework_prompt.version_pin`) is in effect. Works on any revision state.",+ "description": "Returns the fully-assembled system prompt the runner would pass to the model at session start — framework preamble + agent.md (or `spec.entrypoint`) + skills index. Use to verify what the model actually sees before promoting; particularly useful for confirming `spec.framework_prompt.omit` opt-outs took effect or for debugging author-vs-framework precedence. Response also includes `framework_prompt_version` so you can tell whether a pin (`spec.framework_prompt.version_pin`) is in effect. Works on any revision state. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "Preview the assembled system prompt for a revision",@@ -667,7 +667,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-tools-destroy": {- "description": "Removes source.ts, compiled.js, schema.json from the bundle. Returns 404 if the tool doesn't exist. Draft-only.",+ "description": "Removes source.ts, compiled.js, schema.json from the bundle. Returns 404 if the tool doesn't exist. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Delete one custom tool",@@ -682,7 +682,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-tools-update": {- "description": "Body `{ description, args_schema, source }`. `source` is the TypeScript tool source — the janitor runs an AST shape check + esbuild compile synchronously and rejects a bad shape with structured diagnostics in the 422 response. Required shape: `export default { actions: { default: async (args, ctx) => { ... } } }`. Do NOT include `compiled.js` — it's generated. Tool id comes from the URL. Draft-only.",+ "description": "Body `{ description, args_schema, source }`. `source` is the TypeScript tool source — the janitor runs an AST shape check + esbuild compile synchronously and rejects a bad shape with structured diagnostics in the 422 response. Required shape: `export default { actions: { default: async (args, ctx) => { ... } } }`. Do NOT include `compiled.js` — it's generated. Tool id comes from the URL. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Upsert one custom tool",@@ -697,7 +697,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-validate-create": {- "description": "Pre-flight checks before deploying. Returns `{ ok, errors: [...] }`. Catches: missing entrypoint file, unknown native tool ids, custom tools missing `compiled.js` / `schema.json`, skill paths that don't exist in the bundle, declared secrets that aren't set in the application env. Works on any revision state — use this on a draft before calling `agent-applications-revisions-freeze-create`.",+ "description": "Pre-flight checks before deploying. Returns `{ ok, errors: [...] }`. Catches: missing entrypoint file, unknown native tool ids, custom tools missing `compiled.js` / `schema.json`, skill paths that don't exist in the bundle, declared secrets that aren't set in the application env. Works on any revision state — use this on a draft before calling `agent-applications-revisions-freeze-create`. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Validate a revision's bundle + spec",@@ -712,7 +712,7 @@"feature_flag": "agent-platform"},"agent-applications-sessions-list": {- "description": "Newest-first list of sessions for this agent across all revisions. Each summary carries id, state (queued / running / completed / closed / cancelled / failed), revision_id, principal, turn count, retry count, timestamps, a `preview` of the last assistant text (~120 chars), and `usage_total` (tokens + cost aggregated over the whole conversation). The transcript body is omitted — use `agent-applications-sessions-retrieve` for that. Filters: `state` (comma-separated for multiple, e.g. `completed,failed`), `revision_id` (UUID), `created_after` / `created_before` (ISO datetimes). Paging via `limit` (default 100, capped at 500) + `offset`. Filters AND together.",+ "description": "Newest-first list of sessions for this agent across all revisions. Each summary carries id, state (queued / running / completed / closed / cancelled / failed), revision_id, principal, turn count, retry count, timestamps, a `preview` of the last assistant text (~120 chars), and `usage_total` (tokens + cost aggregated over the whole conversation). The transcript body is omitted — use `agent-applications-sessions-retrieve` for that. Filters: `state` (comma-separated for multiple, e.g. `completed,failed`), `revision_id` (UUID), `created_after` / `created_before` (ISO datetimes). Paging via `limit` (default 100, capped at 500) + `offset`. Filters AND together. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.","category": "Agent stack","feature": "agent_platform","summary": "List sessions for an agent",@@ -727,7 +727,7 @@"feature_flag": "agent-platform"},"agent-applications-sessions-retrieve": {- "description": "Full `AgentSession` row: state, principal, conversation (user / assistant / toolResult messages), pending_inputs, retry_count, timestamps. Always includes a `usage_total` block (tokens + cost) aggregated over the entire session. Pass `last_n=<int>` to trim the response to the most recent N messages — useful for long sessions where you only care about the tail; `conversation_trimmed: true` plus `conversation_total_turns` tells you how much was hidden, and `usage_total` is still computed over the full untrimmed conversation so cost reporting stays accurate.",+ "description": "Full `AgentSession` row: state, principal, conversation (user / assistant / toolResult messages), pending_inputs, retry_count, timestamps. Always includes a `usage_total` block (tokens + cost) aggregated over the entire session. Pass `last_n=<int>` to trim the response to the most recent N messages — useful for long sessions where you only care about the tail; `conversation_trimmed: true` plus `conversation_total_turns` tells you how much was hidden, and `usage_total` is still computed over the full untrimmed conversation so cost reporting stays accurate. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.","category": "Agent stack","feature": "agent_platform","summary": "Get one session",@@ -742,7 +742,7 @@"feature_flag": "agent-platform"},"agent-native-tools-list": {- "description": "Read-only catalog of every `@posthog/*` native tool an agent can wire into `spec.tools`. Each entry includes the id, description, args schema (TypeBox-shaped), required integrations + scopes, and a cost hint (`cheap` / `medium` / `expensive`). Authoring flows use this to validate tool ids before writing them into a revision's spec.",+ "description": "Read-only catalog of every `@posthog/*` native tool an agent can wire into `spec.tools`. Each entry includes the id, description, args schema (TypeBox-shaped), required integrations + scopes, and a cost hint (`cheap` / `medium` / `expensive`). Authoring flows use this to validate tool ids before writing them into a revision's spec. Playbook: read the `authoring-new-agents` playbook via `agent-resolve-resource` for the end-to-end authoring flow.","category": "Agent stack","feature": "agent_platform","summary": "List native tools the runner knows",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 9aa810c5b7bd..4cc0e1b956d0 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -247,7 +247,7 @@}},"agent-applications-create": {- "description": "Create a new agent. Requires `name` + `slug` (unique within the team). The fresh application has no revisions; create a draft via `agent-applications-revisions-create`, populate its bundle, then freeze + promote.",+ "description": "Create a new agent. Requires `name` + `slug` (unique within the team). The fresh application has no revisions; create a draft via `agent-applications-revisions-create`, populate its bundle, then freeze + promote. Playbook: read the `authoring-new-agents` playbook via `agent-resolve-resource` for the end-to-end authoring flow.","category": "Agent stack","feature": "agent_platform","summary": "Create an agent application",@@ -277,7 +277,7 @@"feature_flag": "agent-platform"},"agent-applications-env-keys-clear": {- "description": "Remove one key from the encrypted env. No-op when the key wasn't set. Use this when a secret is no longer required by the spec or after a credential is known to be compromised. Does NOT trigger session restarts — in-flight sessions keep the value they resolved at start.",+ "description": "Remove one key from the encrypted env. No-op when the key wasn't set. Use this when a secret is no longer required by the spec or after a credential is known to be compromised. Does NOT trigger session restarts — in-flight sessions keep the value they resolved at start. Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the credential punch-out flow.","category": "Agent stack","feature": "agent_platform","summary": "Clear one secret",@@ -292,7 +292,7 @@"feature_flag": "agent-platform"},"agent-applications-env-keys-get": {- "description": "Returns `{ key, is_set }` for one name. The value is never returned. Use as a pre-check before asking the user to set or rotate a key, and again after the user completes the punch-out flow to confirm the write landed.",+ "description": "Returns `{ key, is_set }` for one name. The value is never returned. Use as a pre-check before asking the user to set or rotate a key, and again after the user completes the punch-out flow to confirm the write landed. Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the credential punch-out flow.","category": "Agent stack","feature": "agent_platform","summary": "Check whether one secret is set",@@ -307,7 +307,7 @@"feature_flag": "agent-platform"},"agent-applications-env-keys-list": {- "description": "Returns `{ keys: [name, ...] }` — names only, never values. Use to know which declared secrets are already populated so you don't ask the user to set something that's already set. Pair with `agent-applications-revisions-retrieve` (`spec.secrets[]`) to spot which declared keys are still unset.",+ "description": "Returns `{ keys: [name, ...] }` — names only, never values. Use to know which declared secrets are already populated so you don't ask the user to set something that's already set. Pair with `agent-applications-revisions-retrieve` (`spec.secrets[]`) to spot which declared keys are still unset. Playbook: read the `secrets-and-integrations` playbook via `agent-resolve-resource` for the credential punch-out flow.","category": "Agent stack","feature": "agent_platform","summary": "List the names of secrets currently set",@@ -322,7 +322,7 @@"feature_flag": "agent-platform"},"agent-applications-list": {- "description": "List every agent application in the project. Returns id, slug, name, description, live_revision, archived state. Use the slug to drive subsequent calls — it's stable and human-readable.",+ "description": "List every agent application in the project. Returns id, slug, name, description, live_revision, archived state. Use the slug to drive subsequent calls — it's stable and human-readable. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "List agent applications",@@ -357,7 +357,7 @@"feature": "agent_platform","summary": "Invoke a draft revision via the Django preview-proxy","title": "Invoke a draft revision via the Django preview-proxy",- "required_scopes": ["agents:read"],+ "required_scopes": ["agents:write"],"annotations": {"destructiveHint": false,"idempotentHint": false,@@ -367,7 +367,7 @@"feature_flag": "agent-platform"},"agent-applications-retrieve": {- "description": "Fetch one application by id or slug (both unique within the team). Returns metadata only — to inspect the running spec or bundle, look up the live revision via `agent-applications-revisions-list` then call `agent-applications-revisions-retrieve` and `agent-applications-revisions-manifest-retrieve`.",+ "description": "Fetch one application by id or slug (both unique within the team). Returns metadata only — to inspect the running spec or bundle, look up the live revision via `agent-applications-revisions-list` then call `agent-applications-revisions-retrieve` and `agent-applications-revisions-manifest-retrieve`. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "Get an agent application",@@ -382,7 +382,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-agent-md-update": {- "description": "Body `{ content: \"…\" }`. Overwrites the agent's system prompt. Use for surgical edits to the prompt; leaves skills, tools, and spec untouched. Draft-only.",+ "description": "Body `{ content: \"…\" }`. Overwrites the agent's system prompt. Use for surgical edits to the prompt; leaves skills, tools, and spec untouched. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Replace agent.md",@@ -397,7 +397,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-archive-create": {- "description": "Mark a revision archived. If it was the live revision, clears the parent application's `live_revision` (the app has no deployable version until another revision is promoted). Idempotent.",+ "description": "Mark a revision archived. If it was the live revision, clears the parent application's `live_revision` (the app has no deployable version until another revision is promoted). Idempotent. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Archive a revision",@@ -412,7 +412,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-bundle-retrieve": {- "description": "Returns `{ agent_md, skills, tools, spec }` — the typed view of the revision. Use this when you want to edit the whole agent locally (pull, mutate in-memory, push back via the bundle PUT). Skills carry `description` and `body` (stored at `skills/<id>/SKILL.md`). Tools carry `description`, `args_schema`, `source` (TypeScript). `spec` is the author-facing slice (skills/tools are server-derived at freeze).",+ "description": "Returns `{ agent_md, skills, tools, spec }` — the typed view of the revision. Use this when you want to edit the whole agent locally (pull, mutate in-memory, push back via the bundle PUT). Skills carry `description` and `body` (stored at `skills/<id>/SKILL.md`). Tools carry `description`, `args_schema`, `source` (TypeScript). `spec` is the author-facing slice (skills/tools are server-derived at freeze). Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "Get the typed bundle",@@ -427,7 +427,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-bundle-update": {- "description": "Body shape matches the GET response: `{ agent_md, skills, tools, spec }`. **Full replace** — anything not in the payload is deleted. For incremental edits use the single-resource PUTs (`agent-applications-revisions-skills-update`, etc.). Each tool source is AST-checked + esbuild-compiled synchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this.",+ "description": "Body shape matches the GET response: `{ agent_md, skills, tools, spec }`. **Full replace** — anything not in the payload is deleted. For incremental edits use the single-resource PUTs (`agent-applications-revisions-skills-update`, etc.). Each tool source is AST-checked + esbuild-compiled synchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Full-replace the typed bundle",@@ -442,7 +442,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-clone-from-create": {- "description": "Copy every file in `source_revision_id`'s bundle into this (draft) revision. Use after `agent-applications-revisions-create` if you didn't go through `new-draft` for some reason. Both revisions must belong to the same team.",+ "description": "Copy every file in `source_revision_id`'s bundle into this (draft) revision. Use after `agent-applications-revisions-create` if you didn't go through `new-draft` for some reason. Both revisions must belong to the same team. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Clone bundle from another revision",@@ -457,7 +457,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-create": {- "description": "Create a new revision in state `draft`. Body shape mirrors the AgentRevision serializer — the only fields you typically set are `spec` (initial JSON) and `parent_revision` (optional, lets the diff UI show what you're changing). The bundle starts empty; use `agent-applications-revisions-clone-from-create` or `agent-applications-revisions-new-draft-create` to seed it from an existing revision.",+ "description": "Create a new revision in state `draft`. Body shape mirrors the AgentRevision serializer — the only fields you typically set are `spec` (initial JSON) and `parent_revision` (optional, lets the diff UI show what you're changing). The bundle starts empty; use `agent-applications-revisions-clone-from-create` or `agent-applications-revisions-new-draft-create` to seed it from an existing revision. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Create a draft revision",@@ -472,7 +472,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-cron-fire-create": {- "description": "Fire a single cron job out-of-band, bypassing the scheduler's window logic. Use this to iterate on a cron agent's `prompt` (or to debug `external_key` placeholder expansion) without waiting for the next real firing. Required: `cron_name` (matches `spec.triggers[].config.name` on a `type: cron` trigger). Optional: `request_id` — pass a stable id per logical click so repeat fires resolve to the same session instead of stacking duplicates. Returns `{ ok, session_id, fired_at, idempotency_key }`; track the session via `agent-applications-sessions-retrieve` to read the conversation. Authoring-loop completion piece — without this, \"did my prompt do the right thing?\" is unanswerable until the cron actually fires.",+ "description": "Fire a single cron job out-of-band, bypassing the scheduler's window logic. Use this to iterate on a cron agent's `prompt` (or to debug `external_key` placeholder expansion) without waiting for the next real firing. Required: `cron_name` (matches `spec.triggers[].config.name` on a `type: cron` trigger). Optional: `request_id` — pass a stable id per logical click so repeat fires resolve to the same session instead of stacking duplicates. Returns `{ ok, session_id, fired_at, idempotency_key }`; track the session via `agent-applications-sessions-retrieve` to read the conversation. Authoring-loop completion piece — without this, \"did my prompt do the right thing?\" is unanswerable until the cron actually fires. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.","category": "Agent stack","feature": "agent_platform","summary": "Manually fire one cron job",@@ -487,7 +487,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-freeze-create": {- "description": "Walks the bundle, computes a manifest sha256, stamps it on the row, flips state `draft → ready`. After this the bundle is immutable. Idempotent — freezing a `ready` revision is a no-op that returns the existing sha256.",+ "description": "Walks the bundle, computes a manifest sha256, stamps it on the row, flips state `draft → ready`. After this the bundle is immutable. Idempotent — freezing a `ready` revision is a no-op that returns the existing sha256. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Freeze a draft revision",@@ -502,7 +502,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-list": {- "description": "List every revision (draft, ready, live, archived) for one application, newest first. Use to find the current live revision id or pick a known-good revision to clone for an edit.",+ "description": "List every revision (draft, ready, live, archived) for one application, newest first. Use to find the current live revision id or pick a known-good revision to clone for an edit. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "List revisions of an application",@@ -517,7 +517,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-manifest-retrieve": {- "description": "Returns `{ revision_id, state, bundle_sha256, files: [{ path, size, sha256 }, …] }`. Use to discover what's in a bundle without pulling all the bytes — sha256 lets you spot which files have changed since you last looked.",+ "description": "Returns `{ revision_id, state, bundle_sha256, files: [{ path, size, sha256 }, …] }`. Use to discover what's in a bundle without pulling all the bytes — sha256 lets you spot which files have changed since you last looked. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "List files in a revision's bundle",@@ -532,7 +532,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-new-draft-create": {- "description": "One-shot helper: creates a draft revision under `application_id` and clones every file from `source_revision_id` into the new bundle in a single round-trip. Use this for the common \"edit live\" workflow — branch from the current live revision, mutate files, freeze, promote.",+ "description": "One-shot helper: creates a draft revision under `application_id` and clones every file from `source_revision_id` into the new bundle in a single round-trip. Use this for the common \"edit live\" workflow — branch from the current live revision, mutate files, freeze, promote. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Branch a new draft from an existing revision",@@ -547,7 +547,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-partial-update": {- "description": "Replace `spec` on a draft revision. Only `state=draft` revisions accept spec edits — promote bumps the revision to `ready` which freezes the spec. Validation against the AgentSpec zod schema runs on the runner side; an invalid spec will surface when the next session starts, not here.",+ "description": "Replace `spec` on a draft revision. Only `state=draft` revisions accept spec edits — promote bumps the revision to `ready` which freezes the spec. Validation against the AgentSpec zod schema runs on the runner side; an invalid spec will surface when the next session starts, not here. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Update a revision's spec",@@ -562,7 +562,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-promote-create": {- "description": "Flips a `ready` revision to `live` and sets the parent application's `live_revision`. The previously live revision is archived automatically. Requires `state=ready` and `bundle_sha256` set (call `freeze` first). Idempotent: promoting an already-live revision is a no-op.",+ "description": "Flips a `ready` revision to `live` and sets the parent application's `live_revision`. The previously live revision is archived automatically. Requires `state=ready` and `bundle_sha256` set (call `freeze` first). Idempotent: promoting an already-live revision is a no-op. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Promote a revision to live",@@ -577,7 +577,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-retrieve": {- "description": "Fetch one revision's metadata: state, spec (the structural JSON), bundle_uri, bundle_sha256, parent revision id, timestamps. For the bundle contents see `agent-applications-revisions-manifest-retrieve` / `agent-applications-revisions-bundle-retrieve`.",+ "description": "Fetch one revision's metadata: state, spec (the structural JSON), bundle_uri, bundle_sha256, parent revision id, timestamps. For the bundle contents see `agent-applications-revisions-manifest-retrieve` / `agent-applications-revisions-bundle-retrieve`. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "Get a revision",@@ -592,7 +592,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-skills-destroy": {- "description": "Removes the skill folder (`skills/<id>/`, holding its `SKILL.md`). Returns 404 if the skill doesn't exist. Draft-only.",+ "description": "Removes the skill folder (`skills/<id>/`, holding its `SKILL.md`). Returns 404 if the skill doesn't exist. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Delete one skill",@@ -607,7 +607,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-skills-update": {- "description": "Body `{ description, body }`. Creates the skill if it doesn't exist, replaces it if it does. The `body` is stored at `skills/<skill_id>/SKILL.md`. Skill id comes from the URL. Draft-only.",+ "description": "Body `{ description, body }`. Creates the skill if it doesn't exist, replaces it if it does. The `body` is stored at `skills/<skill_id>/SKILL.md`. Skill id comes from the URL. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Upsert one skill",@@ -637,7 +637,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-spec-update": {- "description": "Body `{ spec: { … } }`. Replaces the author-writable spec slice (model, triggers, mcps, integrations, secrets, limits, auth, entrypoint, reasoning). `skills[]` and `tools[]` are NOT author-writable — they're derived at freeze from the typed resources. Draft-only.",+ "description": "Body `{ spec: { … } }`. Replaces the author-writable spec slice (model, triggers, mcps, integrations, secrets, limits, auth, entrypoint, reasoning). `skills[]` and `tools[]` are NOT author-writable — they're derived at freeze from the typed resources. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Replace the author-facing spec",@@ -652,7 +652,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-system-prompt": {- "description": "Returns the fully-assembled system prompt the runner would pass to the model at session start — framework preamble + agent.md (or `spec.entrypoint`) + skills index. Use to verify what the model actually sees before promoting; particularly useful for confirming `spec.framework_prompt.omit` opt-outs took effect or for debugging author-vs-framework precedence. Response also includes `framework_prompt_version` so you can tell whether a pin (`spec.framework_prompt.version_pin`) is in effect. Works on any revision state.",+ "description": "Returns the fully-assembled system prompt the runner would pass to the model at session start — framework preamble + agent.md (or `spec.entrypoint`) + skills index. Use to verify what the model actually sees before promoting; particularly useful for confirming `spec.framework_prompt.omit` opt-outs took effect or for debugging author-vs-framework precedence. Response also includes `framework_prompt_version` so you can tell whether a pin (`spec.framework_prompt.version_pin`) is in effect. Works on any revision state. Playbook: read the `reading-an-agent` playbook via `agent-resolve-resource` for how to inspect and summarize an agent.","category": "Agent stack","feature": "agent_platform","summary": "Preview the assembled system prompt for a revision",@@ -667,7 +667,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-tools-destroy": {- "description": "Removes source.ts, compiled.js, schema.json from the bundle. Returns 404 if the tool doesn't exist. Draft-only.",+ "description": "Removes source.ts, compiled.js, schema.json from the bundle. Returns 404 if the tool doesn't exist. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Delete one custom tool",@@ -682,7 +682,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-tools-update": {- "description": "Body `{ description, args_schema, source }`. `source` is the TypeScript tool source — the janitor runs an AST shape check + esbuild compile synchronously and rejects a bad shape with structured diagnostics in the 422 response. Required shape: `export default { actions: { default: async (args, ctx) => { ... } } }`. Do NOT include `compiled.js` — it's generated. Tool id comes from the URL. Draft-only.",+ "description": "Body `{ description, args_schema, source }`. `source` is the TypeScript tool source — the janitor runs an AST shape check + esbuild compile synchronously and rejects a bad shape with structured diagnostics in the 422 response. Required shape: `export default { actions: { default: async (args, ctx) => { ... } } }`. Do NOT include `compiled.js` — it's generated. Tool id comes from the URL. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Upsert one custom tool",@@ -697,7 +697,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-validate-create": {- "description": "Pre-flight checks before deploying. Returns `{ ok, errors: [...] }`. Catches: missing entrypoint file, unknown native tool ids, custom tools missing `compiled.js` / `schema.json`, skill paths that don't exist in the bundle, declared secrets that aren't set in the application env. Works on any revision state — use this on a draft before calling `agent-applications-revisions-freeze-create`.",+ "description": "Pre-flight checks before deploying. Returns `{ ok, errors: [...] }`. Catches: missing entrypoint file, unknown native tool ids, custom tools missing `compiled.js` / `schema.json`, skill paths that don't exist in the bundle, declared secrets that aren't set in the application env. Works on any revision state — use this on a draft before calling `agent-applications-revisions-freeze-create`. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Validate a revision's bundle + spec",@@ -712,7 +712,7 @@"feature_flag": "agent-platform"},"agent-applications-sessions-list": {- "description": "Newest-first list of sessions for this agent across all revisions. Each summary carries id, state (queued / running / completed / closed / cancelled / failed), revision_id, principal, turn count, retry count, timestamps, a `preview` of the last assistant text (~120 chars), and `usage_total` (tokens + cost aggregated over the whole conversation). The transcript body is omitted — use `agent-applications-sessions-retrieve` for that. Filters: `state` (comma-separated for multiple, e.g. `completed,failed`), `revision_id` (UUID), `created_after` / `created_before` (ISO datetimes). Paging via `limit` (default 100, capped at 500) + `offset`. Filters AND together.",+ "description": "Newest-first list of sessions for this agent across all revisions. Each summary carries id, state (queued / running / completed / closed / cancelled / failed), revision_id, principal, turn count, retry count, timestamps, a `preview` of the last assistant text (~120 chars), and `usage_total` (tokens + cost aggregated over the whole conversation). The transcript body is omitted — use `agent-applications-sessions-retrieve` for that. Filters: `state` (comma-separated for multiple, e.g. `completed,failed`), `revision_id` (UUID), `created_after` / `created_before` (ISO datetimes). Paging via `limit` (default 100, capped at 500) + `offset`. Filters AND together. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.","category": "Agent stack","feature": "agent_platform","summary": "List sessions for an agent",@@ -727,7 +727,7 @@"feature_flag": "agent-platform"},"agent-applications-sessions-retrieve": {- "description": "Full `AgentSession` row: state, principal, conversation (user / assistant / toolResult messages), pending_inputs, retry_count, timestamps. Always includes a `usage_total` block (tokens + cost) aggregated over the entire session. Pass `last_n=<int>` to trim the response to the most recent N messages — useful for long sessions where you only care about the tail; `conversation_trimmed: true` plus `conversation_total_turns` tells you how much was hidden, and `usage_total` is still computed over the full untrimmed conversation so cost reporting stays accurate.",+ "description": "Full `AgentSession` row: state, principal, conversation (user / assistant / toolResult messages), pending_inputs, retry_count, timestamps. Always includes a `usage_total` block (tokens + cost) aggregated over the entire session. Pass `last_n=<int>` to trim the response to the most recent N messages — useful for long sessions where you only care about the tail; `conversation_trimmed: true` plus `conversation_total_turns` tells you how much was hidden, and `usage_total` is still computed over the full untrimmed conversation so cost reporting stays accurate. Playbook: read the `debugging-sessions` playbook via `agent-resolve-resource` for the failure taxonomy and how to read the logs.","category": "Agent stack","feature": "agent_platform","summary": "Get one session",@@ -758,7 +758,7 @@}},"agent-native-tools-list": {- "description": "Read-only catalog of every `@posthog/*` native tool an agent can wire into `spec.tools`. Each entry includes the id, description, args schema (TypeBox-shaped), required integrations + scopes, and a cost hint (`cheap` / `medium` / `expensive`). Authoring flows use this to validate tool ids before writing them into a revision's spec.",+ "description": "Read-only catalog of every `@posthog/*` native tool an agent can wire into `spec.tools`. Each entry includes the id, description, args schema (TypeBox-shaped), required integrations + scopes, and a cost hint (`cheap` / `medium` / `expensive`). Authoring flows use this to validate tool ids before writing them into a revision's spec. Playbook: read the `authoring-new-agents` playbook via `agent-resolve-resource` for the end-to-end authoring flow.","category": "Agent stack","feature": "agent_platform","summary": "List native tools the runner knows",@@ -772,6 +772,20 @@},"feature_flag": "agent-platform"},+ "agent-resolve-resource": {+ "description": "Fetch an operator playbook — a markdown guide for doing a class of agent-platform operations well. These are the same skills the agent concierge loads; resolve the relevant one BEFORE a non-trivial operation (editing/promoting a revision, wiring secrets, authoring an agent, debugging a session). Many `agent-applications-*` tool descriptions name the playbook to read first. Pass either a bare id or its `posthog://agent-platform/playbooks/<id>` URI — the `resource` parameter enumerates the available playbooks. Returns `{ id, uri, title, content }` where `content` is the full markdown.",+ "category": "Agent stack",+ "feature": "agent_platform",+ "summary": "Fetch an agent-platform operator playbook (markdown).",+ "title": "Resolve an agent operator playbook",+ "required_scopes": ["agents:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": false,+ "readOnlyHint": true+ }+ },"alert-create": {"description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds — at least one of lower or upper is required (omit detector_config). For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nNote: subscribed_users only controls email recipients. For Slack, HTTPS webhook, or Discord delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.","category": "Alerts",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex fefa326cfa27..341a08e3659e 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -29,6 +29,20 @@"readOnlyHint": true}},+ "agent-resolve-resource": {+ "description": "Fetch an operator playbook — a markdown guide for doing a class of agent-platform operations well. These are the same skills the agent concierge loads; resolve the relevant one BEFORE a non-trivial operation (editing/promoting a revision, wiring secrets, authoring an agent, debugging a session). Many `agent-applications-*` tool descriptions name the playbook to read first. Pass either a bare id or its `posthog://agent-platform/playbooks/<id>` URI — the `resource` parameter enumerates the available playbooks. Returns `{ id, uri, title, content }` where `content` is the full markdown.",+ "category": "Agent stack",+ "feature": "agent_platform",+ "summary": "Fetch an agent-platform operator playbook (markdown).",+ "title": "Resolve an agent operator playbook",+ "required_scopes": ["agents:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": false,+ "readOnlyHint": true+ }+ },"experiment-results-get": {"description": "Get experiment metric results and exposure data in one call. Each row in `metrics.primary.results` and `metrics.secondary.results` carries a self-describing `metric` summary: `uuid`, `name` (the label users see in the experiment UI), `metric_type`, `goal`, and `source` — `inline` for metrics defined on the experiment, `shared` for metrics attached via a saved metric. For `shared` rows, `saved_metric_id` and `saved_metric_name` identify the underlying saved metric; both are `null` for `inline` rows. Rows are ordered to match the experiment UI (`primary_metrics_ordered_uuids` / `secondary_metrics_ordered_uuids`). A row whose underlying metric query failed is kept with `data: null` so positions stay aligned with the ordered UUIDs — check `data === null` to detect failures. The raw source surfaces (`experiment.metrics`, `experiment.metrics_secondary`, `experiment.saved_metrics`) are preserved on the response for callers who want to audit them, but you do not need to reconcile them yourself — the result rows already merge inline and shared. UI-only bulk fields are stripped from each `data` payload: `clickhouse_sql`, `hogql`, the legacy `insight` visualization payload, and the per-funnel-step session samples — `step_sessions` is removed from `baseline`, each `variant_results` entry, and from `baseline` / `variants[]` inside every `breakdown_results` entry. Statistical fields (`sum`, `sum_squares`, `step_counts`, `number_of_samples`, `credible_intervals`, per-breakdown stats, etc.) are preserved. Only works with new experiments (not legacy `ExperimentTrendsQuery` / `ExperimentFunnelsQuery`).","category": "Experiments",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 6f416dd36d4f..a9ec196ae4b5 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -15,6 +15,16 @@},"required": ["projectId"]},+ "AgentResolveResourceSchema": {+ "type": "object",+ "properties": {+ "resource": {+ "type": "string",+ "description": "Which operator playbook to fetch. Accepts either a bare id (one of: auditing-the-fleet, authoring-new-agents, choosing-the-model, cost-and-quota-analysis, debugging-sessions, designing-mcp-surfaces, editing-agents-safely, platform-mental-model, querying-ai-observability, reading-an-agent, running-and-evaluating-tests, safety-and-boundaries, secrets-and-integrations, setting-up-slack-app, using-the-console-ui, working-outside-the-console) or its URI form (`posthog://agent-platform/playbooks/<id>`). A playbook is a markdown guide for doing a class of agent-platform operations well — the same skills the agent concierge uses."+ }+ },+ "required": ["resource"]+ },"BusinessKnowledgeUrlSourceCreateSchema": {"type": "object","properties": {diff --git a/services/mcp/scripts/build-cli-release.ts b/services/mcp/scripts/build-cli-release.tsindex 3068e2f4e0c8..6a41a25dbf1e 100644--- a/services/mcp/scripts/build-cli-release.ts+++ b/services/mcp/scripts/build-cli-release.ts@@ -3,6 +3,7 @@ import { mkdir } from 'node:fs/promises'import { dirname, resolve } from 'node:path'import { fileURLToPath } from 'node:url'+import { copyInstructions } from './copy-instructions'import { cliEsbuildOptions } from './hono-esbuild-config'const scriptDir = dirname(fileURLToPath(import.meta.url))@@ -14,6 +15,9 @@ process.chdir(mcpRoot)async function main(): Promise<void> {await mkdir(dirname(releaseOutfile), { recursive: true })+ // Populate the gitignored `shared/` tree (playbooks + guidelines) so esbuild+ // can inline it via `@shared/*`. Mirrors build-hono.ts.+ copyInstructions()await build(cliEsbuildOptions({outfile: releaseOutfile,diff --git a/services/mcp/scripts/build-cli.ts b/services/mcp/scripts/build-cli.tsindex 00eb4512d44d..e13b388c3982 100644--- a/services/mcp/scripts/build-cli.ts+++ b/services/mcp/scripts/build-cli.ts@@ -1,7 +1,12 @@import { build } from 'esbuild'+import { copyInstructions } from './copy-instructions'import { cliEsbuildOptions, cliOutfile } from './hono-esbuild-config'+// Populate the gitignored `shared/` tree (playbooks + guidelines) so esbuild+// can inline it via `@shared/*`. Mirrors build-hono.ts.+copyInstructions()+build(cliEsbuildOptions()).then(() => {console.info(`Built PostHog API CLI -> ${cliOutfile}`)diff --git a/services/mcp/scripts/copy-instructions.ts b/services/mcp/scripts/copy-instructions.tsindex 8bae179c2d26..7ba9d183966d 100644--- a/services/mcp/scripts/copy-instructions.ts+++ b/services/mcp/scripts/copy-instructions.ts@@ -1,22 +1,103 @@#!/usr/bin/env tsx/*** Copies shared prompt files into `shared/` (gitignored) so esbuild can inline- * them via the `@shared/*` tsconfig alias at bundle time. Called from+ * them via the `@shared/*` tsconfig alias at bundle time, and regenerates the+ * agent-platform playbook manifest from the concierge skills dir. Called from* build-hono.ts / dev-hono.ts before bundling, and standalone in CI.*/-import { cpSync, mkdirSync, rmSync } from 'fs'-import { dirname, resolve } from 'path'+import { cpSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs'+import { dirname, join, resolve } from 'path'const ROOT_DIR = resolve(__dirname, '..')const REPO_ROOT = resolve(ROOT_DIR, '../..')+// Single source of truth for the operator playbooks: the agent concierge+// bundle's skills, one `<id>/SKILL.md` per skill.+const SKILLS_DIR = resolve(+ REPO_ROOT,+ 'products/agent_platform/services/agent-tests/src/examples/agent-concierge/skills'+)+const PROMPTS = [{src: 'products/posthog_ai/skills/querying-posthog-data/references/guidelines.md',dest: 'shared/guidelines.md',},+ {+ // Operator playbooks embedded so the `agent-resolve-resource` tool can+ // serve them. Copied from the concierge skills dir (the files the+ // concierge itself loads); the manifest below is generated from the same.+ src: 'products/agent_platform/services/agent-tests/src/examples/agent-concierge/skills',+ dest: 'shared/playbooks',+ },]+/** `auditing-the-fleet` → `auditingTheFleet` (valid JS identifier). */+function camelCase(id: string): string {+ return id.replace(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase())+}++/** `auditing-the-fleet` → `Auditing the fleet`. */+function titleCase(id: string): string {+ const spaced = id.replace(/-/g, ' ')+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)+}++/** Skill ids = subdirs of SKILLS_DIR that contain a SKILL.md, sorted for determinism. */+function discoverPlaybookIds(): string[] {+ return readdirSync(SKILLS_DIR, { withFileTypes: true })+ .filter((e) => e.isDirectory())+ .map((e) => e.name)+ .sort()+}++// Write only if changed so dev watch rebuilds don't churn the git tree.+function writeIfChanged(path: string, content: string): void {+ let existing: string | undefined+ try {+ existing = readFileSync(path, 'utf-8')+ } catch {+ existing = undefined+ }+ if (existing !== content) {+ writeFileSync(path, content)+ }+}++const GEN_HEADER =+ '// AUTO-GENERATED by scripts/copy-instructions.ts from the agent concierge skills dir\n' ++ '// (products/agent_platform/services/agent-tests/src/examples/agent-concierge/skills/<id>/SKILL.md).\n' ++ '// Do not edit by hand — run `tsx services/mcp/scripts/copy-instructions.ts`.\n'++/**+ * Regenerate the playbook manifest (ids + titles) and content (the embedded+ * SKILL.md bodies) from whatever skills exist, so adding/renaming/relayouting a+ * concierge skill needs no hand edits here.+ */+export function generatePlaybookManifest(): void {+ const ids = discoverPlaybookIds()+ const agentPlatformDir = resolve(ROOT_DIR, 'src/tools/agentPlatform')++ const manifest =+ `${GEN_HEADER}export const PLAYBOOK_IDS = [\n` ++ ids.map((id) => ` '${id}',`).join('\n') ++ `\n] as const\n\n` ++ `export type PlaybookId = (typeof PLAYBOOK_IDS)[number]\n\n` ++ `export const PLAYBOOK_TITLES: Record<PlaybookId, string> = {\n` ++ ids.map((id) => ` '${id}': '${titleCase(id)}',`).join('\n') ++ `\n}\n`+ writeIfChanged(join(agentPlatformDir, 'playbookManifest.generated.ts'), manifest)++ const content =+ GEN_HEADER ++ ids.map((id) => `import ${camelCase(id)} from '@shared/playbooks/${id}/SKILL.md'`).join('\n') ++ `\n\nimport type { PlaybookId } from './playbookManifest.generated'\n\n` ++ `export const PLAYBOOK_CONTENT: Record<PlaybookId, string> = {\n` ++ ids.map((id) => ` '${id}': ${camelCase(id)},`).join('\n') ++ `\n}\n`+ writeIfChanged(join(agentPlatformDir, 'playbookContent.generated.ts'), content)+}+export function copyInstructions(): void {for (const prompt of PROMPTS) {const src = resolve(REPO_ROOT, prompt.src)@@ -28,6 +109,7 @@ export function copyInstructions(): void {rmSync(dest, { force: true, recursive: true })cpSync(src, dest, { recursive: true, force: true })}+ generatePlaybookManifest()}// Standalone execution: `tsx scripts/copy-instructions.ts` (used in CI).diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7beefdcd03ca..3173ce4b302c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8262,6 +8262,7 @@ export namespace Schemas {/** @nullable */parent_revision?: string | null;readonly state: AgentRevisionStateEnum;+ /** Storage-prefix metadata for the bundle, e.g. `fs://my-agent/`. Optional — leave blank and the server fills `fs://<application-slug>/`. Bundles are addressed by revision id regardless, so this is only a prefix hint. */bundle_uri?: string;/** @nullable */readonly bundle_sha256: string | null;@@ -33266,6 +33267,7 @@ export namespace Schemas {/** @nullable */parent_revision?: string | null;readonly state?: AgentRevisionStateEnum;+ /** Storage-prefix metadata for the bundle, e.g. `fs://my-agent/`. Optional — leave blank and the server fills `fs://<application-slug>/`. Bundles are addressed by revision id regardless, so this is only a prefix hint. */bundle_uri?: string;/** @nullable */readonly bundle_sha256?: string | null;@@ -39704,6 +39706,24 @@ export namespace Schemas {is_preview_link: boolean;}+ /**+ * Body forwarded verbatim to the agent ingress for a *preview* invoke of a+ * non-live revision. The meaningful shape depends on the `rest` path segment:+ *+ * - `run` — `{ message }`: the user message that starts a new session.+ * - `send` — `{ session_id, message }`: append a message to a running session.+ * - `cancel` / `listen` — no body.+ *+ * Documents `message` / `session_id` so the generated MCP tool exposes them;+ * any extra keys are still forwarded as-is to ingress.+ */+ export interface PreviewProxyInvokeRequest {+ /** User message to deliver to the agent. Required for `run` (starts the session) and `send` (appends to it); ignored for `cancel` / `listen`. */+ message?: string;+ /** Target session id for `send` — the running session to append the message to. Omit for `run` (a fresh session is created). */+ session_id?: string;+ }+/*** Mapping from event name to the team-configured primary property for that event. Names without a configured primary property are omitted; callers should fall back to the core taxonomy defaults for those.*/diff --git a/services/mcp/src/generated/agent_platform/api.ts b/services/mcp/src/generated/agent_platform/api.tsindex 2453d0fb90cd..43a98cccf31c 100644--- a/services/mcp/src/generated/agent_platform/api.ts+++ b/services/mcp/src/generated/agent_platform/api.ts@@ -263,7 +263,12 @@ export const agentApplicationsRevisionsCreateBodySpecResumeMaxCompletedAgeMsMaxexport const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({parent_revision: zod.uuid().nullish(),- bundle_uri: zod.string().default(agentApplicationsRevisionsCreateBodyBundleUriDefault),+ bundle_uri: zod+ .string()+ .default(agentApplicationsRevisionsCreateBodyBundleUriDefault)+ .describe(+ 'Storage-prefix metadata for the bundle, e.g. `fs://my-agent/`. Optional — leave blank and the server fills `fs://<application-slug>/`. Bundles are addressed by revision id regardless, so this is only a prefix hint.'+ ),spec: zod.object({model: zod.string().min(1),@@ -910,7 +915,12 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecResumeMaxCompletedAgexport const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.object({parent_revision: zod.uuid().nullish(),- bundle_uri: zod.string().optional(),+ bundle_uri: zod+ .string()+ .optional()+ .describe(+ 'Storage-prefix metadata for the bundle, e.g. `fs://my-agent/`. Optional — leave blank and the server fills `fs://<application-slug>/`. Bundles are addressed by revision id regardless, so this is only a prefix hint.'+ ),spec: zod.object({model: zod.string().min(1),@@ -2082,7 +2092,8 @@ export const AgentApplicationsEnvKeysClearParams = /* @__PURE__ */ zod.object({* this proxy attaches it after authenticating the Django caller.** URL: `/api/projects/<team>/agent_applications/<app>/preview-proxy/<rest>`- * Auth: standard PAT / session — `agents:read` scope.+ * Auth: standard PAT / session — `agents:write` scope (POST run/send/cancel+ * is a mutating invoke; the read-only `listen` GET is `agents:read`).*/export const AgentApplicationsPreviewProxyParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this agent application.'),@@ -2099,6 +2110,25 @@ export const AgentApplicationsPreviewProxyQueryParams = /* @__PURE__ */ zod.objerevision_id: zod.string().describe('Target draft revision. Must belong to this application and not be live.'),})+export const AgentApplicationsPreviewProxyBody = /* @__PURE__ */ zod+ .object({+ message: zod+ .string()+ .optional()+ .describe(+ 'User message to deliver to the agent. Required for `run` (starts the session) and `send` (appends to it); ignored for `cancel` / `listen`.'+ ),+ session_id: zod+ .string()+ .optional()+ .describe(+ 'Target session id for `send` — the running session to append the message to. Omit for `run` (a fresh session is created).'+ ),+ })+ .describe(+ 'Body forwarded verbatim to the agent ingress for a *preview* invoke of a\nnon-live revision. The meaningful shape depends on the `rest` path segment:\n\n- `run` — `{ message }`: the user message that starts a new session.\n- `send` — `{ session_id, message }`: append a message to a running session.\n- `cancel` / `listen` — no body.\n\nDocuments `message` / `session_id` so the generated MCP tool exposes them;\nany extra keys are still forwarded as-is to ingress.'+ )+/*** List sessions for this application, newest first. Strips the* conversation transcript from each summary, but includes a `preview`diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 63f72e30e324..9ccf457e9123 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -1,5 +1,9 @@import { z } from 'zod'+// Relative (not `@/`) import: this module is loaded by the tsx schema-generation+// script, and `playbookIds` is pure constants — no `.md` imports to choke on.+import { PLAYBOOK_IDS, PLAYBOOK_URI_PREFIX } from '../tools/agentPlatform/playbookIds'+export const BusinessKnowledgeUrlSourceCreateSchema = z.object({name: z.string()@@ -14,6 +18,14 @@ export const BusinessKnowledgeUrlSourceCreateSchema = z.object({.describe('How often to auto-refresh this source in the background. Defaults to "manual" (no auto-refresh).'),})+export const AgentResolveResourceSchema = z.object({+ resource: z+ .string()+ .describe(+ `Which operator playbook to fetch. Accepts either a bare id (one of: ${PLAYBOOK_IDS.join(', ')}) or its URI form (\`${PLAYBOOK_URI_PREFIX}<id>\`). A playbook is a markdown guide for doing a class of agent-platform operations well — the same skills the agent concierge uses.`+ ),+})+export const ExternalDataJobsAfterSchema = z.string().describe('ISO timestamp — only return jobs created after this date (e.g. "2025-01-01T00:00:00Z").')diff --git a/services/mcp/src/tools/agentPlatform/playbookContent.generated.ts b/services/mcp/src/tools/agentPlatform/playbookContent.generated.tsnew file mode 100644index 000000000000..e8324978b27b--- /dev/null+++ b/services/mcp/src/tools/agentPlatform/playbookContent.generated.ts@@ -0,0 +1,40 @@+// AUTO-GENERATED by scripts/copy-instructions.ts from the agent concierge skills dir+// (products/agent_platform/services/agent-tests/src/examples/agent-concierge/skills/<id>/SKILL.md).+// Do not edit by hand — run `tsx services/mcp/scripts/copy-instructions.ts`.+import auditingTheFleet from '@shared/playbooks/auditing-the-fleet/SKILL.md'+import authoringNewAgents from '@shared/playbooks/authoring-new-agents/SKILL.md'+import choosingTheModel from '@shared/playbooks/choosing-the-model/SKILL.md'+import costAndQuotaAnalysis from '@shared/playbooks/cost-and-quota-analysis/SKILL.md'+import debuggingSessions from '@shared/playbooks/debugging-sessions/SKILL.md'+import designingMcpSurfaces from '@shared/playbooks/designing-mcp-surfaces/SKILL.md'+import editingAgentsSafely from '@shared/playbooks/editing-agents-safely/SKILL.md'+import platformMentalModel from '@shared/playbooks/platform-mental-model/SKILL.md'+import queryingAiObservability from '@shared/playbooks/querying-ai-observability/SKILL.md'+import readingAnAgent from '@shared/playbooks/reading-an-agent/SKILL.md'+import runningAndEvaluatingTests from '@shared/playbooks/running-and-evaluating-tests/SKILL.md'+import safetyAndBoundaries from '@shared/playbooks/safety-and-boundaries/SKILL.md'+import secretsAndIntegrations from '@shared/playbooks/secrets-and-integrations/SKILL.md'+import settingUpSlackApp from '@shared/playbooks/setting-up-slack-app/SKILL.md'+import usingTheConsoleUi from '@shared/playbooks/using-the-console-ui/SKILL.md'+import workingOutsideTheConsole from '@shared/playbooks/working-outside-the-console/SKILL.md'++import type { PlaybookId } from './playbookManifest.generated'++export const PLAYBOOK_CONTENT: Record<PlaybookId, string> = {+ 'auditing-the-fleet': auditingTheFleet,+ 'authoring-new-agents': authoringNewAgents,+ 'choosing-the-model': choosingTheModel,+ 'cost-and-quota-analysis': costAndQuotaAnalysis,+ 'debugging-sessions': debuggingSessions,+ 'designing-mcp-surfaces': designingMcpSurfaces,+ 'editing-agents-safely': editingAgentsSafely,+ 'platform-mental-model': platformMentalModel,+ 'querying-ai-observability': queryingAiObservability,+ 'reading-an-agent': readingAnAgent,+ 'running-and-evaluating-tests': runningAndEvaluatingTests,+ 'safety-and-boundaries': safetyAndBoundaries,+ 'secrets-and-integrations': secretsAndIntegrations,+ 'setting-up-slack-app': settingUpSlackApp,+ 'using-the-console-ui': usingTheConsoleUi,+ 'working-outside-the-console': workingOutsideTheConsole,+}diff --git a/services/mcp/src/tools/agentPlatform/playbookIds.ts b/services/mcp/src/tools/agentPlatform/playbookIds.tsnew file mode 100644index 000000000000..ecbf0da0e7ae--- /dev/null+++ b/services/mcp/src/tools/agentPlatform/playbookIds.ts@@ -0,0 +1,26 @@+// Playbook ids + titles are generated from the concierge skills dir — see+// playbookManifest.generated.ts (regenerated by scripts/copy-instructions.ts).+// This module re-exports them and adds the fixed URI scheme. It stays free of+// `.md` imports so it's safe to load from the tsx schema-generation script via+// src/schema/tool-inputs.ts.+import { type PlaybookId, PLAYBOOK_IDS, PLAYBOOK_TITLES } from './playbookManifest.generated'++export { type PlaybookId, PLAYBOOK_IDS, PLAYBOOK_TITLES }++// Fixed URI scheme, declared once. The resolver tool accepts a playbook by a+// bare id or by its `<PLAYBOOK_URI_PREFIX><id>` URI form; the schema describe and+// the resolver both derive from this constant.+export const PLAYBOOK_URI_PREFIX = 'posthog://agent-platform/playbooks/'++export const playbookUri = (id: PlaybookId): string => `${PLAYBOOK_URI_PREFIX}${id}`++export const PLAYBOOK_URIS: readonly string[] = PLAYBOOK_IDS.map(playbookUri)++/**+ * Normalize a caller-supplied reference (bare id or full `<PLAYBOOK_URI_PREFIX><id>`+ * URI) to a known PlaybookId, or `undefined` if it matches no playbook.+ */+export function playbookIdFromRef(ref: string): PlaybookId | undefined {+ const candidate = ref.startsWith(PLAYBOOK_URI_PREFIX) ? ref.slice(PLAYBOOK_URI_PREFIX.length) : ref+ return (PLAYBOOK_IDS as readonly string[]).includes(candidate) ? (candidate as PlaybookId) : undefined+}diff --git a/services/mcp/src/tools/agentPlatform/playbookManifest.generated.ts b/services/mcp/src/tools/agentPlatform/playbookManifest.generated.tsnew file mode 100644index 000000000000..e0770eb92774--- /dev/null+++ b/services/mcp/src/tools/agentPlatform/playbookManifest.generated.ts@@ -0,0 +1,42 @@+// AUTO-GENERATED by scripts/copy-instructions.ts from the agent concierge skills dir+// (products/agent_platform/services/agent-tests/src/examples/agent-concierge/skills/<id>/SKILL.md).+// Do not edit by hand — run `tsx services/mcp/scripts/copy-instructions.ts`.+export const PLAYBOOK_IDS = [+ 'auditing-the-fleet',+ 'authoring-new-agents',+ 'choosing-the-model',+ 'cost-and-quota-analysis',+ 'debugging-sessions',+ 'designing-mcp-surfaces',+ 'editing-agents-safely',+ 'platform-mental-model',+ 'querying-ai-observability',+ 'reading-an-agent',+ 'running-and-evaluating-tests',+ 'safety-and-boundaries',+ 'secrets-and-integrations',+ 'setting-up-slack-app',+ 'using-the-console-ui',+ 'working-outside-the-console',+] as const++export type PlaybookId = (typeof PLAYBOOK_IDS)[number]++export const PLAYBOOK_TITLES: Record<PlaybookId, string> = {+ 'auditing-the-fleet': 'Auditing the fleet',+ 'authoring-new-agents': 'Authoring new agents',+ 'choosing-the-model': 'Choosing the model',+ 'cost-and-quota-analysis': 'Cost and quota analysis',+ 'debugging-sessions': 'Debugging sessions',+ 'designing-mcp-surfaces': 'Designing mcp surfaces',+ 'editing-agents-safely': 'Editing agents safely',+ 'platform-mental-model': 'Platform mental model',+ 'querying-ai-observability': 'Querying ai observability',+ 'reading-an-agent': 'Reading an agent',+ 'running-and-evaluating-tests': 'Running and evaluating tests',+ 'safety-and-boundaries': 'Safety and boundaries',+ 'secrets-and-integrations': 'Secrets and integrations',+ 'setting-up-slack-app': 'Setting up slack app',+ 'using-the-console-ui': 'Using the console ui',+ 'working-outside-the-console': 'Working outside the console',+}diff --git a/services/mcp/src/tools/agentPlatform/playbookTools.ts b/services/mcp/src/tools/agentPlatform/playbookTools.tsnew file mode 100644index 000000000000..518cd7ea6cdc--- /dev/null+++ b/services/mcp/src/tools/agentPlatform/playbookTools.ts@@ -0,0 +1,135 @@+import { hasScope } from '@/lib/api'+import { getToolDefinitions, type ToolDefinitions } from '@/tools/toolDefinitions'++import type { PlaybookId } from './playbookIds'++// Representative MCP tools for executing each playbook. Curated (not derived from+// the per-tool description pointers, which map each tool to a single playbook —+// here a tool can legitimately appear under several). Only playbooks with tools+// are listed; the rest default to []. A vitest drift guard asserts every name+// resolves to a real tool definition; names absent from the running surface are+// skipped silently at render time.+export const PLAYBOOK_TOOLS: Partial<Record<PlaybookId, readonly string[]>> = {+ 'reading-an-agent': [+ 'agent-applications-list',+ 'agent-applications-retrieve',+ 'agent-applications-revisions-list',+ 'agent-applications-revisions-retrieve',+ 'agent-applications-revisions-manifest-retrieve',+ 'agent-applications-revisions-bundle-retrieve',+ 'agent-applications-revisions-system-prompt',+ 'agent-applications-sessions-list',+ 'agent-applications-sessions-retrieve',+ ],+ 'debugging-sessions': [+ 'agent-applications-sessions-list',+ 'agent-applications-sessions-retrieve',+ 'agent-applications-revisions-system-prompt',+ 'agent-applications-revisions-cron-fire-create',+ ],+ 'editing-agents-safely': [+ 'agent-applications-revisions-new-draft-create',+ 'agent-applications-revisions-clone-from-create',+ 'agent-applications-revisions-agent-md-update',+ 'agent-applications-revisions-spec-update',+ 'agent-applications-revisions-skills-update',+ 'agent-applications-revisions-skills-destroy',+ 'agent-applications-revisions-tools-update',+ 'agent-applications-revisions-tools-destroy',+ 'agent-applications-revisions-bundle-update',+ 'agent-applications-revisions-partial-update',+ 'agent-applications-revisions-validate-create',+ 'agent-applications-revisions-freeze-create',+ 'agent-applications-revisions-promote-create',+ 'agent-applications-revisions-archive-create',+ ],+ 'authoring-new-agents': [+ 'agent-applications-create',+ 'agent-native-tools-list',+ // The no-source first-revision creator — the one agents keep failing to find.+ 'agent-applications-revisions-create',+ 'agent-applications-revisions-partial-update',+ 'agent-applications-revisions-bundle-update',+ 'agent-applications-revisions-validate-create',+ 'agent-applications-revisions-freeze-create',+ 'agent-applications-revisions-promote-create',+ ],+ 'secrets-and-integrations': [+ 'agent-applications-env-keys-list',+ 'agent-applications-env-keys-get',+ 'agent-applications-env-keys-clear',+ ],+ 'designing-mcp-surfaces': ['agent-native-tools-list'],+}++export interface PlaybookToolRef {+ name: string+ title: string+ requiredScopes: string[]+ /** Required scopes the caller's credential is missing. Empty = callable now. */+ missingScopes: string[]+}++/**+ * Resolve a playbook's representative tools against the live catalog + the caller's+ * scopes. Tools not present in the running surface are dropped (the catalog is the+ * ground truth — this is exactly what stops agents guessing a tool doesn't exist).+ *+ * `defs` defaults to the live catalog; it's a parameter so the drop-absent+ * behaviour can be exercised against a partial catalog in tests.+ */+export function buildToolSurface(+ playbookId: PlaybookId,+ scopes: string[],+ defs: ToolDefinitions = getToolDefinitions()+): PlaybookToolRef[] {+ const refs: PlaybookToolRef[] = []+ for (const name of PLAYBOOK_TOOLS[playbookId] ?? []) {+ const def = defs[name]+ if (!def) {+ continue+ }+ const requiredScopes = def.required_scopes ?? []+ const missingScopes = requiredScopes.filter((scope) => !hasScope(scopes, scope))+ refs.push({ name, title: def.title, requiredScopes, missingScopes })+ }+ return refs+}++/**+ * Render the tool surface as a markdown appendix. When `scopesKnown` is true the+ * tools are split into callable-now vs scope-gated (with the missing scope named);+ * otherwise they're listed flat with their required scopes.+ */+export function renderToolSurface(refs: PlaybookToolRef[], scopesKnown: boolean): string {+ if (refs.length === 0) {+ return ''+ }+ if (!scopesKnown) {+ const lines = ['## Tools for this playbook', '']+ for (const ref of refs) {+ const scopeNote = ref.requiredScopes.length ? ` (requires: ${ref.requiredScopes.join(', ')})` : ''+ lines.push(`- \`${ref.name}\` — ${ref.title}${scopeNote}`)+ }+ return lines.join('\n')+ }++ const callable = refs.filter((r) => r.missingScopes.length === 0)+ const gated = refs.filter((r) => r.missingScopes.length > 0)+ const lines = ['## Tools for this playbook (live)', '']+ if (callable.length) {+ lines.push('Callable with your current credential:')+ for (const ref of callable) {+ lines.push(`- \`${ref.name}\` — ${ref.title}`)+ }+ lines.push('')+ }+ if (gated.length) {+ lines.push('Present but NOT callable with your credential — add the scope, do not work around:')+ for (const ref of gated) {+ lines.push(`- \`${ref.name}\` — ${ref.title} (needs: ${ref.missingScopes.join(', ')})`)+ }+ lines.push('')+ }+ return lines.join('\n').trimEnd()+}diff --git a/services/mcp/src/tools/agentPlatform/playbooks.ts b/services/mcp/src/tools/agentPlatform/playbooks.tsnew file mode 100644index 000000000000..aa338497c4bd--- /dev/null+++ b/services/mcp/src/tools/agentPlatform/playbooks.ts@@ -0,0 +1,15 @@+import { PLAYBOOK_CONTENT } from './playbookContent.generated'+// Embedded operator playbooks. Ids/titles come from playbookManifest.generated.ts+// and the markdown bodies from playbookContent.generated.ts — both regenerated+// from the concierge skills dir by scripts/copy-instructions.ts.+import { type PlaybookId, PLAYBOOK_IDS, PLAYBOOK_TITLES } from './playbookIds'++export interface Playbook {+ id: PlaybookId+ title: string+ content: string+}++export const PLAYBOOKS: Record<PlaybookId, Playbook> = Object.fromEntries(+ PLAYBOOK_IDS.map((id) => [id, { id, title: PLAYBOOK_TITLES[id], content: PLAYBOOK_CONTENT[id] }])+) as Record<PlaybookId, Playbook>diff --git a/services/mcp/src/tools/agentPlatform/resolveResource.ts b/services/mcp/src/tools/agentPlatform/resolveResource.tsnew file mode 100644index 000000000000..ae9ec9154dcf--- /dev/null+++ b/services/mcp/src/tools/agentPlatform/resolveResource.ts@@ -0,0 +1,69 @@+import type { z } from 'zod'++import { AgentResolveResourceSchema } from '@/schema/tool-inputs'+import { playbookIdFromRef, playbookUri } from '@/tools/agentPlatform/playbookIds'+import { PLAYBOOKS } from '@/tools/agentPlatform/playbooks'+import { buildToolSurface, renderToolSurface } from '@/tools/agentPlatform/playbookTools'+import type { Context, ToolBase } from '@/tools/types'++const schema = AgentResolveResourceSchema++type Params = z.infer<typeof schema>++type Result = {+ id: string+ uri: string+ title: string+ content: string+ /** Representative tools for this playbook that exist in the live surface, split by callability. */+ tools: { callable: string[]; gated: string[] }+}++export const resolveResourceHandler: ToolBase<typeof schema, Result>['handler'] = async (+ context: Context,+ params: Params+) => {+ // Accept either a bare id or the full resource URI (`PLAYBOOK_URI_PREFIX` + id).+ const id = playbookIdFromRef(params.resource)+ const playbook = id ? PLAYBOOKS[id] : undefined+ if (!playbook?.content) {+ throw new Error(+ `Unknown playbook "${params.resource}". Pass an id (${Object.keys(PLAYBOOKS).join(', ')}) or its URI (${playbookUri(+ Object.keys(PLAYBOOKS)[0] as keyof typeof PLAYBOOKS+ )}).`+ )+ }++ // Append a live tool surface computed against the caller's actual scopes, so the+ // agent reads ground-truth tool names (not stale prose) and sees exactly which+ // are scope-gated — the two things agents keep getting wrong. Best-effort:+ // a missing/erroring key just renders the flat list with required scopes.+ let scopes: string[] | undefined+ try {+ scopes = (await context.stateManager.getApiKey()).scopes+ } catch {+ scopes = undefined+ }+ const refs = buildToolSurface(playbook.id, scopes ?? [])+ const appendix = renderToolSurface(refs, scopes !== undefined)+ const content = appendix ? `${playbook.content.trimEnd()}\n\n${appendix}\n` : playbook.content++ return {+ id: playbook.id,+ uri: playbookUri(playbook.id),+ title: playbook.title,+ content,+ tools: {+ callable: refs.filter((r) => r.missingScopes.length === 0).map((r) => r.name),+ gated: refs.filter((r) => r.missingScopes.length > 0).map((r) => r.name),+ },+ }+}++const tool = (): ToolBase<typeof schema, Result> => ({+ name: 'agent-resolve-resource',+ schema,+ handler: resolveResourceHandler,+})++export default tooldiff --git a/services/mcp/src/tools/generated/agent_platform.ts b/services/mcp/src/tools/generated/agent_platform.tsindex 63c9a2a5a689..28a32b726ef4 100644--- a/services/mcp/src/tools/generated/agent_platform.ts+++ b/services/mcp/src/tools/generated/agent_platform.ts@@ -11,6 +11,7 @@ import {AgentApplicationsListQueryParams,AgentApplicationsPartialUpdateBody,AgentApplicationsPartialUpdateParams,+ AgentApplicationsPreviewProxyBody,AgentApplicationsPreviewProxyParams,AgentApplicationsPreviewProxyQueryParams,AgentApplicationsRetrieveParams,@@ -205,21 +206,26 @@ const agentApplicationsPartialUpdate = (): ToolBase<},})-const AgentApplicationsPreviewProxySchema = AgentApplicationsPreviewProxyParams.omit({ project_id: true }).extend(- AgentApplicationsPreviewProxyQueryParams.omit({ format: true }).shape-)+const AgentApplicationsPreviewProxySchema = AgentApplicationsPreviewProxyParams.omit({ project_id: true })+ .extend(AgentApplicationsPreviewProxyQueryParams.omit({ format: true }).shape)+ .extend(AgentApplicationsPreviewProxyBody.shape)-const agentApplicationsPreviewProxy = (): ToolBase<- typeof AgentApplicationsPreviewProxySchema,- Schemas.AgentApplication-> => ({+const agentApplicationsPreviewProxy = (): ToolBase<typeof AgentApplicationsPreviewProxySchema, unknown> => ({name: 'agent-applications-preview-proxy',schema: AgentApplicationsPreviewProxySchema,handler: async (context: Context, params: z.infer<typeof AgentApplicationsPreviewProxySchema>) => {const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.AgentApplication>({+ const body: Record<string, unknown> = {}+ if (params.message !== undefined) {+ body['message'] = params.message+ }+ if (params.session_id !== undefined) {+ body['session_id'] = params.session_id+ }+ const result = await context.api.request<unknown>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.id))}/preview-proxy/${encodeURIComponent(String(params.rest))}/`,+ body,query: {revision_id: params.revision_id,},diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex a1fa8557c4ea..59faaa917e11 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -1,5 +1,7 @@import { hasScopes } from '@/lib/api'+// Agent platform (hand-written — CRUD is codegen in generated/agent_platform.ts)+import resolveResource from './agentPlatform/resolveResource'// AI observabilityimport getLLMCosts from './aiObservability/getLLMCosts'// Debug@@ -83,6 +85,9 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {// Feedback'agent-feedback': submitFeedback,+ // Agent platform (read-only playbook resolver — CRUD lives in generated/agent_platform.ts)+ 'agent-resolve-resource': resolveResource,+// PostHog AI tools'execute-sql': executeSql,'read-data-schema': readDataSchema,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-preview-proxy.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-preview-proxy.jsonindex 820a155be082..e3f4ac382bb6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-preview-proxy.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-preview-proxy.json@@ -5,6 +5,10 @@"description": "A UUID string identifying this agent application.","type": "string"},+ "message": {+ "description": "User message to deliver to the agent. Required for `run` (starts the session) and `send` (appends to it); ignored for `cancel` / `listen`.",+ "type": "string"+ },"rest": {"description": "Ingress sub-path under the agent slug. One of: `run`, `send`, `cancel`, `listen`.","type": "string"@@ -12,6 +16,10 @@"revision_id": {"description": "Target draft revision. Must belong to this application and not be live.","type": "string"+ },+ "session_id": {+ "description": "Target session id for `send` — the running session to append the message to. Omit for `run` (a fresh session is created).",+ "type": "string"}},"required": ["id", "rest", "revision_id"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.jsonindex a6efdd81a160..342f83af40ec 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json@@ -6,6 +6,7 @@},"bundle_uri": {"default": "",+ "description": "Storage-prefix metadata for the bundle, e.g. `fs://my-agent/`. Optional — leave blank and the server fills `fs://<application-slug>/`. Bundles are addressed by revision id regardless, so this is only a prefix hint.","type": "string"},"parent_revision": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.jsonindex 3823f0c8da11..f85b9547fdd5 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json@@ -5,6 +5,7 @@"type": "string"},"bundle_uri": {+ "description": "Storage-prefix metadata for the bundle, e.g. `fs://my-agent/`. Optional — leave blank and the server fills `fs://<application-slug>/`. Bundles are addressed by revision id regardless, so this is only a prefix hint.","type": "string"},"id": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-resolve-resource.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-resolve-resource.jsonnew file mode 100644index 000000000000..b8d9ecf625d3--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-resolve-resource.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "resource": {+ "description": "Which operator playbook to fetch. Accepts either a bare id (one of: auditing-the-fleet, authoring-new-agents, choosing-the-model, cost-and-quota-analysis, debugging-sessions, designing-mcp-surfaces, editing-agents-safely, platform-mental-model, querying-ai-observability, reading-an-agent, running-and-evaluating-tests, safety-and-boundaries, secrets-and-integrations, setting-up-slack-app, using-the-console-ui, working-outside-the-console) or its URI form (`posthog://agent-platform/playbooks/<id>`). A playbook is a markdown guide for doing a class of agent-platform operations well — the same skills the agent concierge uses.",+ "type": "string"+ }+ },+ "required": ["resource"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/agent-resolve-resource.test.ts b/services/mcp/tests/unit/agent-resolve-resource.test.tsnew file mode 100644index 000000000000..a546f28700a2--- /dev/null+++ b/services/mcp/tests/unit/agent-resolve-resource.test.ts@@ -0,0 +1,143 @@+import { readdirSync } from 'node:fs'+import { resolve } from 'node:path'+import { describe, expect, it } from 'vitest'++import { AgentResolveResourceSchema } from '@/schema/tool-inputs'+import { PLAYBOOK_IDS, PLAYBOOK_URI_PREFIX, playbookUri } from '@/tools/agentPlatform/playbookIds'+import { PLAYBOOKS } from '@/tools/agentPlatform/playbooks'+import { buildToolSurface, PLAYBOOK_TOOLS } from '@/tools/agentPlatform/playbookTools'+import { resolveResourceHandler } from '@/tools/agentPlatform/resolveResource'+import { getToolDefinitions } from '@/tools/toolDefinitions'+import type { Context } from '@/tools/types'++// Canonical source: the agent concierge bundle's skills dir (one `<id>/SKILL.md`+// per skill). The build copies these into shared/playbooks/ (embedded) — both+// must stay in lockstep with PLAYBOOK_IDS.+const SKILLS_DIR = resolve(+ __dirname,+ '../../../../products/agent_platform/services/agent-tests/src/examples/agent-concierge/skills'+)++// Context whose api key carries the given scopes (drives the live tool surface).+const ctxWithScopes = (scopes: string[]): Context =>+ ({ stateManager: { getApiKey: async () => ({ scopes }) } }) as unknown as Context+// No stateManager → getApiKey throws → handler renders the flat (scope-unknown) surface.+const ctx = {} as Context++describe('agent-resolve-resource', () => {+ describe('AgentResolveResourceSchema', () => {+ it('accepts a bare playbook id', () => {+ expect(AgentResolveResourceSchema.safeParse({ resource: 'editing-agents-safely' }).success).toBe(true)+ })++ it('accepts a full resource URI', () => {+ const uri = `${PLAYBOOK_URI_PREFIX}editing-agents-safely`+ expect(AgentResolveResourceSchema.safeParse({ resource: uri }).success).toBe(true)+ })++ it('rejects a missing / non-string resource', () => {+ expect(AgentResolveResourceSchema.safeParse({}).success).toBe(false)+ expect(AgentResolveResourceSchema.safeParse({ resource: 5 }).success).toBe(false)+ })+ })++ describe('resolveResourceHandler', () => {+ it('returns id, uri, title and markdown content for a bare id', async () => {+ const result = await resolveResourceHandler(ctx, { resource: 'debugging-sessions' })+ expect(result.id).toBe('debugging-sessions')+ expect(result.uri).toBe(`${PLAYBOOK_URI_PREFIX}debugging-sessions`)+ expect(result.title.length).toBeGreaterThan(0)+ expect(result.content.length).toBeGreaterThan(100)+ })++ it('resolves the same playbook whether passed an id or its URI', async () => {+ const byId = await resolveResourceHandler(ctx, { resource: 'reading-an-agent' })+ const byUri = await resolveResourceHandler(ctx, { resource: playbookUri('reading-an-agent') })+ expect(byUri).toEqual(byId)+ })++ it('throws a helpful error on an unknown reference', async () => {+ await expect(resolveResourceHandler(ctx, { resource: 'does-not-exist' })).rejects.toThrow(+ /Unknown playbook/+ )+ })+ })++ describe('playbook inventory', () => {+ it('PLAYBOOK_IDS matches the skill dirs in the concierge bundle', () => {+ const skillDirs = readdirSync(SKILLS_DIR, { withFileTypes: true })+ .filter((e) => e.isDirectory())+ .map((e) => e.name)+ .sort()+ expect(skillDirs).toEqual([...PLAYBOOK_IDS].sort())+ })++ it('every id has embedded, non-empty content', () => {+ for (const id of PLAYBOOK_IDS) {+ expect(PLAYBOOKS[id]?.content.length, id).toBeGreaterThan(100)+ }+ })+ })++ describe('live tool surface', () => {+ it('every tool named in PLAYBOOK_TOOLS resolves to a real tool definition', () => {+ const defs = getToolDefinitions()+ for (const [id, names] of Object.entries(PLAYBOOK_TOOLS)) {+ for (const name of names) {+ expect(defs[name], `${id} → ${name}`).not.toBeUndefined()+ }+ }+ })++ it('drops tool names absent from the live catalog without throwing', () => {+ // Only one of authoring-new-agents' tools exists in this partial+ // catalog — the rest are silently skipped (ground-truth wins).+ const partial = {+ 'agent-applications-create': { title: 'Create', required_scopes: ['agents:write'] },+ } as unknown as Parameters<typeof buildToolSurface>[2]+ const refs = buildToolSurface('authoring-new-agents', ['*'], partial)+ expect(refs.map((r) => r.name)).toEqual(['agent-applications-create'])+ })++ it('classifies the no-source creator as gated without agents:write, callable with it', () => {+ const readOnly = buildToolSurface('authoring-new-agents', ['agents:read'])+ const create = readOnly.find((t) => t.name === 'agent-applications-revisions-create')!+ expect(create.missingScopes).toEqual(['agents:write'])++ const writer = buildToolSurface('authoring-new-agents', ['agents:write'])+ expect(writer.find((t) => t.name === 'agent-applications-revisions-create')!.missingScopes).toEqual([])++ // all-access wildcard satisfies everything+ const star = buildToolSurface('authoring-new-agents', ['*'])+ expect(star.every((t) => t.missingScopes.length === 0)).toBe(true)+ })++ it('appends a scope-aware surface to the returned content', async () => {+ const result = await resolveResourceHandler(ctxWithScopes(['agents:read']), {+ resource: 'authoring-new-agents',+ })+ expect(result.content).toContain('## Tools for this playbook (live)')+ // The creator agents keep "not finding" is named, and shown as scope-gated.+ expect(result.content).toMatch(/agent-applications-revisions-create.*needs: agents:write/)+ expect(result.tools.gated).toContain('agent-applications-revisions-create')+ expect(result.tools.gated).toContain('agent-applications-create') // create needs agents:write+ // a read-scoped tool stays callable under agents:read+ expect(result.tools.callable).toContain('agent-native-tools-list')+ })++ it('with agents:write the creator moves into the callable set', async () => {+ const result = await resolveResourceHandler(ctxWithScopes(['agents:write']), {+ resource: 'authoring-new-agents',+ })+ expect(result.tools.callable).toContain('agent-applications-revisions-create')+ expect(result.tools.gated).not.toContain('agent-applications-revisions-create')+ })++ it('playbooks with no associated tools omit the surface section', async () => {+ const result = await resolveResourceHandler(ctxWithScopes(['*']), { resource: 'safety-and-boundaries' })+ expect(result.content).not.toContain('Tools for this playbook')+ expect(result.tools.callable).toHaveLength(0)+ expect(result.tools.gated).toHaveLength(0)+ })+ })+})