Skip to content

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

feat(agent-platform): capability-based client tools + typed trigger_metadata (#66161)

Ben Whitee6f983492571
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 00b986ec0b45..4536b8ef151e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5361,13 +5361,13 @@ snapshots:
scenes-app-feature-flags--new-feature-flag--light:
hash: v1.k794b7964.727ad87e0926fee11742fcb9a3925cd8247cee3136c882319043b31ce2bec519.IMOClX-wgcfkL3mCHym-EwK4bPMzFWfC-Q1jS60AnR0
scenes-app-feature-flags--new-multivariate-flag-variant-key-error--dark:
- hash: v1.k794b7964.f61edcc3faee1780859338b411e5a411045cd9cdffc9c4e7c57bd36cfb688fb4.ii2nAjS44zy4OMsAN43Rv69G4pvsXrRjKX79RsLpoNs
+ hash: v1.k794b7964.a16a6e7374ab04142aa5fe22a63c96a8b03161d3365ca9f20fe2b67c5f6508ae.d4UlULDadIKoQ8Myg3tlck49AXZikj8ZELd3jv2nxZc
scenes-app-feature-flags--new-multivariate-flag-variant-key-error--light:
- hash: v1.k794b7964.6bfb5fb749c3dde83f973e0ad06e23ee9b7eb2f0168226631ee34dbe849ded0a.BC-syt4reSnhcPZ8PpivN5xAlcLFqTAuQu9WDSElsIA
+ hash: v1.k794b7964.ec2cef31ba38e77b273db5f31fb8ebf0ab54fd2743a4215b64546d2fb3b6befd.8cXZyn3DSEXahZUzGmBzA9klphOGrJhkzRUmbbUgdlE
scenes-app-feature-flags--new-remote-config-flag-payload-error--dark:
- hash: v1.k794b7964.8658214f05277d1993c4f3c3e2e26d2f7a1be4352cc9efd6459b641fe429ba61.tr0v5RTq0pkpUCq4bXSlwLYhHAwf8S3Xtn0gLOgli0Q
+ hash: v1.k794b7964.a16a6e7374ab04142aa5fe22a63c96a8b03161d3365ca9f20fe2b67c5f6508ae.2P2RmRIUmAgLjgOFWl5SxPABQeZg0TvQJC9bunJIARo
scenes-app-feature-flags--new-remote-config-flag-payload-error--light:
- hash: v1.k794b7964.486a154f8e9065c1c617360149bbcfd4c32f7944eb8ecbc00108821608778900.q-nY4Dq5KNrxKwiH8vx1cTyjXUShFFYBg-r6JRDKyL8
+ hash: v1.k794b7964.3cd967b3c2f64308cdd76c0e0fccb2248924a34825fce47a39b799d21ef6359a.BniHMFmxEBBoWOap-0ks83HBkfqJytE4kGffhwlUkI8
scenes-app-feature-flags-code-examples--code-instructions-node-with-group-multivariate-flag-local-evaluation--dark:
hash: v1.k794b7964.3ce50a6c3abbe37a320a41b9b595595f1f563ee2810f7039c1077de0de2ce541.NshMoutmoo5MZNYuOO7ESAXGz5weprcVLeWqVRJevZA
scenes-app-feature-flags-code-examples--code-instructions-node-with-group-multivariate-flag-local-evaluation--light:
diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.py
index 6eac46560845..319a6a12c925 100644
--- a/products/agent_platform/backend/presentation/views.py
+++ b/products/agent_platform/backend/presentation/views.py
@@ -1016,11 +1016,12 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
allow_null=True,
required=False,
help_text=(
- "Trigger-specific metadata stamped at session creation. Shape varies "
- "by trigger kind; cron firings carry "
- "`{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. "
- "Render this on session-detail so the operator can tell at a glance "
- "that a session was fired by which cron / when."
+ "Trigger-specific metadata stamped at session creation. Discriminated on "
+ "`kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is "
+ "`agent-shared/src/runtime/trigger-metadata.ts`; the node side validates "
+ "and strips unknown keys at the persistence boundary, so consumers can "
+ "trust `kind` and per-kind fields. TODO: narrow this DictField to a "
+ "polymorphic serializer mirroring the union (needs `hogli build:openapi`)."
),
),
"principal": _AGENT_SESSION_PRINCIPAL,
@@ -1222,11 +1223,12 @@ class AgentApplicationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
allow_null=True,
required=False,
help_text=(
- "Trigger-specific metadata stamped at session creation. Shape varies "
- "by trigger kind; cron firings carry "
- "`{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. "
- "Render this on session-detail so the operator can tell at a glance "
- "that a session was fired by which cron / when."
+ "Trigger-specific metadata stamped at session creation. Discriminated on "
+ "`kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is "
+ "`agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and "
+ "strips unknown keys at the persistence boundary, so consumers can trust "
+ "`kind` and per-kind fields. TODO: narrow this DictField to a polymorphic "
+ "serializer mirroring the union (needs `hogli build:openapi`)."
),
),
"state": drf_serializers.ChoiceField(choices=_AGENT_SESSION_STATE_VALUES),
@@ -3091,11 +3093,12 @@ class AgentFleetViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
allow_null=True,
required=False,
help_text=(
- "Trigger-specific metadata stamped at session creation. Shape varies "
- "by trigger kind; cron firings carry "
- "`{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. "
- "Render this on session-detail so the operator can tell at a glance "
- "that a session was fired by which cron / when."
+ "Trigger-specific metadata stamped at session creation. Discriminated on "
+ "`kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is "
+ "`agent-shared/src/runtime/trigger-metadata.ts`; the node side validates "
+ "and strips unknown keys at the persistence boundary, so consumers can "
+ "trust `kind` and per-kind fields. TODO: narrow this DictField to a "
+ "polymorphic serializer mirroring the union (needs `hogli build:openapi`)."
),
),
"principal": _AGENT_SESSION_PRINCIPAL,
diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.ts
index 0f9bdd597c2a..d8a20650ce44 100644
--- a/products/agent_platform/frontend/generated/api.schemas.ts
+++ b/products/agent_platform/frontend/generated/api.schemas.ts
@@ -1494,7 +1494,7 @@ export const AgentSessionStateEnumApi = {
} as const
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
export type AgentSessionSummaryApiTriggerMetadata = { [key: string]: unknown } | null
@@ -1509,7 +1509,7 @@ export interface AgentSessionSummaryApi {
/** @nullable */
external_key: string | null
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
trigger_metadata?: AgentSessionSummaryApiTriggerMetadata
@@ -1532,7 +1532,7 @@ export interface AgentApplicationSessionsListResponseApi {
}
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
export type AgentApplicationSessionsRetrieveResponseApiTriggerMetadata = { [key: string]: unknown } | null
@@ -1625,7 +1625,7 @@ export interface AgentApplicationSessionsRetrieveResponseApi {
/** @nullable */
external_key: string | null
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
trigger_metadata?: AgentApplicationSessionsRetrieveResponseApiTriggerMetadata
@@ -1706,7 +1706,7 @@ export interface AgentUsersListApi {
}
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
export type AgentFleetLiveSessionSummaryApiTriggerMetadata = { [key: string]: unknown } | null
@@ -1722,7 +1722,7 @@ export interface AgentFleetLiveSessionSummaryApi {
/** @nullable */
external_key: string | null
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
trigger_metadata?: AgentFleetLiveSessionSummaryApiTriggerMetadata
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts
index f329595cdc60..3c033dcc4275 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts
@@ -53,6 +53,10 @@ function makePair(): { app: AgentApplication; rev: AgentRevision } {
const ALICE: SessionPrincipal = { kind: 'slack', workspace_id: 'T1', slack_user_id: 'user-alice' }
const BOB: SessionPrincipal = { kind: 'slack', workspace_id: 'T1', slack_user_id: 'user-bob' }
+// Slack-trigger sessions must carry full metadata (workspace/channel/ts/thread_ts);
+// `bareTriggerMetadata` no longer accepts a bare `{ kind: 'slack' }`.
+const SLACK_META = { kind: 'slack' as const, workspace_id: 'T1', channel: 'C01', ts: '1', thread_ts: '4' }
+
describe('enqueueOrResume', () => {
it('creates a fresh session without externalKey', async () => {
const queue = new PgSessionQueue(pool)
@@ -177,6 +181,7 @@ describe('enqueueOrResume', () => {
seed: { role: 'user', content: 'alice opens thread', timestamp: Date.now() },
principal: ALICE,
trigger: 'slack',
+ triggerMetadata: SLACK_META,
}
)
const second = await enqueueOrResume(
@@ -188,6 +193,7 @@ describe('enqueueOrResume', () => {
seed: { role: 'user', content: 'bob replies', timestamp: Date.now() },
principal: BOB,
trigger: 'slack',
+ triggerMetadata: SLACK_META,
}
)
expect(second.kind).toBe('elevation_required')
@@ -230,6 +236,7 @@ describe('enqueueOrResume', () => {
seed: { role: 'user', content: 'live opens thread', timestamp: Date.now() },
principal: ALICE,
trigger: 'slack',
+ triggerMetadata: SLACK_META,
}
)
const preview = await enqueueOrResume(
@@ -241,6 +248,7 @@ describe('enqueueOrResume', () => {
seed: { role: 'user', content: 'preview author tests draft', timestamp: Date.now() },
principal: ALICE,
trigger: 'slack',
+ triggerMetadata: SLACK_META,
}
)
expect(preview.kind).toBe('created')
@@ -262,6 +270,7 @@ describe('enqueueOrResume', () => {
seed: { role: 'user', content: 'live follow-up', timestamp: Date.now() },
principal: ALICE,
trigger: 'slack',
+ triggerMetadata: SLACK_META,
}
)
expect(liveAgain.kind).toBe('resumed')
@@ -278,6 +287,7 @@ describe('enqueueOrResume', () => {
seed: { role: 'user', content: 'other draft', timestamp: Date.now() },
principal: ALICE,
trigger: 'slack',
+ triggerMetadata: SLACK_META,
}
)
expect(otherPreview.kind).toBe('created')
@@ -296,6 +306,7 @@ describe('enqueueOrResume', () => {
seed: { role: 'user', content: 'alice opens', timestamp: Date.now() },
principal: ALICE,
trigger: 'slack',
+ triggerMetadata: SLACK_META,
}
)
// Six denials — the seventh would also fit if we ever lift the cap,
@@ -310,6 +321,7 @@ describe('enqueueOrResume', () => {
seed: { role: 'user', content: `bob #${i}`, timestamp: Date.now() + i },
principal: { ...BOB, slack_user_id: `bob-${i}` },
trigger: 'slack',
+ triggerMetadata: SLACK_META,
}
)
}
@@ -566,4 +578,45 @@ describe('enqueueOrResume', () => {
).rejects.toThrow('boom')
})
})
+
+ describe('bareTriggerMetadata exhaustiveness', () => {
+ it('throws if a slack trigger is enqueued without triggerMetadata', async () => {
+ const queue = new PgSessionQueue(pool)
+ const { app, rev } = makePair()
+ await expect(
+ enqueueOrResume(
+ { queue },
+ {
+ application: app,
+ revision: rev,
+ externalKey: null,
+ trigger: 'slack',
+ seed: { role: 'user', content: 'hi', timestamp: Date.now() },
+ }
+ )
+ ).rejects.toThrow(/slack trigger requires explicit triggerMetadata/)
+ })
+
+ it.each([
+ ['webhook', 'webhook'],
+ ['mcp', 'mcp'],
+ ['chat', 'chat'],
+ ] as const)('stamps bare {kind:%s} when trigger=%s and no triggerMetadata', async (kind, trigger) => {
+ const queue = new PgSessionQueue(pool)
+ const { app, rev } = makePair()
+ const out = await enqueueOrResume(
+ { queue },
+ {
+ application: app,
+ revision: rev,
+ externalKey: null,
+ trigger,
+ seed: { role: 'user', content: 'hi', timestamp: Date.now() },
+ }
+ )
+ expect(out.kind).toBe('created')
+ const session = await queue.get(out.sessionId)
+ expect(session!.trigger_metadata).toEqual({ kind })
+ })
+ })
})
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts
index 020b108d212d..87ba59534e93 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts
@@ -30,6 +30,7 @@ import {
EMPTY_USAGE_TOTAL,
SessionPrincipal,
SessionQueue,
+ TriggerMetadata,
} from '@posthog/agent-shared'
import { enqueueTotal } from '../metrics'
@@ -70,12 +71,19 @@ export interface EnqueueInput {
*/
idempotencyKey?: string
/**
- * Trigger-specific metadata stamped on the session row at creation.
- * Forwarded straight to `AgentSession.trigger_metadata` JSONB.
- * Surfaced by `/sessions/list` so the UI can render a "fired by
- * <cron_name> at <fired_at>" badge etc.
+ * Typed trigger metadata stamped on the session row at CREATION time.
+ * When omitted, a bare `{ kind }` is derived from `trigger`
+ * (chat/webhook/mcp); slack + cron always supply the full object.
+ *
+ * Frozen on resume: when this call matches an existing session via
+ * `externalKey`, the stored `trigger_metadata` is preserved verbatim and
+ * any incoming value is silently ignored. For chat that means
+ * `supported_client_tools` declared on a second `/run` for the same
+ * external_key do NOT expand the runner's capability surface — it's
+ * pinned at session open. A client that gained new capabilities
+ * mid-session needs a new session to expose them.
*/
- triggerMetadata?: Record<string, unknown>
+ triggerMetadata?: TriggerMetadata
/**
* Skip the per-session owner/ACL check on resume. Only set by triggers
* that have ALREADY authorized the incoming principal via a broader,
@@ -167,12 +175,8 @@ async function enqueueOrResumeInner(deps: EnqueueDeps, input: EnqueueInput): Pro
team_id: input.application.team_id,
external_key: input.externalKey,
idempotency_key: input.idempotencyKey ?? null,
- // Always stamp the trigger source as `kind` so every session is
- // attributable to how it started (chat / webhook / slack / mcp) — the
- // console reads + filters on this. Trigger-specific extras (slack
- // channel, etc.) merge on top. Cron sessions are created by the
- // janitor, which stamps `kind: 'cron'` itself.
- trigger_metadata: { kind: input.trigger ?? 'chat', ...input.triggerMetadata },
+ // Typed metadata; bare `{ kind }` when the caller supplied none.
+ trigger_metadata: input.triggerMetadata ?? bareTriggerMetadata(input.trigger),
state: 'queued' as const,
conversation: [input.seed],
pending_inputs: [],
@@ -204,6 +208,31 @@ async function enqueueOrResumeInner(deps: EnqueueDeps, input: EnqueueInput): Pro
return { kind: 'created', sessionId: session.id, isResume: false }
}
+/**
+ * Bare `{ kind }` for triggers with no extra metadata. Exhaustive over
+ * `ElevationTrigger` — slack callers MUST supply full `triggerMetadata`
+ * (workspace_id/channel/ts/thread_ts), so the slack branch throws. Adding a
+ * new value to `ElevationTrigger` without updating this function is a compile
+ * error via the `never` assertion below.
+ */
+function bareTriggerMetadata(trigger: ElevationTrigger | undefined): TriggerMetadata {
+ switch (trigger) {
+ case 'webhook':
+ return { kind: 'webhook' }
+ case 'mcp':
+ return { kind: 'mcp' }
+ case 'chat':
+ case undefined:
+ return { kind: 'chat' }
+ case 'slack':
+ throw new Error('slack trigger requires explicit triggerMetadata (workspace_id, channel, ts, thread_ts)')
+ default: {
+ const _exhaustive: never = trigger
+ throw new Error(`unhandled trigger kind: ${String(_exhaustive)}`)
+ }
+ }
+}
+
/**
* Postgres unique-violation SQLSTATE. `pg` surfaces this as `err.code`;
* tests passing in arbitrary mocks can match the same shape by setting
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/chat.schemas.ts b/products/agent_platform/services/agent-ingress/src/triggers/chat.schemas.ts
index e5bfe92e063a..043705e92f9c 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/chat.schemas.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/chat.schemas.ts
@@ -11,9 +11,19 @@
import { z } from 'zod'
+import { SUPPORTED_CLIENT_TOOL_ID_MAX_LEN, SUPPORTED_CLIENT_TOOLS_MAX_LEN } from '@posthog/agent-shared'
+
export const ChatRunBodySchema = z.object({
message: z.string().min(1, 'message must be a non-empty string'),
external_key: z.string().optional(),
+ // `kind:'client'` tool ids this client can fulfil; the runner exposes the
+ // matching spec tools to the model. UX hint, never a security boundary.
+ // Capped to stop a misbehaving caller from inflating the session row's
+ // `trigger_metadata` JSONB. Bounds mirror trigger-metadata.ts.
+ supported_client_tools: z
+ .array(z.string().min(1).max(SUPPORTED_CLIENT_TOOL_ID_MAX_LEN))
+ .max(SUPPORTED_CLIENT_TOOLS_MAX_LEN)
+ .optional(),
})
/**
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts b/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
index 9cde9baf4610..76aaa34c2e89 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
@@ -13,7 +13,7 @@
import { z } from 'zod'
-import { buildClientToolResultMarker, CLIENT_KIND_HEADER, parseClientKind } from '@posthog/agent-shared'
+import { buildClientToolResultMarker } from '@posthog/agent-shared'
import { buildElevationResponse, principalDisplay, recordElevationRequest, requireAclAccess } from '../enqueue/acl'
import { enqueueOrResume } from '../enqueue/enqueue'
@@ -30,13 +30,8 @@ import { defineRoute, type AuthedRouteCtx, type TriggerModule } from './types'
async function runHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatRunBodySchema>>): Promise<void> {
const { res, deps, resolved } = ctx
- const { message, external_key: externalKey = null } = ctx.parsed
+ const { message, external_key: externalKey = null, supported_client_tools: supportedClientTools } = ctx.parsed
const sessionPrincipal = ctx.principal
- // Stash the caller's client_kind on the session row so the runner can
- // tailor model-facing prose (e.g. suppress the approval-URL guidance for
- // posthog-code, whose chat preview renders an in-line approval card).
- // Unauthenticated header — UX gating only, never a security boundary.
- const clientKind = parseClientKind(ctx.req.headers[CLIENT_KIND_HEADER])
const outcome = await enqueueOrResume(
{ queue: deps.queue },
{
@@ -47,7 +42,10 @@ async function runHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatRunBodySchema>>
principal: sessionPrincipal,
trigger: 'chat',
requesterDisplay: principalDisplay(sessionPrincipal),
- triggerMetadata: clientKind ? { client_kind: clientKind } : undefined,
+ triggerMetadata: {
+ kind: 'chat',
+ ...(supportedClientTools?.length ? { supported_client_tools: supportedClientTools } : {}),
+ },
}
)
if (outcome.kind === 'elevation_required') {
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
index f5f6b1caad16..c99cffe65fde 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
@@ -260,7 +260,7 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {
// Stash the originating thread coordinates so the runner can post a
// sanitized failure reply if the session dies before answering.
triggerMetadata: {
- type: 'slack',
+ kind: 'slack',
workspace_id: workspaceId,
channel: event.channel,
ts: event.ts,
diff --git a/products/agent_platform/services/agent-janitor/src/validate-spec.test.ts b/products/agent_platform/services/agent-janitor/src/validate-spec.test.ts
index e0749ac32356..736a395a29a6 100644
--- a/products/agent_platform/services/agent-janitor/src/validate-spec.test.ts
+++ b/products/agent_platform/services/agent-janitor/src/validate-spec.test.ts
@@ -398,4 +398,95 @@ describe('validateRevisionBundle', () => {
expect(report.ok).toBe(true)
})
})
+
+ describe('required client tool + non-chat trigger', () => {
+ const chatAuth = { type: 'public' as const, acknowledge_public_exposure: true as const }
+ const requiredClientTool = {
+ kind: 'client' as const,
+ id: 'connect_mcp',
+ description: 'connect an mcp',
+ args_schema: { type: 'object' },
+ required: true,
+ }
+ const optionalClientTool = {
+ kind: 'client' as const,
+ id: 'focus',
+ description: 'focus a panel',
+ args_schema: { type: 'object' },
+ required: false,
+ }
+
+ it('accepts a required client tool when only chat triggers are configured', async () => {
+ const bundles = makeBundles()
+ await bundles.write('rev1', 'agent.md', 'hi')
+ const report = await validateRevisionBundle(
+ mkRev({
+ triggers: [{ type: 'chat', config: {}, auth: { modes: [chatAuth] } }],
+ tools: [requiredClientTool],
+ }),
+ bundles
+ )
+ expect(report.ok).toBe(true)
+ })
+
+ it('rejects a required client tool when a webhook trigger is also configured', async () => {
+ const bundles = makeBundles()
+ await bundles.write('rev1', 'agent.md', 'hi')
+ const report = await validateRevisionBundle(
+ mkRev({
+ triggers: [
+ { type: 'chat', config: {}, auth: { modes: [chatAuth] } },
+ { type: 'webhook', config: { path: '/w' }, auth: { modes: [chatAuth] } },
+ ],
+ tools: [requiredClientTool],
+ }),
+ bundles
+ )
+ expect(report.ok).toBe(false)
+ expect(report.errors).toEqual([
+ {
+ code: 'required_client_tool_with_non_chat_trigger',
+ message: expect.stringContaining('connect_mcp'),
+ pointer: 'spec.tools[0].required',
+ },
+ ])
+ expect(report.errors[0].message).toContain('webhook')
+ })
+
+ it('accepts a non-required client tool alongside non-chat triggers', async () => {
+ const bundles = makeBundles()
+ await bundles.write('rev1', 'agent.md', 'hi')
+ const report = await validateRevisionBundle(
+ mkRev({
+ triggers: [
+ { type: 'chat', config: {}, auth: { modes: [chatAuth] } },
+ { type: 'webhook', config: { path: '/w' }, auth: { modes: [chatAuth] } },
+ ],
+ tools: [optionalClientTool],
+ }),
+ bundles
+ )
+ expect(report.ok).toBe(true)
+ })
+
+ it('emits one error per required client tool, listing every non-chat trigger kind', async () => {
+ const bundles = makeBundles()
+ await bundles.write('rev1', 'agent.md', 'hi')
+ const report = await validateRevisionBundle(
+ mkRev({
+ triggers: [
+ { type: 'webhook', config: { path: '/w' }, auth: { modes: [chatAuth] } },
+ { type: 'mcp', config: {}, auth: { modes: [chatAuth] } },
+ ],
+ tools: [requiredClientTool, { ...optionalClientTool, required: true }],
+ }),
+ bundles
+ )
+ expect(report.errors).toHaveLength(2)
+ for (const err of report.errors) {
+ expect(err.code).toBe('required_client_tool_with_non_chat_trigger')
+ expect(err.message).toMatch(/webhook.*mcp|mcp.*webhook/)
+ }
+ })
+ })
})
diff --git a/products/agent_platform/services/agent-janitor/src/validate-spec.ts b/products/agent_platform/services/agent-janitor/src/validate-spec.ts
index d4317cf87893..e66438858032 100644
--- a/products/agent_platform/services/agent-janitor/src/validate-spec.ts
+++ b/products/agent_platform/services/agent-janitor/src/validate-spec.ts
@@ -29,6 +29,7 @@ export type ValidationCode =
| 'duplicate_cron_name'
| 'unknown_cron_placeholder'
| 'secret_no_host_binding'
+ | 'required_client_tool_with_non_chat_trigger'
/**
* Non-blocking soft signals — surface to the author before freeze, but the
@@ -146,6 +147,30 @@ export async function validateRevisionBundle(rev: AgentRevision, bundle: BundleS
// kind:'custom' / kind:'client' need no presence check — see above.
}
+ // `kind:'client'` `required:true` tools need a chat trigger: only the chat
+ // /run body carries `supported_client_tools`. Webhook/slack/cron/mcp
+ // sessions have no client to declare support, so the runner hides every
+ // client tool there (see build-agent-tools.ts). A `required` client tool
+ // combined with any non-chat trigger would fail every non-chat session,
+ // so reject the combination at freeze.
+ const nonChatTriggers = rev.spec.triggers.filter((t) => t.type !== 'chat')
+ if (nonChatTriggers.length > 0) {
+ for (const [i, tool] of rev.spec.tools.entries()) {
+ if (tool.kind === 'client' && tool.required) {
+ const kinds = [...new Set(nonChatTriggers.map((t) => t.type))].join(', ')
+ errors.push({
+ code: 'required_client_tool_with_non_chat_trigger',
+ message:
+ `client tool "${tool.id}" is required:true but spec.triggers includes non-chat trigger(s) ` +
+ `(${kinds}). Non-chat triggers have no connecting client to declare support, so every ` +
+ `non-chat session would fail session open. Either mark the tool required:false or ` +
+ `remove the non-chat trigger(s).`,
+ pointer: `spec.tools[${i}].required`,
+ })
+ }
+ }
+ }
+
// Cron-specific freeze-time checks. Zod has already validated the field
// shapes (`name` regex, `prompt` length, `max_catch_up_age_seconds`
// bounds, etc.) — these are the cross-cutting / runtime checks zod can't
diff --git a/products/agent_platform/services/agent-runner/src/loop/approval.test.ts b/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
index f399e70f2830..136d94938c2b 100644
--- a/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/approval.test.ts
@@ -2,8 +2,7 @@
* Unit tests for the pure-logic branches inside `approval.ts`. The PG-backed
* end-to-end behaviour (intercept → upsert → wake → dispatch) is covered by
* `agent-tests/src/cases/approval-gated.test.ts`; this file pins the model-
- * facing envelope shape that varies on per-caller hints — currently the
- * posthog-code `client_kind` suppressing the URL + admin hint.
+ * facing envelope shape.
*/
import { describe, expect, it } from 'vitest'
@@ -12,8 +11,8 @@ import {
AgentSession,
ApprovalRequest,
ApprovalStore,
- CLIENT_KIND_POSTHOG_CODE,
EMPTY_USAGE_TOTAL,
+ type TriggerMetadata,
UpsertApprovalRequestInput,
UpsertApprovalRequestResult,
} from '@posthog/agent-shared'
@@ -138,35 +137,24 @@ describe('queueApprovalResult: model-facing envelope', () => {
})
})
- it('omits approver_hint + approval_url when the session was opened by posthog-code', async () => {
+ // The approval envelope used to suppress approver_hint + approval_url for
+ // posthog-code (`client_kind`-gated). That gating is gone — the envelope
+ // is now uniform across every trigger kind. Pin that contract by
+ // exercising each TriggerMetadata variant + null.
+ it.each<[string, TriggerMetadata | null]>([
+ ['null trigger_metadata', null],
+ ['chat with no declared client tools', { kind: 'chat' }],
+ ['chat with declared client tools', { kind: 'chat', supported_client_tools: ['connect_mcp'] }],
+ ['slack', { kind: 'slack', workspace_id: 'W', channel: 'C', ts: 't', thread_ts: 't' }],
+ ['webhook', { kind: 'webhook' }],
+ ['mcp', { kind: 'mcp' }],
+ ['cron', { kind: 'cron', cron_name: 'daily', schedule: '0 9 * * *', fired_at: '2026-06-25T09:00:00Z' }],
+ ])('includes approver_hint + approval_url for %s', async (_label, trigger_metadata) => {
const store = makeStubStore()
const out = await queueApprovalResult({
approvals: store,
buildApprovalUrl: (id) => `https://console.example.com/approvals?request=${id}`,
- session: makeSession({ trigger_metadata: { kind: 'chat', client_kind: CLIENT_KIND_POSTHOG_CODE } }),
- revisionId: TEST_REV_ID,
- turn: 1,
- toolName: '@posthog/memory-write',
- toolCallId: 'tc-1',
- args: { note: 'apples' },
- policy: POLICY,
- })
- const envelope = parseEnvelope((out.content[0] as { text: string }).text)
- // Posthog-code's chat preview renders an in-line approval card — the
- // model has nothing to repeat about how the user should approve, so
- // the URL + admin hint must not appear in the envelope it sees.
- expect(envelope.approval.approver_hint).toBeUndefined()
- expect(envelope.approval.approval_url).toBeUndefined()
- // Still has the bits the model uses to know it's gated.
- expect(envelope.approval).toMatchObject({ state: 'queued', request_id: expect.any(String) })
- })
-
- it('treats an unrecognised client_kind as the default (URL + hint preserved)', async () => {
- const store = makeStubStore()
- const out = await queueApprovalResult({
- approvals: store,
- buildApprovalUrl: (id) => `https://console.example.com/approvals?request=${id}`,
- session: makeSession({ trigger_metadata: { kind: 'chat', client_kind: 'some-future-client' } }),
+ session: makeSession({ trigger_metadata }),
revisionId: TEST_REV_ID,
turn: 1,
toolName: '@posthog/memory-write',
diff --git a/products/agent_platform/services/agent-runner/src/loop/approval.ts b/products/agent_platform/services/agent-runner/src/loop/approval.ts
index 27a0a806dbbe..2d40ad8011ae 100644
--- a/products/agent_platform/services/agent-runner/src/loop/approval.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/approval.ts
@@ -28,11 +28,9 @@ import {
ApprovalStore,
type ApprovalType,
AssistantMessageRecord,
- CLIENT_KIND_POSTHOG_CODE,
ConversationMessage,
hashCanonicalArgs,
parseApprovalDecidedMarker,
- readSessionClientKind,
} from '@posthog/agent-shared'
import type { RealToolExecute, ToolResultDetails } from './build-agent-tools'
@@ -103,13 +101,6 @@ export async function queueApprovalResult(input: {
expires_at: new Date(Date.now() + input.policy.ttl_ms).toISOString(),
})
- // Posthog-code sessions render an in-chat approval card on top of every
- // queued tool call; the model echoing a "track it here: <url>" line on top
- // of that card is redundant when the user is already in the app the deep
- // link would open. Drop the URL + approver hint so the model has nothing to
- // repeat about how the user should approve. Other clients (Slack, MCP) still
- // surface the deep link so the approval can be opened in PostHog Code.
- const suppressApprovalChannel = readSessionClientKind(input.session.trigger_metadata) === CLIENT_KIND_POSTHOG_CODE
const buildUrl = input.buildApprovalUrl ?? defaultApprovalUrl
const approval: Record<string, unknown> = {
request_id: upsert.request.id,
@@ -120,10 +111,8 @@ export async function queueApprovalResult(input: {
// (`principal`) or console-only (`agent`); neither is on the tool_call.
allow_edit: input.policy.allow_edit,
approver_scope: { type: input.policy.type },
- }
- if (!suppressApprovalChannel) {
- approval.approver_hint = input.policy.type === 'agent' ? APPROVER_HINT_AGENT : APPROVER_HINT_PRINCIPAL
- approval.approval_url = buildUrl(upsert.request.id)
+ approver_hint: input.policy.type === 'agent' ? APPROVER_HINT_AGENT : APPROVER_HINT_PRINCIPAL,
+ approval_url: buildUrl(upsert.request.id),
}
if (!upsert.deduped && previous && isTerminal(previous.state)) {
approval.prior_decision = { state: previous.state, reason: previous.decision_reason ?? undefined }
diff --git a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
index 8281d56a7566..d5fe10df55d3 100644
--- a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
@@ -231,12 +231,29 @@ export async function buildAgentTools(rev: AgentRevision, deps: AgentToolDeps):
continue
}
if (t.kind === 'client') {
- // Always exposed when dispatcher is wired. No upfront capability
- // handshake: if the connecting client doesn't handle the id, the
- // dispatcher's await times out and the model gets an error
- // tool_result it can adapt to. Keeps the protocol simple +
- // matches the agent.md degradation rules.
+ // Client tools need a connected client to fulfil the call. Only
+ // chat-triggered sessions have one, so for non-chat triggers we
+ // hide every client tool and let the agent.md degrade — `required`
+ // is only enforced when there's a client to declare support.
+ // Spec freeze rejects `required:true` client tools combined with
+ // non-chat triggers, so this branch is the runtime safety net.
+ const chatMeta = deps.session.trigger_metadata?.kind === 'chat' ? deps.session.trigger_metadata : null
+ const supported = chatMeta?.supported_client_tools ?? []
+ // Dispatcher availability is a runner-side concern (server
+ // misconfig); check before the caller-declaration gate so the
+ // failure code points at the right party. `dispatchClientTool` is
+ // always wired in prod (driver.ts:447); this branch catches the
+ // case where a runner instance ships without it.
if (!deps.dispatchClientTool) {
+ if (t.required && chatMeta) {
+ throw new Error(`client_tool_dispatcher_unavailable:${t.id}`)
+ }
+ continue
+ }
+ if (!supported.includes(t.id)) {
+ if (t.required && chatMeta) {
+ throw new Error(`client_tool_unsupported:${t.id}`)
+ }
continue
}
tools.push(makeClientTool(t, deps))
diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.ts
index db9fa778e708..0a1ac6557548 100644
--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts
@@ -61,7 +61,6 @@ import {
IdentityLinkStateStore,
IdentityStore,
isDeltaEventKind,
- isSlackTriggerMetadata,
LogLevel,
LogSink,
MemoryStore,
@@ -256,7 +255,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
// Slack-triggered sessions relay the model's reply back into the originating
// thread (the system prompt below tells the model to answer in natural
// language instead of calling a slack tool).
- const slackReply = isSlackTriggerMetadata(session.trigger_metadata) ? session.trigger_metadata : null
+ const slackReply = session.trigger_metadata?.kind === 'slack' ? session.trigger_metadata : null
const system = await buildSystemPrompt(rev, deps.bundle, {
unavailableMcps: (deps.mcpFailures ?? []).map((f) => ({
id: f.ref.id,
diff --git a/products/agent_platform/services/agent-shared/src/index.ts b/products/agent_platform/services/agent-shared/src/index.ts
index faa000c65c36..3e3ef531bdc0 100644
--- a/products/agent_platform/services/agent-shared/src/index.ts
+++ b/products/agent_platform/services/agent-shared/src/index.ts
@@ -45,8 +45,8 @@ export * from './sandbox/secret-broker'
export * from './runtime/analytics-sink'
export * from './runtime/bus'
-export * from './runtime/client-kind'
export * from './runtime/client-tool-result-marker'
+export * from './runtime/trigger-metadata'
export * from './runtime/credential-broker'
export * from './runtime/pg-credential-broker'
export * from './runtime/identity-credential-store'
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
index d8deaec759ae..825befccfa4b 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
@@ -10,6 +10,8 @@
import type { Pool, PoolClient } from 'pg'
+import { createLogger } from '../runtime/logger'
+import { parseTriggerMetadata } from '../runtime/trigger-metadata'
import {
AgentSession,
ConversationMessage,
@@ -33,6 +35,8 @@ const SELECT_COLS = `id, application_id, revision_id, team_id, external_key,
usage_total, acl, pending_elevation_requests,
created_at, updated_at`
+const log = createLogger('pg-queue')
+
export class PgSessionQueue implements SessionQueue {
constructor(private readonly pool: Pool) {}
@@ -615,6 +619,21 @@ function buildSessionFilter(
}
function rowToSession(row: DbRow): AgentSession {
+ const triggerMetadata = parseTriggerMetadata(row.trigger_metadata)
+ // Surface schema drift: a non-null JSONB blob that the discriminated union
+ // can't validate becomes `null` here, which silently disables every kind-
+ // gated reader (slack reply relay, failure notifier, etc.). Log so an
+ // operator can see drift instead of hunting it through user reports.
+ if (row.trigger_metadata !== null && triggerMetadata === null) {
+ log.warn(
+ {
+ session_id: row.id,
+ raw_kind:
+ typeof row.trigger_metadata === 'object' ? (row.trigger_metadata as { kind?: unknown }).kind : null,
+ },
+ 'trigger_metadata_parse_failed'
+ )
+ }
return {
id: row.id,
application_id: row.application_id,
@@ -623,10 +642,7 @@ function rowToSession(row: DbRow): AgentSession {
principal: (row.principal as AgentSession['principal']) ?? null,
external_key: row.external_key,
idempotency_key: row.idempotency_key,
- trigger_metadata:
- row.trigger_metadata && typeof row.trigger_metadata === 'object'
- ? (row.trigger_metadata as Record<string, unknown>)
- : null,
+ trigger_metadata: triggerMetadata,
state: row.state as AgentSession['state'],
conversation: Array.isArray(row.conversation) ? (row.conversation as AgentSession['conversation']) : [],
pending_inputs: Array.isArray(row.pending_inputs) ? (row.pending_inputs as AgentSession['pending_inputs']) : [],
diff --git a/products/agent_platform/services/agent-shared/src/runtime/client-kind.ts b/products/agent_platform/services/agent-shared/src/runtime/client-kind.ts
deleted file mode 100644
index bb0cf7f6165a..000000000000
--- a/products/agent_platform/services/agent-shared/src/runtime/client-kind.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Caller-supplied `client_kind` tag stamped on a session at /run time.
- *
- * Purely a UX hint — NOT a security boundary. The header is unauthenticated
- * (forgeable under `shared_secret`); the runner only uses it to suppress
- * surfaces that don't make sense for a given client (e.g. the
- * "approve it here: <url>" prose for posthog-code, whose chat preview
- * already renders an in-line approval card).
- *
- * Storage: lives in `trigger_metadata.client_kind` on `agent_session`, set
- * once at session creation and never rewritten.
- */
-
-/** Canonical header name (case-insensitive at the HTTP layer). */
-export const CLIENT_KIND_HEADER = 'x-posthog-client'
-
-/** PostHog Code desktop app — the chat preview renders approvals in-line. */
-export const CLIENT_KIND_POSTHOG_CODE = 'posthog-code'
-
-/** Allowlist of recognised client_kind values. Unknown values are dropped. */
-export const KNOWN_CLIENT_KINDS = [CLIENT_KIND_POSTHOG_CODE] as const
-
-export type ClientKind = (typeof KNOWN_CLIENT_KINDS)[number]
-
-/**
- * Normalise a raw header value into a recognised `ClientKind`, or `null`.
- * Forward-compat: unknown values are dropped silently rather than throwing —
- * an old runner seeing a new client_kind from a newer ingress shouldn't crash.
- */
-export function parseClientKind(raw: string | string[] | undefined | null): ClientKind | null {
- if (raw === undefined || raw === null) {
- return null
- }
- const value = Array.isArray(raw) ? raw[0] : raw
- if (typeof value !== 'string') {
- return null
- }
- const trimmed = value.trim().toLowerCase()
- return (KNOWN_CLIENT_KINDS as readonly string[]).includes(trimmed) ? (trimmed as ClientKind) : null
-}
-
-/**
- * Read `client_kind` off a session row's `trigger_metadata`. Same forward-compat
- * shape as `parseClientKind` — unknown / missing → `null`.
- */
-export function readSessionClientKind(triggerMetadata: Record<string, unknown> | null | undefined): ClientKind | null {
- if (!triggerMetadata) {
- return null
- }
- const raw = triggerMetadata.client_kind
- return typeof raw === 'string' ? parseClientKind(raw) : null
-}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts b/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts
index c3c1b63c0af5..775de7ee45d0 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.test.ts
@@ -8,6 +8,7 @@ import {
TriggerAwareFailureNotifier,
userFacingMessage,
} from './failure-notifier'
+import type { TriggerMetadata } from './trigger-metadata'
const APP: AgentApplication = {
id: 'app-1',
@@ -32,7 +33,7 @@ const REV: AgentRevision = {
encrypted_env: null,
}
-function makeSession(triggerMetadata: Record<string, unknown> | null): AgentSession {
+function makeSession(triggerMetadata: TriggerMetadata | null): AgentSession {
return {
id: 'sess-1',
application_id: APP.id,
@@ -80,6 +81,11 @@ describe('categorize', () => {
['tool threw at dispatcher', 'tool_error'],
['tool_call_failed: timeout', 'tool_error'],
['sandbox timeout after 30s', 'transient_infra'], // sandbox keyword wins → infra
+
+ ['client_tool_unsupported:connect_mcp', 'capability_mismatch'],
+ ['Error: client_tool_unsupported:set_secret', 'capability_mismatch'],
+
+ ['client_tool_dispatcher_unavailable:focus', 'configuration'],
])('"%s" → %s', (reason, expected) => {
expect(categorize(reason)).toBe(expected)
})
@@ -96,12 +102,20 @@ describe('userFacingMessage', () => {
expect(userFacingMessage('configuration')).toMatch(/owner/i)
expect(userFacingMessage('quota_exhausted')).toMatch(/limit/i)
expect(userFacingMessage('tool_error')).toMatch(/tool/i)
+ expect(userFacingMessage('capability_mismatch')).toMatch(/client/i)
expect(userFacingMessage('unknown')).toMatch(/wasn't able/i)
})
it('never contains raw infra detail', () => {
// Sanitization invariant: messages must not mention docker, MCP, kafka, etc.
- for (const cat of ['transient_infra', 'configuration', 'quota_exhausted', 'tool_error', 'unknown'] as const) {
+ for (const cat of [
+ 'transient_infra',
+ 'configuration',
+ 'quota_exhausted',
+ 'tool_error',
+ 'capability_mismatch',
+ 'unknown',
+ ] as const) {
const msg = userFacingMessage(cat)
expect(msg.toLowerCase()).not.toMatch(/docker|kafka|redis|postgres|mcp|stack/i)
}
@@ -124,12 +138,12 @@ describe('TriggerAwareFailureNotifier', () => {
}
}
- it('dispatches by trigger_metadata.type', async () => {
+ it('dispatches by trigger_metadata.kind', async () => {
const slack = makeSub()
const webhook = makeSub()
const n = new TriggerAwareFailureNotifier({ slack, webhook })
await n.notify({
- session: makeSession({ type: 'slack', channel: 'C1', thread_ts: '123' }),
+ session: makeSession({ kind: 'slack', workspace_id: 'W', channel: 'C1', ts: 't', thread_ts: '123' }),
application: APP,
revision: REV,
reason: 'x',
@@ -152,18 +166,18 @@ describe('TriggerAwareFailureNotifier', () => {
expect(slack.notify).not.toHaveBeenCalled()
})
- it('no-ops when trigger_metadata.type is missing or unregistered', async () => {
+ it('no-ops when trigger_metadata.kind is unregistered', async () => {
const slack = makeSub()
const n = new TriggerAwareFailureNotifier({ slack })
await n.notify({
- session: makeSession({ channel: 'C1' }),
+ session: makeSession({ kind: 'chat' }),
application: APP,
revision: REV,
reason: 'x',
category: 'unknown',
})
await n.notify({
- session: makeSession({ type: 'discord' }),
+ session: makeSession({ kind: 'mcp' }),
application: APP,
revision: REV,
reason: 'x',
@@ -182,7 +196,7 @@ describe('TriggerAwareFailureNotifier', () => {
const n = new TriggerAwareFailureNotifier({ slack }, logger)
await expect(
n.notify({
- session: makeSession({ type: 'slack' }),
+ session: makeSession({ kind: 'slack', workspace_id: 'W', channel: 'C1', ts: 't', thread_ts: '123' }),
application: APP,
revision: REV,
reason: 'x',
diff --git a/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.ts b/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.ts
index ae43eb1e85ff..bb29256457f6 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/failure-notifier.ts
@@ -27,7 +27,13 @@ import { AgentApplication, AgentRevision, AgentSession } from '../spec/spec'
* `failed` event and the session conversation's synthetic assistant turn
* also reuse this — single source of truth for "what does the user see."
*/
-export type FailureCategory = 'transient_infra' | 'configuration' | 'quota_exhausted' | 'tool_error' | 'unknown'
+export type FailureCategory =
+ | 'transient_infra'
+ | 'configuration'
+ | 'quota_exhausted'
+ | 'tool_error'
+ | 'capability_mismatch'
+ | 'unknown'
export interface FailureNotifierInput {
session: AgentSession
@@ -57,8 +63,8 @@ export class NoopFailureNotifier implements FailureNotifier {
}
/**
- * Dispatch by `trigger_metadata.type`. The runner wires this with one or
- * more per-trigger sub-notifiers; types without a registered sub-notifier
+ * Dispatch by `trigger_metadata.kind`. The runner wires this with one or
+ * more per-trigger sub-notifiers; kinds without a registered sub-notifier
* fall through silently. Sub-notifier failures are caught and logged here
* so a single misbehaving channel can't crash the dispatcher.
*/
@@ -70,14 +76,10 @@ export class TriggerAwareFailureNotifier implements FailureNotifier {
async notify(input: FailureNotifierInput): Promise<void> {
const meta = input.session.trigger_metadata
- if (!meta || typeof meta !== 'object') {
+ if (!meta) {
return
}
- const type = (meta as { type?: unknown }).type
- if (typeof type !== 'string') {
- return
- }
- const sub = this.registry[type]
+ const sub = this.registry[meta.kind]
if (!sub) {
return
}
@@ -87,7 +89,7 @@ export class TriggerAwareFailureNotifier implements FailureNotifier {
this.logger?.warn(
{
session_id: input.session.id,
- trigger_type: type,
+ trigger_kind: meta.kind,
err: err instanceof Error ? err.message : String(err),
},
'failure_notifier_dispatch_threw'
@@ -133,7 +135,8 @@ export function categorize(reason: string): FailureCategory {
r.includes('bundle_missing') ||
r.includes('revision_missing') ||
r.includes('integration_host_validator') ||
- r.includes('encryption')
+ r.includes('encryption') ||
+ r.includes('client_tool_dispatcher_unavailable')
) {
return 'configuration'
}
@@ -150,6 +153,13 @@ export function categorize(reason: string): FailureCategory {
if (r.includes('tool threw') || r.includes('tool_call_failed') || r.includes('sandbox timeout')) {
return 'tool_error'
}
+ // `client_tool_unsupported:<id>` is thrown by build-agent-tools.ts when a
+ // chat caller did not declare a `required:true` client tool. The user's
+ // client is out of date or doesn't support the tool — neither a
+ // misconfiguration nor an infra issue.
+ if (r.includes('client_tool_unsupported')) {
+ return 'capability_mismatch'
+ }
return 'unknown'
}
@@ -158,6 +168,8 @@ const MESSAGES: Record<FailureCategory, string> = {
configuration: "This agent isn't configured correctly. The agent owner has been notified.",
quota_exhausted: "I've hit a usage limit on this conversation. Please try again later.",
tool_error: 'I ran into an error while using one of my tools. The agent owner can see details.',
+ capability_mismatch:
+ "This agent needs a tool your client doesn't support. Please update your client or contact the agent owner.",
unknown: "I wasn't able to respond to that. The agent owner has been notified.",
}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts
index 5e59d2f51e79..cc4a04480413 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.test.ts
@@ -4,6 +4,7 @@ import { AgentApplication, AgentRevision, AgentSession } from '../spec/spec'
import { HttpFetcher } from './http-client'
import { SecretResolver } from './secret-resolver'
import { SlackFailureNotifier } from './slack-failure-notifier'
+import type { TriggerMetadata } from './trigger-metadata'
const APP: AgentApplication = {
id: 'app-1',
@@ -29,7 +30,7 @@ const REV: AgentRevision = {
encrypted_env: 'fernet-blob',
}
-function makeSession(triggerMetadata: Record<string, unknown> | null): AgentSession {
+function makeSession(triggerMetadata: TriggerMetadata | null): AgentSession {
return {
id: 'sess-1',
application_id: APP.id,
@@ -62,7 +63,13 @@ function tokenResolver(returns: string | null): SecretResolver {
return { resolve: vi.fn(async () => returns) }
}
-const SLACK_META = { type: 'slack', workspace_id: 'W1', channel: 'C1', ts: '111.222', thread_ts: '111.222' }
+const SLACK_META: TriggerMetadata = {
+ kind: 'slack',
+ workspace_id: 'W1',
+ channel: 'C1',
+ ts: '111.222',
+ thread_ts: '111.222',
+}
describe('SlackFailureNotifier', () => {
it('posts a sanitized message to chat.postMessage on the originating thread', async () => {
@@ -98,23 +105,7 @@ describe('SlackFailureNotifier', () => {
const n = new SlackFailureNotifier({ http, resolver: tokenResolver('xoxb-token') })
await n.notify({
- session: makeSession({ type: 'webhook', url: 'https://example.com' }),
- application: APP,
- revision: REV,
- reason: 'x',
- category: 'unknown',
- })
-
- expect(fetch).not.toHaveBeenCalled()
- })
-
- it('no-ops when channel or thread_ts missing', async () => {
- const fetch = vi.fn()
- const http: HttpFetcher = { fetch: fetch as unknown as HttpFetcher['fetch'] }
- const n = new SlackFailureNotifier({ http, resolver: tokenResolver('xoxb-token') })
-
- await n.notify({
- session: makeSession({ type: 'slack', channel: 'C1' }),
+ session: makeSession({ kind: 'webhook' }),
application: APP,
revision: REV,
reason: 'x',
diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts
index 5aeb9fc474e0..0f555b431d33 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-failure-notifier.ts
@@ -17,7 +17,7 @@ import { SLACK_BOT_TOKEN_KEY } from '../spec/trigger-secrets'
import { FailureNotifier, FailureNotifierInput, userFacingMessage } from './failure-notifier'
import { HttpFetcher } from './http-client'
import { SecretResolver } from './secret-resolver'
-import { isSlackTriggerMetadata, SlackTriggerMetadata } from './slack-reply'
+import type { SlackTriggerMetadata } from './trigger-metadata'
export interface SlackFailureNotifierDeps {
http: HttpFetcher
@@ -33,7 +33,7 @@ export class SlackFailureNotifier implements FailureNotifier {
async notify(input: FailureNotifierInput): Promise<void> {
const meta = input.session.trigger_metadata
- if (!isSlackTriggerMetadata(meta)) {
+ if (meta?.kind !== 'slack') {
return
}
const token = await this.resolveTokenSafely(input.revision, input.application, input.session.id)
diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-reply.test.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-reply.test.ts
index bd9a80721b31..4a080ccd6b8f 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/slack-reply.test.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-reply.test.ts
@@ -3,7 +3,6 @@ import { describe, expect, it, vi } from 'vitest'
import { HttpFetcher } from './http-client'
import {
decodeApprovalActionValue,
- isSlackTriggerMetadata,
postSlackApprovalButtons,
postSlackReply,
SlackStatusReporter,
@@ -253,18 +252,3 @@ describe('SlackStatusReporter', () => {
expect(calls.filter((c) => c.url.endsWith('chat.postMessage'))).toHaveLength(2)
})
})
-
-describe('isSlackTriggerMetadata', () => {
- it('accepts a well-formed slack metadata object', () => {
- expect(
- isSlackTriggerMetadata({ type: 'slack', workspace_id: 'W', channel: 'C1', ts: 't', thread_ts: 't' })
- ).toBe(true)
- })
-
- it.each([null, undefined, {}, { type: 'chat' }, { type: 'slack', channel: 'C1' }])(
- 'rejects non-slack / incomplete metadata: %j',
- (meta) => {
- expect(isSlackTriggerMetadata(meta)).toBe(false)
- }
- )
-})
diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-reply.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-reply.ts
index 943649bedb38..2facb4986809 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/slack-reply.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-reply.ts
@@ -13,28 +13,6 @@
import { HttpFetcher } from './http-client'
import { markdownToMrkdwn } from './slack-mrkdwn'
-export interface SlackTriggerMetadata {
- type: 'slack'
- workspace_id: string
- channel: string
- ts: string
- thread_ts: string
-}
-
-export function isSlackTriggerMetadata(meta: unknown): meta is SlackTriggerMetadata {
- if (!meta || typeof meta !== 'object') {
- return false
- }
- const m = meta as Record<string, unknown>
- return (
- m.type === 'slack' &&
- typeof m.channel === 'string' &&
- typeof m.thread_ts === 'string' &&
- m.channel.length > 0 &&
- m.thread_ts.length > 0
- )
-}
-
/** Join the text blocks of an assistant message into one Slack message body. */
export function slackTextFromContent(content: ReadonlyArray<{ type: string; text?: string }>): string {
return content
diff --git a/products/agent_platform/services/agent-shared/src/runtime/trigger-metadata.test.ts b/products/agent_platform/services/agent-shared/src/runtime/trigger-metadata.test.ts
new file mode 100644
index 000000000000..75e2e1b1ae4c
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/trigger-metadata.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ parseTriggerMetadata,
+ SUPPORTED_CLIENT_TOOL_ID_MAX_LEN,
+ SUPPORTED_CLIENT_TOOLS_MAX_LEN,
+} from './trigger-metadata'
+
+describe('parseTriggerMetadata', () => {
+ it.each([
+ { kind: 'chat' },
+ { kind: 'chat', supported_client_tools: ['connect_mcp', 'set_secret'] },
+ { kind: 'slack', workspace_id: 'W', channel: 'C', ts: 't', thread_ts: 't' },
+ { kind: 'cron', cron_name: 'daily', schedule: '0 9 * * *', fired_at: '2026-06-25T09:00:00Z' },
+ { kind: 'webhook' },
+ { kind: 'mcp' },
+ ])('accepts %j', (meta) => {
+ expect(parseTriggerMetadata(meta)).toEqual(meta)
+ })
+
+ it('strips extra keys (e.g. a stale `type` or `client_kind`)', () => {
+ expect(
+ parseTriggerMetadata({
+ kind: 'slack',
+ type: 'slack',
+ workspace_id: 'W',
+ channel: 'C',
+ ts: 't',
+ thread_ts: 't',
+ })
+ ).toEqual({
+ kind: 'slack',
+ workspace_id: 'W',
+ channel: 'C',
+ ts: 't',
+ thread_ts: 't',
+ })
+ expect(parseTriggerMetadata({ kind: 'chat', client_kind: 'posthog-code' })).toEqual({ kind: 'chat' })
+ })
+
+ it.each([null, undefined, {}, 'x', { kind: 'discord' }, { kind: 'slack', channel: 'C' }])(
+ 'returns null for missing/unknown/incomplete: %j',
+ (meta) => {
+ expect(parseTriggerMetadata(meta)).toBeNull()
+ }
+ )
+
+ describe('supported_client_tools bounds', () => {
+ it('rejects an array longer than the cap', () => {
+ const tools = Array.from({ length: SUPPORTED_CLIENT_TOOLS_MAX_LEN + 1 }, (_, i) => `t${i}`)
+ expect(parseTriggerMetadata({ kind: 'chat', supported_client_tools: tools })).toBeNull()
+ })
+
+ it('rejects an id longer than the per-element cap', () => {
+ const tooLong = 'a'.repeat(SUPPORTED_CLIENT_TOOL_ID_MAX_LEN + 1)
+ expect(parseTriggerMetadata({ kind: 'chat', supported_client_tools: [tooLong] })).toBeNull()
+ })
+
+ it('rejects an empty-string id', () => {
+ expect(parseTriggerMetadata({ kind: 'chat', supported_client_tools: [''] })).toBeNull()
+ })
+
+ it('accepts an array at exactly the cap', () => {
+ const tools = Array.from({ length: SUPPORTED_CLIENT_TOOLS_MAX_LEN }, (_, i) => `t${i}`)
+ expect(parseTriggerMetadata({ kind: 'chat', supported_client_tools: tools })).toEqual({
+ kind: 'chat',
+ supported_client_tools: tools,
+ })
+ })
+ })
+
+ describe('supported_client_tools normalization', () => {
+ it('trims whitespace and dedupes', () => {
+ expect(
+ parseTriggerMetadata({
+ kind: 'chat',
+ supported_client_tools: ['focus', ' focus ', 'focus', 'toast'],
+ })
+ ).toEqual({ kind: 'chat', supported_client_tools: ['focus', 'toast'] })
+ })
+
+ it('rejects a whitespace-only id (fails min(1) post-trim)', () => {
+ expect(parseTriggerMetadata({ kind: 'chat', supported_client_tools: [' '] })).toBeNull()
+ })
+
+ it('preserves first-seen order across duplicates', () => {
+ expect(
+ parseTriggerMetadata({
+ kind: 'chat',
+ supported_client_tools: ['c', 'a', 'b', 'a', 'c'],
+ })
+ ).toEqual({ kind: 'chat', supported_client_tools: ['c', 'a', 'b'] })
+ })
+ })
+})
diff --git a/products/agent_platform/services/agent-shared/src/runtime/trigger-metadata.ts b/products/agent_platform/services/agent-shared/src/runtime/trigger-metadata.ts
new file mode 100644
index 000000000000..53af460acfe9
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/trigger-metadata.ts
@@ -0,0 +1,82 @@
+/**
+ * Typed `agent_session.trigger_metadata`. Discriminated on `kind`, parsed once
+ * at the persistence boundary (`pg-queue` `rowToSession`) so readers narrow on
+ * `kind` instead of re-validating a loose bag.
+ *
+ * Strip-on-read contract: Zod's default `.strip()` mode drops any key not
+ * declared in the schema. The dropped keys still live in the JSONB on disk
+ * — `rowToSession` never writes the normalized shape back. Two consequences
+ * for future contributors:
+ *
+ * 1. **Every writer must go through this schema.** Don't insert
+ * `trigger_metadata` rows via raw SQL or a typed-as-unknown shortcut;
+ * anything not in the discriminated union becomes a runtime ghost
+ * (visible to JSONB queries, invisible to every reader).
+ * 2. **Adding a field is a schema change, not a write-side change.** A
+ * writer stamping `{ kind: 'chat', new_field: '…' }` without adding
+ * `new_field` to this schema gets it silently dropped on first read —
+ * bug class to watch for in PR review.
+ *
+ * Authors who want a defense-in-depth test that the column is clean can scan
+ * `agent_session.trigger_metadata` for unknown keys per `kind`; that test
+ * lives at the persistence layer, not here.
+ */
+
+import { z } from 'zod'
+
+// Realistic bounds for `supported_client_tools`: agent specs cap at a few dozen
+// client tool kinds, and ids follow short snake_case (`focus`, `connect_mcp`).
+// Caps stop a misbehaving caller from bloating `agent_session.trigger_metadata`
+// JSONB without breaking any legitimate caller.
+export const SUPPORTED_CLIENT_TOOLS_MAX_LEN = 64
+export const SUPPORTED_CLIENT_TOOL_ID_MAX_LEN = 128
+
+export const TriggerMetadataSchema = z.discriminatedUnion('kind', [
+ z.object({
+ kind: z.literal('chat'),
+ // Client tool ids the connecting client can fulfil this session (from the
+ // /run body). The runner exposes a `kind:'client'` spec tool to the model
+ // only if its id is listed here.
+ // Trim + dedupe at the parse boundary so `supported.includes(t.id)` in
+ // build-agent-tools.ts can be an exact-string match. A caller that
+ // sent `['focus', ' focus ', 'focus']` collapses to `['focus']`. Trim
+ // happens before length validation so a whitespace-only string fails
+ // the `min(1)` check rather than slipping through as empty.
+ supported_client_tools: z
+ .array(
+ z
+ .string()
+ .transform((s) => s.trim())
+ .pipe(z.string().min(1).max(SUPPORTED_CLIENT_TOOL_ID_MAX_LEN))
+ )
+ .max(SUPPORTED_CLIENT_TOOLS_MAX_LEN)
+ .transform((xs) => Array.from(new Set(xs)))
+ .optional(),
+ }),
+ z.object({
+ kind: z.literal('slack'),
+ workspace_id: z.string(),
+ channel: z.string(),
+ ts: z.string(),
+ thread_ts: z.string(),
+ }),
+ z.object({
+ kind: z.literal('cron'),
+ cron_name: z.string(),
+ schedule: z.string(),
+ fired_at: z.string(),
+ manual: z.boolean().optional(),
+ }),
+ z.object({ kind: z.literal('webhook') }),
+ z.object({ kind: z.literal('mcp') }),
+])
+
+export type TriggerMetadata = z.infer<typeof TriggerMetadataSchema>
+
+export type SlackTriggerMetadata = Extract<TriggerMetadata, { kind: 'slack' }>
+
+/** Validate a stored row's `trigger_metadata`; unknown/missing/malformed → null. */
+export function parseTriggerMetadata(raw: unknown): TriggerMetadata | null {
+ const parsed = TriggerMetadataSchema.safeParse(raw)
+ return parsed.success ? parsed.data : null
+}
diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.ts
index 3c94f94d97d4..58a76652685c 100644
--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts
@@ -7,6 +7,8 @@
import { z } from 'zod'
+import type { TriggerMetadata } from '../runtime/trigger-metadata'
+
export const ModelIdSchema = z
.string()
.min(1)
@@ -1107,15 +1109,8 @@ export interface AgentSession {
* `cron-trigger-scheduler.md` §6.
*/
idempotency_key: string | null
- /**
- * Trigger-specific metadata stamped at enqueue time. Shape varies by
- * trigger kind; for cron firings:
- * `{ kind: 'cron', cron_name, schedule, fired_at }`. Read by the
- * session-detail UI to render a "fired by `<cron_name>` at `<fired_at>`"
- * badge. Stash-don't-parse — the runtime doesn't introspect this beyond
- * forwarding it to the UI.
- */
- trigger_metadata: Record<string, unknown> | null
+ /** Trigger-specific metadata stamped at enqueue, discriminated on `kind`. */
+ trigger_metadata: TriggerMetadata | null
/**
* Session state. See the session-restart redesign for the contract:
*
diff --git a/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts b/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts
index d3c9c11ca015..838381b54b5b 100644
--- a/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/approval-gated.test.ts
@@ -556,13 +556,10 @@ describe('approval-gated tools: real e2e', () => {
})
// ─────────────────────────────────────────────────────────────
- // Case 8 — posthog-code client suppresses URL prose.
- // Same flow as case 1 but the caller sets X-PostHog-Client: posthog-code,
- // so the queued envelope must NOT carry approval_url / approver_hint —
- // the desktop chat preview renders an in-line approval card and the
- // standalone console (port 3040) is going away.
+ // Case 8 — the queued envelope always carries approval_url + approver_hint,
+ // regardless of the connecting client (no per-client suppression).
// ─────────────────────────────────────────────────────────────
- it('case 8: posthog-code client omits approval_url + approver_hint from the queued envelope', async () => {
+ it('case 8: queued envelope always includes approval_url + approver_hint', async () => {
c.setScript([
fauxCallTool('@posthog/query', { project_id: 1, query: 'select 1' }),
fauxText('queued for approval'),
@@ -576,21 +573,16 @@ describe('approval-gated tools: real e2e', () => {
const run = await request(c.ingress)
.post('/agents/gated-8/run')
.set('authorization', `Bearer ${APPROVAL_PAT}`)
- .set('X-PostHog-Client', 'posthog-code')
- .send({ message: 'go' })
+ .send({ message: 'go', supported_client_tools: ['connect_mcp'] })
expect(run.status).toBe(200)
await c.drain()
const session = await c.queue.get(run.body.session_id)
const queued = findApproval(session!.conversation, 'queued')
expect(queued).not.toBeNull()
- // The model still sees the request_id + state so it knows the call
- // is gated, but neither the URL nor the admin hint — its only
- // option is to acknowledge the queued state in plain text.
expect(queued!.request_id).toMatch(/^[0-9a-f-]+$/)
- expect(queued!.approval_url).toBeUndefined()
- expect(queued!.approver_hint).toBeUndefined()
- // Sanity: client_kind landed on the session row.
- expect(session!.trigger_metadata).toMatchObject({ client_kind: 'posthog-code' })
+ expect(queued!.approval_url).not.toBeUndefined()
+ expect(queued!.approver_hint).not.toBeUndefined()
+ expect(session!.trigger_metadata).toEqual({ kind: 'chat', supported_client_tools: ['connect_mcp'] })
})
})
diff --git a/products/agent_platform/services/agent-tests/src/cases/chat-trigger.test.ts b/products/agent_platform/services/agent-tests/src/cases/chat-trigger.test.ts
index a0463bf5306b..c719a9ee3c26 100644
--- a/products/agent_platform/services/agent-tests/src/cases/chat-trigger.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/chat-trigger.test.ts
@@ -126,32 +126,26 @@ describe('chat trigger: real e2e', () => {
expect(res.body).toMatchObject({ error: 'no_chat_trigger' })
})
- it('stamps client_kind on the session row when X-PostHog-Client is supplied at /run', async () => {
+ it('stamps supported_client_tools from the /run body', async () => {
c.setScript([fauxText('ok')])
- await c.deployAgent({ slug: 'kind' })
+ await c.deployAgent({ slug: 'supports' })
const res = await request(c.ingress)
- .post('/agents/kind/run')
- .set('X-PostHog-Client', 'posthog-code')
- .send({ message: 'hi' })
+ .post('/agents/supports/run')
+ .send({ message: 'hi', supported_client_tools: ['connect_mcp', 'set_secret'] })
expect(res.status).toBe(200)
const session = await c.queue.get(res.body.session_id)
- // Posthog-code is the only recognised value today; the runner
- // gates the approval-URL prose on this exact string.
- expect(session!.trigger_metadata).toMatchObject({ kind: 'chat', client_kind: 'posthog-code' })
+ expect(session!.trigger_metadata).toEqual({
+ kind: 'chat',
+ supported_client_tools: ['connect_mcp', 'set_secret'],
+ })
})
- it('drops an unrecognised X-PostHog-Client value silently (no client_kind stamped)', async () => {
+ it('omits supported_client_tools when none are supplied', async () => {
c.setScript([fauxText('ok')])
- await c.deployAgent({ slug: 'kind-unknown' })
- const res = await request(c.ingress)
- .post('/agents/kind-unknown/run')
- .set('X-PostHog-Client', 'not-a-real-client')
- .send({ message: 'hi' })
+ await c.deployAgent({ slug: 'supports-none' })
+ const res = await request(c.ingress).post('/agents/supports-none/run').send({ message: 'hi' })
expect(res.status).toBe(200)
const session = await c.queue.get(res.body.session_id)
- // Unrecognised → null; never crash, never store the unknown value
- // (so a future allowlist add can't pick up stale rows from old
- // clients that guessed the new name).
expect(session!.trigger_metadata).toEqual({ kind: 'chat' })
})
})
diff --git a/products/agent_platform/services/agent-tests/src/cases/client-tool.test.ts b/products/agent_platform/services/agent-tests/src/cases/client-tool.test.ts
index d004bd572c41..7b7d73558961 100644
--- a/products/agent_platform/services/agent-tests/src/cases/client-tool.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/client-tool.test.ts
@@ -48,7 +48,9 @@ describe('client-fulfilled tool dispatch: real e2e', () => {
// on the same bus (which is exactly what the ingress
// /client_tool_result endpoint does in production).
const seenCalls: Array<{ tool_id: string; call_id: string }> = []
- const res = await request(c.ingress).post('/agents/concierge-like/run').send({ message: 'fetch context' })
+ const res = await request(c.ingress)
+ .post('/agents/concierge-like/run')
+ .send({ message: 'fetch context', supported_client_tools: ['get_context'] })
const sessionId = res.body.session_id as string
const unsub = c.bus.subscribe(sessionId, (e) => {
if (e.kind !== 'client_tool_call') {
@@ -99,7 +101,9 @@ describe('client-fulfilled tool dispatch: real e2e', () => {
],
},
})
- const res = await request(c.ingress).post('/agents/no-client/run').send({ message: 'focus the file' })
+ const res = await request(c.ingress)
+ .post('/agents/no-client/run')
+ .send({ message: 'focus the file', supported_client_tools: ['focus'] })
const sessionId = res.body.session_id as string
await c.drain({ iterations: 100 })
@@ -133,7 +137,9 @@ describe('client-fulfilled tool dispatch: real e2e', () => {
],
},
})
- const res = await request(c.ingress).post('/agents/order/run').send({ message: 'go' })
+ const res = await request(c.ingress)
+ .post('/agents/order/run')
+ .send({ message: 'go', supported_client_tools: ['toast'] })
const sessionId = res.body.session_id as string
const unsub = c.bus.subscribe(sessionId, (e) => {
if (e.kind === 'client_tool_call' || e.kind === 'client_tool_result') {
diff --git a/products/agent_platform/services/agent-tests/src/cases/interactive-client-tool.test.ts b/products/agent_platform/services/agent-tests/src/cases/interactive-client-tool.test.ts
index 331e78a06907..5f26ba7ec3ae 100644
--- a/products/agent_platform/services/agent-tests/src/cases/interactive-client-tool.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/interactive-client-tool.test.ts
@@ -76,7 +76,9 @@ describe('interactive client tool dispatch: real e2e', () => {
// the in-process await; we should NOT see a matching
// `client_tool_result` bus event (those only flow through the
// legacy /client_tool_result path).
- const res = await request(c.ingress).post('/agents/demo/run').send({ message: 'set the puns key' })
+ const res = await request(c.ingress)
+ .post('/agents/demo/run')
+ .send({ message: 'set the puns key', supported_client_tools: ['set_secret'] })
const sessionId = res.body.session_id as string
const busEvents: Array<{ kind: string; data: Record<string, unknown> }> = []
const unsub = c.bus.subscribe(sessionId, (e) => {
@@ -185,7 +187,9 @@ describe('interactive client tool dispatch: real e2e', () => {
},
})
- const res = await request(c.ingress).post('/agents/demo/run').send({ message: 'set it' })
+ const res = await request(c.ingress)
+ .post('/agents/demo/run')
+ .send({ message: 'set it', supported_client_tools: ['set_secret'] })
const sessionId = res.body.session_id as string
const calls: string[] = []
const unsub = c.bus.subscribe(sessionId, (e) => {
diff --git a/products/agent_platform/services/agent-tests/src/cases/supported-client-tools.test.ts b/products/agent_platform/services/agent-tests/src/cases/supported-client-tools.test.ts
new file mode 100644
index 000000000000..10f49ec0f2f5
--- /dev/null
+++ b/products/agent_platform/services/agent-tests/src/cases/supported-client-tools.test.ts
@@ -0,0 +1,148 @@
+/**
+ * `supported_client_tools` gating: the /run caller declares which `kind:'client'`
+ * tool ids it can fulfil; the runner exposes only those to the model. A
+ * `required` client tool the caller can't fulfil fails chat session open;
+ * non-chat triggers (webhook/slack/cron/mcp) have no client to declare
+ * support, so every client tool is hidden there and the model degrades.
+ */
+
+import request from 'supertest'
+
+import { buildCluster, closeSharedPool, Cluster, fauxCallTool, fauxText } from '../harness'
+
+interface ClientToolSpec {
+ kind: 'client'
+ id: string
+ description: string
+ args_schema: Record<string, unknown>
+ required: boolean
+}
+
+const clientTool = (id: string, required = false): ClientToolSpec => ({
+ kind: 'client',
+ id,
+ description: `client tool ${id}`,
+ args_schema: { type: 'object', properties: {}, additionalProperties: false },
+ required,
+})
+
+describe('supported_client_tools: capability-gated exposure', () => {
+ let c: Cluster
+
+ beforeEach(async () => {
+ c = await buildCluster()
+ })
+
+ afterEach(async () => {
+ await c.teardown()
+ })
+
+ afterAll(async () => {
+ await closeSharedPool()
+ })
+
+ it('exposes a declared client tool to the model and round-trips it; stores the declaration', async () => {
+ c.setScript([fauxCallTool('get_context', {}), fauxText('saw context')])
+ await c.deployAgent({
+ slug: 'gated-supported',
+ spec: { tools: [clientTool('get_context'), clientTool('focus')] },
+ })
+ const res = await request(c.ingress)
+ .post('/agents/gated-supported/run')
+ .send({ message: 'go', supported_client_tools: ['get_context'] })
+ const sessionId = res.body.session_id as string
+
+ // Stored on the session row exactly as declared (typed `chat` variant).
+ const stored = await c.queue.get(sessionId)
+ expect(stored!.trigger_metadata).toEqual({ kind: 'chat', supported_client_tools: ['get_context'] })
+
+ const seen: string[] = []
+ const unsub = c.bus.subscribe(sessionId, (e) => {
+ if (e.kind !== 'client_tool_call') {
+ return
+ }
+ const d = e.data as { call_id: string; tool_id: string }
+ seen.push(d.tool_id)
+ void c.bus.publish({
+ session_id: sessionId,
+ kind: 'client_tool_result',
+ data: { call_id: d.call_id, result: { ok: true } },
+ ts: new Date().toISOString(),
+ })
+ })
+ await c.drain()
+ unsub()
+
+ const session = await c.queue.get(sessionId)
+ expect(session!.state).toBe('completed')
+ // The runner exposed get_context (model called it, runner dispatched it).
+ expect(seen).toEqual(['get_context'])
+ const toolResult = session!.conversation.find((m) => m.role === 'toolResult')
+ expect(toolResult).toBeTruthy()
+ })
+
+ it('hides a non-required client tool the caller did not declare', async () => {
+ // Model tries to call `focus`, which the caller did not declare → it was
+ // never exposed, so the runner never dispatches it (no client_tool_call).
+ c.setScript([fauxCallTool('focus', {}), fauxText('no panel')])
+ await c.deployAgent({
+ slug: 'gated-hidden',
+ spec: { tools: [clientTool('get_context'), clientTool('focus')] },
+ })
+ const res = await request(c.ingress)
+ .post('/agents/gated-hidden/run')
+ .send({ message: 'focus please', supported_client_tools: ['get_context'] })
+ const sessionId = res.body.session_id as string
+
+ const seen: string[] = []
+ const unsub = c.bus.subscribe(sessionId, (e) => {
+ if (e.kind === 'client_tool_call') {
+ seen.push((e.data as { tool_id: string }).tool_id)
+ }
+ })
+ await c.drain({ iterations: 100 })
+ unsub()
+
+ expect(seen).not.toContain('focus')
+ // Undeclared tool is silently skipped, not a session failure: the model
+ // gets an unknown-tool error result and continues to its next turn.
+ const session = await c.queue.get(sessionId)
+ expect(session!.state).toBe('completed')
+ })
+
+ it('fails session open when a required client tool is not declared', async () => {
+ c.setScript([fauxText('never runs')])
+ await c.deployAgent({
+ slug: 'gated-required',
+ spec: { tools: [clientTool('connect_mcp', true)] },
+ })
+ const res = await request(c.ingress)
+ .post('/agents/gated-required/run')
+ .send({ message: 'go', supported_client_tools: [] })
+ const sessionId = res.body.session_id as string
+ await c.drain({ iterations: 100 })
+
+ const session = await c.queue.get(sessionId)
+ expect(session!.state).toBe('failed')
+ })
+
+ // Non-chat triggers have no connecting client to declare capabilities, so
+ // every `kind:'client'` tool — required or not — is hidden and the model
+ // degrades per agent.md. The `required` check fires only when there's
+ // actually a client to disappoint (chat triggers); webhook/slack/cron/mcp
+ // sessions never throw `client_tool_unsupported`.
+ it('webhook session degrades silently when the spec has a required client tool', async () => {
+ c.setScript([fauxText('handled the webhook')])
+ await c.deployAgent({
+ slug: 'webhook-required-client',
+ spec: { tools: [clientTool('connect_mcp', true)] },
+ })
+ const res = await request(c.ingress).post('/agents/webhook-required-client/webhook').send({ alert: 'fired' })
+ expect(res.status).toBe(200)
+ await c.drain({ iterations: 100 })
+
+ const session = await c.queue.get(res.body.session_id)
+ expect(session!.state).toBe('completed')
+ expect(session!.trigger_metadata).toEqual({ kind: 'webhook' })
+ })
+})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 14e9f860f469..3a601922900c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7854,7 +7854,7 @@ export namespace Schemas {
} as const;
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
export type AgentSessionSummaryTriggerMetadata = { [key: string]: unknown } | null;
@@ -7869,7 +7869,7 @@ export namespace Schemas {
/** @nullable */
external_key: string | null;
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
trigger_metadata?: AgentSessionSummaryTriggerMetadata;
@@ -7892,7 +7892,7 @@ export namespace Schemas {
}
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
export type AgentApplicationSessionsRetrieveResponseTriggerMetadata = { [key: string]: unknown } | null;
@@ -7983,7 +7983,7 @@ export namespace Schemas {
/** @nullable */
external_key: string | null;
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
trigger_metadata?: AgentApplicationSessionsRetrieveResponseTriggerMetadata;
@@ -8040,7 +8040,7 @@ export namespace Schemas {
} as const;
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
export type AgentFleetLiveSessionSummaryTriggerMetadata = { [key: string]: unknown } | null;
@@ -8056,7 +8056,7 @@ export namespace Schemas {
/** @nullable */
external_key: string | null;
/**
- * Trigger-specific metadata stamped at session creation. Shape varies by trigger kind; cron firings carry `{ kind: 'cron', cron_name, schedule, fired_at, manual? }`. Render this on session-detail so the operator can tell at a glance that a session was fired by which cron / when.
+ * Trigger-specific metadata stamped at session creation. Discriminated on `kind`: chat | slack | cron | webhook | mcp. The Zod source of truth is `agent-shared/src/runtime/trigger-metadata.ts`; the node side validates and strips unknown keys at the persistence boundary, so consumers can trust `kind` and per-kind fields. TODO: narrow this DictField to a polymorphic serializer mirroring the union (needs `hogli build:openapi`).
* @nullable
*/
trigger_metadata?: AgentFleetLiveSessionSummaryTriggerMetadata;