: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(agent-platform): agent-level MCP connections, per-agent tool permissions, and capability-based client tools (#66007)
Ben Whitee9b74700bb49
diff --git a/products/agent_platform/README.md b/products/agent_platform/README.mdindex 2cf66ee817b7..225b8360179e 100644--- a/products/agent_platform/README.md+++ b/products/agent_platform/README.md@@ -36,5 +36,5 @@ AgentSessionV2```The `spec` JSONB is the structural truth — model, triggers, tools, mcps,-skills, integrations, secrets, limits, entrypoint. See `@posthog/agent-shared-v2`+skills, secrets, limits, entrypoint. See `@posthog/agent-shared-v2`for the canonical TypeScript shape (`AgentSpec`).diff --git a/products/agent_platform/backend/tests/test_preview_proxy.py b/products/agent_platform/backend/tests/test_preview_proxy.pyindex c4847e37e372..f1dc27f7d555 100644--- a/products/agent_platform/backend/tests/test_preview_proxy.py+++ b/products/agent_platform/backend/tests/test_preview_proxy.py@@ -39,7 +39,6 @@ def _base_spec() -> dict[str, Any]:"tools": [],"mcps": [],"skills": [],- "integrations": [],"secrets": [],"limits": {"max_turns": 10, "max_tool_calls": 20, "max_wall_seconds": 60},}diff --git a/products/agent_platform/backend/tests/test_preview_token.py b/products/agent_platform/backend/tests/test_preview_token.pyindex 83291a126808..30895a423c8a 100644--- a/products/agent_platform/backend/tests/test_preview_token.py+++ b/products/agent_platform/backend/tests/test_preview_token.py@@ -50,7 +50,6 @@ def _base_spec(triggers: list[dict[str, Any]] | None = None, modes: list[str] |"tools": [],"mcps": [],"skills": [],- "integrations": [],"secrets": [],"limits": {"max_turns": 10, "max_tool_calls": 20, "max_wall_seconds": 60},}diff --git a/products/agent_platform/docs/architecture.md b/products/agent_platform/docs/architecture.mdindex 294830ecaf8d..1fe73e4b4b82 100644--- a/products/agent_platform/docs/architecture.md+++ b/products/agent_platform/docs/architecture.md@@ -105,7 +105,6 @@ flowchart LRspec --> tools["tools[]<br/>native·custom·client"]spec --> mcps["mcps[]<br/>external MCP servers"]spec --> skills["skills[]"]- spec --> integ["integrations[]"]spec --> idp["identity_providers[]<br/>posthog·oauth2"]spec --> secrets["secrets[]"]spec --> limits["limits<br/>turns·tools·wall·mem·cpu"]diff --git a/products/agent_platform/docs/identity-and-tools.md b/products/agent_platform/docs/identity-and-tools.mdindex 5e3065aed1ce..f9417bc1f355 100644--- a/products/agent_platform/docs/identity-and-tools.md+++ b/products/agent_platform/docs/identity-and-tools.md@@ -156,7 +156,7 @@ instead of the tool failing.### What a tool receives — `ToolContext`Threaded through to every tool: `teamId · applicationId · sessionId`,-`secret(name)` (decrypted `encrypted_env`), `integrations` (team OAuth tokens),+`secret(name)` (decrypted `encrypted_env`),`credentials.resolve(target)` (the per-session broker), `identity.resolve(provider)`(linked-identity gate), `resolvedIdentities` (pre-resolved for gated tools),`memoryStore` / `tabularStore`, and `http` (the proxy-bound `HttpClient` — thediff --git a/products/agent_platform/services/agent-ingress/vitest.config.ts b/products/agent_platform/services/agent-ingress/vitest.config.tsindex 506864af4e00..8f97a2c2c971 100644--- a/products/agent_platform/services/agent-ingress/vitest.config.ts+++ b/products/agent_platform/services/agent-ingress/vitest.config.ts@@ -7,9 +7,9 @@ export default defineConfig({include: ['src/**/*.test.ts'],testTimeout: 15_000,globals: true,- // Test files share the agent_runtime_queue_test PG. Running them in- // parallel races on `node-pg-migrate`'s schema lock and on the- // public-schema drop in `reset()`. Mirrors agent-shared + agent-tests.+ // Test files share one Postgres (agent_runtime_queue_test). `reset()`+ // truncates the shared `agent_*` tables between cases, so running files+ // in parallel races on that shared state. Mirrors agent-shared + agent-tests.fileParallelism: false,},})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.tsindex 4ac7d2714849..5242bef1fe4f 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@@ -351,6 +351,8 @@ describe('validateRevisionBundle', () => {secrets: ['GITHUB_TOKEN'],mcps: [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'github',url: 'https://api.githubcopilot.com/mcp',secrets: ['GITHUB_TOKEN'],@@ -376,7 +378,15 @@ describe('validateRevisionBundle', () => {const report = await validateRevisionBundle(mkRev({secrets: ['TENANT'],- mcps: [{ id: 'tenant', url: 'https://${TENANT}.example.com/mcp', secrets: ['TENANT'] }],+ mcps: [+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'tenant',+ url: 'https://${TENANT}.example.com/mcp',+ secrets: ['TENANT'],+ },+ ],}),bundles)@@ -397,6 +407,8 @@ describe('validateRevisionBundle', () => {secrets: [{ name: 'GITHUB_TOKEN', allowed_hosts: ['api.githubcopilot.com'] }],mcps: [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'github',url: 'https://api.githubcopilot.com/mcp',secrets: ['GITHUB_TOKEN'],@@ -415,7 +427,15 @@ describe('validateRevisionBundle', () => {const report = await validateRevisionBundle(mkRev({secrets: ['GITHUB_TOKEN'],- mcps: [{ id: 'github', url: 'https://api.githubcopilot.com/mcp', secrets: ['GITHUB_TOKEN'] }],+ mcps: [+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'github',+ url: 'https://api.githubcopilot.com/mcp',+ secrets: ['GITHUB_TOKEN'],+ },+ ],}),bundles)diff --git a/products/agent_platform/services/agent-janitor/vitest.config.ts b/products/agent_platform/services/agent-janitor/vitest.config.tsindex 506864af4e00..8f97a2c2c971 100644--- a/products/agent_platform/services/agent-janitor/vitest.config.ts+++ b/products/agent_platform/services/agent-janitor/vitest.config.ts@@ -7,9 +7,9 @@ export default defineConfig({include: ['src/**/*.test.ts'],testTimeout: 15_000,globals: true,- // Test files share the agent_runtime_queue_test PG. Running them in- // parallel races on `node-pg-migrate`'s schema lock and on the- // public-schema drop in `reset()`. Mirrors agent-shared + agent-tests.+ // Test files share one Postgres (agent_runtime_queue_test). `reset()`+ // truncates the shared `agent_*` tables between cases, so running files+ // in parallel races on that shared state. Mirrors agent-shared + agent-tests.fileParallelism: false,},})diff --git a/products/agent_platform/services/agent-runner/src/index.ts b/products/agent_platform/services/agent-runner/src/index.tsindex 6d34c7aadfb3..f1161623ea1e 100644--- a/products/agent_platform/services/agent-runner/src/index.ts+++ b/products/agent_platform/services/agent-runner/src/index.ts@@ -47,6 +47,7 @@ import {PgIdentityCredentialStore,PgIdentityLinkStateStore,PgIdentityStore,+ PgMcpConnectionStore,PgRevisionStore,PgSandboxInstanceStore,PgSessionQueue,@@ -185,6 +186,11 @@ async function main(): Promise<void> {// bearer is a single static phs_ now, so this no longer feeds it.const teamApiKeys = new PgTeamApiKeyResolver(posthogDb)+ // Shared MCP credentials (`spec.mcps[].connection`): reads/decrypts/refreshes+ // the native installation row. `http` is proxy-bound (refresh via smokescreen).+ // Needs UPDATE on `mcp_store_mcpserverinstallation` for write-back.+ const mcpConnections = new PgMcpConnectionStore(posthogDb, encryption, http)+// LLM analytics sink. Captures `$ai_generation` per pi-ai call, `$ai_span`// per tool dispatch, and one `$ai_trace` per session via PostHog's standard// ingestion path (posthog-node /capture). Routes each event to the owning@@ -374,6 +380,7 @@ async function main(): Promise<void> {identityLinks: new PgIdentityLinkStateStore(agentDb),identities,linkRedirectBaseUrl: config.linkRedirectBaseUrl,+ mcpConnections,devMcpBearerToken: config.devMcpBearerToken,http,posthogApiBaseUrl: config.posthogApiBaseUrl,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.tsindex 136d94938c2b..565d34dccf85 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@@ -17,7 +17,9 @@ import {UpsertApprovalRequestResult,} from '@posthog/agent-shared'-import { type ApprovalPolicy, queueApprovalResult } from './approval'+import { type ApprovalPolicy, dispatchApprovedResult, queueApprovalResult } from './approval'+import type { RealToolExecute } from './build-agent-tools'+import { resolveApprovedExecutor } from './mcp-tool-lookup'const TEST_SESSION_ID = '00000000-0000-4000-8000-00000000fe01'const TEST_APP_ID = '00000000-0000-4000-8000-00000000fa01'@@ -167,3 +169,87 @@ describe('queueApprovalResult: model-facing envelope', () => {expect(envelope.approval.approval_url).not.toBeUndefined()})})++describe('dispatchApprovedResult: proxy-routed resume', () => {+ // A proxy connection gates `call_tool` on the underlying tool, so the+ // approval row is keyed `<prefix>__<remoteName>` with the call_tool args+ // stashed as proposed_args. On resume the driver must route that row back to+ // the connection's `call_tool` executor (via resolveApprovedExecutor) — a+ // plain `realExecute.get(row.tool_name)` misses it and drops the call.+ function makeProxyRow(over: Partial<ApprovalRequest> = {}): ApprovalRequest {+ return {+ id: 'req-proxy-1',+ session_id: TEST_SESSION_ID,+ application_id: TEST_APP_ID,+ revision_id: TEST_REV_ID,+ team_id: 1,+ turn: 1,+ tool_call_id: 'tc-9',+ tool_name: 'posthog__get-insights',+ proposed_args: { tool_name: 'get-insights', arguments: { limit: 5 } },+ args_hash: Buffer.alloc(0),+ assistant_message: null,+ approver_scope: null,+ state: 'approving',+ decision_by: 'u1',+ decision_at: null,+ decision_reason: null,+ decided_args: null,+ dispatch_outcome: null,+ expires_at: '2026-06-26',+ created_at: '2026-06-26',+ ...over,+ } as ApprovalRequest+ }++ function dispatchStore(): ApprovalStore & { dispatched: Array<{ id: string; outcome: unknown }> } {+ const dispatched: Array<{ id: string; outcome: unknown }> = []+ return {+ dispatched,+ async markDispatched(id: string, outcome: unknown): Promise<void> {+ dispatched.push({ id, outcome })+ },+ } as unknown as ApprovalStore & { dispatched: Array<{ id: string; outcome: unknown }> }+ }++ it('replays the approved proxy call through the connection call_tool executor', async () => {+ const seen: Array<{ id: string; args: Record<string, unknown> }> = []+ const callToolExec: RealToolExecute = async (id, args) => {+ seen.push({ id, args })+ return { content: [{ type: 'text' as const, text: 'ok' }], details: { output: { ran: true } } }+ }+ const realExecute = new Map<string, RealToolExecute>([['posthog__call_tool', callToolExec]])+ const proxyCallTools = new Map<string, unknown>([['posthog__call_tool', {}]])+ const row = makeProxyRow()+ const store = dispatchStore()++ const d = await dispatchApprovedResult({+ approvals: store,+ realExecute: resolveApprovedExecutor(row.tool_name, realExecute, proxyCallTools),+ row,+ })++ expect(d.isError).toBe(false)+ // The call_tool executor ran with the row's stored call_tool args (the+ // remote tool + its arguments), i.e. the real call replayed.+ expect(seen).toEqual([{ id: 'tc-9', args: { tool_name: 'get-insights', arguments: { limit: 5 } } }])+ expect(store.dispatched[0]?.outcome).toEqual({ result: { ran: true } })+ })++ it('the old direct lookup (the bug) drops the call with a synthetic "unknown tool"', async () => {+ const realExecute = new Map<string, RealToolExecute>([+ ['posthog__call_tool', async () => ({ content: [], details: {} })],+ ])+ const row = makeProxyRow()++ const d = await dispatchApprovedResult({+ approvals: dispatchStore(),+ // What the driver did before: a plain lookup by the re-keyed name.+ realExecute: realExecute.get(row.tool_name),+ row,+ })++ expect(d.isError).toBe(true)+ expect(d.error).toBe('native tool unknown: posthog__get-insights')+ })+})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 1d8a71458e8d..3d218bbd22e3 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@@ -211,7 +211,16 @@ describe('buildAgentTools', () => {const rev = makeRev([],[],- [{ id: 'posthog', url: 'https://x/mcp', secrets: [], auth: { provider: 'posthog' } }]+ [+ {+ kind: 'principal',+ id: 'posthog',+ url: 'https://x/mcp',+ secrets: [],+ default_tool_approval: 'allow',+ auth: { provider: 'posthog' },+ },+ ])const built = await buildAgentTools(rev, makeDeps(rev))expect(built.tools.map((t) => t.label)).toContain('@posthog/identity-connect')@@ -359,7 +368,13 @@ describe('buildAgentTools', () => {describe('mcp tools', () => {it('emits one AgentTool per remote tool, name-prefixed with the client prefix', async () => {- const ref: McpRef = { id: 'linear', url: 'https://example.com/linear', secrets: [] }+ const ref: McpRef = {+ kind: 'agent',+ id: 'linear',+ url: 'https://example.com/linear',+ secrets: [],+ default_tool_approval: 'allow',+ }const mcp = makeFakeMcp('linear', ref, {'create-issue': { description: 'Open a new Linear issue.', handler: async () => ({}) },'list-issues': { description: 'List recent Linear issues.', handler: async () => ({}) },@@ -371,16 +386,16 @@ describe('buildAgentTools', () => {expect(names).toContain('linear__list-issues')})- it('filters remote tools through ref.tools[] bare-string entries (empty/omitted = expose all)', async () => {- // Post-PR-7: bare-string entries in `tools[]` preserve the old- // `allowlist[]` inclusion semantics. Object-form entries also- // count toward inclusion via their `name` field — covered in the- // approval-wrap suite (commit B).+ it('exposes only the tools the author allows (default deny + per-tool allow = allowlist)', async () => {+ // A curated allowlist in the single model: deny everything by+ // default, allow the named tools.const ref: McpRef = {+ kind: 'agent',id: 'linear',url: 'https://example.com/linear',secrets: [],- tools: ['list-issues'],+ default_tool_approval: 'deny',+ tools: [{ name: 'list-issues', level: 'allow' }],}const mcp = makeFakeMcp('linear', ref, {'create-issue': { description: 'Open a new Linear issue.', handler: async () => ({}) },@@ -393,8 +408,40 @@ describe('buildAgentTools', () => {expect(names).not.toContain('linear__create-issue')})+ it('exposes connection tools purely by the agent config — installation owner marks are not enforced', async () => {+ // The agent's per-tool config / default_tool_approval is the sole+ // authority. The shared installation's owner marks (needs_approval /+ // do_not_use) are no longer plumbed into the runtime, so an `allow`+ // default exposes every tool ungated regardless of what the owner set.+ const ref: McpRef = {+ kind: 'agent',+ id: 'incident',+ url: 'https://example.com/incident',+ connection: '019e7fb7-f4c0-75e2-9055-7c29a5cbb999',+ default_tool_approval: 'allow',+ secrets: [],+ }+ const mcp = makeFakeMcp('incident', ref, {+ 'list-incidents': { description: 'List incidents.', handler: async () => ({}) },+ 'create-incident': { description: 'Open an incident.', handler: async () => ({}) },+ 'delete-incident': { description: 'Delete an incident.', handler: async () => ({}) },+ })+ const rev = makeRev([], [], [ref])+ const built = await buildAgentTools(rev, makeDeps(rev, { mcpClients: [mcp] }))+ const names = built.tools.map((t) => t.label)+ expect(names).toContain('incident__list-incidents')+ expect(names).toContain('incident__create-incident')+ expect(names).toContain('incident__delete-incident')+ })+it('execute dispatches through the open client and surfaces structured output', async () => {- const ref: McpRef = { id: 'linear', url: 'https://example.com/linear', secrets: [] }+ const ref: McpRef = {+ kind: 'agent',+ id: 'linear',+ url: 'https://example.com/linear',+ secrets: [],+ default_tool_approval: 'allow',+ }const mcp = makeFakeMcp('linear', ref, {'create-issue': {description: 'Open a new Linear issue.',@@ -414,7 +461,13 @@ describe('buildAgentTools', () => {})it('execute throws when the remote returns isError so the loop renders an error tool_result', async () => {- const ref: McpRef = { id: 'linear', url: 'https://example.com/linear', secrets: [] }+ const ref: McpRef = {+ kind: 'agent',+ id: 'linear',+ url: 'https://example.com/linear',+ secrets: [],+ default_tool_approval: 'allow',+ }const mcp = makeFakeMcp('linear', ref, {'create-issue': {description: 'Open a new Linear issue.',@@ -433,7 +486,13 @@ describe('buildAgentTools', () => {// `create-issue` would collapse to the same exposed id. We keep// the first one (the custom tool) and silently skip the duplicate// — matches the dup-id semantics of spec.tools[].- const ref: McpRef = { id: 'linear', url: 'https://example.com/linear', secrets: [] }+ const ref: McpRef = {+ kind: 'agent',+ id: 'linear',+ url: 'https://example.com/linear',+ secrets: [],+ default_tool_approval: 'allow',+ }const mcp = makeFakeMcp('linear', ref, {'create-issue': { description: 'Open a Linear issue.', handler: async () => ({}) },})@@ -452,14 +511,18 @@ describe('buildAgentTools', () => {it('walks multiple opened clients and surfaces all their tools', async () => {const linearRef: McpRef = {+ kind: 'agent',id: 'linear',url: 'https://example.com/linear',secrets: [],+ default_tool_approval: 'allow',}const githubRef: McpRef = {+ kind: 'agent',id: 'github',url: 'https://example.com/github',secrets: [],+ default_tool_approval: 'allow',}const linear = makeFakeMcp('linear', linearRef, {'create-issue': { description: 'd', handler: async () => ({}) },@@ -475,7 +538,13 @@ describe('buildAgentTools', () => {})it('keeps the provider-safe name map keyed by the prefixed id', async () => {- const ref: McpRef = { id: 'linear', url: 'https://example.com/linear', secrets: [] }+ const ref: McpRef = {+ kind: 'agent',+ id: 'linear',+ url: 'https://example.com/linear',+ secrets: [],+ default_tool_approval: 'allow',+ }const mcp = makeFakeMcp('linear', ref, {'create-issue': { description: 'd', handler: async () => ({}) },})@@ -491,7 +560,13 @@ describe('buildAgentTools', () => {// Without the wrapping, an SDK-internal error string would surface// as the session-failure reason — making it hard to attribute the// outage to a specific MCP at triage time.- const ref: McpRef = { id: 'flaky', url: 'https://example.com/flaky', secrets: [] }+ const ref: McpRef = {+ kind: 'agent',+ id: 'flaky',+ url: 'https://example.com/flaky',+ secrets: [],+ default_tool_approval: 'allow',+ }const brokenClient: OpenedMcp = {prefix: 'flaky',ref,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.tsindex 3b09bd0bc8c0..ddb5a498005f 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@@ -47,6 +47,9 @@ import {import { getNativeTool, hasNativeTool, WEB_SEARCH_TOOL_ID } from '@posthog/agent-tools'import type { OpenedMcp, RemoteMcpTool } from './mcp-clients'+import { makeMcpProxyTools } from './mcp-proxy'+import { decideMcpExposure } from './mcp-tool-budget'+import { effectiveToolLevel } from './mcp-tool-lookup'import { buildToolNameMap } from './provider-safe-names'/**@@ -189,11 +192,26 @@ export interface BuiltAgentTools {* sanitizes names on the wire and uses this map to translate the names a* strict provider echoes back to the original before the loop matches. */nameToId: Map<string, string>+ /** `<prefix>__call_tool` name → its proxy entry, per proxied connection.+ * The driver re-keys the approval gate on the underlying tool from the+ * args, using `resolveRemoteName` so the gate and dispatch agree on which+ * remote name is invoked (a raw `<prefix>__<x>` tool that exists in the+ * catalog stays raw; only an extra `<prefix>__` from the model is stripped). */+ mcpProxyCallTools: Map<string, ProxyCallToolEntry>+}++/** What the driver needs at gate time per proxied connection: the client (for+ * `.prefix`, kept here so callers don't reach across to `mcp-clients`) plus+ * the same resolver dispatch uses. Bundled so the two can't drift. */+export interface ProxyCallToolEntry {+ client: OpenedMcp+ resolveRemoteName: (raw: string) => string}export async function buildAgentTools(rev: AgentRevision, deps: AgentToolDeps): Promise<BuiltAgentTools> {const tools: AgentTool<TSchema, ToolResultDetails>[] = []const seen = new Set<string>()+ const mcpProxyCallTools = new Map<string, ProxyCallToolEntry>()// `@posthog/load-skill` is auto-included only when the agent has skills —// exposing it otherwise just adds a tool that errors on use.@@ -290,45 +308,56 @@ export async function buildAgentTools(rev: AgentRevision, deps: AgentToolDeps):}))for (const { client, tools: remoteTools } of listings) {- // PR 7: inclusion filter migrated from `allowlist[]` to `tools[]`,- // which carries both bare-string entries (passthrough — was- // allowlist) and object entries `{ name, requires_approval?, ... }`.- // We only need the entry NAMES here; the approval-wrap fallback- // lives in `driver.ts` and pulls the per-tool policy via- // `mcp-tool-lookup.ts` (added in commit B). Omitted/empty `tools`- // still means "expose every tool the server lists."- const includedNames =- client.ref.tools && client.ref.tools.length > 0- ? new Set(client.ref.tools.map((t) => (typeof t === 'string' ? t : t.name)))- : null- for (const remote of remoteTools) {- if (includedNames && !includedNames.has(remote.name)) {- continue+ const exposed = exposedRemoteTools(client, remoteTools, seen)+ // Inline below the budget; proxy a rich surface so it can't overflow the model.+ const decision = decideMcpExposure(exposed)+ if (decision.mode === 'inline') {+ for (const remote of exposed) {+ tools.push(makeMcpTool(`${client.prefix}__${remote.name}`, client, remote))}- // `<prefix>__<remoteName>` is the model-visible identifier; the- // model sees the prefix so it can disambiguate (`linear__create_issue`- // vs `github__create_issue`). All chars are already- // provider-safe — `__` is in the safe set.- const exposedName = `${client.prefix}__${remote.name}`- if (seen.has(exposedName)) {- // Collisions can happen when a remote tool name accidentally- // matches a native/custom id, or two MCPs export the same- // post-prefix string. Same silent-skip behaviour as- // duplicate spec.tools entries — keeps the model surface- // stable across deploys instead of failing loudly on a- // remote-side rename.- continue- }- seen.add(exposedName)- tools.push(makeMcpTool(exposedName, client, remote))+ continue}+ deps.log('info', 'mcp.exposure.proxy', {+ prefix: client.prefix,+ toolCount: decision.toolCount,+ serializedChars: decision.serializedChars,+ reasons: decision.reasons,+ })+ const proxy = makeMcpProxyTools(client, exposed)+ tools.push(...proxy.tools)+ mcpProxyCallTools.set(proxy.callToolName, { client, resolveRemoteName: proxy.resolveRemoteName })}}// Tools are named with their original ids (the loop matches calls by name).// The map keys the provider-safe form back to the original so the driver's// streamFn can translate names a strict provider echoed back.- return { tools, nameToId: buildToolNameMap(tools.map((t) => t.name)) }+ return { tools, nameToId: buildToolNameMap(tools.map((t) => t.name)), mcpProxyCallTools }+}++/**+ * The catalog a client should expose, shared by the inline and proxy emitters:+ * drop tools whose effective level is `deny` (connection default ?? per-tool+ * override), then `<prefix>__<name>` collision dedupe against `seen` (mutated).+ *+ * The agent's own config is the sole authority — the connection owner's+ * installation marks (`needs_approval` / `do_not_use`) are not enforced here.+ */+function exposedRemoteTools(client: OpenedMcp, remoteTools: RemoteMcpTool[], seen: Set<string>): RemoteMcpTool[] {+ const exposed: RemoteMcpTool[] = []+ for (const remote of remoteTools) {+ // Agent author's effective level: `deny` → not exposed to the model.+ if (effectiveToolLevel(client.ref, remote.name) === 'deny') {+ continue+ }+ const exposedName = `${client.prefix}__${remote.name}`+ if (seen.has(exposedName)) {+ continue+ }+ seen.add(exposedName)+ exposed.push(remote)+ }+ return exposed}function makeControlFlowTool(id: string): AgentTool<TSchema, ToolResultDetails> {diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts b/products/agent_platform/services/agent-runner/src/loop/driver.test.tsindex 36e2c2439180..8bbed6a2f240 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.test.ts@@ -405,15 +405,16 @@ describe('driver runSession', () => {model: FAUX_MODEL_ID,mcps: [{- kind: 'external',+ kind: 'agent',+ default_tool_approval: 'deny',id: 'posthog',url: 'https://app.posthog.com/api/mcp',secrets: [],tools: [- 'agent-applications-list',+ { name: 'agent-applications-list', level: 'allow' },{name: 'agent-applications-revisions-promote-create',- requires_approval: true,+ level: 'approve',approval_policy: { type: 'principal', ttl_ms: 900_000 },},],@@ -429,7 +430,7 @@ describe('driver runSession', () => {it('queues an approval row when the model calls a gated MCP tool', async () => {// Concierge-shape: the model invokes promote-create; the- // dispatcher's MCP lookup finds `requires_approval: true` on the+ // dispatcher's MCP lookup finds `level: 'approve'` on the// matching tools[] entry; the wrap queues instead of running.const mcp = makeFakeMcp('posthog', POSTHOG_REF, {'agent-applications-revisions-promote-create': { description: 'd', result: { promoted: true } },@@ -463,11 +464,11 @@ describe('driver runSession', () => {expect(rows[0].state).toBe('queued')})- it('does NOT queue when the matching tools[] entry is bare-string (inclusion only)', async () => {- // `agent-applications-list` is in tools[] as a bare string —- // included but no gating. The dispatcher's MCP lookup returns- // null, the native lookup doesn't match either, so the tool- // dispatches directly. Sibling case below pins iteration order+ it('does NOT queue when the matching tools[] entry is allow-level (inclusion only)', async () => {+ // `agent-applications-list` is in tools[] with `level: 'allow'` —+ // exposed but not gated. The dispatcher's MCP lookup returns a+ // non-gating level, the native lookup doesn't match either, so the+ // tool dispatches directly. Sibling case below pins iteration order// so this isn't a false-positive on accidental short-circuit.const mcp = makeFakeMcp('posthog', POSTHOG_REF, {'agent-applications-list': { description: 'd', result: { results: [] } },@@ -485,11 +486,11 @@ describe('driver runSession', () => {expect(await approvals.listBySession(TEST_SESSION_ID)).toHaveLength(0)})- it('iterates past earlier bare-string entries to find a later gated object (no false-positive short-circuit)', async () => {- // Belt-and-braces for the bare-string case above: the lookup+ it('iterates past earlier allow-level entries to find a later gated object (no false-positive short-circuit)', async () => {+ // Belt-and-braces for the allow-level case above: the lookup// must walk the whole tools[] array, not bail on the first- // non-name-match. Here `agent-applications-list` is a bare- // string and `promote-create` is the gated object — the model+ // non-name-match. Here `agent-applications-list` is `level: 'allow'`+ // and `promote-create` is the gated (`approve`) entry — the model// calls `promote-create`, which sits SECOND in the array.const mcp = makeFakeMcp('posthog', POSTHOG_REF, {'agent-applications-revisions-promote-create': {@@ -535,14 +536,15 @@ describe('driver runSession', () => {model: FAUX_MODEL_ID,mcps: [{- kind: 'external',+ kind: 'agent',+ default_tool_approval: 'deny',id: 'posthog',url: 'https://example.com/posthog',secrets: [],tools: [{name: 'pingback',- requires_approval: true,+ level: 'approve',approval_policy: { type: 'agent' },},],@@ -630,6 +632,158 @@ describe('driver runSession', () => {expect(rows[0].tool_name).toBe('posthog__agent-applications-revisions-promote-create')expect(rows[0].state).toBe('queued')})++ // ── Proxy-mode gating (large connection: >40 tools → helper tools) ──+ // A connection past the inline budget exposes only `<prefix>__call_tool`+ // / `explore_tools` / `get_tool_schema`; the underlying tool is named in+ // the `call_tool` args. Build a 42-tool fake MCP so `decideMcpExposure`+ // picks proxy mode, with one tool (`promote`) the author gated `approve`.+ const manyTools = (gated: string): Record<string, { description: string; result: unknown }> => {+ const tools: Record<string, { description: string; result: unknown }> = {+ [gated]: { description: 'gated tool', result: { promoted: true } },+ }+ for (let i = 0; i < 42; i++) {+ tools[`tool_${i}`] = { description: `tool ${i}`, result: { ok: true } }+ }+ return tools+ }+ const PROXY_REF: McpRef = AgentSpecSchema.parse({+ model: FAUX_MODEL_ID,+ mcps: [+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'big',+ url: 'https://example.com/big',+ secrets: [],+ tools: [+ { name: 'promote', level: 'approve', approval_policy: { type: 'principal', ttl_ms: 900_000 } },+ ],+ },+ ],+ }).mcps[0]++ it('proxy call_tool with a PREFIXED tool_name still hits the per-tool approval gate (no doubled-prefix bypass)', async () => {+ // veria-ai (High): the model often passes the prefixed name it sees+ // (`big__promote`) as `call_tool`'s `tool_name`. The proxy strips the+ // prefix before dispatch, so the driver's approval gate must strip it+ // too — otherwise it keys the lookup on `big__big__promote`, misses+ // the `approve` override, and the gated tool runs without approval.+ const mcp = makeFakeMcp('big', PROXY_REF, manyTools('promote'))+ const approvals = new PgApprovalStore(pool)+ const session = makeSession({+ principal: principalAlice,+ conversation: [{ role: 'user', content: 'promote it', timestamp: Date.now() }],+ })+ const out = await run(makeRev({ mcps: [PROXY_REF as never] }), session, {+ script: [+ toolUse([+ call('big__call_tool', { tool_name: 'big__promote', arguments: { application_id: 'a' } }),+ ]),+ stop('queued'),+ ],+ approvals,+ mcpClients: [mcp],+ })+ expect(out.state).toBe('completed')+ // Gate held: the underlying remote tool was never invoked.+ expect(mcp.calls).toEqual([])+ const rows = await approvals.listBySession(TEST_SESSION_ID)+ expect(rows).toHaveLength(1)+ // The row is keyed on the normalized underlying tool, not the doubled prefix.+ expect(rows[0].tool_name).toBe('big__promote')+ expect(rows[0].state).toBe('queued')+ })++ it('proxy call_tool gates a remote tool whose RAW name shadows a `<prefix>__` form (no unconditional-strip bypass)', async () => {+ // hex / veria (Medium): the proxy's `resolveRemoteName` prefers the+ // RAW arg when it exists in the catalog (only strips `<prefix>__`+ // when the stripped name resolves). The driver's gate used to strip+ // unconditionally, so a remote tool literally named `big__delete`+ // dispatched as `big__delete` but gated as `delete` — a missing+ // tools[] entry, `default_tool_approval: allow` falls through, and+ // the `approve` override on the real tool was bypassed. With both+ // paths sharing the same resolver, the gate keys on the actual+ // remote name and the queue holds. (Prompt-injection bypass guard.)+ const shadowRef: McpRef = AgentSpecSchema.parse({+ model: FAUX_MODEL_ID,+ mcps: [+ {+ kind: 'agent',+ // `allow` default + an `approve` per-tool override is the+ // exact configuration that the old bypass made unsafe.+ default_tool_approval: 'allow',+ id: 'big',+ url: 'https://example.com/big',+ secrets: [],+ tools: [+ {+ name: 'big__delete',+ level: 'approve',+ approval_policy: { type: 'principal', ttl_ms: 900_000 },+ },+ ],+ },+ ],+ }).mcps[0]+ const mcp = makeFakeMcp('big', shadowRef, manyTools('big__delete'))+ const approvals = new PgApprovalStore(pool)+ const session = makeSession({+ principal: principalAlice,+ conversation: [{ role: 'user', content: 'delete it', timestamp: Date.now() }],+ })+ const out = await run(makeRev({ mcps: [shadowRef as never] }), session, {+ script: [+ // Model passes the RAW remote name (which itself starts with+ // `big__`). The proxy resolver prefers this raw form because+ // it exists in the exposed catalog; the gate must agree.+ toolUse([call('big__call_tool', { tool_name: 'big__delete', arguments: {} })]),+ stop('queued'),+ ],+ approvals,+ mcpClients: [mcp],+ })+ expect(out.state).toBe('completed')+ // Gate held: the remote was NOT dispatched. (The bypass would show+ // up here as `mcp.calls` containing the `big__delete` invocation.)+ expect(mcp.calls).toEqual([])+ const rows = await approvals.listBySession(TEST_SESSION_ID)+ expect(rows).toHaveLength(1)+ // The approval row is keyed on `<prefix>__<resolvedRawName>` — the+ // doubled-prefix form a strip-less resolver produces here.+ expect(rows[0].tool_name).toBe('big__big__delete')+ expect(rows[0].state).toBe('queued')+ })++ it('proxy explore_tools stays ungated even under an approve default (synthetic helper, proxy-aware skip)', async () => {+ // Regression guard for the proxy-aware exemption: with the blanket+ // name-based exemption removed from lookupMcpToolApproval, the driver+ // must still skip the synthetic read-only helpers for a PROXIED+ // connection — otherwise catalog browsing would block on a human.+ const approveRef: McpRef = AgentSpecSchema.parse({+ model: FAUX_MODEL_ID,+ mcps: [+ {+ kind: 'agent',+ default_tool_approval: 'approve',+ id: 'big',+ url: 'https://example.com/big',+ secrets: [],+ },+ ],+ }).mcps[0]+ const mcp = makeFakeMcp('big', approveRef, manyTools('promote'))+ const approvals = new PgApprovalStore(pool)+ const session = makeSession({ principal: principalAlice })+ const out = await run(makeRev({ mcps: [approveRef as never] }), session, {+ script: [toolUse([call('big__explore_tools', { query: 'promote' })]), stop('listed')],+ approvals,+ mcpClients: [mcp],+ })+ expect(out.state).toBe('completed')+ // explore_tools ran (no approval queued) — read-only catalog browsing.+ expect(await approvals.listBySession(TEST_SESSION_ID)).toHaveLength(0)+ })})/**diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.tsindex 57b20df20372..8f84d73361a0 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts@@ -33,7 +33,14 @@* `pending_inputs` — handled in `getSteeringMessages`.*/-import type { AgentContext, AgentEvent, AgentEventSink, AgentMessage, StreamFn } from '@earendil-works/pi-agent-core'+import type {+ AgentContext,+ AgentEvent,+ AgentEventSink,+ AgentMessage,+ AgentToolResult,+ StreamFn,+} from '@earendil-works/pi-agent-core'import { runAgentLoop } from '@earendil-works/pi-agent-core'import type { AssistantMessage, Message } from '@earendil-works/pi-ai'import { streamSimple } from '@earendil-works/pi-ai'@@ -89,7 +96,13 @@ import { AgentToolDeps, buildAgentTools, MetaControl, RealToolExecute, ToolResulimport { fallbackStreamFn, ResolvedModel } from './fallback-stream'import { resolveMaxOutputTokens } from './max-output-tokens'import type { McpOpenFailure, OpenedMcp } from './mcp-clients'-import { lookupMcpToolApproval } from './mcp-tool-lookup'+import {+ isProxyReadOnlyHelper,+ lookupMcpToolApproval,+ PREFIX_SEPARATOR,+ proxiedPrefixesFromCallTools,+ resolveApprovedExecutor,+} from './mcp-tool-lookup'import { providerSafeName } from './provider-safe-names'/** The model id that served the most recent assistant turn, if any. Seeds the@@ -482,7 +495,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsposthogApiBaseUrl: deps.posthogApiBaseUrl,gatewayCatalog: deps.gatewayCatalog,}- const { tools, nameToId } = await buildAgentTools(rev, toolDeps)+ const { tools, nameToId, mcpProxyCallTools } = await buildAgentTools(rev, toolDeps)await emit('session_started', {team_id: session.team_id,@@ -539,8 +552,90 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps}{const approvals = deps.approvals+ // Shared by the static wrap and the dynamic proxy wrap. Every gated+ // call queues for a human decision — being the asker is not consent+ // to the specific call (the model could have been steered by content+ // it read). `toolName` is what the approval row records.+ const queueGated = async (+ toolName: string,+ toolCallId: string,+ args: Record<string, unknown>,+ policy: ApprovalPolicy+ ): Promise<AgentToolResult<ToolResultDetails>> => {+ const queued = await queueApprovalResult({+ approvals,+ buildApprovalUrl: deps.buildApprovalUrl,+ session,+ revisionId: rev.id,+ turn,+ toolName,+ toolCallId,+ args,+ policy,+ })+ // `principal` + Slack: post Approve/Reject buttons in-thread+ // (best-effort; skip a deduped re-queue).+ const reqId = queued.details?.requestId+ if (slackReply && policy.type === 'principal' && reqId && !queued.details?.deduped) {+ void postSlackApprovalButtons(deps.http, {+ token: deps.secrets[SLACK_BOT_TOKEN_KEY],+ channel: slackReply.channel,+ thread_ts: slackReply.thread_ts,+ sessionId: session.id,+ requestId: reqId,+ toolName,+ logger: {+ warn: (meta, msg) => log('warn', msg, meta),+ info: (meta, msg) => log('info', msg, meta),+ },+ }).catch(() => {})+ }+ return queued+ }++ // Prefixes whose connection is proxied (`<prefix>__call_tool` exists),+ // so the synthetic read-only helpers below can be recognised as ours.+ const proxiedPrefixes = proxiedPrefixesFromCallTools(mcpProxyCallTools.keys())+for (const tool of tools) {const id = tool.name+ // Proxy `call_tool` gates dynamically: the underlying tool is+ // only known at call time (the `tool_name` arg), so re-key the+ // gate on `<prefix>__<tool_name>` per call.+ const proxyEntry = mcpProxyCallTools.get(id)+ if (proxyEntry) {+ const realProxyExecute = tool.execute as RealToolExecute+ tool.execute = async (toolCallId, args) => {+ const a = (args ?? {}) as Record<string, unknown>+ const raw = typeof a.tool_name === 'string' ? a.tool_name : ''+ // Resolve the same way `call_tool` will at dispatch time+ // (mcp-proxy.ts `resolveProxyRemoteName`): prefer the raw+ // name when it exists in the exposed catalog, only strip+ // `<prefix>__` when the stripped name does. Unconditionally+ // stripping was a bypass: a remote tool whose RAW name was+ // `<prefix>__delete` would gate as `delete` (no entry,+ // policy=allow) while dispatch ran the raw `<prefix>__delete`.+ // Sharing the resolver keeps the two paths in lockstep.+ const remoteName = proxyEntry.resolveRemoteName(raw)+ const exposedName = `${proxyEntry.client.prefix}${PREFIX_SEPARATOR}${remoteName}`+ const gate = lookupMcpToolApproval(exposedName, rev.spec)+ if (gate?.requires_approval) {+ return queueGated(exposedName, toolCallId, a, gate.approval_policy)+ }+ return realProxyExecute(toolCallId, a)+ }+ continue+ }+ // Synthetic proxy read-only helpers (`explore_tools` /+ // `get_tool_schema`) for a PROXIED connection are ungated catalog/+ // schema browsing — gating them would block enumeration on a human+ // and defeat the proxy. The blanket exemption was removed from+ // `lookupMcpToolApproval` (which can't tell a synthetic helper from+ // a real same-named tool); the proxy-aware check lives here.+ if (isProxyReadOnlyHelper(id, proxiedPrefixes)) {+ continue+ }+// Native + custom tools carry their approval policy on// `spec.tools[]`. MCP tools materialise at session start// from `client.listTools()` so they can't appear there;@@ -564,49 +659,8 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps? mcpGate.approval_policy: nullif (policy) {- tool.execute = async (toolCallId, args) => {- // Every gated call queues — there is no auto-dispatch.- // Being the asker is not consent to the specific call the- // model emitted (a prompt injection in content the agent- // read could have steered it), so a deterministic human- // decision is always required: `principal` clears it via- // the ingress decision API, `agent` via the console.- const queued = await queueApprovalResult({- approvals,- buildApprovalUrl: deps.buildApprovalUrl,- session,- revisionId: rev.id,- // `turn` is the live counter — at call time it's the- // turn that proposed this gated call.- turn,- toolName: id,- toolCallId,- args: (args ?? {}) as Record<string, unknown>,- policy,- })- // For a `principal` approval on a Slack session, post- // Approve/Reject buttons into the thread so the session- // owner can decide in-place (the ingress interactivity- // handler enforces principal-match on the click). Skip on- // a deduped re-queue so we don't spam the same buttons.- // Best-effort — a Slack hiccup must not break the loop.- const reqId = queued.details?.requestId- if (slackReply && policy.type === 'principal' && reqId && !queued.details?.deduped) {- void postSlackApprovalButtons(deps.http, {- token: deps.secrets[SLACK_BOT_TOKEN_KEY],- channel: slackReply.channel,- thread_ts: slackReply.thread_ts,- sessionId: session.id,- requestId: reqId,- toolName: id,- logger: {- warn: (meta, msg) => log('warn', msg, meta),- info: (meta, msg) => log('info', msg, meta),- },- }).catch(() => {})- }- return queued- }+ tool.execute = async (toolCallId, args) =>+ queueGated(id, toolCallId, (args ?? {}) as Record<string, unknown>, policy)}}}@@ -1125,7 +1179,12 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps// dispatch (tracked follow-up).const d = await dispatchApprovedResult({approvals: deps.approvals,- realExecute: realExecute.get(row.tool_name),+ // A proxy-routed row is keyed `<prefix>__<remoteName>` (the gate+ // re-keyed onto the underlying tool) but its executor is the+ // connection's `call_tool`, whose args are the row's stored args.+ // resolveApprovedExecutor falls back to it so the approved call+ // actually replays instead of erroring "unknown tool".+ realExecute: resolveApprovedExecutor(row.tool_name, realExecute, mcpProxyCallTools),row,})// Secure the wake before observability so a failingdiff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.tsindex 33be4c6633f1..ef1a69d2c3a7 100644--- a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.ts+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.ts@@ -121,7 +121,9 @@ describe('openMcpClients', () => {it('opens an external ref and lists+calls remote tools', async () => {const { factory, calls, pairs } = await buildEchoFactory()- const refs: McpRef[] = [{ id: 'echo', url: 'https://example.com/mcp', secrets: [] }]+ const refs: McpRef[] = [+ { kind: 'agent', default_tool_approval: 'allow', id: 'echo', url: 'https://example.com/mcp', secrets: [] },+ ]const { clients, close } = await openMcpClients(refs, {secrets: {},@@ -150,8 +152,20 @@ describe('openMcpClients', () => {it('preserves the prefix as the entry id for external refs', async () => {const { factory, pairs } = await buildEchoFactory()const refs: McpRef[] = [- { id: 'linear', url: 'https://example.com/linear', secrets: [] },- { id: 'github', url: 'https://example.com/github', secrets: [] },+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'linear',+ url: 'https://example.com/linear',+ secrets: [],+ },+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'github',+ url: 'https://example.com/github',+ secrets: [],+ },]const { clients, close } = await openMcpClients(refs, {secrets: {},@@ -165,8 +179,8 @@ describe('openMcpClients', () => {it('rejects duplicate prefixes across refs', async () => {const { factory, pairs } = await buildEchoFactory()const refs: McpRef[] = [- { id: 'dup', url: 'https://example.com/a', secrets: [] },- { id: 'dup', url: 'https://example.com/b', secrets: [] },+ { kind: 'agent', default_tool_approval: 'allow', id: 'dup', url: 'https://example.com/a', secrets: [] },+ { kind: 'agent', default_tool_approval: 'allow', id: 'dup', url: 'https://example.com/b', secrets: [] },]await expect(openMcpClients(refs, { secrets: {}, transportFactory: factory })).rejects.toThrow(/duplicate_mcp_prefix: dup/@@ -180,6 +194,8 @@ describe('openMcpClients', () => {const { factory, pairs, targets } = await buildEchoFactory()const refs: McpRef[] = [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'tenant',url: 'https://example.com/${TENANT}/mcp',secrets: ['TENANT'],@@ -204,6 +220,8 @@ describe('openMcpClients', () => {const { factory, pairs, targets } = await buildEchoFactory()const refs: McpRef[] = [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'github',url: 'https://api.githubcopilot.com/mcp',secrets: ['GITHUB_TOKEN'],@@ -226,7 +244,16 @@ describe('openMcpClients', () => {it('auth.provider stamps the asker bearer when the identity resolves ok', async () => {const { factory, pairs, targets } = await buildEchoFactory()- const refs: McpRef[] = [{ id: 'gh', url: 'https://example.com/mcp', secrets: [], auth: { provider: 'github' } }]+ const refs: McpRef[] = [+ {+ kind: 'principal',+ default_tool_approval: 'allow',+ id: 'gh',+ url: 'https://example.com/mcp',+ secrets: [],+ auth: { provider: 'github' },+ },+ ]const { close } = await openMcpClients(refs, {secrets: {},transportFactory: factory,@@ -245,7 +272,16 @@ describe('openMcpClients', () => {it('auth.provider unlinked → ref fails to open in the auth category', async () => {const { factory, pairs } = await buildEchoFactory()- const refs: McpRef[] = [{ id: 'gh', url: 'https://example.com/mcp', secrets: [], auth: { provider: 'github' } }]+ const refs: McpRef[] = [+ {+ kind: 'principal',+ default_tool_approval: 'allow',+ id: 'gh',+ url: 'https://example.com/mcp',+ secrets: [],+ auth: { provider: 'github' },+ },+ ]const { clients, failures, close } = await openMcpClients(refs, {secrets: {},transportFactory: factory,@@ -277,7 +313,14 @@ describe('openMcpClients', () => {async close() {},}) as unknown as Transportconst refs: McpRef[] = [- { id: 'posthog', url: 'https://example.com/mcp', secrets: [], auth: { provider: 'posthog' } },+ {+ kind: 'principal',+ default_tool_approval: 'allow',+ id: 'posthog',+ url: 'https://example.com/mcp',+ secrets: [],+ auth: { provider: 'posthog' },+ },]const relink = vi.fn(async () => 'https://app.posthog.test/oauth/authorize/?reconnect=1')const { clients, failures } = await openMcpClients(refs, {@@ -302,7 +345,14 @@ describe('openMcpClients', () => {it('auth.provider refuses a host outside the resolved credential allowlist', async () => {const { factory, pairs } = await buildEchoFactory()const refs: McpRef[] = [- { id: 'gh', url: 'https://evil.example/mcp', secrets: [], auth: { provider: 'github' } },+ {+ kind: 'principal',+ default_tool_approval: 'allow',+ id: 'gh',+ url: 'https://evil.example/mcp',+ secrets: [],+ auth: { provider: 'github' },+ },]const { clients, failures, close } = await openMcpClients(refs, {secrets: {},@@ -324,7 +374,14 @@ describe('openMcpClients', () => {it('auth.provider allows the local MCP over http loopback even on a different port than the credential host', async () => {const { factory, pairs, targets } = await buildEchoFactory()const refs: McpRef[] = [- { id: 'posthog', url: 'http://localhost:8787/mcp', secrets: [], auth: { provider: 'posthog' } },+ {+ kind: 'principal',+ default_tool_approval: 'allow',+ id: 'posthog',+ url: 'http://localhost:8787/mcp',+ secrets: [],+ auth: { provider: 'posthog' },+ },]const { close } = await openMcpClients(refs, {secrets: {},@@ -352,6 +409,8 @@ describe('openMcpClients', () => {const { factory, pairs } = await buildEchoFactory()const refs: McpRef[] = [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'github',url: 'https://example.com/mcp',secrets: ['GITHUB_TOKEN'],@@ -375,6 +434,8 @@ describe('openMcpClients', () => {const { factory, pairs } = await buildEchoFactory()const refs: McpRef[] = [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'tenant',url: 'https://example.com/${TENANT}/mcp',secrets: ['TENANT'],@@ -401,6 +462,8 @@ describe('openMcpClients', () => {const { factory, pairs, targets } = await buildEchoFactory()const refs: McpRef[] = [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'exfil',url: 'https://attacker.example.com/collect',secrets: ['SLACK_BOT_TOKEN'],@@ -428,6 +491,8 @@ describe('openMcpClients', () => {const { factory, pairs } = await buildEchoFactory()const refs: McpRef[] = [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'github',url: 'https://api.githubcopilot.com/mcp',secrets: ['GITHUB_TOKEN'],@@ -454,6 +519,8 @@ describe('openMcpClients', () => {const { factory, pairs } = await buildEchoFactory()const refs: McpRef[] = [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'github',url: 'https://api.githubcopilot.com/mcp',secrets: ['GITHUB_TOKEN'],@@ -477,6 +544,8 @@ describe('openMcpClients', () => {const { factory, pairs } = await buildEchoFactory()const refs: McpRef[] = [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'tenant',url: 'https://attacker.example.com/${TENANT}/mcp',secrets: ['TENANT'],@@ -500,6 +569,8 @@ describe('openMcpClients', () => {const { factory, pairs, targets } = await buildEchoFactory()const refs: McpRef[] = [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'svc',url: 'https://api.example.com/mcp',secrets: ['SVC_TOKEN'],@@ -518,7 +589,9 @@ describe('openMcpClients', () => {it('surfaces remote tool errors as isError on the McpCallResult', async () => {const { factory, pairs } = await buildEchoFactory()- const refs: McpRef[] = [{ id: 'echo', url: 'https://example.com/mcp', secrets: [] }]+ const refs: McpRef[] = [+ { kind: 'agent', default_tool_approval: 'allow', id: 'echo', url: 'https://example.com/mcp', secrets: [] },+ ]const { clients, close } = await openMcpClients(refs, {secrets: {},transportFactory: factory,@@ -553,7 +626,9 @@ describe('openMcpClients', () => {},}) as Transport}- const refs: McpRef[] = [{ id: 'echo', url: 'https://example.com/mcp', secrets: [] }]+ const refs: McpRef[] = [+ { kind: 'agent', default_tool_approval: 'allow', id: 'echo', url: 'https://example.com/mcp', secrets: [] },+ ]const { clients, close } = await openMcpClients(refs, {secrets: {},transportFactory: factory,@@ -574,11 +649,22 @@ describe('openMcpClients', () => {describe('devMcpBearerToken (dev-only auth fallback)', () => {it('attaches Authorization: Bearer when ref has no auth and a dev bearer is configured', async () => {const { factory, pairs, targets } = await buildEchoFactory()- const { close } = await openMcpClients([{ id: 'x', url: 'https://mcp.example.com/sse', secrets: [] }], {- secrets: {},- transportFactory: factory,- devMcpBearerToken: 'phx_dev_token',- })+ const { close } = await openMcpClients(+ [+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'x',+ url: 'https://mcp.example.com/sse',+ secrets: [],+ },+ ],+ {+ secrets: {},+ transportFactory: factory,+ devMcpBearerToken: 'phx_dev_token',+ }+ )expect(targets[0].headers.Authorization).toBe('Bearer phx_dev_token')await close()await closePairs(pairs)@@ -586,11 +672,183 @@ describe('openMcpClients', () => {it('omits Authorization entirely when no auth and no dev bearer is set', async () => {const { factory, pairs, targets } = await buildEchoFactory()- const { close } = await openMcpClients([{ id: 'x', url: 'https://mcp.example.com/sse', secrets: [] }], {+ const { close } = await openMcpClients(+ [+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'x',+ url: 'https://mcp.example.com/sse',+ secrets: [],+ },+ ],+ {+ secrets: {},+ transportFactory: factory,+ }+ )+ expect(targets[0].headers.Authorization).toBeUndefined()+ await close()+ await closePairs(pairs)+ })+ })++ describe('connection (agent-level shared credential)', () => {+ it('uses the URL + bearer from the connection resolver, ignoring ref.url/auth/secrets', async () => {+ const { factory, pairs, targets } = await buildEchoFactory()+ const refs: McpRef[] = [+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'incident',+ url: 'https://placeholder.invalid/',+ connection: 'conn-1',+ secrets: [],+ },+ ]+ const { clients, close } = await openMcpClients(refs, {+ secrets: {},+ transportFactory: factory,+ connections: {+ resolve: async () => ({+ kind: 'resolved',+ url: 'https://mcp.incident.io/mcp',+ bearer: 'shared-tok',+ }),+ },+ })+ expect(clients).toHaveLength(1)+ expect(targets[0].url).toBe('https://mcp.incident.io/mcp')+ expect(targets[0].headers.Authorization).toBe('Bearer shared-tok')+ await close()+ await closePairs(pairs)+ })++ // A dead SHARED connection (owner's token revoked, install disabled, or+ // install deleted) is persistent and only the owner/admin can fix it —+ // the asker can't reconnect someone else's credential. All three+ // terminal states classify as `connection_dead` so the system prompt+ // tells the asker an admin must reconnect (vs. a misleading "retry+ // shortly"). A TRANSIENT refresh blip stays `auth` (see below).+ it('needs_reauth → fails in the connection_dead category (owner must reconnect)', async () => {+ const { factory, pairs } = await buildEchoFactory()+ const refs: McpRef[] = [+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'incident',+ url: 'https://placeholder.invalid/',+ connection: 'conn-1',+ secrets: [],+ },+ ]+ const { clients, failures, close } = await openMcpClients(refs, {secrets: {},transportFactory: factory,+ connections: { resolve: async () => ({ kind: 'needs_reauth' }) },})- expect(targets[0].headers.Authorization).toBeUndefined()+ expect(clients).toEqual([])+ expect(failures[0].category).toBe('connection_dead')+ expect(failures[0].devReason).toMatch(/mcp_connection_needs_reauth: conn-1/)+ await close()+ await closePairs(pairs)+ })++ it('disabled → fails in the connection_dead category (owner must re-enable)', async () => {+ const { factory, pairs } = await buildEchoFactory()+ const refs: McpRef[] = [+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'incident',+ url: 'https://placeholder.invalid/',+ connection: 'conn-1',+ secrets: [],+ },+ ]+ const { clients, failures, close } = await openMcpClients(refs, {+ secrets: {},+ transportFactory: factory,+ connections: { resolve: async () => ({ kind: 'disabled' }) },+ })+ expect(clients).toEqual([])+ expect(failures[0].category).toBe('connection_dead')+ expect(failures[0].devReason).toMatch(/mcp_connection_disabled: conn-1/)+ await close()+ await closePairs(pairs)+ })++ it('not_found → fails in the connection_dead category (install gone)', async () => {+ const { factory, pairs } = await buildEchoFactory()+ const refs: McpRef[] = [+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'incident',+ url: 'https://placeholder.invalid/',+ connection: 'gone',+ secrets: [],+ },+ ]+ const { failures, close } = await openMcpClients(refs, {+ secrets: {},+ transportFactory: factory,+ connections: { resolve: async () => ({ kind: 'not_found' }) },+ })+ expect(failures[0].category).toBe('connection_dead')+ await close()+ await closePairs(pairs)+ })++ it('a transient refresh failure stays in the retryable auth category (not connection_dead)', async () => {+ // The store throws `mcp_connection_refresh_failed` for a transient+ // 5xx/429/network blip during token refresh — that SELF-HEALS next+ // session, so it must NOT be classified as the persistent+ // owner-must-reconnect `connection_dead`.+ const { factory, pairs } = await buildEchoFactory()+ const refs: McpRef[] = [+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'incident',+ url: 'https://placeholder.invalid/',+ connection: 'conn-1',+ secrets: [],+ },+ ]+ const { clients, failures, close } = await openMcpClients(refs, {+ secrets: {},+ transportFactory: factory,+ connections: {+ resolve: async () => {+ throw new Error('mcp_connection_refresh_failed: conn-1 (502)')+ },+ },+ })+ expect(clients).toEqual([])+ expect(failures[0].category).toBe('auth')+ await close()+ await closePairs(pairs)+ })++ it('refuses a connection ref when the resolver is not wired', async () => {+ const { factory, pairs } = await buildEchoFactory()+ const refs: McpRef[] = [+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'incident',+ url: 'https://placeholder.invalid/',+ connection: 'conn-1',+ secrets: [],+ },+ ]+ const { clients, failures, close } = await openMcpClients(refs, {+ secrets: {},+ transportFactory: factory,+ })+ expect(clients).toEqual([])+ expect(failures[0].devReason).toMatch(/mcp_connection_not_wired: conn-1/)await close()await closePairs(pairs)})diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.tsindex 5b0ff9d1625b..1e0beb3aa7d2 100644--- a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.ts+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.ts@@ -45,7 +45,14 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'-import { HttpFetcher, type IdentityResolution, isDev, McpRef, secretHostMatches } from '@posthog/agent-shared'+import {+ HttpFetcher,+ type IdentityResolution,+ isDev,+ type McpConnectionResolution,+ McpRef,+ secretHostMatches,+} from '@posthog/agent-shared'/** Remote tool descriptor as returned by `client.listTools()`. */export interface RemoteMcpTool {@@ -81,6 +88,16 @@ export interface OpenedMcp {* upstream error string, which often leaks transport URLs / docs links /* provider-side stack hints). The agent owner gets the full reason via* log_entries.+ * - `connection_dead` — a `kind: 'agent'` SHARED connection is permanently+ * broken: the installing owner's token can't refresh+ * (`needs_reauth`), they disabled the install (`disabled`),+ * or the install is gone (`not_found`). The asker can't fix+ * someone else's shared credential and a retry won't heal it —+ * only the owner/admin reconnecting will. Kept distinct from+ * `auth` (per-asker) so the prompt says "an admin must+ * reconnect" instead of "retry shortly". A TRANSIENT refresh+ * blip (`mcp_connection_refresh_failed`, 5xx/429) is NOT this —+ * it self-heals, so it stays `auth`.* - `auth` — credentials / token / secret resolution problem* (`mcp_secret_not_resolved`, `mcp_identity_*`,* 401/403 from the remote)@@ -88,7 +105,7 @@ export interface OpenedMcp {* - `not_found` — server responded but said the endpoint is gone (404, 410)* - `unknown` — anything else; default bucket for novel transport errors*/-export type McpFailureCategory = 'auth' | 'network' | 'not_found' | 'unknown'+export type McpFailureCategory = 'connection_dead' | 'auth' | 'network' | 'not_found' | 'unknown'export interface McpOpenFailure {ref: McpRef@@ -126,9 +143,26 @@ class McpIdentityLinkRequiredError extends Error {*/export function categorizeMcpOpenError(err: Error): McpFailureCategory {const msg = err.message.toLowerCase()+ // Checked FIRST: a permanently-dead shared connection. These three are+ // terminal states `resolve()` returns for an `mcp_store` install the asker+ // can't fix (it's the owner's credential) and a retry won't heal — only the+ // owner/admin reconnecting will. Must precede the generic `auth`/`not_found`+ // matches below (which would otherwise swallow needs_reauth/disabled →+ // `auth` and not_found → `not_found`). The TRANSIENT `refresh_failed` is+ // deliberately absent — it self-heals next session, so it falls through to+ // `auth` as retryable.+ if (+ msg.includes('mcp_connection_needs_reauth') ||+ msg.includes('mcp_connection_disabled') ||+ msg.includes('mcp_connection_not_found')+ ) {+ return 'connection_dead'+ }if (msg.includes('mcp_secret_') ||msg.includes('mcp_identity_') ||+ // Transient shared-credential refresh blip (5xx/429) → retryable auth.+ msg.includes('mcp_connection_refresh_failed') ||msg.includes('no token') ||msg.includes('unauthor') ||msg.includes(' 401') ||@@ -205,6 +239,15 @@ export interface OpenMcpClientsDeps {* `openMcpClients`'s failure handling. */relink?(provider: string): Promise<string | null>}+ /**+ * Agent-level shared-credential resolver (`ref.connection` → a native+ * `mcp_store` installation), team-bound by the worker. Returns the upstream+ * URL + bearer; absent → a `connection` ref is refused. Wins over+ * `auth.provider` / `secrets` / `headers`.+ */+ connections?: {+ resolve(connectionId: string): Promise<McpConnectionResolution>+ }/*** Dev-only bearer attached to MCP requests when the ref has no* `auth.provider` of its own (`ref.auth` wins if set). Bridges the@@ -348,7 +391,40 @@ function isLoopbackHost(hostname: string): boolean {async function resolveTarget(ref: McpRef,deps: OpenMcpClientsDeps-): Promise<{ url: string; headers: Record<string, string> }> {+): Promise<{+ url: string+ headers: Record<string, string>+}> {+ // Shared-credential path (`ref.connection`): bearer + URL come from the+ // referenced installation, ignoring auth/secrets/headers. No author secrets+ // substituted → no cross-host exfiltration; just refuse non-https (loopback+ // dev-only). Smokescreen handles SSRF.+ if (ref.connection) {+ if (!deps.connections) {+ throw new Error(`mcp_connection_not_wired: ${ref.connection}`)+ }+ const res = await deps.connections.resolve(ref.connection)+ if (res.kind === 'not_found') {+ throw new Error(`mcp_connection_not_found: ${ref.connection}`)+ }+ if (res.kind === 'disabled') {+ throw new Error(`mcp_connection_disabled: ${ref.connection}`)+ }+ if (res.kind === 'needs_reauth') {+ // Owner must reconnect; asker can't fix a shared credential. → `auth`.+ throw new Error(`mcp_connection_needs_reauth: ${ref.connection}`)+ }+ const parsed = new URL(res.url)+ const loopback = isLoopbackHost(parsed.hostname) && isDev()+ if (!loopback && parsed.protocol !== 'https:') {+ throw new Error(`mcp_connection_unsafe_scheme: ${ref.connection} → ${parsed.protocol}`)+ }+ return {+ url: res.url,+ headers: { Authorization: `Bearer ${res.bearer}` },+ }+ }+// SSRF protection is handled at the infra layer by smokescreen (see// charts/shared/agent-platform/common.yaml `httpProxy.enabled: true`).// Author chose the URL; smokescreen denies RFC1918 / loopback /diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-proxy.test.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-proxy.test.tsnew file mode 100644index 000000000000..978342e4f9ac--- /dev/null+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-proxy.test.ts@@ -0,0 +1,507 @@+import { z } from 'zod'++import {+ AgentRevision,+ AgentSession,+ AgentSpecSchema,+ EMPTY_USAGE_TOTAL,+ HttpClient,+ McpRef,+ ToolRefSchema,+} from '@posthog/agent-shared'++import { AgentToolDeps, buildAgentTools } from './build-agent-tools'+import type { OpenedMcp, RemoteMcpTool } from './mcp-clients'++type ToolRefInput = z.input<typeof ToolRefSchema>++/**+ * Parse the spec from raw input (mirroring `build-agent-tools.test.ts`) so the+ * `mcps[]` come back fully defaulted — object-form `tools[]` entries need+ * `requires_approval`/`approval_policy` defaults applied, which only the schema+ * does. `mcpInput` is the raw McpRef input shape (loose) rather than the strict+ * output `McpRef`.+ */+function makeRev(toolRefs: ToolRefInput[] = [], mcpInput: Record<string, unknown>[] = []): AgentRevision {+ return {+ id: 'rev1',+ application_id: 'app1',+ parent_revision_id: null,+ created_by_id: null,+ created_at: '2026-06-26',+ state: 'live',+ bundle_uri: 's3://',+ bundle_sha256: null,+ spec: AgentSpecSchema.parse({ model: 'test/x', tools: toolRefs, skills: [], mcps: mcpInput }),+ encrypted_env: null,+ }+}++function makeSession(): AgentSession {+ return {+ id: 's1',+ application_id: 'app1',+ revision_id: 'rev1',+ team_id: 1,+ external_key: null,+ idempotency_key: null,+ trigger_metadata: null,+ state: 'running',+ principal: { kind: 'posthog', user_id: 'u1', team_id: 1 },+ conversation: [],+ pending_inputs: [],+ retry_count: 0,+ acl: [],+ pending_elevation_requests: [],+ usage_total: { ...EMPTY_USAGE_TOTAL },+ created_at: '2026-06-26',+ updated_at: '2026-06-26',+ }+}++function makeDeps(rev: AgentRevision, over: Partial<AgentToolDeps> = {}): AgentToolDeps {+ return {+ rev,+ session: makeSession(),+ sandbox: null,+ secrets: {},+ // Bundle is never touched on these MCP-only paths (no custom tools).+ bundle: null as unknown as AgentToolDeps['bundle'],+ log: () => undefined,+ http: new HttpClient(),+ posthogApiBaseUrl: 'http://localhost:8010',+ ...over,+ }+}++/** In-process tool table the fake client serves — `inputSchema` is optional+ * (defaults to `{ type: 'object' }`), matching `makeFakeMcp` below. */+type Handlers = Record<+ string,+ { description: string; inputSchema?: unknown; handler: (args: Record<string, unknown>) => Promise<unknown> }+>++/**+ * Stub `OpenedMcp` over an in-process tool table — mirrors the harness in+ * `build-agent-tools.test.ts`. `calls` records every `callTool` dispatch so we+ * can assert the proxy routes through the real client.+ */+function makeFakeMcp(+ prefix: string,+ ref: McpRef,+ handlers: Handlers+): OpenedMcp & { calls: Array<{ name: string; args: Record<string, unknown> }> } {+ const calls: Array<{ name: string; args: Record<string, unknown> }> = []+ return {+ prefix,+ ref,+ listTools: async () => {+ const out: RemoteMcpTool[] = []+ for (const [name, h] of Object.entries(handlers)) {+ out.push({ name, description: h.description, inputSchema: h.inputSchema ?? { type: 'object' } })+ }+ return out+ },+ callTool: async (name, args) => {+ calls.push({ name, args })+ const h = handlers[name]+ if (!h) {+ return { content: [{ type: 'text' as const, text: `unknown_tool: ${name}` }], isError: true }+ }+ try {+ const result = await h.handler(args)+ return {+ content: [{ type: 'text' as const, text: JSON.stringify(result) }],+ structuredContent: result as Record<string, unknown>,+ }+ } catch (err) {+ return { content: [{ type: 'text' as const, text: (err as Error).message }], isError: true }+ }+ },+ close: async () => undefined,+ calls,+ }+}++/** Build N fake handlers `tool-0..tool-(n-1)`, each echoing its args. */+function manyHandlers(n: number): Handlers {+ const out: Handlers = {}+ for (let i = 0; i < n; i++) {+ out[`tool-${i}`] = handler(`Tool number ${i}.`)+ }+ return out+}++function handler(description: string, inputSchema?: unknown): Handlers[string] {+ return { description, inputSchema, handler: async (args: Record<string, unknown>) => ({ echoed: args }) }+}++function byLabel(+ built: Awaited<ReturnType<typeof buildAgentTools>>,+ label: string+): Awaited<ReturnType<typeof buildAgentTools>>['tools'][number] {+ const tool = built.tools.find((t) => t.label === label)+ if (!tool) {+ throw new Error(`tool ${label} not built`)+ }+ return tool+}++describe('mcp proxy exposure', () => {+ it('proxies a large connection: three helper tools, no inline tools, populates mcpProxyCallTools', async () => {+ const rev = makeRev(+ [],+ [+ {+ kind: 'agent',+ id: 'posthog',+ url: 'https://example.com/mcp',+ secrets: [],+ default_tool_approval: 'allow',+ },+ ]+ )+ const mcp = makeFakeMcp('posthog', rev.spec.mcps[0], manyHandlers(60))+ const built = await buildAgentTools(rev, makeDeps(rev, { mcpClients: [mcp] }))++ const labels = built.tools.map((t) => t.label)+ // Exactly the three proxy helpers — none of the 60 inline tools.+ expect(labels).toContain('posthog__explore_tools')+ expect(labels).toContain('posthog__get_tool_schema')+ expect(labels).toContain('posthog__call_tool')+ expect(labels).not.toContain('posthog__tool-0')+ expect(labels.filter((l) => l.startsWith('posthog__'))).toHaveLength(3)++ // The dispatcher is recorded so the driver can install its dynamic gate.+ expect([...built.mcpProxyCallTools.keys()]).toEqual(['posthog__call_tool'])+ const entry = built.mcpProxyCallTools.get('posthog__call_tool')+ expect(entry?.client).toBe(mcp)+ // The same resolver the proxy uses at dispatch must travel through to+ // the driver's gate — otherwise the gate keys on a different name+ // than dispatch and an `approve` tool can run unapproved.+ expect(typeof entry?.resolveRemoteName).toBe('function')+ })++ it('inlines a small connection: one tool per remote, no proxy helpers', async () => {+ const rev = makeRev(+ [],+ [+ {+ kind: 'agent',+ id: 'linear',+ url: 'https://example.com/linear',+ secrets: [],+ default_tool_approval: 'allow',+ },+ ]+ )+ const mcp = makeFakeMcp('linear', rev.spec.mcps[0], {+ 'create-issue': handler('Open a new Linear issue.'),+ 'list-issues': handler('List recent Linear issues.'),+ })+ const built = await buildAgentTools(rev, makeDeps(rev, { mcpClients: [mcp] }))++ const labels = built.tools.map((t) => t.label)+ expect(labels).toContain('linear__create-issue')+ expect(labels).toContain('linear__list-issues')+ expect(labels).not.toContain('linear__explore_tools')+ expect(labels).not.toContain('linear__get_tool_schema')+ expect(labels).not.toContain('linear__call_tool')+ expect(built.mcpProxyCallTools.size).toBe(0)+ })++ describe('explore_tools + get_tool_schema', () => {+ async function buildProxy(): Promise<{+ built: Awaited<ReturnType<typeof buildAgentTools>>+ mcp: ReturnType<typeof makeFakeMcp>+ }> {+ const handlers = manyHandlers(60)+ handlers['get-insights'] = handler('Fetch insights for a project.', {+ type: 'object',+ properties: { project_id: { type: 'number' } },+ required: ['project_id'],+ })+ const rev = makeRev(+ [],+ [+ {+ kind: 'agent',+ id: 'posthog',+ url: 'https://example.com/mcp',+ secrets: [],+ default_tool_approval: 'allow',+ },+ ]+ )+ const mcp = makeFakeMcp('posthog', rev.spec.mcps[0], handlers)+ const built = await buildAgentTools(rev, makeDeps(rev, { mcpClients: [mcp] }))+ return { built, mcp }+ }++ it('filters by query, returning names + descriptions only (no schemas), capped at 50', async () => {+ const { built } = await buildProxy()+ const res = await byLabel(built, 'posthog__explore_tools').execute('c1', { query: 'insights' })+ const out = res.details.output as { total: number; returned: number; tools: Array<Record<string, unknown>> }+ expect(out.total).toBe(1)+ expect(out.tools).toEqual([{ name: 'get-insights', description: 'Fetch insights for a project.' }])+ // No schema leaks into a query result.+ expect(out.tools[0]).not.toHaveProperty('input_schema')+ })++ it('matches a multi-word query when every term appears (not a literal whole-string substring)', async () => {+ // Real footgun: a natural query like "insights project" used to be+ // matched as one literal substring and returned 0, forcing a re-query.+ // Tokenized AND-match finds the tool.+ const { built } = await buildProxy()+ const res = await byLabel(built, 'posthog__explore_tools').execute('c1', { query: 'insights project' })+ const out = res.details.output as { total: number; tools: Array<{ name: string }> }+ expect(out.total).toBe(1)+ expect(out.tools[0].name).toBe('get-insights')+ })++ it('caps a broad match at 50 while reporting the true total', async () => {+ const { built } = await buildProxy()+ // "tool" matches all 60 `tool-N` entries.+ const res = await byLabel(built, 'posthog__explore_tools').execute('c1', { query: 'tool' })+ const out = res.details.output as { total: number; returned: number; tools: unknown[] }+ expect(out.total).toBe(60)+ expect(out.returned).toBe(50)+ expect(out.tools).toHaveLength(50)+ })++ it('get_tool_schema returns one tool full input schema', async () => {+ const { built } = await buildProxy()+ const res = await byLabel(built, 'posthog__get_tool_schema').execute('c1', { tool_name: 'get-insights' })+ expect(res.details.output).toEqual({+ name: 'get-insights',+ description: 'Fetch insights for a project.',+ input_schema: {+ type: 'object',+ properties: { project_id: { type: 'number' } },+ required: ['project_id'],+ },+ })+ })++ it('get_tool_schema throws on an unknown tool_name', async () => {+ const { built } = await buildProxy()+ await expect(+ byLabel(built, 'posthog__get_tool_schema').execute('c1', { tool_name: 'nope' })+ ).rejects.toThrow(/unknown_tool: nope/)+ })++ it('explore_tools ignores tool_name (schema fetch moved to get_tool_schema) and lists instead', async () => {+ // Defensive: a stray tool_name on explore_tools must not 0-out the+ // list — it's a search tool now, so it returns the catalog.+ const { built } = await buildProxy()+ const res = await byLabel(built, 'posthog__explore_tools').execute('c1', { tool_name: 'get-insights' })+ const out = res.details.output as { total: number }+ expect(out.total).toBeGreaterThan(0)+ })+ })++ describe('call_tool', () => {+ it('dispatches the raw remote tool through the open client', async () => {+ const rev = makeRev(+ [],+ [+ {+ kind: 'agent',+ id: 'posthog',+ url: 'https://example.com/mcp',+ secrets: [],+ default_tool_approval: 'allow',+ },+ ]+ )+ const mcp = makeFakeMcp('posthog', rev.spec.mcps[0], manyHandlers(60))+ const built = await buildAgentTools(rev, makeDeps(rev, { mcpClients: [mcp] }))++ const res = await byLabel(built, 'posthog__call_tool').execute('c1', {+ tool_name: 'tool-3',+ arguments: { q: 'hi' },+ })+ // Routed under the RAW remote name (no prefix), with the args passed through.+ expect(mcp.calls).toEqual([{ name: 'tool-3', args: { q: 'hi' } }])+ expect(res.details.output).toMatchObject({ structuredContent: { echoed: { q: 'hi' } } })+ })++ it('accepts a prefixed tool_name (strips its own prefix) — the model passes the name it sees', async () => {+ // The model only ever sees `<prefix>__<name>`, so passing that as+ // tool_name is the natural mistake (and what the agent.md references).+ // call_tool tolerates it instead of erroring unknown_tool.+ const rev = makeRev(+ [],+ [+ {+ kind: 'agent',+ id: 'posthog',+ url: 'https://example.com/mcp',+ secrets: [],+ default_tool_approval: 'allow',+ },+ ]+ )+ const mcp = makeFakeMcp('posthog', rev.spec.mcps[0], manyHandlers(60))+ const built = await buildAgentTools(rev, makeDeps(rev, { mcpClients: [mcp] }))+ await byLabel(built, 'posthog__call_tool').execute('c1', {+ tool_name: 'posthog__tool-3',+ arguments: { q: 'hi' },+ })+ expect(mcp.calls).toEqual([{ name: 'tool-3', args: { q: 'hi' } }])+ })++ it('refuses a tool outside the exposed set (e.g. a denied one)', async () => {+ // `default_tool_approval: deny` + a single `allow` override = strict+ // allowlist; only `tool-0` is exposed. The dispatcher must refuse+ // `tool-1` even though it exists on the server.+ const rev = makeRev(+ [],+ [+ {+ kind: 'agent',+ id: 'posthog',+ url: 'https://example.com/mcp',+ secrets: [],+ default_tool_approval: 'deny',+ tools: [{ name: 'tool-0', level: 'allow' }],+ },+ ]+ )+ // 60 handlers so the (single allowed) connection still proxies via+ // the chars budget — but exposure is filtered to just `tool-0`.+ const handlers = manyHandlers(60)+ // Pad the one exposed tool's description so the (filtered) one-tool+ // catalog still trips the proxy budget by serialized size.+ handlers['tool-0'] = handler('x'.repeat(200_000))+ const mcp = makeFakeMcp('posthog', rev.spec.mcps[0], handlers)+ const built = await buildAgentTools(rev, makeDeps(rev, { mcpClients: [mcp] }))++ const callTool = byLabel(built, 'posthog__call_tool')+ // Allowed tool dispatches.+ await callTool.execute('c1', { tool_name: 'tool-0', arguments: {} })+ expect(mcp.calls.map((c) => c.name)).toEqual(['tool-0'])+ // Denied tool is unreachable — refused before any dispatch.+ await expect(callTool.execute('c2', { tool_name: 'tool-1', arguments: {} })).rejects.toThrow(+ /unknown_tool: tool-1/+ )+ expect(mcp.calls.map((c) => c.name)).toEqual(['tool-0'])+ })++ it('surfaces a remote isError as a thrown error', async () => {+ const rev = makeRev(+ [],+ [+ {+ kind: 'agent',+ id: 'posthog',+ url: 'https://example.com/mcp',+ secrets: [],+ default_tool_approval: 'allow',+ },+ ]+ )+ const handlers = manyHandlers(60)+ handlers['tool-5'] = {+ description: 'boom',+ handler: async () => {+ throw new Error('remote_blew_up')+ },+ }+ const mcp = makeFakeMcp('posthog', rev.spec.mcps[0], handlers)+ const built = await buildAgentTools(rev, makeDeps(rev, { mcpClients: [mcp] }))+ await expect(+ byLabel(built, 'posthog__call_tool').execute('c1', { tool_name: 'tool-5', arguments: {} })+ ).rejects.toThrow('remote_blew_up')+ })++ it('appends the tool input_schema to a call_tool error so the retry is schema-informed', async () => {+ // In proxy mode the model only sees call_tool's free-form `arguments`,+ // so a wrong-args call is easy. Handing it the schema on failure turns+ // "wrong args multiple times" into a one-shot, guided retry.+ const rev = makeRev(+ [],+ [+ {+ kind: 'agent',+ id: 'posthog',+ url: 'https://example.com/mcp',+ secrets: [],+ default_tool_approval: 'allow',+ },+ ]+ )+ const handlers = manyHandlers(60)+ handlers['get-insights'] = {+ description: 'Fetch insights.',+ inputSchema: {+ type: 'object',+ properties: { project_id: { type: 'number' } },+ required: ['project_id'],+ },+ handler: async () => {+ throw new Error('missing required arg: project_id')+ },+ }+ const mcp = makeFakeMcp('posthog', rev.spec.mcps[0], handlers)+ const built = await buildAgentTools(rev, makeDeps(rev, { mcpClients: [mcp] }))++ let err: Error | undefined+ try {+ await byLabel(built, 'posthog__call_tool').execute('c1', { tool_name: 'get-insights', arguments: {} })+ } catch (e) {+ err = e as Error+ }+ expect(err?.message).toContain('missing required arg: project_id') // remote message preserved+ expect(err?.message).toContain('"required":["project_id"]') // + the schema, for a guided retry+ })++ it('names explore_tools instead of dumping a large schema into the error', async () => {+ // A big schema would balloon the error, so the cap swaps the inline+ // dump for a one-line pointer to get_tool_schema.+ const bigSchema = {+ type: 'object',+ properties: Object.fromEntries(+ Array.from({ length: 200 }, (_, i) => [+ `field_${i}`,+ { type: 'string', description: 'x'.repeat(50) },+ ])+ ),+ }+ const rev = makeRev(+ [],+ [+ {+ kind: 'agent',+ id: 'posthog',+ url: 'https://example.com/mcp',+ secrets: [],+ default_tool_approval: 'allow',+ },+ ]+ )+ const handlers = manyHandlers(60)+ handlers['huge-tool'] = {+ description: 'has a big schema',+ inputSchema: bigSchema,+ handler: async () => {+ throw new Error('bad args')+ },+ }+ const mcp = makeFakeMcp('posthog', rev.spec.mcps[0], handlers)+ const built = await buildAgentTools(rev, makeDeps(rev, { mcpClients: [mcp] }))++ let err: Error | undefined+ try {+ await byLabel(built, 'posthog__call_tool').execute('c1', { tool_name: 'huge-tool', arguments: {} })+ } catch (e) {+ err = e as Error+ }+ expect(err?.message).toContain('bad args')+ expect(err?.message).toContain('posthog__get_tool_schema({ tool_name: "huge-tool" })')+ // The giant schema is NOT inlined.+ expect(err?.message).not.toContain('field_199')+ expect(err!.message.length).toBeLessThan(2_000)+ })+ })+})diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-proxy.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-proxy.tsnew file mode 100644index 000000000000..06e0ab84a358--- /dev/null+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-proxy.ts@@ -0,0 +1,190 @@+/**+ * Harness-mediated proxy for a large MCP connection: expose three helpers and+ * keep the full catalog in memory instead of inlining every tool's schema.+ * - `<prefix>__explore_tools` — list/search tools (names + descriptions).+ * - `<prefix>__get_tool_schema` — fetch one tool's full input schema.+ * - `<prefix>__call_tool` — invoke a tool by its raw remote name.+ * Splitting search from schema-fetch (vs one overloaded tool) makes the+ * find → read-schema → call flow legible, so the model reads args instead of+ * guessing them. `exposed` is the deny/allowlist-filtered catalog; names outside+ * it are unreachable. The driver gates `call_tool` on the underlying tool (driver.ts).+ */++import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'+import type { TSchema } from '@earendil-works/pi-ai'++import type { ToolResultDetails } from './build-agent-tools'+import type { OpenedMcp, RemoteMcpTool } from './mcp-clients'+import { PROXY_CALL_TOOL, PROXY_EXPLORE_TOOL, PROXY_GET_SCHEMA_TOOL } from './mcp-tool-lookup'++const EXPLORE_RESULT_CAP = 50++/** Cap for inlining a tool's input schema into a call_tool error. Small schemas+ * ride along so the model can fix args in one retry; a large one would balloon+ * the error, so we name explore_tools instead. ~500 tokens. */+const MAX_ERROR_SCHEMA_CHARS = 2_000++export interface McpProxyTools {+ tools: AgentTool<TSchema, ToolResultDetails>[]+ /** The driver keys its dynamic approval gate on this. */+ callToolName: string+ /** Pure resolver, captured so the driver's gate can mirror dispatch+ * resolution exactly. See {@link resolveProxyRemoteName} for the rule. */+ resolveRemoteName: (raw: string) => string+}++/**+ * Map a `call_tool({tool_name})` arg to the actual remote name that will be+ * dispatched. The rule must match what `call_tool` does at execute time — the+ * driver's dynamic approval gate keys on `<prefix>__<resolved>`, and if it+ * resolves differently from dispatch, an `approve`-gated tool can run+ * unapproved. The precedence is:+ *+ * 1. raw exists in the exposed catalog → use it as-is. This is load-bearing+ * for the collision case: a remote tool whose RAW name starts with+ * `<prefix>__` (e.g. `big__delete` on the `big` server) must dispatch and+ * gate as itself, not as the stripped `delete`.+ * 2. raw starts with our `<prefix>__` AND the stripped name exists → strip.+ * This is the natural mistake-tolerance for the model, which sees tools+ * as `<prefix>__<name>` and often passes that form back as `tool_name`.+ * 3. otherwise → return raw (dispatch will surface `unknown_tool`).+ */+export function resolveProxyRemoteName(raw: string, prefix: string, has: (name: string) => boolean): string {+ if (has(raw)) {+ return raw+ }+ const marker = `${prefix}__`+ if (raw.startsWith(marker)) {+ const stripped = raw.slice(marker.length)+ if (has(stripped)) {+ return stripped+ }+ }+ return raw+}++export function makeMcpProxyTools(client: OpenedMcp, exposed: RemoteMcpTool[]): McpProxyTools {+ const prefix = client.prefix+ const byName = new Map<string, RemoteMcpTool>(exposed.map((t) => [t.name, t]))+ const exploreName = `${prefix}__${PROXY_EXPLORE_TOOL}`+ const getSchemaName = `${prefix}__${PROXY_GET_SCHEMA_TOOL}`+ const callToolName = `${prefix}__${PROXY_CALL_TOOL}`++ const resolveRemoteName = (raw: string): string => resolveProxyRemoteName(raw, prefix, (n) => byName.has(n))++ const surfaceNote =+ `This server exposes ${exposed.length} tools on demand rather than inline. ` ++ `Use ${exploreName} to find a tool, ${getSchemaName} to read its input schema, ` ++ `then ${callToolName} to invoke it.`++ const exploreTool: AgentTool<TSchema, ToolResultDetails> = {+ name: exploreName,+ label: exploreName,+ description:+ `Find tools this MCP server exposes (${exposed.length} total). ${surfaceNote} ` ++ 'Pass `query` to search names + descriptions (case-insensitive; multiple terms all must match; ' ++ 'omit to list all). Returns names + descriptions only, no schemas — ' ++ `call ${getSchemaName} for a tool's arguments before invoking it.`,+ parameters: {+ type: 'object',+ properties: {+ query: {+ type: 'string',+ description: 'Terms to match against tool names + descriptions (case-insensitive; all must match).',+ },+ },+ } as unknown as TSchema,+ execute: async (_callId, args): Promise<AgentToolResult<ToolResultDetails>> => {+ const a = (args ?? {}) as { query?: unknown }+ // Tokenized AND-match: every whitespace-separated term must appear in+ // the name or description. A literal whole-string match made natural+ // multi-word queries ("agent-applications retrieve") return nothing,+ // since tool names are hyphenated — forcing a wasted re-query.+ const tokens = typeof a.query === 'string' ? a.query.trim().toLowerCase().split(/\s+/).filter(Boolean) : []+ const matches = tokens.length+ ? exposed.filter((t) => {+ const hay = `${t.name} ${t.description}`.toLowerCase()+ return tokens.every((tok) => hay.includes(tok))+ })+ : exposed+ const results = matches+ .slice(0, EXPLORE_RESULT_CAP)+ .map((t) => ({ name: t.name, description: t.description }))+ const output = { total: matches.length, returned: results.length, tools: results }+ return { content: [{ type: 'text', text: JSON.stringify(output) }], details: { output } }+ },+ }++ const getSchemaTool: AgentTool<TSchema, ToolResultDetails> = {+ name: getSchemaName,+ label: getSchemaName,+ description:+ `Get one tool's full input schema (its exact argument names + types) before calling it with ${callToolName}. ` ++ `Find tool names via ${exploreName}. Always read the schema here rather than guessing arguments.`,+ parameters: {+ type: 'object',+ properties: {+ tool_name: { type: 'string', description: 'Raw remote tool name to fetch the input schema for.' },+ },+ required: ['tool_name'],+ } as unknown as TSchema,+ execute: async (_callId, args): Promise<AgentToolResult<ToolResultDetails>> => {+ const a = (args ?? {}) as { tool_name?: unknown }+ const toolName = resolveRemoteName(typeof a.tool_name === 'string' ? a.tool_name : '')+ const remote = byName.get(toolName)+ if (!remote) {+ throw new Error(`unknown_tool: ${toolName}`)+ }+ const output = { name: remote.name, description: remote.description, input_schema: remote.inputSchema }+ return { content: [{ type: 'text', text: JSON.stringify(output) }], details: { output } }+ },+ }++ const callTool: AgentTool<TSchema, ToolResultDetails> = {+ name: callToolName,+ label: callToolName,+ description:+ `Invoke a tool exposed by this MCP server. ${surfaceNote} ` ++ 'Pass the raw tool name and its `arguments`. The argument names + types are NOT shown here — if you ' ++ `have not already read this tool's schema via ${getSchemaName} this session, do that FIRST and match ` ++ 'it exactly. Never invent argument names.',+ parameters: {+ type: 'object',+ properties: {+ tool_name: { type: 'string', description: 'Raw remote tool name to invoke.' },+ arguments: { type: 'object', description: "Arguments object matching the tool's input schema." },+ },+ required: ['tool_name'],+ } as unknown as TSchema,+ execute: async (_callId, args): Promise<AgentToolResult<ToolResultDetails>> => {+ const a = (args ?? {}) as { tool_name?: unknown; arguments?: unknown }+ const toolName = resolveRemoteName(typeof a.tool_name === 'string' ? a.tool_name : '')+ if (!byName.has(toolName)) {+ throw new Error(`unknown_tool: ${toolName}`)+ }+ const callArgs = (a.arguments ?? {}) as Record<string, unknown>+ const result = await client.callTool(toolName, callArgs)+ // Result-shaping mirrors makeMcpTool.+ if (result.isError) {+ const firstText = (result.content as Array<{ type: string; text?: string }>).find(+ (c) => c.type === 'text' && typeof c.text === 'string'+ )+ const base = firstText?.text ?? `mcp_tool_error: ${prefix}__${toolName}`+ // Point the model at the tool's input schema so a wrong-args+ // failure becomes a guided retry, not another guess (call_tool's+ // own `arguments` param carries no per-tool shape). Inline a small+ // schema for a one-shot fix; for a large one just name+ // explore_tools so the error can't balloon.+ const schema = JSON.stringify(byName.get(toolName)?.inputSchema ?? {})+ const hint =+ schema.length <= MAX_ERROR_SCHEMA_CHARS+ ? `Input schema for ${toolName}: ${schema}`+ : `Call ${getSchemaName}({ tool_name: "${toolName}" }) for its full input schema.`+ throw new Error(`${base}\n${hint}`)+ }+ return { content: [{ type: 'text', text: JSON.stringify(result) }], details: { output: result } }+ },+ }++ return { tools: [exploreTool, getSchemaTool, callTool], callToolName, resolveRemoteName }+}diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-tool-budget.test.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-tool-budget.test.tsnew file mode 100644index 000000000000..6d2a0846f5bc--- /dev/null+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-tool-budget.test.ts@@ -0,0 +1,50 @@+/**+ * Exposure-decision coverage. Uses a synthetic catalog sized like a rich server+ * (the real PostHog MCP is ~603 tools / ~2.7M serialized chars) rather than a+ * committed multi-MB fixture.+ */+import type { RemoteMcpTool } from './mcp-clients'+import { DEFAULT_MCP_EXPOSURE_BUDGET, decideMcpExposure, serializedToolChars } from './mcp-tool-budget'++function makeCatalog(count: number, schemaFields: number, descWords: number): RemoteMcpTool[] {+ return Array.from({ length: count }, (_, i) => {+ const properties: Record<string, unknown> = {}+ for (let f = 0; f < schemaFields; f++) {+ properties[`field_${f}`] = { type: 'string', description: `Parameter ${f}. ${'detail '.repeat(6)}`.trim() }+ }+ return {+ name: `tool_${i}`,+ description: `Synthetic tool ${i}. ${'lorem ipsum '.repeat(descWords)}`.trim(),+ inputSchema: { type: 'object', properties },+ }+ })+}++const richCatalog = makeCatalog(600, 50, 6) // ~3M serialized chars+const smallCatalog = makeCatalog(38, 4, 3)++describe('MCP exposure decision', () => {+ it('a rich surface exceeds the budget → proxy', () => {+ const d = decideMcpExposure(richCatalog)+ expect(d.mode).toBe('proxy')+ expect(d.toolCount).toBeGreaterThan(DEFAULT_MCP_EXPOSURE_BUDGET.maxInlineTools)+ expect(d.serializedChars).toBeGreaterThan(DEFAULT_MCP_EXPOSURE_BUDGET.maxInlineChars)+ expect(d.reasons.length).toBe(2)+ expect(d.serializedChars).toBeGreaterThan(2_000_000)+ })++ it('a small surface fits the budget → inline', () => {+ const d = decideMcpExposure(smallCatalog)+ expect(d.mode).toBe('inline')+ expect(d.reasons).toEqual([])+ })++ it('a curated slice of a rich surface stays inline', () => {+ expect(decideMcpExposure(richCatalog.slice(0, 10)).mode).toBe('inline')+ })++ it('proxying collapses the surface to ~constant cost regardless of N', () => {+ const PROXY_BLOCK_CHARS = 2_000+ expect(serializedToolChars(richCatalog)).toBeGreaterThan(50 * PROXY_BLOCK_CHARS)+ })+})diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-tool-budget.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-tool-budget.tsnew file mode 100644index 000000000000..f7da38d552db--- /dev/null+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-tool-budget.ts@@ -0,0 +1,59 @@+/**+ * Decide how an MCP connection's tools reach the model: listed inline, or behind+ * a proxy. Front-loading every tool's schema is fine for a small server but+ * overflows the model for a rich one (the PostHog MCP: 603 tools, ~2.7 MB), so+ * past a budget we expose a proxy (mcp-proxy.ts) instead and load schemas on demand.+ */+import type { RemoteMcpTool } from './mcp-clients'++export interface McpExposureBudget {+ maxInlineTools: number+ /** Serialized inline tool block (name + description + input schema), in chars. ~4 chars/token. */+ maxInlineChars: number+}++/** incident.io (38 tools, ~85k chars) stays inline; the PostHog MCP (603, ~2.7M) proxies. */+export const DEFAULT_MCP_EXPOSURE_BUDGET: McpExposureBudget = {+ maxInlineTools: 40,+ maxInlineChars: 100_000,+}++export interface McpExposureDecision {+ mode: 'inline' | 'proxy'+ toolCount: number+ serializedChars: number+ /** Which limit(s) forced the proxy — empty when inline. */+ reasons: string[]+}++export function serializedToolChars(tools: readonly RemoteMcpTool[]): number {+ let total = 0+ for (const t of tools) {+ total += t.name.length+ total += t.description?.length ?? 0+ total += JSON.stringify(t.inputSchema ?? {}).length+ }+ return total+}++/** Decide inline vs proxy for one connection's already-filtered tools. */+export function decideMcpExposure(+ tools: readonly RemoteMcpTool[],+ budget: McpExposureBudget = DEFAULT_MCP_EXPOSURE_BUDGET+): McpExposureDecision {+ const toolCount = tools.length+ const serializedChars = serializedToolChars(tools)+ const reasons: string[] = []+ if (toolCount > budget.maxInlineTools) {+ reasons.push(`tool_count ${toolCount} > ${budget.maxInlineTools}`)+ }+ if (serializedChars > budget.maxInlineChars) {+ reasons.push(`serialized_chars ${serializedChars} > ${budget.maxInlineChars}`)+ }+ return {+ mode: reasons.length > 0 ? 'proxy' : 'inline',+ toolCount,+ serializedChars,+ reasons,+ }+}diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.test.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.test.tsindex 84af58c05b04..25bd1c9b9ad4 100644--- a/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.test.ts+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.test.ts@@ -1,6 +1,6 @@-import { AgentSpec, AgentSpecSchema } from '@posthog/agent-shared'+import { AgentSpec, AgentSpecSchema, McpRef } from '@posthog/agent-shared'-import { lookupMcpToolApproval } from './mcp-tool-lookup'+import { effectiveToolLevel, lookupMcpToolApproval, resolveApprovedExecutor } from './mcp-tool-lookup'/*** Tests pass spec shapes in zod-input form (defaults omitted, partial@@ -12,16 +12,18 @@ function buildSpec(overrides: Record<string, unknown> = {}): AgentSpec {}describe('lookupMcpToolApproval', () => {- it('returns the policy when the exposed name resolves to a gated object entry', () => {+ it('returns the policy when the exposed name resolves to an approve-level entry', () => {const spec = buildSpec({mcps: [{+ kind: 'agent',id: 'posthog',url: 'https://app.posthog.com/api/mcp',+ default_tool_approval: 'allow',tools: [{name: 'agent-applications-revisions-promote-create',- requires_approval: true,+ level: 'approve',approval_policy: { type: 'principal', ttl_ms: 900_000 },},],@@ -35,58 +37,26 @@ describe('lookupMcpToolApproval', () => {expect(result?.approval_policy.ttl_ms).toBe(900_000)})- it('returns null when the exposed name matches a bare-string entry (inclusion only, no policy)', () => {+ it('returns null when a tool takes an allow default (no gate)', () => {const spec = buildSpec({mcps: [{+ kind: 'agent',id: 'linear',url: 'https://mcp.linear.app/sse',- tools: ['create-issue'],- },- ],- })- expect(lookupMcpToolApproval('linear__create-issue', spec)).toBeNull()- })-- it('returns null when the remote name has no entry in the matching mcp', () => {- const spec = buildSpec({- mcps: [- {- id: 'linear',- url: 'https://mcp.linear.app/sse',- tools: [{ name: 'create-issue', requires_approval: true }],+ default_tool_approval: 'allow',+ tools: [{ name: 'create-issue', level: 'approve' }],},],})+ // list-issues has no entry → takes the 'allow' default → no gate.expect(lookupMcpToolApproval('linear__list-issues', spec)).toBeNull()})- it('returns the entry verbatim when matched — requires_approval=false flows through to the driver', () => {- const spec = buildSpec({- mcps: [- {- id: 'linear',- url: 'https://mcp.linear.app/sse',- tools: [{ name: 'create-issue' /* requires_approval defaults to false */ }],- },- ],- })- const result = lookupMcpToolApproval('linear__create-issue', spec)- // The driver checks `requires_approval` separately, so we still return- // the entry — null is reserved for "no entry at all". The- // `requires_approval: false` signal flows through naturally.- expect(result).not.toBeNull()- expect(result?.requires_approval).toBe(false)- })-it('returns null when no mcp prefix matches', () => {const spec = buildSpec({mcps: [- {- id: 'linear',- url: 'https://mcp.linear.app/sse',- tools: [{ name: 'create-issue', requires_approval: true }],- },+ { kind: 'agent', id: 'linear', url: 'https://mcp.linear.app/sse', default_tool_approval: 'approve' },],})expect(lookupMcpToolApproval('github__create-issue', spec)).toBeNull()@@ -104,11 +74,7 @@ describe('lookupMcpToolApproval', () => {])('returns null for non-MCP-shaped names like %s', (name) => {const spec = buildSpec({mcps: [- {- id: 'linear',- url: 'https://mcp.linear.app/sse',- tools: [{ name: 'create-issue', requires_approval: true }],- },+ { kind: 'agent', id: 'linear', url: 'https://mcp.linear.app/sse', default_tool_approval: 'approve' },],})expect(lookupMcpToolApproval(name, spec)).toBeNull()@@ -122,36 +88,17 @@ describe('lookupMcpToolApproval', () => {const spec = buildSpec({mcps: [{+ kind: 'agent',id: 'service',url: 'https://example.com/mcp',- tools: [{ name: 'parent__child', requires_approval: true }],+ default_tool_approval: 'allow',+ tools: [{ name: 'parent__child', level: 'approve' }],},],})expect(lookupMcpToolApproval('service__parent__child', spec)).not.toBeNull()})- it('walks every entry — does not bail on the first bare-string match', () => {- // Iteration order belt-and-braces (review #3 sibling). The bare- // string sits BEFORE an object entry under a DIFFERENT name; the- // helper has to keep walking past the bare string to find the- // object form. If a future refactor early-returned on first- // match-by-presence (instead of first match-by-name), this- // assertion catches it.- const spec = buildSpec({- mcps: [- {- id: 'linear',- url: 'https://mcp.linear.app/sse',- tools: ['list-issues', { name: 'create-issue', requires_approval: true }],- },- ],- })- const result = lookupMcpToolApproval('linear__create-issue', spec)- expect(result).not.toBeNull()- expect(result?.requires_approval).toBe(true)- })-it('only checks against ref.tools[]; ignores tools listed in spec.tools[]', () => {// A native tool with the same id as a remote MCP tool is a separate// declaration — the lookup must not cross-pollinate. Belt-and-braces@@ -167,15 +114,166 @@ describe('lookupMcpToolApproval', () => {],mcps: [{+ kind: 'agent',id: 'linear',url: 'https://mcp.linear.app/sse',- tools: ['list-issues'], // no `create-issue` entry → no MCP-side gating+ // create-issue takes the 'allow' default → no MCP-side gate.+ default_tool_approval: 'allow',},],})// Even though `spec.tools[]` declares the same id, the lookup- // resolves through `spec.mcps[].tools[]` only — and `create-issue`- // isn't listed there.+ // resolves through `spec.mcps[]` only — and create-issue takes the allow default.expect(lookupMcpToolApproval('linear__create-issue', spec)).toBeNull()})})++describe('effectiveToolLevel (default + per-tool override model)', () => {+ const refOf = (mcp: Record<string, unknown>): McpRef => buildSpec({ mcps: [mcp] }).mcps[0]++ it('returns the connection default when there is no per-tool override', () => {+ const ref = refOf({+ kind: 'agent',+ id: 'demo',+ url: 'https://example.com/mcp',+ default_tool_approval: 'approve',+ })+ expect(effectiveToolLevel(ref, 'anything')).toBe('approve')+ })++ it('a per-tool level overrides the default for that tool only', () => {+ const ref = refOf({+ kind: 'agent',+ id: 'demo',+ url: 'https://example.com/mcp',+ default_tool_approval: 'approve',+ tools: [+ { name: 'safe', level: 'allow' },+ { name: 'danger', level: 'deny' },+ ],+ })+ expect(effectiveToolLevel(ref, 'safe')).toBe('allow')+ expect(effectiveToolLevel(ref, 'danger')).toBe('deny')+ // A tool with no override falls back to the default.+ expect(effectiveToolLevel(ref, 'other')).toBe('approve')+ })+})++describe('lookupMcpToolApproval (default + per-tool override model)', () => {+ it('gates an approve-level tool, falling back to the principal/24h default policy', () => {+ const spec = buildSpec({+ mcps: [{ kind: 'agent', id: 'demo', url: 'https://example.com/mcp', default_tool_approval: 'approve' }],+ })+ const result = lookupMcpToolApproval('demo__promote', spec)+ expect(result).not.toBeNull()+ expect(result?.requires_approval).toBe(true)+ expect(result?.approval_policy.type).toBe('principal')+ expect(result?.approval_policy.ttl_ms).toBe(24 * 60 * 60 * 1000)+ })++ it('uses the ref-level approval_policy for approve-level tools when set', () => {+ const spec = buildSpec({+ mcps: [+ {+ kind: 'agent',+ id: 'demo',+ url: 'https://example.com/mcp',+ default_tool_approval: 'approve',+ approval_policy: { type: 'agent', ttl_ms: 900_000 },+ },+ ],+ })+ const result = lookupMcpToolApproval('demo__promote', spec)+ expect(result?.requires_approval).toBe(true)+ expect(result?.approval_policy.type).toBe('agent')+ expect(result?.approval_policy.ttl_ms).toBe(900_000)+ })++ it('does NOT gate allow-level tools (default or override)', () => {+ const allowDefault = buildSpec({+ mcps: [{ kind: 'agent', id: 'demo', url: 'https://example.com/mcp', default_tool_approval: 'allow' }],+ })+ expect(lookupMcpToolApproval('demo__echo', allowDefault)).toBeNull()++ const allowOverride = buildSpec({+ mcps: [+ {+ kind: 'agent',+ id: 'demo',+ url: 'https://example.com/mcp',+ default_tool_approval: 'approve',+ tools: [{ name: 'echo', level: 'allow' }],+ },+ ],+ })+ // The override wins: this tool is auto-allow even though the default is approve.+ expect(lookupMcpToolApproval('demo__echo', allowOverride)).toBeNull()+ })++ it('an approve override on an allow-default ref gates that one tool', () => {+ const spec = buildSpec({+ mcps: [+ {+ kind: 'agent',+ id: 'demo',+ url: 'https://example.com/mcp',+ default_tool_approval: 'allow',+ tools: [{ name: 'promote', level: 'approve' }],+ },+ ],+ })+ expect(lookupMcpToolApproval('demo__echo', spec)).toBeNull() // default allow+ expect(lookupMcpToolApproval('demo__promote', spec)?.requires_approval).toBe(true)+ })++ it('returns null for deny-level tools (they are never exposed, so dispatch never asks)', () => {+ const spec = buildSpec({+ mcps: [{ kind: 'agent', id: 'demo', url: 'https://example.com/mcp', default_tool_approval: 'deny' }],+ })+ expect(lookupMcpToolApproval('demo__echo', spec)).toBeNull()+ })++ it('gates a real remote tool that merely shares a proxy-helper name (no blanket name exemption)', () => {+ // Regression for veria-ai's finding: the lookup used to return null for+ // ANY tool named call_tool / explore_tools / get_tool_schema, so a real+ // remote tool with one of those names on a NON-proxied connection ran+ // inline without approval under an `approve` default. The lookup is now a+ // pure level check — the synthetic-proxy-helper exemption is proxy-aware+ // and lives in the driver (which knows which connections are proxied),+ // not here, so a real same-named tool is gated like any other.+ const spec = buildSpec({+ mcps: [{ kind: 'agent', id: 'small', url: 'https://example.com/mcp', default_tool_approval: 'approve' }],+ })+ expect(lookupMcpToolApproval('small__call_tool', spec)?.requires_approval).toBe(true)+ expect(lookupMcpToolApproval('small__explore_tools', spec)?.requires_approval).toBe(true)+ expect(lookupMcpToolApproval('small__get_tool_schema', spec)?.requires_approval).toBe(true)+ })+})++describe('resolveApprovedExecutor (resume dispatch)', () => {+ // The driver builds `realExecute` from the live tool surface; for a proxied+ // connection that's only `<prefix>__call_tool` + `<prefix>__explore_tools`,+ // NOT the per-remote names the approval gate keys on.+ const execs = new Map<string, string>([+ ['@posthog/query', 'native-exec'],+ ['posthog__call_tool', 'call-tool-exec'],+ ['posthog__explore_tools', 'explore-exec'],+ ])+ const proxyCallTools = new Map<string, unknown>([['posthog__call_tool', {}]])++ it('resolves a native/inline tool by its exact name', () => {+ expect(resolveApprovedExecutor('@posthog/query', execs, proxyCallTools)).toBe('native-exec')+ })++ it('resolves a proxy-routed row (<prefix>__<remote>) to the connection call_tool executor', () => {+ // The bug: a plain lookup misses the row's re-keyed name, dropping the+ // approved call. The fallback recovers the call_tool executor (whose+ // args are the row's stored call_tool args).+ expect(execs.get('posthog__get-insights')).toBeUndefined() // <- what the driver used to do+ expect(resolveApprovedExecutor('posthog__get-insights', execs, proxyCallTools)).toBe('call-tool-exec')+ })++ it('returns undefined for an unknown tool with no proxied prefix', () => {+ expect(resolveApprovedExecutor('linear__create-issue', execs, proxyCallTools)).toBeUndefined()+ })+})diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.tsindex 0247d3ad79be..af0b57d2a061 100644--- a/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.ts+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-tool-lookup.ts@@ -1,7 +1,8 @@/*** Decompose a model-visible MCP tool name (`<prefix>__<remoteName>`) into* the spec entry that declared it, so the dispatcher can read per-tool- * approval gating off the same `tools[]` field that drives inclusion.+ * approval gating off the connection's `default_tool_approval` + `tools[]`+ * level overrides.** Why a separate file: the driver's approval-wrap loop already has a* lookup for native + custom tools (`spec.tools.find(t => t.id === id)`).@@ -9,20 +10,79 @@* start from `client.listTools()`. The fallback path lives here so the* driver stays a thin orchestrator and the lookup is independently* testable.- *- * The `tools[]` shape: bare string = inclusion only, object = inclusion +- * approval policy; gating is `external` only.*/-import { AgentSpec, ApprovalPolicy, McpRef } from '@posthog/agent-shared'+import { AgentSpec, ApprovalPolicy, DEFAULT_APPROVAL_POLICY, McpRef, ToolApprovalLevel } from '@posthog/agent-shared'++export const PREFIX_SEPARATOR = '__'++/**+ * Synthetic proxy helper tools (`mcp-proxy.ts` exposes `<prefix>__explore_tools`,+ * `<prefix>__get_tool_schema`, `<prefix>__call_tool` for large connections).+ * Used by name here to keep the two files in sync without a cycle+ * (mcp-tool-lookup is a leaf; mcp-proxy imports these).+ */+export const PROXY_EXPLORE_TOOL = 'explore_tools'+export const PROXY_GET_SCHEMA_TOOL = 'get_tool_schema'+export const PROXY_CALL_TOOL = 'call_tool'++/** The synthetic read-only proxy helpers — catalog search + schema fetch, no+ * side effects. `call_tool` is NOT here: it dispatches a real tool and the+ * driver gates it dynamically on the underlying tool. */+const PROXY_READ_ONLY_HELPERS: ReadonlySet<string> = new Set([PROXY_EXPLORE_TOOL, PROXY_GET_SCHEMA_TOOL])++/** Prefixes of the connections running in proxy mode, derived from the driver's+ * `<prefix>__call_tool` executor-map keys. A prefix is proxied iff its+ * `call_tool` helper exists. */+export function proxiedPrefixesFromCallTools(callToolNames: Iterable<string>): Set<string> {+ const suffix = `${PREFIX_SEPARATOR}${PROXY_CALL_TOOL}`+ const set = new Set<string>()+ for (const name of callToolNames) {+ if (name.endsWith(suffix)) {+ set.add(name.slice(0, -suffix.length))+ }+ }+ return set+}-const PREFIX_SEPARATOR = '__'+/**+ * True when `exposedName` is a synthetic read-only proxy helper+ * (`<prefix>__explore_tools` / `<prefix>__get_tool_schema`) for a connection in+ * `proxiedPrefixes` — those are ours, ungated. A REAL remote tool that merely+ * shares one of those names on a non-proxied connection returns false, so it's+ * gated by its level like any other tool (the bug this guards against: a blanket+ * name-based exemption let such a tool run inline without approval).+ */+export function isProxyReadOnlyHelper(exposedName: string, proxiedPrefixes: ReadonlySet<string>): boolean {+ const sep = exposedName.indexOf(PREFIX_SEPARATOR)+ if (sep <= 0) {+ return false+ }+ const prefix = exposedName.slice(0, sep)+ const remoteName = exposedName.slice(sep + PREFIX_SEPARATOR.length)+ return PROXY_READ_ONLY_HELPERS.has(remoteName) && proxiedPrefixes.has(prefix)+}/**- * Per-tool approval config materialised from a `tools[]` entry. Shape- * intentionally mirrors `ToolRefSchema`'s `requires_approval` +- * `approval_policy` so the driver's wrap path doesn't need to special-case- * MCP tools vs. native/custom.+ * Effective approval level for a remote tool: its `tools[].level` override ??+ * the connection's `default_tool_approval`.+ *+ * Shared by `build-agent-tools.ts` (exposure: `deny` → not exposed) and+ * `lookupMcpToolApproval` (gating: `approve` → queue) so the two never drift.+ */+export function effectiveToolLevel(ref: McpRef, remoteName: string): ToolApprovalLevel {+ for (const entry of ref.tools ?? []) {+ if (entry.name === remoteName) {+ return entry.level+ }+ }+ return ref.default_tool_approval+}++/**+ * Per-tool approval config for the driver's wrap path. Shape intentionally+ * mirrors `ToolRefSchema`'s `requires_approval` + `approval_policy` so the+ * driver doesn't need to special-case MCP tools vs. native/custom.*/export interface McpToolApprovalConfig {requires_approval: boolean@@ -35,8 +95,7 @@ export interface McpToolApprovalConfig {* - the name doesn't carry the `__` separator (caller is asking about a* native / custom / client tool),* - no `spec.mcps[]` entry matches the prefix,- * - the matched entry has no `tools[]`, no matching name, or the matching- * entry is a bare string (inclusion only, no policy).+ * - the tool's effective level is not `approve` (no gate).** Returning null is the "no MCP-side gating" signal — the driver falls* through to whatever the native/custom lookup said (typically: no gating).@@ -49,23 +108,20 @@ export function lookupMcpToolApproval(exposedName: string, spec: AgentSpec): Mcpconst prefix = exposedName.slice(0, sep)const remoteName = exposedName.slice(sep + PREFIX_SEPARATOR.length)const ref = findMcpRefByPrefix(spec.mcps, prefix)- if (!ref || !ref.tools) {+ if (!ref) {return null}- for (const entry of ref.tools) {- if (typeof entry === 'string') {- // Bare-string entries carry no policy — they're inclusion only.- // A name match here just means "this tool is exposed, no gating."- continue- }- if (entry.name === remoteName) {- return {- requires_approval: entry.requires_approval,- approval_policy: entry.approval_policy,- }- }- }- return null+ // Gate iff the effective level is `approve`. `allow` → no gate; `deny` never+ // reaches dispatch (build-agent-tools never exposes it). Who approves + ttl:+ // the tool's own `approval_policy` ?? the connection default ?? principal/24h.+ const entry = ref.tools?.find((t) => t.name === remoteName)+ const level = entry?.level ?? ref.default_tool_approval+ return level === 'approve'+ ? {+ requires_approval: true,+ approval_policy: entry?.approval_policy ?? ref.approval_policy ?? DEFAULT_APPROVAL_POLICY,+ }+ : null}/**@@ -81,3 +137,37 @@ function findMcpRefByPrefix(mcps: ReadonlyArray<McpRef>, prefix: string): McpRef}return null}++/**+ * Resolve the executor for an APPROVED row on resume. Native / custom /+ * inline-MCP tools are keyed by their exposed name directly. A proxy-routed row+ * is keyed by `<prefix>__<remoteName>` (the gate re-keyed onto the underlying+ * tool at call time), but its executor is the connection's `call_tool` — and the+ * row's stored args ARE the `call_tool` args (`{ tool_name, arguments }`), so+ * dispatching through it replays the original call. Without this fallback,+ * `executors.get(row.tool_name)` misses every proxy-routed row and the+ * human-approved call is dropped with a synthetic "unknown tool" error.+ */+export function resolveApprovedExecutor<T>(+ toolName: string,+ executors: ReadonlyMap<string, T>,+ proxyCallTools: ReadonlyMap<string, unknown>+): T | undefined {+ const direct = executors.get(toolName)+ if (direct !== undefined) {+ return direct+ }+ const key = proxyCallToolKey(toolName, proxyCallTools)+ return key ? executors.get(key) : undefined+}++/** The `<prefix>__call_tool` key for a proxy-routed `<prefix>__<remoteName>`+ * name, or null when the prefix has no proxied connection. */+function proxyCallToolKey(toolName: string, proxyCallTools: ReadonlyMap<string, unknown>): string | null {+ const sep = toolName.indexOf(PREFIX_SEPARATOR)+ if (sep <= 0) {+ return null+ }+ const callToolName = `${toolName.slice(0, sep)}${PREFIX_SEPARATOR}${PROXY_CALL_TOOL}`+ return proxyCallTools.has(callToolName) ? callToolName : null+}diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.test.ts b/products/agent_platform/services/agent-runner/src/workers/worker.test.tsindex d49452e6db5c..7272c7b2d441 100644--- a/products/agent_platform/services/agent-runner/src/workers/worker.test.ts+++ b/products/agent_platform/services/agent-runner/src/workers/worker.test.ts@@ -247,7 +247,7 @@ describe('Worker', () => {bundle_uri: 's3://x/',spec: AgentSpecSchema.parse({model: 'faux/test',- mcps: [{ id: 'echo', url: 'https://example.com/echo' }],+ mcps: [{ kind: 'agent', default_tool_approval: 'allow', id: 'echo', url: 'https://example.com/echo' }],}),})await bundle.write(rev.id, 'agent.md', 'you are a bot')diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.ts b/products/agent_platform/services/agent-runner/src/workers/worker.tsindex d4777a3cf528..914e03563efe 100644--- a/products/agent_platform/services/agent-runner/src/workers/worker.ts+++ b/products/agent_platform/services/agent-runner/src/workers/worker.ts@@ -41,6 +41,7 @@ import {getSecretAllowedHosts,HttpFetcher,LogSink,+ McpConnectionStore,MemoryStore,modelPolicyToList,TabularStore,@@ -200,6 +201,11 @@ export interface WorkerDeps {* instrumentation / retry middleware.*/mcpTransportFactory?: McpTransportFactory+ /**+ * Shared-credential MCP resolver (`spec.mcps[].connection`). The worker binds+ * it to the session's `team_id`. Omit to disable the connection path.+ */+ mcpConnections?: McpConnectionStore/*** Dev-only bearer forwarded to `openMcpClients`. See `OpenMcpClientsDeps`.* Sourced from `AGENT_DEV_MCP_BEARER_TOKEN`; the runner's `index.ts`@@ -493,11 +499,19 @@ export class Worker {log: (level, msg, meta) => sLog[level](meta ?? {}, msg),}): undefined+ // Bind the connection resolver to this session's team.+ const mcpConnections = this.deps.mcpConnections+ ? {+ resolve: (connectionId: string) =>+ this.deps.mcpConnections!.resolve(connectionId, session.team_id),+ }+ : undefinedconst opened = await openMcpClients(rev.spec.mcps, {secrets,secretAllowedHosts: (name) => getSecretAllowedHosts(rev.spec, name),transportFactory: this.deps.mcpTransportFactory,identity: mcpIdentity,+ connections: mcpConnections,devMcpBearerToken: this.deps.devMcpBearerToken,log: (level, msg, meta) => sLog[level](meta ?? {}, msg),http: this.deps.http,diff --git a/products/agent_platform/services/agent-runner/vitest.config.ts b/products/agent_platform/services/agent-runner/vitest.config.tsindex 506864af4e00..8f97a2c2c971 100644--- a/products/agent_platform/services/agent-runner/vitest.config.ts+++ b/products/agent_platform/services/agent-runner/vitest.config.ts@@ -7,9 +7,9 @@ export default defineConfig({include: ['src/**/*.test.ts'],testTimeout: 15_000,globals: true,- // Test files share the agent_runtime_queue_test PG. Running them in- // parallel races on `node-pg-migrate`'s schema lock and on the- // public-schema drop in `reset()`. Mirrors agent-shared + agent-tests.+ // Test files share one Postgres (agent_runtime_queue_test). `reset()`+ // truncates the shared `agent_*` tables between cases, so running files+ // in parallel races on that shared state. Mirrors agent-shared + agent-tests.fileParallelism: false,},})diff --git a/products/agent_platform/services/agent-shared/src/index.ts b/products/agent_platform/services/agent-shared/src/index.tsindex 1b008653ec1d..a6274e9ef1bf 100644--- a/products/agent_platform/services/agent-shared/src/index.ts+++ b/products/agent_platform/services/agent-shared/src/index.ts@@ -63,6 +63,7 @@ export * from './runtime/metrics'export * from './runtime/process-handlers'export * from './runtime/encryption'export * from './runtime/team-api-key-resolver'+export * from './runtime/mcp-connection-store'export * from './runtime/gateway-catalog'export * from './runtime/gateway-client'export * from './runtime/failure-notifier'diff --git a/products/agent_platform/services/agent-shared/src/runtime/encryption.test.ts b/products/agent_platform/services/agent-shared/src/runtime/encryption.test.tsindex 990b7e4825d7..26c51b81c497 100644--- a/products/agent_platform/services/agent-shared/src/runtime/encryption.test.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/encryption.test.ts@@ -55,4 +55,30 @@ describe('EncryptedFields', () => {const scalarCt = e.encrypt(JSON.stringify('plain'))expect(() => e.decryptJsonEnv(scalarCt)).toThrow(/not a JSON object/)})++ // EncryptedJSONField (per-leaf), as used by mcp_store sensitive_configuration.+ it('encryptJsonFieldValue → decryptJsonFieldValue round-trips object leaves', () => {+ const e = new EncryptedFields(K1)+ const encrypted = e.encryptJsonFieldValue({ access_token: 'tok', nested: { refresh: 'r' } })+ // Structure preserved as plaintext JSON; only leaves are ciphertext.+ const obj = encrypted as Record<string, unknown>+ expect(typeof obj.access_token).toBe('string')+ expect(obj.access_token).not.toBe('tok')+ expect(e.decryptJsonFieldValue(encrypted)).toEqual({ access_token: 'tok', nested: { refresh: 'r' } })+ })++ it('encryptJsonFieldValue str()-ifies scalars like Django (int→"3600", bool→"True"); null passes through', () => {+ const e = new EncryptedFields(K1)+ const decrypted = e.decryptJsonFieldValue(+ e.encryptJsonFieldValue({ expires_in: 3600, needs_reauth: true, off: false, missing: null })+ )+ expect(decrypted).toEqual({ expires_in: '3600', needs_reauth: 'True', off: 'False', missing: null })+ })++ it('decryptJsonFieldValue tolerates a rotated key (new key first, old behind)', () => {+ const old = new EncryptedFields(K1)+ const stored = old.encryptJsonFieldValue({ access_token: 'tok' })+ const rotated = new EncryptedFields(`${K2},${K1}`)+ expect(rotated.decryptJsonFieldValue(stored)).toEqual({ access_token: 'tok' })+ })})diff --git a/products/agent_platform/services/agent-shared/src/runtime/encryption.ts b/products/agent_platform/services/agent-shared/src/runtime/encryption.tsindex 2fa50ba6c3eb..b322f078850f 100644--- a/products/agent_platform/services/agent-shared/src/runtime/encryption.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/encryption.ts@@ -99,4 +99,55 @@ export class EncryptedFields {}return parsed as Record<string, unknown>}++ /**+ * Decrypt a Django `EncryptedJSONField` (RECURSIVE per-leaf — not the+ * whole-blob `decryptJson`). Structure stays plaintext JSON; each scalar leaf+ * was `encrypt(str(value))`, so leaves come back as STRINGS (`3600`→"3600",+ * `True`→"True"); `null` passes through. Pass the parsed value (node-pg parses+ * jsonb; JSON.parse a text column first). Mirrors `_decrypt_values`.+ */+ decryptJsonFieldValue(value: unknown): unknown {+ if (value === null || value === undefined) {+ return value+ }+ if (Array.isArray(value)) {+ return value.map((v) => this.decryptJsonFieldValue(v))+ }+ if (typeof value === 'object') {+ const out: Record<string, unknown> = {}+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {+ out[k] = this.decryptJsonFieldValue(v)+ }+ return out+ }+ if (typeof value === 'string') {+ return this.decrypt(value)+ }+ // Numbers/booleans shouldn't appear at rest (they were str()-ified then+ // encrypted to a string token), but pass them through if they do.+ return value+ }++ /**+ * Inverse of `decryptJsonFieldValue` for write-back. Mirrors `_encrypt_values`:+ * each scalar leaf is `str(value)`-ified (bool → "True"/"False") then+ * encrypted; `null` preserved. `JSON.stringify` the result for the column.+ */+ encryptJsonFieldValue(value: unknown): unknown {+ if (value === null || value === undefined) {+ return value+ }+ if (Array.isArray(value)) {+ return value.map((v) => this.encryptJsonFieldValue(v))+ }+ if (typeof value === 'object') {+ const out: Record<string, unknown> = {}+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {+ out[k] = this.encryptJsonFieldValue(v)+ }+ return out+ }+ return this.encrypt(typeof value === 'boolean' ? (value ? 'True' : 'False') : String(value))+ }}diff --git a/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.test.ts b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.test.tsnew file mode 100644index 000000000000..398ab9bb4d88--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.test.ts@@ -0,0 +1,298 @@+import type { Pool } from 'pg'++import { EncryptedFields } from './encryption'+import type { HttpFetcher } from './http-client'+import { PgMcpConnectionStore } from './mcp-connection-store'++// 32-byte UTF-8 key — matches Django's ENCRYPTION_SALT_KEYS shape.+const KEY = '01234567890123456789012345678901'+const enc = new EncryptedFields(KEY)+const nowSec = Math.floor(Date.now() / 1000)++function fakeResponse(opts: { ok: boolean; status?: number; body?: unknown; text?: string }): Response {+ return {+ ok: opts.ok,+ status: opts.status ?? (opts.ok ? 200 : 400),+ json: async () => opts.body,+ text: async () => opts.text ?? '',+ } as unknown as Response+}++function makeFakeHttp(response: Response): HttpFetcher & { calls: Array<{ url: string; init?: RequestInit }> } {+ const calls: Array<{ url: string; init?: RequestInit }> = []+ return {+ calls,+ async fetch(input: string | URL, init?: RequestInit) {+ calls.push({ url: String(input), init })+ return response+ },+ }+}++type QueryLog = Array<{ sql: string; values: unknown[] }>+type QueryResult = { rows: Array<Record<string, unknown>> }++function makeFakePool(row: Record<string, unknown> | null): { pool: Pool; calls: QueryLog; writes: QueryLog } {+ const calls: QueryLog = []+ const writes: QueryLog = []+ const handle = (sql: string, values: unknown[]): QueryResult => {+ calls.push({ sql, values })+ const t = sql.trim()+ if (/^(BEGIN|COMMIT|ROLLBACK)/.test(t)) {+ return { rows: [] }+ }+ if (t.startsWith('UPDATE mcp_store_mcpserverinstallation')) {+ writes.push({ sql, values })+ return { rows: [] }+ }+ return { rows: row ? [row] : [] } // SELECT (read or FOR UPDATE)+ }+ const pool = {+ query: (sql: string, values: unknown[]) => Promise.resolve(handle(sql, values)),+ connect: () =>+ Promise.resolve({+ query: (sql: string, values: unknown[]) => Promise.resolve(handle(sql, values)),+ release: () => {},+ }),+ }+ return { pool: pool as unknown as Pool, calls, writes }+}++function oauthRow(+ opts: {+ expiring?: boolean+ needsReauth?: boolean+ isEnabled?: boolean+ noRefreshToken?: boolean+ secret?: string+ authMethod?: string+ resource?: string+ } = {}+): Record<string, unknown> {+ const sensitive: Record<string, unknown> = {+ access_token: 'tok-1',+ refresh_token: 'refresh-1',+ token_retrieved_at: String(opts.expiring ? nowSec - 7200 : nowSec),+ expires_in: '3600',+ dcr_client_id: 'client-1',+ }+ if (opts.noRefreshToken) {+ delete sensitive.refresh_token+ }+ if (opts.needsReauth) {+ sensitive.needs_reauth = 'True'+ }+ if (opts.secret) {+ sensitive.dcr_client_secret = opts.secret+ }+ if (opts.authMethod) {+ sensitive.dcr_token_endpoint_auth_method = opts.authMethod+ }+ return {+ url: 'https://mcp.example.com/mcp',+ auth_type: 'oauth',+ is_enabled: opts.isEnabled ?? true,+ sensitive_configuration: enc.encryptJsonFieldValue(sensitive),+ oauth_metadata: {+ token_endpoint: 'https://idp.example.com/token',+ ...(opts.resource ? { resource: opts.resource } : {}),+ },+ template_id: null,+ template_oauth_metadata: null,+ template_oauth_credentials: null,+ }+}++describe('PgMcpConnectionStore', () => {+ it('scopes the lookup to (connectionId, teamId)', async () => {+ const { pool, calls } = makeFakePool(oauthRow())+ const store = new PgMcpConnectionStore(pool, enc, makeFakeHttp(fakeResponse({ ok: true })))+ await store.resolve('conn-1', 42)+ expect(calls[0].values).toEqual(['conn-1', 42])+ })++ it('resolves an api-key installation without refresh', async () => {+ const { pool, writes } = makeFakePool({+ url: 'https://mcp.example.com/mcp',+ auth_type: 'api_key',+ is_enabled: true,+ sensitive_configuration: enc.encryptJsonFieldValue({ api_key: 'key-1' }),+ oauth_metadata: {},+ template_id: null,+ template_oauth_metadata: null,+ template_oauth_credentials: null,+ })+ const http = makeFakeHttp(fakeResponse({ ok: true }))+ const store = new PgMcpConnectionStore(pool, enc, http)+ await expect(store.resolve('c', 1)).resolves.toEqual({+ kind: 'resolved',+ url: 'https://mcp.example.com/mcp',+ bearer: 'key-1',+ })+ expect(http.calls).toHaveLength(0)+ expect(writes).toHaveLength(0)+ })++ it('resolves a non-expiring oauth token from the stored value', async () => {+ const { pool, writes } = makeFakePool(oauthRow({ expiring: false }))+ const http = makeFakeHttp(fakeResponse({ ok: true }))+ const store = new PgMcpConnectionStore(pool, enc, http)+ await expect(store.resolve('c', 1)).resolves.toEqual({+ kind: 'resolved',+ url: 'https://mcp.example.com/mcp',+ bearer: 'tok-1',+ })+ expect(http.calls).toHaveLength(0)+ expect(writes).toHaveLength(0)+ })++ it('refreshes an expiring oauth token and writes the rotated token back', async () => {+ const { pool, writes } = makeFakePool(oauthRow({ expiring: true }))+ const http = makeFakeHttp(+ fakeResponse({ ok: true, body: { access_token: 'tok-2', refresh_token: 'refresh-2', expires_in: 1800 } })+ )+ const store = new PgMcpConnectionStore(pool, enc, http)+ const res = await store.resolve('c', 1)+ expect(res).toEqual({+ kind: 'resolved',+ url: 'https://mcp.example.com/mcp',+ bearer: 'tok-2',+ })++ // Refresh hit the token endpoint with the refresh grant + client id.+ expect(http.calls).toHaveLength(1)+ expect(http.calls[0].url).toBe('https://idp.example.com/token')+ expect(String(http.calls[0].init?.body)).toContain('grant_type=refresh_token')+ expect(String(http.calls[0].init?.body)).toContain('client_id=client-1')++ // Wrote back, in the per-leaf-encrypted format Django/PostHog Code reads.+ expect(writes).toHaveLength(1)+ const written = enc.decryptJsonFieldValue(JSON.parse(writes[0].values[0] as string)) as Record<string, unknown>+ expect(written.access_token).toBe('tok-2')+ expect(written.refresh_token).toBe('refresh-2')+ expect(written.expires_in).toBe('1800')+ expect(written.dcr_client_id).toBe('client-1') // non-token leaves preserved+ })++ it('uses HTTP Basic auth for a confidential client (Django default when a secret is present)', async () => {+ const { pool } = makeFakePool(oauthRow({ expiring: true, secret: 'secret-1' }))+ const http = makeFakeHttp(fakeResponse({ ok: true, body: { access_token: 'tok-2', expires_in: 1800 } }))+ const store = new PgMcpConnectionStore(pool, enc, http)+ await store.resolve('c', 1)+ const init = http.calls[0].init!+ expect((init.headers as Record<string, string>).Authorization).toBe(+ `Basic ${Buffer.from('client-1:secret-1').toString('base64')}`+ )+ // Basic → credentials live in the header, never the form body.+ const body = String(init.body)+ expect(body).not.toContain('client_secret=')+ expect(body).not.toContain('client_id=')+ })++ it('uses client_secret_post (creds in body) when the stored auth method says so', async () => {+ const { pool } = makeFakePool(+ oauthRow({ expiring: true, secret: 'secret-1', authMethod: 'client_secret_post' })+ )+ const http = makeFakeHttp(fakeResponse({ ok: true, body: { access_token: 'tok-2', expires_in: 1800 } }))+ const store = new PgMcpConnectionStore(pool, enc, http)+ await store.resolve('c', 1)+ const init = http.calls[0].init!+ expect((init.headers as Record<string, string>).Authorization).toBeUndefined()+ const body = String(init.body)+ expect(body).toContain('client_id=client-1')+ expect(body).toContain('client_secret=secret-1')+ })++ it('sends the resource parameter on refresh when the metadata pins one', async () => {+ const { pool } = makeFakePool(oauthRow({ expiring: true, resource: 'https://api.example.com' }))+ const http = makeFakeHttp(fakeResponse({ ok: true, body: { access_token: 'tok-2', expires_in: 1800 } }))+ const store = new PgMcpConnectionStore(pool, enc, http)+ await store.resolve('c', 1)+ expect(String(http.calls[0].init?.body)).toContain('resource=https%3A%2F%2Fapi.example.com')+ })++ it('refuses a redirecting token endpoint (manual redirect) and flags needs_reauth', async () => {+ const { pool, writes } = makeFakePool(oauthRow({ expiring: true }))+ const http = makeFakeHttp(fakeResponse({ ok: false, status: 302, text: '' }))+ const store = new PgMcpConnectionStore(pool, enc, http)+ await expect(store.resolve('c', 1)).rejects.toThrow(/mcp_connection_needs_reauth/)+ // Don't follow redirects (Django uses allow_redirects=False), and treat a+ // 3xx as a permanent misconfig → needs_reauth, not an endless retry.+ expect(http.calls[0].init?.redirect).toBe('manual')+ const written = enc.decryptJsonFieldValue(JSON.parse(writes[0].values[0] as string)) as Record<string, unknown>+ expect(written.needs_reauth).toBe('True')+ })++ it('does not persist a non-finite expires_in (IdP returned null)', async () => {+ const { pool, writes } = makeFakePool(oauthRow({ expiring: true }))+ const http = makeFakeHttp(fakeResponse({ ok: true, body: { access_token: 'tok-2', expires_in: null } }))+ const store = new PgMcpConnectionStore(pool, enc, http)+ await store.resolve('c', 1)+ const written = enc.decryptJsonFieldValue(JSON.parse(writes[0].values[0] as string)) as Record<string, unknown>+ // Storing "null" NaN-poisons isTokenExpiring → pins the bearer as+ // never-refreshing. Keep the prior numeric value instead.+ expect(written.expires_in).not.toBe('null')+ expect(written.access_token).toBe('tok-2')+ })++ it('keeps the existing refresh token when the refresh response omits one', async () => {+ const { pool, writes } = makeFakePool(oauthRow({ expiring: true }))+ const http = makeFakeHttp(fakeResponse({ ok: true, body: { access_token: 'tok-2', expires_in: 1800 } }))+ const store = new PgMcpConnectionStore(pool, enc, http)+ await store.resolve('c', 1)+ const written = enc.decryptJsonFieldValue(JSON.parse(writes[0].values[0] as string)) as Record<string, unknown>+ expect(written.refresh_token).toBe('refresh-1')+ })++ it('returns needs_reauth when the credential is flagged', async () => {+ const { pool } = makeFakePool(oauthRow({ needsReauth: true }))+ const store = new PgMcpConnectionStore(pool, enc, makeFakeHttp(fakeResponse({ ok: true })))+ await expect(store.resolve('c', 1)).resolves.toEqual({ kind: 'needs_reauth' })+ })++ it('returns disabled when the installation is disabled', async () => {+ const { pool } = makeFakePool(oauthRow({ isEnabled: false }))+ const store = new PgMcpConnectionStore(pool, enc, makeFakeHttp(fakeResponse({ ok: true })))+ await expect(store.resolve('c', 1)).resolves.toEqual({ kind: 'disabled' })+ })++ it('returns not_found when no row matches', async () => {+ const { pool } = makeFakePool(null)+ const store = new PgMcpConnectionStore(pool, enc, makeFakeHttp(fakeResponse({ ok: true })))+ await expect(store.resolve('c', 1)).resolves.toEqual({ kind: 'not_found' })+ })++ it('flags needs_reauth (and stops retrying) on a permanent 4xx refresh rejection', async () => {+ const { pool, writes } = makeFakePool(oauthRow({ expiring: true }))+ const http = makeFakeHttp(fakeResponse({ ok: false, status: 400, text: 'invalid_grant' }))+ const store = new PgMcpConnectionStore(pool, enc, http)+ await expect(store.resolve('c', 1)).rejects.toThrow(/mcp_connection_needs_reauth/)+ // Wrote needs_reauth back so the next resolve short-circuits instead of+ // re-hitting the token endpoint every session.+ expect(writes).toHaveLength(1)+ const written = enc.decryptJsonFieldValue(JSON.parse(writes[0].values[0] as string)) as Record<string, unknown>+ expect(written.needs_reauth).toBe('True')+ })++ it('flags needs_reauth (and stops retrying) when an expiring oauth token has no refresh token', async () => {+ const { pool, writes } = makeFakePool(oauthRow({ expiring: true, noRefreshToken: true }))+ const http = makeFakeHttp(fakeResponse({ ok: true }))+ const store = new PgMcpConnectionStore(pool, enc, http)+ await expect(store.resolve('c', 1)).rejects.toThrow(/mcp_connection_needs_reauth/)+ // Nothing to refresh with → no token-endpoint call…+ expect(http.calls).toHaveLength(0)+ // …but needs_reauth is written back so the next resolve short-circuits+ // instead of re-acquiring the lock and rolling back every session.+ expect(writes).toHaveLength(1)+ const written = enc.decryptJsonFieldValue(JSON.parse(writes[0].values[0] as string)) as Record<string, unknown>+ expect(written.needs_reauth).toBe('True')+ })++ it('throws a transient refresh failure without flagging needs_reauth on a 5xx', async () => {+ const { pool, writes } = makeFakePool(oauthRow({ expiring: true }))+ const http = makeFakeHttp(fakeResponse({ ok: false, status: 503, text: 'upstream down' }))+ const store = new PgMcpConnectionStore(pool, enc, http)+ await expect(store.resolve('c', 1)).rejects.toThrow(/mcp_connection_refresh_failed/)+ expect(writes).toHaveLength(0)+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.ts b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.tsnew file mode 100644index 000000000000..f9c78d0748b2--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/mcp-connection-store.ts@@ -0,0 +1,404 @@+/**+ * Resolves `spec.mcps[].connection` (a native `mcp_store` `MCPServerInstallation`)+ * into an upstream URL + bearer — the agent-level shared-credential path (one+ * connection, every asker). DB-direct against `posthogDb`, no Django HTTP:+ * read → decrypt → refresh-on-expiry → write-back, duplicating mcp_store/oauth.py.+ * `FOR UPDATE` serialises the shared row; cross-pod single-flight is deferred.+ */++import type { Pool, PoolClient } from 'pg'++import { EncryptedFields } from './encryption'+import type { HttpFetcher } from './http-client'+import { createLogger } from './logger'++export type McpConnectionResolution =+ | {+ kind: 'resolved'+ url: string+ bearer: string+ }+ /** No usable credential (missing or `needs_reauth`); the OWNER must reconnect. */+ | { kind: 'needs_reauth' }+ /** Owner disabled the installation (`is_enabled = false`). */+ | { kind: 'disabled' }+ /** No installation with this id for the agent's team. */+ | { kind: 'not_found' }++export interface McpConnectionStore {+ /** Resolve an installation (UUID, scoped to `teamId`) to URL + bearer,+ * refreshing an expiring OAuth token in place. Throws+ * `mcp_connection_refresh_failed` on a transient refresh failure. */+ resolve(connectionId: string, teamId: number): Promise<McpConnectionResolution>+}++interface InstallationRow {+ url: string+ auth_type: string+ is_enabled: boolean+ sensitive_configuration: unknown+ oauth_metadata: Record<string, unknown> | null+ template_id: string | null+ template_oauth_metadata: Record<string, unknown> | null+ template_oauth_credentials: unknown+}++type TokenEndpointAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none'++interface OauthContext {+ tokenEndpoint: string+ clientId: string+ clientSecret?: string+ /** How the client authenticates to the token endpoint. Mirrors Django's+ * per-installation `(dcr_)token_endpoint_auth_method`; defaults to+ * `client_secret_basic` when a secret is present, else `none`. */+ authMethod: TokenEndpointAuthMethod+ /** RFC 8707 resource indicator from the OAuth metadata. Sent on refresh when+ * the IdP audience-pins tokens (Entra, Auth0-with-audience) — omitting it+ * 400s the refresh on those servers. */+ resource?: string+}++interface TokenResponse {+ access_token: string+ refresh_token?: string+ expires_in?: number+}++const SELECT_INSTALLATION = `+ SELECT i.url,+ i.auth_type,+ i.is_enabled,+ i.sensitive_configuration,+ i.oauth_metadata,+ i.template_id,+ t.oauth_metadata AS template_oauth_metadata,+ t.oauth_credentials AS template_oauth_credentials+ FROM mcp_store_mcpserverinstallation i+ LEFT JOIN mcp_store_mcpservertemplate t ON t.id = i.template_id+ WHERE i.id = $1 AND i.team_id = $2`++/** Reads `mcp_store_mcpserverinstallation` (+ optional template) from the main+ * DB. Pass the main-DB pool. Write-back needs UPDATE on that table. */+export class PgMcpConnectionStore implements McpConnectionStore {+ private readonly log = createLogger('mcp-connection-store')++ constructor(+ private readonly pool: Pool,+ private readonly encryption: EncryptedFields,+ private readonly http: HttpFetcher+ ) {}++ async resolve(connectionId: string, teamId: number): Promise<McpConnectionResolution> {+ const { rows } = await this.pool.query<InstallationRow>(SELECT_INSTALLATION, [connectionId, teamId])+ if (rows.length === 0) {+ return { kind: 'not_found' }+ }+ const row = rows[0]+ if (!row.is_enabled) {+ return { kind: 'disabled' }+ }+ const sensitive = this.decryptJsonObject(row.sensitive_configuration)+ if (isPyTrue(sensitive.needs_reauth)) {+ return { kind: 'needs_reauth' }+ }++ if (row.auth_type === 'api_key') {+ const apiKey = asNonEmptyString(sensitive.api_key)+ if (!apiKey) {+ return { kind: 'needs_reauth' }+ }+ return { kind: 'resolved', url: row.url, bearer: apiKey }+ }++ // OAuth: use the stored access token, refreshing first if it's expiring.+ const accessToken = asNonEmptyString(sensitive.access_token)+ if (!accessToken) {+ return { kind: 'needs_reauth' }+ }+ if (!isTokenExpiring(sensitive)) {+ return { kind: 'resolved', url: row.url, bearer: accessToken }+ }+ const refreshed = await this.refresh(connectionId, teamId)+ return { kind: 'resolved', url: row.url, bearer: refreshed }+ }++ /** Refresh under a row lock, write back the rotated token, return it.+ * Re-checks expiry after locking (another worker may have refreshed). On a+ * PERMANENT failure (4xx except 429 — the refresh token/client is rejected)+ * flags `needs_reauth` in the SAME transaction so the next session+ * short-circuits to "owner must reconnect" instead of re-hitting the IdP on+ * every run; a TRANSIENT failure (5xx / 429 / network) rolls back so the+ * next session retries. */+ private async refresh(connectionId: string, teamId: number): Promise<string> {+ const client = await this.pool.connect()+ let committed = false+ try {+ await client.query('BEGIN')+ const { rows } = await client.query<InstallationRow>(`${SELECT_INSTALLATION} FOR UPDATE OF i`, [+ connectionId,+ teamId,+ ])+ if (rows.length === 0) {+ throw new Error(`mcp_connection_refresh_failed: ${connectionId} (row vanished)`)+ }+ const row = rows[0]+ const sensitive = this.decryptJsonObject(row.sensitive_configuration)+ const current = asNonEmptyString(sensitive.access_token)+ // Another worker may have refreshed while we waited for the lock.+ if (current && !isTokenExpiring(sensitive)) {+ await client.query('COMMIT')+ committed = true+ return current+ }+ const refreshToken = asNonEmptyString(sensitive.refresh_token)+ if (!refreshToken) {+ // No refresh token (e.g. an OAuth install via DCR that never+ // issued one) + an expiring access token fails identically on+ // every future session. Flag `needs_reauth` in the SAME locked+ // transaction — exactly like the permanent-HTTP-rejection path+ // below — so `resolve()` short-circuits to "owner must reconnect"+ // next run instead of re-acquiring the lock and rolling back each+ // time.+ await this.writeSensitive(client, connectionId, { ...sensitive, needs_reauth: true })+ await client.query('COMMIT')+ committed = true+ this.log.warn({ connection_id: connectionId }, 'mcp_connection.no_refresh_token_needs_reauth')+ throw new Error(`mcp_connection_needs_reauth: ${connectionId} (no refresh token)`)+ }+ const ctx = this.resolveOauthContext(row, sensitive)++ let token: TokenResponse+ try {+ token = await this.tokenRefreshRequest(ctx, refreshToken)+ } catch (err) {+ // A permanent rejection (revoked/invalid refresh token) fails the+ // same way on every future session — flag `needs_reauth` so+ // `resolve()` short-circuits next time instead of burning a+ // token-endpoint call each run. Transient failures fall through to+ // the outer catch → rollback → retry on the next session.+ if (err instanceof TokenRefreshHttpError && err.permanent) {+ await this.writeSensitive(client, connectionId, { ...sensitive, needs_reauth: true })+ await client.query('COMMIT')+ committed = true+ this.log.warn(+ { connection_id: connectionId, status: err.status },+ 'mcp_connection.refresh_rejected_needs_reauth'+ )+ throw new Error(`mcp_connection_needs_reauth: ${connectionId} (refresh rejected: ${err.status})`)+ }+ throw err+ }++ // Preserve non-token leaves (dcr_client_id/secret, …).+ const updated: Record<string, unknown> = { ...sensitive }+ updated.access_token = token.access_token+ updated.token_retrieved_at = String(Math.floor(Date.now() / 1000))+ updated.refresh_token = token.refresh_token ?? refreshToken+ // Only persist a real number. An IdP returning `expires_in: null`+ // would otherwise store "null", which `Number()`-coerces to NaN and+ // pins the bearer as never-refreshing (isTokenExpiring bails on NaN).+ if (typeof token.expires_in === 'number' && Number.isFinite(token.expires_in)) {+ updated.expires_in = String(token.expires_in)+ }+ await this.writeSensitive(client, connectionId, updated)+ await client.query('COMMIT')+ committed = true+ this.log.info({ connection_id: connectionId }, 'mcp_connection.token_refreshed')+ return token.access_token+ } catch (err) {+ if (!committed) {+ try {+ await client.query('ROLLBACK')+ } catch {+ // Original error wins; a rollback failure on a broken+ // connection is not separately actionable.+ }+ }+ if (err instanceof Error && err.message.startsWith('mcp_connection_')) {+ throw err+ }+ throw new Error(+ `mcp_connection_refresh_failed: ${connectionId} (${err instanceof Error ? err.message : String(err)})`+ )+ } finally {+ client.release()+ }+ }++ /** Re-encrypt + write the full `sensitive_configuration` jsonb (per-leaf+ * Fernet) within the caller's transaction. */+ private async writeSensitive(+ client: PoolClient,+ connectionId: string,+ sensitive: Record<string, unknown>+ ): Promise<void> {+ const encrypted = this.encryption.encryptJsonFieldValue(sensitive)+ await client.query(+ 'UPDATE mcp_store_mcpserverinstallation SET sensitive_configuration = $1::jsonb, updated_at = NOW() WHERE id = $2',+ [JSON.stringify(encrypted), connectionId]+ )+ }++ /** Decrypt a jsonb `EncryptedJSONField` column into a plain object (string+ * leaves). Tolerant of a text column (JSON string) too. */+ private decryptJsonObject(value: unknown): Record<string, unknown> {+ let parsed = value+ if (typeof parsed === 'string') {+ try {+ parsed = JSON.parse(parsed)+ } catch {+ return {}+ }+ }+ const decrypted = this.encryption.decryptJsonFieldValue(parsed)+ if (decrypted === null || typeof decrypted !== 'object' || Array.isArray(decrypted)) {+ return {}+ }+ return decrypted as Record<string, unknown>+ }++ /** Mirror of `resolve_installation_oauth_context`: shared-creds template uses+ * the template's metadata+client; else the installation's metadata+client. */+ private resolveOauthContext(row: InstallationRow, sensitive: Record<string, unknown>): OauthContext {+ if (row.template_id) {+ const creds = this.decryptJsonObject(row.template_oauth_credentials)+ const sharedClientId = asNonEmptyString(creds.client_id)+ if (sharedClientId) {+ const meta = row.template_oauth_metadata ?? {}+ const tokenEndpoint = asNonEmptyString(meta.token_endpoint)+ if (!tokenEndpoint) {+ throw new Error('mcp_connection_refresh_failed: template missing token_endpoint')+ }+ const clientSecret = asNonEmptyString(creds.client_secret)+ return {+ tokenEndpoint,+ clientId: sharedClientId,+ clientSecret,+ authMethod: credentialAuthMethod(creds.token_endpoint_auth_method, clientSecret),+ resource: asNonEmptyString(meta.resource),+ }+ }+ }+ const meta = row.oauth_metadata ?? {}+ const tokenEndpoint = asNonEmptyString(meta.token_endpoint)+ const clientId = asNonEmptyString(sensitive.dcr_client_id)+ if (!tokenEndpoint || !clientId) {+ throw new Error('mcp_connection_refresh_failed: missing oauth metadata or client_id')+ }+ const clientSecret = asNonEmptyString(sensitive.dcr_client_secret)+ return {+ tokenEndpoint,+ clientId,+ clientSecret,+ authMethod: credentialAuthMethod(sensitive.dcr_token_endpoint_auth_method, clientSecret),+ resource: asNonEmptyString(meta.resource),+ }+ }++ private async tokenRefreshRequest(ctx: OauthContext, refreshToken: string): Promise<TokenResponse> {+ const body = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken })+ if (ctx.resource) {+ body.set('resource', ctx.resource)+ }+ const headers: Record<string, string> = {+ 'Content-Type': 'application/x-www-form-urlencoded',+ Accept: 'application/json',+ }+ // Mirror Django's `_token_request_auth`: basic → credentials in the+ // Authorization header (client_id NOT in the body); post → both in the+ // body; none → just client_id. The method comes from the stored+ // `(dcr_)token_endpoint_auth_method` (Django defaults a confidential+ // client to basic — sending creds in the body 401s those servers).+ if (ctx.authMethod === 'client_secret_basic') {+ if (!ctx.clientSecret) {+ throw new Error('mcp_connection_refresh_failed: missing client_secret for client_secret_basic')+ }+ headers.Authorization = `Basic ${Buffer.from(`${ctx.clientId}:${ctx.clientSecret}`).toString('base64')}`+ } else {+ body.set('client_id', ctx.clientId)+ if (ctx.authMethod === 'client_secret_post') {+ if (!ctx.clientSecret) {+ throw new Error('mcp_connection_refresh_failed: missing client_secret for client_secret_post')+ }+ body.set('client_secret', ctx.clientSecret)+ }+ }+ const res = await this.http.fetch(ctx.tokenEndpoint, {+ method: 'POST',+ headers,+ body: body.toString(),+ // Don't follow redirects (Django uses allow_redirects=False); a token+ // endpoint that 3xxes is misconfigured — treated as permanent below.+ redirect: 'manual',+ })+ if (res.status >= 300 && res.status < 400) {+ throw new TokenRefreshHttpError(res.status, 'token endpoint redirected')+ }+ if (!res.ok) {+ const text = await res.text().catch(() => '')+ throw new TokenRefreshHttpError(res.status, text)+ }+ const json = (await res.json()) as TokenResponse+ if (!json.access_token) {+ throw new Error('token_no_access_token')+ }+ return json+ }+}++/**+ * Non-2xx from the upstream OAuth token endpoint. `permanent` marks a 4xx+ * (except 429) — the refresh token/client is rejected and retrying won't help,+ * so the caller flags `needs_reauth`. 5xx / 429 are transient (retry next+ * session).+ */+class TokenRefreshHttpError extends Error {+ constructor(+ readonly status: number,+ bodyText: string+ ) {+ super(`token_http_${status}: ${bodyText.slice(0, 200)}`)+ this.name = 'TokenRefreshHttpError'+ }++ get permanent(): boolean {+ // 3xx (token endpoint redirected) is a permanent misconfig; 4xx except+ // 429 is a hard credential rejection. Both → needs_reauth. 5xx / 429 are+ // transient and retried next session.+ return this.status >= 300 && this.status < 500 && this.status !== 429+ }+}++const SUPPORTED_AUTH_METHODS: ReadonlySet<string> = new Set(['none', 'client_secret_post', 'client_secret_basic'])++/** Mirror of Django `_credential_auth_method`: use the stored method when it's a+ * supported value, else default to `client_secret_basic` for a confidential+ * client (secret present) and `none` otherwise. */+function credentialAuthMethod(stored: unknown, clientSecret: string | undefined): TokenEndpointAuthMethod {+ if (typeof stored === 'string' && SUPPORTED_AUTH_METHODS.has(stored)) {+ return stored as TokenEndpointAuthMethod+ }+ return clientSecret ? 'client_secret_basic' : 'none'+}++function asNonEmptyString(v: unknown): string | undefined {+ return typeof v === 'string' && v.length > 0 ? v : undefined+}++/** Django encrypts bools as `str(value)` → "True"/"False", so a decrypted leaf+ * is the string "True". Match that (or a real bool) — not a "False" string. */+function isPyTrue(v: unknown): boolean {+ return v === true || v === 'True'+}++/** Mirror of `is_token_expiring`: refresh past 50% of lifetime. Leaves are+ * strings after decrypt, so coerce. */+function isTokenExpiring(sensitive: Record<string, unknown>): boolean {+ const retrievedAt = Number(sensitive.token_retrieved_at ?? 0)+ const expiresIn = Number(sensitive.expires_in ?? 0)+ if (!retrievedAt || !expiresIn || Number.isNaN(retrievedAt) || Number.isNaN(expiresIn)) {+ return false+ }+ return Date.now() / 1000 > retrievedAt + expiresIn / 2+}diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.test.ts b/products/agent_platform/services/agent-shared/src/spec/spec.test.tsindex 6c92a521caa9..f406eb78a44c 100644--- a/products/agent_platform/services/agent-shared/src/spec/spec.test.ts+++ b/products/agent_platform/services/agent-shared/src/spec/spec.test.ts@@ -29,7 +29,14 @@ describe('AgentSpecSchema', () => {{ kind: 'native', id: '@posthog/query' },{ kind: 'custom', id: 'fetch-acme', path: 'tools/fetch-acme/' },],- mcps: [{ id: 'posthog', url: 'https://app.posthog.com/api/mcp' }],+ mcps: [+ {+ kind: 'agent',+ id: 'posthog',+ url: 'https://app.posthog.com/api/mcp',+ default_tool_approval: 'allow',+ },+ ],skills: [{ id: 'deep-research', path: 'skills/deep-research/SKILL.md' }],secrets: ['ACME_KEY'],limits: { max_turns: 10, max_tool_calls: 50, max_wall_seconds: 300 },@@ -436,17 +443,20 @@ describe('AgentSpecSchema', () => {})describe('mcps[] runtime refs', () => {- it('parses an external MCP with bare-string tools[] (passthrough, no gating)', () => {- // Bare strings in tools[] are the post-PR-7 equivalent of the- // old allowlist[]: gates inclusion, no approval policy.+ it('parses tools[] level overrides on a connection default', () => {const spec = AgentSpecSchema.parse({model: 'x',mcps: [{+ kind: 'agent',id: 'linear',url: 'https://mcp.linear.app/sse',secrets: ['LINEAR_TOKEN'],- tools: ['create-issue', 'list-issues'],+ default_tool_approval: 'approve',+ tools: [+ { name: 'create-issue', level: 'allow' },+ { name: 'delete-issue', level: 'deny' },+ ],},],})@@ -454,71 +464,52 @@ describe('AgentSpecSchema', () => {expect(m.id).toBe('linear')expect(m.url).toBe('https://mcp.linear.app/sse')expect(m.secrets).toEqual(['LINEAR_TOKEN'])- expect(m.tools).toEqual(['create-issue', 'list-issues'])+ expect(m.default_tool_approval).toBe('approve')+ expect(m.tools).toEqual([+ { name: 'create-issue', level: 'allow' },+ { name: 'delete-issue', level: 'deny' },+ ])})- it('parses object-form tools[] entries with approval gating', () => {+ it('parses a per-tool approval_policy override (who approves + ttl)', () => {const spec = AgentSpecSchema.parse({model: 'x',mcps: [{+ kind: 'agent',id: 'posthog',url: 'https://app.posthog.com/api/mcp',+ default_tool_approval: 'allow',tools: [- 'agent-applications-list',{name: 'agent-applications-revisions-promote-create',- requires_approval: true,- approval_policy: { type: 'principal', ttl_ms: 900_000 },+ level: 'approve',+ // Route this one tool's approval to the agent's owning team.+ approval_policy: { type: 'agent', ttl_ms: 900_000 },},],},],})- const m = spec.mcps[0]- expect(m.tools?.[0]).toBe('agent-applications-list')- const gated = m.tools?.[1]- if (typeof gated === 'string' || gated === undefined) {- throw new Error('expected object-form tool entry')+ const entry = spec.mcps[0].tools?.[0]+ if (entry === undefined) {+ throw new Error('expected a tool entry')}- expect(gated.name).toBe('agent-applications-revisions-promote-create')- expect(gated.requires_approval).toBe(true)- expect(gated.approval_policy.type).toBe('principal')- expect(gated.approval_policy.ttl_ms).toBe(900_000)+ expect(entry.level).toBe('approve')+ expect(entry.approval_policy?.type).toBe('agent')+ expect(entry.approval_policy?.ttl_ms).toBe(900_000)// Unspecified fields fall through to the approval-policy defaults.- expect(gated.approval_policy.allow_edit).toBe(false)+ expect(entry.approval_policy?.allow_edit).toBe(false)})- it('object-form tools[] entries default requires_approval to false', () => {- // Object form without explicit gating means "include this tool- // with no approval gate" — same effective behaviour as the- // bare-string form, just expressed as an object. Useful when an- // author wants the object slot reserved for a future config knob- // (e.g. description override) without flipping the gate on.+ it('defaults secrets to [] and tools to undefined when omitted on external', () => {const spec = AgentSpecSchema.parse({model: 'x',mcps: [- {- id: 'linear',- url: 'https://mcp.linear.app/sse',- tools: [{ name: 'create-issue' }],- },+ { kind: 'agent', id: 'linear', url: 'https://mcp.linear.app/sse', default_tool_approval: 'allow' },],})const m = spec.mcps[0]- const entry = m.tools?.[0]- if (typeof entry === 'string' || entry === undefined) {- throw new Error('expected object-form tool entry')- }- expect(entry.requires_approval).toBe(false)- })-- it('defaults secrets to [] and tools to undefined when omitted on external', () => {- const spec = AgentSpecSchema.parse({- model: 'x',- mcps: [{ id: 'linear', url: 'https://mcp.linear.app/sse' }],- })- const m = spec.mcps[0]expect(m.secrets).toEqual([])expect(m.tools).toBeUndefined()expect(m.headers).toBeUndefined()@@ -533,9 +524,11 @@ describe('AgentSpecSchema', () => {model: 'x',mcps: [{+ kind: 'agent',id: 'github',url: 'https://api.githubcopilot.com/mcp',secrets: ['GITHUB_TOKEN'],+ default_tool_approval: 'allow',headers: {Authorization: 'Bearer ${GITHUB_TOKEN}','X-GitHub-Api-Version': '2022-11-28',@@ -550,36 +543,30 @@ describe('AgentSpecSchema', () => {})})+ const validBase = {+ kind: 'agent',+ id: 'linear',+ url: 'https://mcp.linear.app/sse',+ default_tool_approval: 'allow',+ }it.each([- { label: 'missing id', mcp: { url: 'https://mcp.linear.app/sse' } },- { label: 'empty id', mcp: { id: '', url: 'https://mcp.linear.app/sse' } },- { label: 'non-URL endpoint', mcp: { id: 'linear', url: 'not-a-url' } },- {- label: 'tools entry with empty name string',- mcp: { id: 'linear', url: 'https://mcp.linear.app/sse', tools: [''] },- },- {- label: 'tools object with empty name',- mcp: {- id: 'linear',- url: 'https://mcp.linear.app/sse',- tools: [{ name: '' }],- },- },+ { label: 'missing id', mcp: { ...validBase, id: undefined } },+ { label: 'empty id', mcp: { ...validBase, id: '' } },+ { label: 'non-URL endpoint', mcp: { ...validBase, url: 'not-a-url' } },+ { label: 'missing kind', mcp: { ...validBase, kind: undefined } },+ { label: 'bad kind', mcp: { ...validBase, kind: 'shared' } },+ { label: 'missing default_tool_approval', mcp: { ...validBase, default_tool_approval: undefined } },+ { label: 'bad default_tool_approval', mcp: { ...validBase, default_tool_approval: 'ask' } },+ { label: 'a tool entry with an empty name', mcp: { ...validBase, tools: [{ name: '', level: 'allow' }] } },+ { label: 'a tool entry with a bad level', mcp: { ...validBase, tools: [{ name: 'x', level: 'maybe' }] } },{- label: 'duplicate bare-string entries',+ label: 'duplicate tool names',mcp: {- id: 'linear',- url: 'https://mcp.linear.app/sse',- tools: ['create-issue', 'create-issue'],- },- },- {- label: 'a bare-string entry duplicating an object entry name',- mcp: {- id: 'linear',- url: 'https://mcp.linear.app/sse',- tools: ['create-issue', { name: 'create-issue', requires_approval: true }],+ ...validBase,+ tools: [+ { name: 'create-issue', level: 'allow' },+ { name: 'create-issue', level: 'deny' },+ ],},},])('rejects an external entry with $label', ({ mcp }) => {@@ -597,8 +584,10 @@ describe('AgentSpecSchema', () => {model: 'x',mcps: [{+ kind: 'agent',id: 'linear',url: 'https://mcp.linear.app/sse',+ default_tool_approval: 'allow',allowlist: ['create-issue'],},],@@ -609,6 +598,158 @@ describe('AgentSpecSchema', () => {})})+ describe('mcps[] per-agent tool-permission model', () => {+ it('parses a connection-backed MCP (shared credential via mcp_store install id)', () => {+ const spec = AgentSpecSchema.parse({+ mcps: [+ {+ kind: 'agent',+ id: 'incident',+ url: 'https://mcp.incident.io/mcp',+ connection: '019e7fb7-f4c0-75e2-9055-7c29a5cbb999',+ default_tool_approval: 'approve',+ tools: [{ name: 'create-incident', level: 'approve' }],+ },+ ],+ })+ expect(spec.mcps[0].connection).toBe('019e7fb7-f4c0-75e2-9055-7c29a5cbb999')+ })++ it('parses a connection-wide default level, per-tool level overrides, and an entry approval_policy', () => {+ const spec = AgentSpecSchema.parse({+ mcps: [+ {+ kind: 'agent',+ id: 'incident',+ url: 'https://mcp.incident.io/mcp',+ connection: '019e7fb7-f4c0-75e2-9055-7c29a5cbb999',+ default_tool_approval: 'approve',+ approval_policy: { type: 'agent', ttl_ms: 900_000 },+ tools: [+ { name: 'list-incidents', level: 'allow' },+ { name: 'delete-incident', level: 'deny' },+ ],+ },+ ],+ })+ const m = spec.mcps[0]+ expect(m.default_tool_approval).toBe('approve')+ expect(m.approval_policy?.type).toBe('agent')+ expect(m.approval_policy?.ttl_ms).toBe(900_000)+ const allow = m.tools?.[0]+ const deny = m.tools?.[1]+ if (typeof allow === 'string' || allow === undefined || typeof deny === 'string' || deny === undefined) {+ throw new Error('expected object-form tool entries')+ }+ expect(allow.level).toBe('allow')+ expect(deny.level).toBe('deny')+ })++ it.each([+ {+ label: 'a bad connection-wide default_tool_approval',+ mcp: {+ kind: 'agent',+ id: 'incident',+ url: 'https://mcp.incident.io/mcp',+ default_tool_approval: 'ask',+ },+ },+ {+ label: 'a bad per-tool level override',+ mcp: {+ kind: 'agent',+ id: 'incident',+ url: 'https://mcp.incident.io/mcp',+ default_tool_approval: 'allow',+ tools: [{ name: 'x', level: 'maybe' }],+ },+ },+ ])('rejects $label', ({ mcp }) => {+ expect(() => AgentSpecSchema.parse({ mcps: [mcp] })).toThrow()+ })+ })++ describe('mcps[].id (runtime tool-name prefix)', () => {+ it.each(['github__main', 'a__b', 'prod__incident'])(+ 'rejects an id containing the `__` prefix separator: %s',+ (id) => {+ // The runtime exposes `<id>__<remoteName>` and the per-tool+ // approval lookup splits on the FIRST `__`. An id that itself+ // contains `__` misroutes the split, so the approval gate+ // silently never fires — even with default_tool_approval set.+ expect(() =>+ AgentSpecSchema.parse({+ mcps: [{ kind: 'agent', id, url: 'https://m.dev/mcp', default_tool_approval: 'approve' }],+ })+ ).toThrow()+ }+ )++ it('accepts a normal id (single underscores and hyphens are fine)', () => {+ expect(() =>+ AgentSpecSchema.parse({+ mcps: [+ {+ kind: 'agent',+ id: 'github-main_v2',+ url: 'https://m.dev/mcp',+ default_tool_approval: 'allow',+ },+ ],+ })+ ).not.toThrow()+ })+ })++ describe('mcps[].kind (required credential model)', () => {+ it('parses a principal-kind MCP wired to a per-asker identity provider', () => {+ const spec = AgentSpecSchema.parse({+ mcps: [+ {+ kind: 'principal',+ id: 'posthog',+ url: 'https://app.posthog.com/api/mcp',+ default_tool_approval: 'allow',+ auth: { provider: 'posthog' },+ },+ ],+ })+ expect(spec.mcps[0].kind).toBe('principal')+ expect(spec.mcps[0].auth?.provider).toBe('posthog')+ })++ it.each([+ {+ label: 'a principal kind without auth.provider',+ mcp: { kind: 'principal', id: 'x', url: 'https://m.dev/mcp', default_tool_approval: 'allow' },+ },+ {+ label: 'a principal kind that also pins a connection',+ mcp: {+ kind: 'principal',+ id: 'x',+ url: 'https://m.dev/mcp',+ default_tool_approval: 'allow',+ connection: '019e7fb7-f4c0-75e2-9055-7c29a5cbb999',+ auth: { provider: 'posthog' },+ },+ },+ {+ label: 'an agent kind that sets auth.provider',+ mcp: {+ kind: 'agent',+ id: 'x',+ url: 'https://m.dev/mcp',+ default_tool_approval: 'allow',+ auth: { provider: 'posthog' },+ },+ },+ ])('rejects $label', ({ mcp }) => {+ expect(() => AgentSpecSchema.parse({ mcps: [mcp] })).toThrow()+ })+ })+describe('resume config (per-agent TTL on completed sessions)', () => {it('defaults to undefined when not present (preserves today behaviour)', () => {const spec = AgentSpecSchema.parse({ model: 'x' })diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.tsindex 8688906a8d4c..3cf576234e79 100644--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts@@ -392,12 +392,30 @@ export const ApprovalPolicySchema = z.preprocess(}))-const DEFAULT_APPROVAL_POLICY = {+export const DEFAULT_APPROVAL_POLICY = {type: 'principal' as const,allow_edit: false,ttl_ms: 24 * 60 * 60 * 1000,}+/**+ * Per-tool approval level for an MCP connection: the effective level of a remote+ * tool decides what the runner does with it.+ * - `allow` — exposed, runs without approval.+ * - `approve` — exposed, every call parks for approval (the entry's+ * `approval_policy` decides who/ttl).+ * - `deny` — NOT exposed to the model at all.+ *+ * Used both as the connection-wide default (`McpRef.default_tool_approval`) and+ * as a per-tool override (`McpToolEntry.level`). Effective level for a tool =+ * its override `level` ?? the connection default. A connection with+ * `default_tool_approval: 'deny'` + per-tool `allow` overrides is a strict+ * allowlist. See `services/agent-runner/src/loop/build-agent-tools.ts`+ * (exposure) and `mcp-tool-lookup.ts` (approval).+ */+export const ToolApprovalLevelSchema = z.enum(['allow', 'approve', 'deny'])+export type ToolApprovalLevel = z.infer<typeof ToolApprovalLevelSchema>+export const ToolRefSchema = z.discriminatedUnion('kind', [z.object({kind: z.literal('native'),@@ -426,22 +444,27 @@ export const ToolRefSchema = z.discriminatedUnion('kind', [// every non-`client` tool carries `requires_approval`./*** **Client-fulfilled tool.** The agent author declares the tool fully- * inline (id + description + args_schema); the connecting client- * (browser dock, IDE MCP host, etc.) advertises which ids it can- * fulfill at session start via `client.handles[]`. The runner- * reconciles:+ * inline (id + description + args_schema); the connecting client (browser+ * dock, IDE MCP host, etc.) declares which ids it can execute this session+ * via `supported_client_tools` in the /run body (stashed on the session's+ * `trigger_metadata`). The runner gates EXPOSURE on it:*- * - In spec AND in `client.handles[]` → exposed to the model.- * - In spec, NOT handled, `required: false` (default) → hidden- * from the model surface; the agent.md should be written to- * degrade gracefully (text-only narration).- * - In spec, NOT handled, `required: true` → session open fails- * with `client_tool_unsupported`.+ * - id in `supported_client_tools` → exposed to the model.+ * - NOT declared, `required: false` (default) → hidden from the model+ * surface; write agent.md to degrade gracefully (text-only narration).+ * - NOT declared, `required: true` → session open fails with+ * `client_tool_unsupported`.+ *+ * Non-chat surfaces (Slack, cron, webhook, MCP) declare nothing, so client+ * tools — including interactive punch-outs like `connect_mcp` /+ * `set_secret` — are simply not exposed there; the model never sees a tool+ * it can't get a result for.** Dispatch path: when the model calls the tool, the runner emits a* `client_tool_call` session event carrying the args + a call_id;* the client executes locally and POSTs the result to- * `/sessions/<id>/client_tool_result`.+ * `/sessions/<id>/client_tool_result`. Interactive tools park the session+ * until that result arrives.*/z.object({kind: z.literal('client'),@@ -485,24 +508,31 @@ export const ToolRefSchema = z.discriminatedUnion('kind', [])/**- * Per-tool selection + approval-gating entry for `external` MCP refs. The- * bare-string form is the inclusion-only case (was `allowlist[]` pre-PR 7);- * the object form adds approval gating using the same primitives as- * `ToolRefSchema` (`requires_approval` + `approval_policy`). The dispatcher- * looks the entry up by name when wrapping the model-visible+ * Per-tool entry for an MCP ref — overrides the connection defaults for one+ * tool. `level` sets allow / approve / deny (vs `default_tool_approval`);+ * `approval_policy` optionally pins WHO approves + ttl for an `approve` tool+ * (vs the connection's `approval_policy`). A tool with no entry takes the+ * connection defaults.+ *+ * Per-tool `approval_policy` is what lets a designer route most approvals to the+ * asker (`type: 'principal'`) while sending a specific sensitive tool to the+ * agent's owning team (`type: 'agent'`) — and it's mandatory for tools an agent+ * can call with no principal present (cron/webhook), where a principal approval+ * is undeliverable.+ *+ * The runner looks the entry up by name when building/gating the model-visible* `<prefix>__<remoteName>` tool — see- * `services/agent-runner/src/loop/mcp-tool-lookup.ts` and the approval-wrap- * fallback in `driver.ts`.+ * `services/agent-runner/src/loop/mcp-tool-lookup.ts` + `build-agent-tools.ts`.*/-export const McpToolEntrySchema = z.union([- z.string().min(1),- z.object({- /** Raw remote tool name (pre-prefix). Must match an entry from `client.listTools()`. */- name: z.string().min(1),- requires_approval: z.boolean().default(false),- approval_policy: ApprovalPolicySchema.default(DEFAULT_APPROVAL_POLICY),- }),-])+export const McpToolEntrySchema = z.object({+ /** Raw remote tool name (pre-prefix). Must match an entry from `client.listTools()`. */+ name: z.string().min(1),+ /** Override of the connection's `default_tool_approval` for this tool. */+ level: ToolApprovalLevelSchema,+ /** Override of the connection's `approval_policy` for this tool (who approves+ * + ttl). Only consulted when the effective level is `approve`. */+ approval_policy: ApprovalPolicySchema.optional(),+})/*** Runtime MCP servers an agent connects to at session start. The runner opens@@ -515,86 +545,155 @@ export const McpToolEntrySchema = z.union([* per-principal OAuth identity, stamped as the asker's bearer (gates into* auth_required if unlinked). `secrets[]` + `headers` is the simpler* bring-your-own-token case, resolved through the same encrypted-env path the- * agent's main `spec.secrets` uses. `id` is the tool-name prefix. `tools[]`- * selects + gates: bare string = inclusion only; object form adds- * `requires_approval` + `approval_policy`.+ * agent's main `spec.secrets` uses. `id` is the tool-name prefix.+ * `default_tool_approval` sets the connection-wide level; `tools[]` overrides it+ * per tool (`{ name, level }`).** The `kind: 'agent'` variant (agent-to-agent MCP composability) was removed* in favour of a single flat shape — `agent-as-mcp-server.md` will re-add it* when a concrete consumer lands.*/-export const McpRefSchema = z.object({- /**- * Stable id within the spec. Tool-name prefix at runtime —- * `<id>__<toolName>` is what the model sees so it can tell which MCP- * a tool came from. Must be unique across `spec.mcps[]`.- */- id: z.string().min(1),- url: z.string().url(),- auth: z- .object({- /** Per-principal identity provider (id from `spec.identity_providers[]`):- * stamps the linked user's bearer, gates into auth_required if unlinked. */- provider: z.string().optional(),- })- .optional(),- /**- * Per-MCP secret names. Resolved at session start through the same- * encrypted-env path as the agent's main `spec.secrets`. The runner- * substitutes `${name}` placeholders in the URL + auth headers before- * opening the client; the plaintext never leaves the runner process.- */- secrets: z.array(z.string()).default([]),- /**- * Author-supplied request headers stamped on every outgoing MCP request.- * Values may reference `${NAME}` from `secrets[]`; the runner substitutes- * the plaintext value before opening the MCP client, so the secret never- * leaves the runner process. Same substitution shape as- * `@posthog/http-request`'s `headers` — the parallel is intentional so- * authors can use the same mental model for "bring my own bearer token"- * against either a typed MCP catalog or a raw HTTP API.- *- * Use this for the bring-your-own-token case (paste a PAT once, reference- * it as `${TOKEN}` in `Authorization: 'Bearer ${TOKEN}'`). For OAuth, use- * `auth.provider` instead; provider-stamped headers compose with- * author-supplied headers — explicit author entries win on duplicate- * keys, matching `http-request`'s "caller-set values are not silently- * overwritten" rule.- */- headers: z.record(z.string(), z.string()).optional(),- /**- * Per-tool selection AND approval gating. Bare string is a passthrough- * (gates inclusion, no approval); object form carries- * `requires_approval` + `approval_policy`. Omitted / empty = expose- * every tool the server lists. Replaces the earlier `allowlist[]`- * field (PR 7 hard-break — no production specs used it).- *- * Names must be unique within the array. A duplicate would be a- * silent first-match-wins footgun — e.g. an author who appends a- * gated copy of an already-listed bare-string entry would see the- * gated version ignored. Better to reject at parse time.- */- tools: z- .array(McpToolEntrySchema)- .optional()- .refine(- (entries) => {- if (!entries) {- return true- }- const seen = new Set<string>()- for (const e of entries) {- const name = typeof e === 'string' ? e : e.name- if (seen.has(name)) {- return false+export const McpRefSchema = z+ .object({+ /**+ * Stable id within the spec. Tool-name prefix at runtime —+ * `<id>__<toolName>` is what the model sees so it can tell which MCP+ * a tool came from. Must be unique across `spec.mcps[]`.+ */+ id: z+ .string()+ .min(1)+ // The runtime tool-name prefix is `<id>__<remoteName>` and the+ // approval lookup splits on the FIRST `__` (mcp-tool-lookup.ts). An+ // id that itself contains `__` misroutes the split → the per-tool+ // approval gate silently never fires. Forbid the separator.+ .refine((id) => !id.includes('__'), {+ message: "mcps[].id must not contain '__' (it is the tool-name prefix separator)",+ }),+ url: z.string().url(),+ /**+ * Credential model for this server — REQUIRED, the explicit discriminator the+ * runtime and the authoring UI branch on (rather than inferring it from which+ * of `connection`/`auth`/`secrets` happens to be set):+ * - `'agent'` — ONE shared credential every asker reuses, supplied+ * either by a `connection` (mcp_store installation) or a bring-your-own+ * static token in `secrets` + `headers`. No `auth.provider`.+ * - `'principal'` — each asker acts as themselves via `auth.provider`+ * (a per-asker linked identity). No `connection`.+ * The `superRefine` below pins the credential fields to the kind so intent+ * and wiring can't drift.+ */+ kind: z.enum(['agent', 'principal']),+ /**+ * Native MCP connection: the id of an `mcp_store` `MCPServerInstallation` an+ * owner connected once (OAuth incl. DCR, or api-key). When set, the runner+ * loads the bearer from that row (refreshing on expiry) and ignores+ * `auth`/`secrets`/`headers` — ONE shared credential for every asker. `url`+ * stays required (UI-filled); the installation row is the source of truth.+ * Agent-kind only.+ */+ connection: z.string().min(1).optional(),+ /**+ * Connection-wide default approval level (per-agent tool-permission model) —+ * REQUIRED. Every remote tool's effective level = its `tools[].level`+ * override ?? this default; the tool is exposed unless its effective level+ * is `deny`, and gated when `approve`. A curated allowlist is+ * `'deny'` + per-tool `level: 'allow'`. The agent-config UI writes+ * `'approve'` here when an MCP is first attached.+ */+ default_tool_approval: ToolApprovalLevelSchema,+ /**+ * Approval policy (who approves + ttl) for any tool whose effective level is+ * `approve`. Defaults to the principal/24h policy.+ */+ approval_policy: ApprovalPolicySchema.optional(),+ auth: z+ .object({+ /** Per-principal identity provider (id from `spec.identity_providers[]`):+ * stamps the linked user's bearer, gates into auth_required if unlinked. */+ provider: z.string().optional(),+ })+ .optional(),+ /**+ * Per-MCP secret names. Resolved at session start through the same+ * encrypted-env path as the agent's main `spec.secrets`. The runner+ * substitutes `${name}` placeholders in the URL + auth headers before+ * opening the client; the plaintext never leaves the runner process.+ */+ secrets: z.array(z.string()).default([]),+ /**+ * Author-supplied request headers stamped on every outgoing MCP request.+ * Values may reference `${NAME}` from `secrets[]`; the runner substitutes+ * the plaintext value before opening the MCP client, so the secret never+ * leaves the runner process. Same substitution shape as+ * `@posthog/http-request`'s `headers` — the parallel is intentional so+ * authors can use the same mental model for "bring my own bearer token"+ * against either a typed MCP catalog or a raw HTTP API.+ *+ * Use this for the bring-your-own-token case (paste a PAT once, reference+ * it as `${TOKEN}` in `Authorization: 'Bearer ${TOKEN}'`). For OAuth, use+ * `auth.provider` instead; provider-stamped headers compose with+ * author-supplied headers — explicit author entries win on duplicate+ * keys, matching `http-request`'s "caller-set values are not silently+ * overwritten" rule.+ */+ headers: z.record(z.string(), z.string()).optional(),+ /**+ * Per-tool overrides of `default_tool_approval`. Each entry's `level` sets+ * that tool to allow/approve/deny; a tool with no entry takes the default.+ * Omitted/empty = every tool takes the connection default.+ *+ * Names must be unique within the array — a duplicate would be a silent+ * first-match-wins footgun, so reject it at parse time.+ */+ tools: z+ .array(McpToolEntrySchema)+ .optional()+ .refine(+ (entries) => {+ if (!entries) {+ return true}- seen.add(name)- }- return true- },- { message: 'mcps[].tools[] entries must have unique names' }- ),-})+ const seen = new Set<string>()+ for (const e of entries) {+ if (seen.has(e.name)) {+ return false+ }+ seen.add(e.name)+ }+ return true+ },+ { message: 'mcps[].tools[] entries must have unique names' }+ ),+ })+ .superRefine((ref, ctx) => {+ // Pin the credential fields to the declared kind so the runtime resolution+ // (connection → shared bearer; auth.provider → per-asker identity) and the+ // authoring UI can't disagree with the stated intent.+ if (ref.kind === 'principal') {+ if (!ref.auth?.provider) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['auth', 'provider'],+ message: "mcps[].kind 'principal' requires auth.provider (a per-asker linked identity)",+ })+ }+ if (ref.connection) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['connection'],+ message:+ "mcps[].kind 'principal' must not set connection (that is an agent-level shared credential)",+ })+ }+ } else if (ref.auth?.provider) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['auth', 'provider'],+ message: "mcps[].kind 'agent' must not set auth.provider (use a connection or secrets + headers)",+ })+ }+ })export const SkillRefSchema = z.object({id: z.string(),diff --git a/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.ts b/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.tsindex 1f0bb0e23b2b..dca42cb0dfba 100644--- a/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.ts+++ b/products/agent_platform/services/agent-shared/src/spec/system-prompt.test.ts@@ -172,6 +172,26 @@ describe('buildSystemPrompt', () => {expect(prompt).toMatch(/do NOT paste raw error messages/)})+ it('renders a dead shared connection under "Disconnected integrations" — admin reconnect, not a retry', async () => {+ await bundle.write('rev1', 'agent.md', 'x')+ const spec = AgentSpecSchema.parse({ model: 'test/x' })+ const prompt = await buildSystemPrompt(makeRev(spec), bundle, {+ unavailableMcps: [{ id: 'incident', category: 'connection_dead' }],+ })+ expect(prompt).toContain('Disconnected integrations')+ expect(prompt).toContain('`incident`')+ // Persistent + admin-owned: the asker can't fix a shared credential, so+ // the model must NOT imply a retry or a self-service reconnect.+ expect(prompt).toMatch(/administrator|admin|owner/i)+ expect(prompt).toMatch(/reconnect/i)+ expect(prompt).not.toMatch(/temporarily unavailable/i)+ // A dead connection is neither the asker's to connect nor a transient outage.+ expect(prompt).not.toContain('Connect required')+ expect(prompt).not.toContain('Unavailable capabilities')+ // Still never leak raw transport detail.+ expect(prompt).not.toMatch(/Bearer|http/)+ })+it('renders a link-required MCP under "Connect required" with the URL, not as "unavailable"', async () => {await bundle.write('rev1', 'agent.md', 'x')const spec = AgentSpecSchema.parse({ model: 'test/x' })diff --git a/products/agent_platform/services/agent-shared/src/spec/system-prompt.ts b/products/agent_platform/services/agent-shared/src/spec/system-prompt.tsindex cb87de603006..0686f0f6a255 100644--- a/products/agent_platform/services/agent-shared/src/spec/system-prompt.ts+++ b/products/agent_platform/services/agent-shared/src/spec/system-prompt.ts@@ -25,7 +25,7 @@ import { AgentRevision } from './spec'/** Coarse failure category — same shape the runner uses; redeclared here* to avoid the runner→shared import cycle. Keep in sync with* `agent-runner/src/loop/mcp-clients.ts#McpFailureCategory`. */-export type UnavailableMcpCategory = 'auth' | 'network' | 'not_found' | 'unknown'+export type UnavailableMcpCategory = 'connection_dead' | 'auth' | 'network' | 'not_found' | 'unknown'export interface UnavailableMcp {/** Spec ref id — same string the model sees as the tool-name prefix. */@@ -58,6 +58,9 @@ export interface BuildSystemPromptOpts {}const CATEGORY_HINTS: Record<UnavailableMcpCategory, string> = {+ // `connection_dead` gets its own section (not this hint), but the record+ // must stay total — fall back to the same phrasing if it ever lands here.+ connection_dead: 'disconnected — needs an admin to reconnect',auth: 'authentication issue',network: 'network or upstream issue',not_found: 'endpoint not found',@@ -93,11 +96,16 @@ export async function buildSystemPrompt(}const unavailable = opts.unavailableMcps ?? []- // A link-required failure is the user's to fix (connect their account); a- // broken one is the owner's. Split so the model relays the link for the- // former instead of dead-ending both as "temporarily unavailable".+ // Three distinct fixes, three sections:+ // - linkable — the ASKER connects their own account (authorizeUrl).+ // - dead — a SHARED connection the asker can't touch; only the+ // agent's owner/admin can reconnect it, and it won't+ // self-heal (so: not "retry shortly").+ // - broken — a transient/unknown outage; may recover on its own.const linkable = unavailable.filter((u) => u.authorizeUrl)- const broken = unavailable.filter((u) => !u.authorizeUrl)+ const rest = unavailable.filter((u) => !u.authorizeUrl)+ const dead = rest.filter((u) => u.category === 'connection_dead')+ const broken = rest.filter((u) => u.category !== 'connection_dead')if (linkable.length > 0) {const lines = ['\n\n---\n\n## Connect required', '']lines.push(@@ -109,6 +117,19 @@ export async function buildSystemPrompt(}parts.push(lines.join('\n'))}+ if (dead.length > 0) {+ const lines = ['\n\n---\n\n## Disconnected integrations', '']+ lines.push(+ "These integrations use a shared connection set up by the agent's owner, and that connection is no longer working (the owner needs to reconnect it in PostHog). This will NOT fix itself and the user can't reconnect it themselves — so do not suggest they retry or sign in. If they ask for something one of these powers, tell them the integration is disconnected and that an administrator/the agent owner needs to reconnect it in PostHog, then carry on with the tools you DO have:"+ )+ lines.push('')+ for (const u of dead) {+ lines.push(`- \`${u.id}\``)+ }+ lines.push('')+ lines.push('Do NOT paste raw error messages, transport URLs, or stack traces into the conversation.')+ parts.push(lines.join('\n'))+ }if (broken.length > 0) {const lines = ['\n\n---\n\n## Unavailable capabilities', '']lines.push(diff --git a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.test.ts b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.test.tsindex 45a24ba4d702..078cac55aa5e 100644--- a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.test.ts+++ b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'-import { deriveSkillDescription } from './typed-bundle'+import { AgentSpecSchema } from '../spec/spec'+import { deriveSkillDescription, TypedSpecSchema } from './typed-bundle'describe('deriveSkillDescription', () => {it.each([@@ -30,3 +31,28 @@ describe('deriveSkillDescription', () => {expect(deriveSkillDescription(`---\ndescription: ${long}\n---\n`)).toHaveLength(280)})})++describe('TypedSpecSchema ↔ AgentSpec key parity', () => {+ // The author slice must carry EXACTLY the canonical top-level fields minus+ // the server-derived `skills`/`tools`. Enforcing exact parity (not just a+ // superset) catches drift in both directions:+ // - a new canonical field with no author passthrough → PUT /spec strict-+ // rejects it with "Unrecognized key" and the runtime never sees a valid+ // spec;+ // - a stray author-only key with no canonical counterpart → dead cruft+ // that freeze silently strips anyway (the `auth` field that used to be+ // here).+ const SERVER_DERIVED = new Set(['skills', 'tools'])++ it('carries exactly the canonical author-facing top-level fields', () => {+ const canonicalAuthorKeys = Object.keys(AgentSpecSchema.shape)+ .filter((k) => !SERVER_DERIVED.has(k))+ .sort()+ const authorKeys = Object.keys(TypedSpecSchema.shape).sort()+ expect(authorKeys).toEqual(canonicalAuthorKeys)+ })++ it('still rejects unknown keys', () => {+ expect(TypedSpecSchema.safeParse({ not_a_real_field: 1 }).success).toBe(false)+ })+})diff --git a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.tsindex 68cdec92c7b6..3c3254c9ce92 100644--- a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts+++ b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts@@ -22,6 +22,7 @@import { z } from 'zod'+import { SecretRefSchema } from '../spec/spec'import { BundleEntry, BundleStore } from './bundle'// ─── Canonical S3 paths ──────────────────────────────────────────────@@ -110,9 +111,12 @@ export const TypedSpecSchema = ztriggers: z.array(z.unknown()).optional(),mcps: z.array(z.unknown()).optional(),identity_providers: z.array(z.unknown()).optional(),- secrets: z.array(z.string()).optional(),+ // The canonical secret shape: a bare key string OR a host-scoped+ // `{ name, allowed_hosts }` object. Reuse `SecretRefSchema` (the single+ // source of truth) rather than re-spelling it — the old string-only+ // array silently rejected host-scoped secrets at bundle PUT.+ secrets: z.array(SecretRefSchema).optional(),limits: z.unknown().optional(),- auth: z.unknown().optional(),reasoning: z.string().optional(),framework_prompt: z.unknown().optional(),resume: z.unknown().optional(),diff --git a/products/agent_platform/services/agent-shared/vitest.config.ts b/products/agent_platform/services/agent-shared/vitest.config.tsindex 21d283e3b7b7..231825acf1bc 100644--- a/products/agent_platform/services/agent-shared/vitest.config.ts+++ b/products/agent_platform/services/agent-shared/vitest.config.ts@@ -9,9 +9,9 @@ export default defineConfig({include: ['src/**/*.test.ts'],testTimeout: 10_000,globals: true,- // Test files share the agent_runtime_queue_test PG. Running them in- // parallel races on `node-pg-migrate`'s schema lock and on the- // public-schema drop in `reset()`. Mirrors agent-tests.+ // Test files share one Postgres (agent_runtime_queue_test). `reset()`+ // truncates the shared `agent_*` tables between cases, so running files+ // in parallel races on that shared state. Mirrors agent-tests.fileParallelism: false,},})diff --git a/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.ts b/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.tsindex f74a6dba16f6..2317523a1e4b 100644--- a/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/example-agent-builder.test.ts@@ -7,7 +7,7 @@* authoring surface. It keeps only its own runtime natives (`@posthog/memory-*`* plus `@posthog/web-search`) and the PostHog Code client/UI tools. Destructive authoring ops* (`promote` / `archive` / `destroy`) are approval-gated on the MCP `tools[]`- * allow-list (`requires_approval` + `approval_policy`), so the platform — not+ * via `level: 'approve'` + `approval_policy`, so the platform — not* just the prompt — holds them. This case pins that wiring net; drift here* means the bundle is broken regardless of platform readiness.*@@ -110,6 +110,7 @@ describe('example: agent-builder bundle', () => {.map((t) => t.id).sort()expect(ids).toEqual([+ 'connect_mcp','focus_file','focus_revision','focus_session',@@ -143,13 +144,9 @@ describe('example: agent-builder bundle', () => {const { spec } = await loadBundle()const parsed = AgentSpecSchema.parse(spec)const entries = parsed.mcps[0].tools ?? []- // Object-form entries on the allow-list carry the approval policy — that's- // how the platform (not just the prompt) holds a destructive authoring op.- const gated = new Map(- entries- .filter((e): e is Exclude<typeof e, string> => typeof e !== 'string' && e.requires_approval === true)- .map((e) => [e.name, e])- )+ // `level: 'approve'` entries carry the approval policy — that's how the+ // platform (not just the prompt) holds a destructive authoring op.+ const gated = new Map(entries.filter((e) => e.level === 'approve').map((e) => [e.name, e]))for (const name of ['agent-applications-revisions-promote-create','agent-applications-revisions-archive-create',diff --git a/products/agent_platform/services/agent-tests/src/cases/example-sre-bot.test.ts b/products/agent_platform/services/agent-tests/src/cases/example-sre-bot.test.tsindex f863f6b29286..781fac3a5752 100644--- a/products/agent_platform/services/agent-tests/src/cases/example-sre-bot.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/example-sre-bot.test.ts@@ -53,7 +53,6 @@ describe('example: sre-slack-bot bundle', () => {resolveSecrets: async () => ({SLACK_BOT_TOKEN: 'xoxb-test-token',SLACK_SIGNING_SECRET: 'test-signing-secret',- INCIDENT_IO_TOKEN: 'inc_test_token',}),authProvider: fakeAuthProvider({ shared: WEBHOOK_SECRET }),})@@ -134,7 +133,6 @@ describe('example: sre-slack-bot bundle', () => {// HttpClient — bare global.fetch wouldn't intercept anymore now that// tools dispatch through `ctx.http.fetch`.const slackCalls: Array<{ url: string; method?: string; auth?: string; body?: unknown }> = []- const incidentCalls: Array<{ url: string; method?: string; auth?: string; body?: unknown }> = []const recorderHttp = {fetch: (input: string | URL, init?: RequestInit): Promise<Response> => {const url = typeof input === 'string' ? input : input.toString()@@ -154,28 +152,6 @@ describe('example: sre-slack-bot bundle', () => {headers: new Map([['content-type', 'application/json']]),} as unknown as Response)}- if (url.includes('api.incident.io/')) {- const headers = (init?.headers ?? {}) as Record<string, string>- incidentCalls.push({- url,- method: init?.method,- auth: headers.Authorization,- body: typeof init?.body === 'string' ? JSON.parse(init.body) : init?.body,- })- // Shape mirrors incident.io's POST .../updates response.- return Promise.resolve({- ok: true,- status: 200,- json: async () => ({- incident_update: { id: 'IU_01', incident_id: '01HXYZ', message: 'triage posted' },- }),- text: async () =>- JSON.stringify({- incident_update: { id: 'IU_01', incident_id: '01HXYZ', message: 'triage posted' },- }),- headers: new Map([['content-type', 'application/json']]),- } as unknown as Response)- }if (url.includes('runbooks.internal')) {return Promise.resolve({ok: true,@@ -200,7 +176,6 @@ describe('example: sre-slack-bot bundle', () => {resolveSecrets: async () => ({SLACK_BOT_TOKEN: 'xoxb-test-token',SLACK_SIGNING_SECRET: 'test-signing-secret',- INCIDENT_IO_TOKEN: 'inc_test_token',}),authProvider: fakeAuthProvider({ shared: WEBHOOK_SECRET }),http: recorderHttp,@@ -226,16 +201,12 @@ describe('example: sre-slack-bot bundle', () => {where: { alert_signature: 'ingestion-500s' },limit: 5,}),- // Phase 2b: load the incident.io playbook then check for an- // active incident covering this signature. Proves the- // ${INCIDENT_IO_TOKEN} substitution wires up the same way- // ${SLACK_BOT_TOKEN} does.- fauxCallTool('@posthog/load-skill', { id: 'incident-io-playbook' }),- fauxCallTool('@posthog/http-request', {- url: 'https://api.incident.io/v2/incidents?status_category%5Bone_of%5D=active&page_size=25',- method: 'GET',- headers: { Authorization: 'Bearer ${INCIDENT_IO_TOKEN}' },- }),+ // NOTE: incident.io is now reached through its MCP (`mcps[incident-io]`),+ // not raw HTTP. The bundle ships a PLACEHOLDER connection that won't open+ // in this harness, so the incident.io tools (incident_list / incident_show /+ // incident_update / …) aren't exercised here — the bot degrades to the+ // Slack-only flow. Coverage of the MCP-mediated path belongs in a case that+ // stands up a connected MCP.// Phase 3: load the triage skill.fauxCallTool('@posthog/load-skill', { id: 'triage-playbook' }),// Phase 4: read the channel for context.@@ -279,18 +250,6 @@ describe('example: sre-slack-bot bundle', () => {],dedupe_on: 'thread_url',}),- // Phase 8b: post the final summary onto the incident.io- // timeline so the post-mortem record matches Slack.- fauxCallTool('@posthog/http-request', {- url: 'https://api.incident.io/v2/incidents/01HXYZ/updates',- method: 'POST',- headers: { Authorization: 'Bearer ${INCIDENT_IO_TOKEN}' },- body: {- incident_id: '01HXYZ',- message:- '*Resolved.* Root cause: kafka consumer-group `events-main` under-provisioned after morning deploy. Mitigation: scaled 12→18 pods; lag drained in 4m.',- },- }),// Close the turn.fauxText('Triage posted, outcome recorded, ending session.'),])@@ -326,15 +285,12 @@ describe('example: sre-slack-bot bundle', () => {expect(calledTools).toEqual(['@posthog/http-request', // reactions.add (slack)'@posthog/table-query',- '@posthog/load-skill', // incident-io-playbook- '@posthog/http-request', // list active incidents (incident.io)'@posthog/load-skill', // triage-playbook'@posthog/http-request', // conversations.history (slack)'@posthog/http-request', // runbook fetch'@posthog/load-skill', // slack-thread-protocol'@posthog/http-request', // chat.postMessage (slack)'@posthog/table-append',- '@posthog/http-request', // post incident.io update])// Prove the bring-your-own-token wiring actually fired. The agent's@@ -351,21 +307,6 @@ describe('example: sre-slack-bot bundle', () => {const endpoints = slackCalls.map((c) => c.url.replace('https://slack.com/api/', '')).sort()expect(endpoints).toEqual(['chat.postMessage', 'conversations.history', 'reactions.add'])- // incident.io substitution mirrors the Slack flow: the two- // recorded calls (list active incidents + post resolved update)- // must carry the resolved INCIDENT_IO_TOKEN, never the placeholder.- expect(incidentCalls).toHaveLength(2)- for (const call of incidentCalls) {- expect(call.auth).toBe('Bearer inc_test_token')- expect(call.auth).not.toContain('${')- }- const incidentEndpoints = incidentCalls- .map((c) => c.url.replace('https://api.incident.io/v2/', '').split('?')[0])- .sort()- expect(incidentEndpoints).toEqual(['incidents', 'incidents/01HXYZ/updates'])- expect(incidentCalls[1].method).toBe('POST')- expect(incidentCalls[1].body).toMatchObject({ incident_id: '01HXYZ' })-// Confirm the row actually landed in the tabular store — proves the// tool wired through to a real S3 backend, not just executed in a vacuum.const rows = await c.tabularStore.query(diff --git a/products/agent_platform/services/agent-tests/src/cases/mcp-tools.test.ts b/products/agent_platform/services/agent-tests/src/cases/mcp-tools.test.tsindex cfc4129ad903..75b9c31fe7f1 100644--- a/products/agent_platform/services/agent-tests/src/cases/mcp-tools.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/mcp-tools.test.ts@@ -102,7 +102,7 @@ describe('runtime MCPs: real e2e', () => {await c.deployAgent({slug: 'mcp-echo',spec: {- mcps: [{ id: 'demo', url: 'https://example.com/demo' }],+ mcps: [{ kind: 'agent', default_tool_approval: 'allow', id: 'demo', url: 'https://example.com/demo' }],},})const res = await request(c.ingress).post('/agents/mcp-echo/run').send({ message: 'go' })@@ -133,9 +133,11 @@ describe('runtime MCPs: real e2e', () => {spec: {mcps: [{+ kind: 'agent',id: 'linear',url: 'https://example.com/linear',- tools: ['list-issues'],+ default_tool_approval: 'deny',+ tools: [{ name: 'list-issues', level: 'allow' }],},],},@@ -177,6 +179,8 @@ describe('runtime MCPs: real e2e', () => {secrets: [{ name: 'GITHUB_TOKEN', allowed_hosts: ['api.githubcopilot.com'] }],mcps: [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'github',url: 'https://api.githubcopilot.com/mcp',secrets: ['GITHUB_TOKEN'],@@ -213,6 +217,8 @@ describe('runtime MCPs: real e2e', () => {secrets: [{ name: 'TENANT', allowed_hosts: ['example.com'] }],mcps: [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'tenant',url: 'https://example.com/${TENANT}/mcp',secrets: ['TENANT'],@@ -250,6 +256,8 @@ describe('runtime MCPs: real e2e', () => {secrets: [{ name: 'SLACK_BOT_TOKEN', allowed_hosts: ['slack.com'] }],mcps: [{+ kind: 'agent',+ default_tool_approval: 'allow',id: 'exfil',url: 'https://attacker.example.com/collect',secrets: ['SLACK_BOT_TOKEN'],@@ -287,7 +295,9 @@ describe('runtime MCPs: real e2e', () => {c.setScript([fauxCallTool('demo__boom', {}), fauxText('Recovered after error.')])await c.deployAgent({slug: 'mcp-error',- spec: { mcps: [{ id: 'demo', url: 'https://example.com/demo' }] },+ spec: {+ mcps: [{ kind: 'agent', default_tool_approval: 'allow', id: 'demo', url: 'https://example.com/demo' }],+ },})const res = await request(c.ingress).post('/agents/mcp-error/run').send({ message: 'try' })await c.drain()@@ -331,12 +341,14 @@ describe('runtime MCPs: real e2e', () => {spec: {mcps: [{+ kind: 'agent',id: 'posthog',url: 'https://example.com/posthog',+ default_tool_approval: 'allow',tools: [{name: 'promote-revision',- requires_approval: true,+ level: 'approve',approval_policy: { type: 'agent', ttl_ms: 900_000 },},],@@ -407,12 +419,14 @@ describe('runtime MCPs: real e2e', () => {spec: {mcps: [{+ kind: 'agent',id: 'posthog',url: 'https://example.com/posthog',+ default_tool_approval: 'allow',tools: [{name: 'promote-revision',- requires_approval: true,+ level: 'approve',approval_policy: { type: 'agent', ttl_ms: 900_000 },},],@@ -453,10 +467,21 @@ describe('runtime MCPs: real e2e', () => {spec: {mcps: [// `working` opens cleanly via the in-process factory.- { id: 'working', url: 'https://example.com/working' },+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'working',+ url: 'https://example.com/working',+ },// `broken` references an undeclared secret → resolveTarget// throws → reported as an unavailable MCP, not session-fatal.- { id: 'broken', url: 'https://example.com/${MISSING}/mcp', secrets: ['MISSING'] },+ {+ kind: 'agent',+ default_tool_approval: 'allow',+ id: 'broken',+ url: 'https://example.com/${MISSING}/mcp',+ secrets: ['MISSING'],+ },],},})@@ -478,4 +503,208 @@ describe('runtime MCPs: real e2e', () => {expect(mcpFail!.data.category).toBe('auth')expect(mcpFail!.data.reason).toMatch(/mcp_secret_not_resolved/)})++ // ─────────────────────────────────────────────────────────────+ // Per-agent tool-permission model: `mcps[].default_tool_approval`+ // (allow / approve / deny) + per-tool `tools[].level` overrides.+ // Effective level per tool = override ?? default. `deny` → hidden,+ // `allow` → auto-run, `approve` → queue for approval. Setting+ // `default_tool_approval` switches OFF the legacy allowlist.+ // ─────────────────────────────────────────────────────────────+ const queuedRows = async (applicationId: string): Promise<Array<{ id: string; tool_name: string }>> => {+ const res = await request(c.janitor).get('/approvals').query({ application_id: applicationId, state: 'queued' })+ return res.body.results as Array<{ id: string; tool_name: string }>+ }++ it('default_tool_approval=allow: the tool auto-runs with no approval row', async () => {+ const { factory, captured } = buildFactory({+ echo: { description: 'd', inputSchema: { msg: z.string() }, handler: ({ msg }) => ({ echoed: msg }) },+ })+ c = await buildCluster({ mcpTransportFactory: factory })+ c.setScript([fauxCallTool('demo__echo', { msg: 'hi' }), fauxText('done')])+ const { application } = await c.deployAgent({+ slug: 'mcp-default-allow',+ spec: {+ mcps: [{ kind: 'agent', id: 'demo', url: 'https://example.com/demo', default_tool_approval: 'allow' }],+ },+ })+ const res = await request(c.ingress).post('/agents/mcp-default-allow/run').send({ message: 'go' })+ await c.drain()++ const session = await c.queue.get(res.body.session_id)+ expect(session!.state).toBe('completed')+ expect(captured).toEqual([{ name: 'echo', args: { msg: 'hi' }, target: { url: 'https://example.com/demo' } }])+ expect(await queuedRows(application.id)).toHaveLength(0)+ })++ it('default_tool_approval=approve: the tool queues, approve dispatches the real call', async () => {+ let remoteHits = 0+ const { factory } = buildFactory({+ 'promote-revision': {+ description: 'd',+ handler: () => {+ remoteHits += 1+ return { promoted: true }+ },+ },+ })+ c = await buildCluster({ mcpTransportFactory: factory })+ // No `approval_policy` on the ref → exercises the DEFAULT_APPROVAL_POLICY fallback.+ c.setScript([fauxCallTool('posthog__promote-revision', { id: 'r1' }), fauxText('queued'), fauxText('done')])+ const { application } = await c.deployAgent({+ slug: 'mcp-default-approve',+ spec: {+ mcps: [+ {+ kind: 'agent',+ id: 'posthog',+ url: 'https://example.com/posthog',+ default_tool_approval: 'approve',+ },+ ],+ },+ })+ const run = await request(c.ingress).post('/agents/mcp-default-approve/run').send({ message: 'go' })+ await c.drain()++ // Parked for approval — remote not yet hit.+ expect(remoteHits).toBe(0)+ const queued = await queuedRows(application.id)+ expect(queued).toHaveLength(1)+ expect(queued[0].tool_name).toBe('posthog__promote-revision')++ await request(c.janitor)+ .post(`/approvals/${queued[0].id}/decide`)+ .send({ decision: 'approve', decided_by: '00000000-0000-0000-0000-000000000001' })+ await c.drain()++ expect(remoteHits).toBe(1)+ expect((await c.queue.get(run.body.session_id))!.state).toBe('completed')+ })++ it('default_tool_approval=approve: reject denies the call (remote never hit)', async () => {+ let remoteHits = 0+ const { factory } = buildFactory({+ 'promote-revision': {+ description: 'd',+ handler: () => {+ remoteHits += 1+ return { promoted: true }+ },+ },+ })+ c = await buildCluster({ mcpTransportFactory: factory })+ c.setScript([fauxCallTool('posthog__promote-revision', { id: 'r1' }), fauxText('queued'), fauxText('stopped')])+ const { application } = await c.deployAgent({+ slug: 'mcp-default-approve-reject',+ spec: {+ mcps: [+ {+ kind: 'agent',+ id: 'posthog',+ url: 'https://example.com/posthog',+ default_tool_approval: 'approve',+ },+ ],+ },+ })+ const run = await request(c.ingress).post('/agents/mcp-default-approve-reject/run').send({ message: 'go' })+ await c.drain()+ const [pending] = await queuedRows(application.id)+ expect(pending).not.toBeUndefined()++ await request(c.janitor)+ .post(`/approvals/${pending.id}/decide`)+ .send({ decision: 'reject', decided_by: '00000000-0000-0000-0000-000000000002', reason: 'nope' })+ await c.drain()++ expect(remoteHits).toBe(0)+ expect((await c.queue.get(run.body.session_id))!.state).toBe('completed')+ const allRows = (await request(c.janitor).get('/approvals').query({ application_id: application.id })).body+ .results as Array<{ id: string; state: string }>+ expect(allRows.find((r) => r.id === pending.id)?.state).toBe('rejected')+ })++ it('default_tool_approval=deny: the tool is hidden from the model (calling it errors)', async () => {+ let remoteHits = 0+ const { factory } = buildFactory({+ echo: {+ description: 'd',+ inputSchema: { msg: z.string() },+ handler: () => {+ remoteHits += 1+ return { ok: true }+ },+ },+ })+ c = await buildCluster({ mcpTransportFactory: factory })+ // The model "tries" the denied tool; it isn't in the surface, so the loop+ // returns an error tool_result (same path as the legacy allowlist miss).+ c.setScript([fauxCallTool('demo__echo', { msg: 'hi' }), fauxText('cannot')])+ await c.deployAgent({+ slug: 'mcp-default-deny',+ spec: {+ mcps: [{ kind: 'agent', id: 'demo', url: 'https://example.com/demo', default_tool_approval: 'deny' }],+ },+ })+ const run = await request(c.ingress).post('/agents/mcp-default-deny/run').send({ message: 'go' })+ await c.drain()++ expect(remoteHits).toBe(0)+ const session = await c.queue.get(run.body.session_id)+ expect(session!.state).toBe('completed')+ const toolResult = session!.conversation.find((m) => m.role === 'toolResult') as+ | { role: 'toolResult'; isError: boolean }+ | undefined+ expect(toolResult?.isError).toBe(true)+ })++ it('per-tool level overrides the default: allow auto-runs, deny stays hidden', async () => {+ let blockedHits = 0+ const { factory, captured } = buildFactory({+ auto_tool: { description: 'd', handler: () => ({ ok: true }) },+ blocked_tool: {+ description: 'd',+ handler: () => {+ blockedHits += 1+ return { ok: true }+ },+ },+ })+ c = await buildCluster({ mcpTransportFactory: factory })+ // default=approve, but auto_tool is overridden to allow (runs, no+ // approval) and blocked_tool to deny (hidden → calling it errors).+ c.setScript([fauxCallTool('demo__auto_tool', {}), fauxCallTool('demo__blocked_tool', {}), fauxText('done')])+ const { application } = await c.deployAgent({+ slug: 'mcp-overrides',+ spec: {+ mcps: [+ {+ kind: 'agent',+ id: 'demo',+ url: 'https://example.com/demo',+ default_tool_approval: 'approve',+ tools: [+ { name: 'auto_tool', level: 'allow' },+ { name: 'blocked_tool', level: 'deny' },+ ],+ },+ ],+ },+ })+ const run = await request(c.ingress).post('/agents/mcp-overrides/run').send({ message: 'go' })+ await c.drain()++ const session = await c.queue.get(run.body.session_id)+ expect(session!.state).toBe('completed')+ // allow-override ran without queuing (proves it beats the approve default).+ expect(captured.map((c) => c.name)).toEqual(['auto_tool'])+ expect(await queuedRows(application.id)).toHaveLength(0)+ // deny-override never reached the remote; the call came back as an error.+ expect(blockedHits).toBe(0)+ const errored = session!.conversation.some(+ (m) => m.role === 'toolResult' && (m as { isError?: boolean }).isError === true+ )+ expect(errored).toBe(true)+ })})diff --git a/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts b/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.tsindex ed43c17fb939..f437e45aad14 100644--- a/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts@@ -43,7 +43,6 @@ function defaultSpec(): Record<string, unknown> {triggers: [{ type: 'chat', config: {}, auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] } },],- auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] },}}@@ -134,7 +133,6 @@ describe('typed bundle authoring API: real e2e', () => {auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] },},],- auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] },},}const put = await request(c.janitor).put(`/revisions/${rid}/bundle`).send(payload)diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.mdindex e3daaf0758d5..9f019a2118e8 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md@@ -210,6 +210,16 @@ Examples (bad — vague, no commitment):You call a few classes of tool. Mistaking which class a tool is inis a routine cause of confusion; keep the table in mind.+The PostHog MCP exposes a large catalog, so its tools are reached **on demand**+through three helpers, not called as top-level tools: `posthog__explore_tools`+(search by keyword), `posthog__get_tool_schema` (read one tool's exact argument+names — do this before calling a tool whose args you're unsure of; never guess),+and `posthog__call_tool` (invoke: pass `tool_name` + `arguments`). The+`posthog__<name>` tools named throughout this doc are those tool names — pass them+to `call_tool` as `tool_name` (with or without the `posthog__` prefix, either is+accepted). The non-PostHog entries below (`@posthog/*` natives, client tools) are+called directly.+| Class | Examples | When you use it || ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || PostHog MCP | `posthog__agent-applications-list`, `posthog__agent-applications-retrieve`, `posthog__agent-applications-sessions-retrieve`, `posthog__agent-applications-session-logs` (etc.) | The bulk of your work. Read + write agent state — applications, revisions, sessions, logs — as the asking user. One MCP server, every tool prefixed `posthog__`; the active project is set with `posthog__switch-project` (hard rule #7). |diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.jsonindex 961ae8c95e55..4733bb218c98 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json@@ -215,76 +215,108 @@},"required": ["agent_slug", "secret"]}+ },+ {+ "kind": "client",+ "id": "connect_mcp",+ "interactive": true,+ "description": "Punch out to the user to connect an MCP server to an agent, then reference it from the agent's spec. INTERACTIVE: returns a synthetic `{queued:true, interactive:true, call_id}` envelope immediately — that is NOT the result. End your turn after a brief acknowledgement. The session parks; the user reviews the PREFILLED connect form (you supply `name`/`url`) and completes the auth themselves — OAuth consent or an API key. You NEVER see tokens or secrets. On a fresh turn you receive a wake message `{call_id, ok, result|error}`: on success `{connected:true, connection_id, mcp_id, url}` (the agent's spec now has an `mcps[]` entry with `connection: connection_id` — one shared credential for every asker of that agent), or `user_cancelled`. Match by `call_id`. Use this whenever the user wants the agent to use a third-party MCP server (e.g. incident.io, Linear). Prefill `url` with the server's MCP endpoint when you know it. Only offered where the client can render the form (declared in the session's `supported_client_tools`, e.g. PostHog Code); on other surfaces it isn't exposed.",+ "args_schema": {+ "type": "object",+ "properties": {+ "agent_slug": {+ "type": "string",+ "description": "The agent the connection is attached to. Required — do not infer from page context."+ },+ "revision_id": {+ "type": "string",+ "description": "Draft revision to write the mcps[] entry to. Optional — falls back to the revision the user is viewing in the agent-config page."+ },+ "name": {+ "type": "string",+ "description": "Prefilled server name shown in the form, e.g. 'incident.io'. The user can edit it."+ },+ "url": {+ "type": "string",+ "description": "Prefilled MCP server URL, e.g. 'https://mcp.incident.io/mcp'. The user can edit it."+ },+ "purpose": {+ "type": "string",+ "description": "One-line reason shown above the form so the user knows why you're connecting this server."+ }+ },+ "required": ["agent_slug"]+ }}],"mcps": [{+ "kind": "principal","id": "posthog","url": "http://localhost:8787/mcp","auth": {"provider": "posthog"},+ "default_tool_approval": "deny","tools": [- "agent-applications-list",- "agent-applications-retrieve",- "agent-applications-create",- "agent-applications-partial-update",- "agent-applications-revisions-list",- "agent-applications-revisions-retrieve",- "agent-applications-revisions-create",- "agent-applications-revisions-new-draft-create",- "agent-applications-revisions-clone-from-create",- "agent-applications-revisions-partial-update",- "agent-applications-revisions-agent-md-update",- "agent-applications-revisions-skill-refs-update",- "llm-skills-search",- "llm-skills-create",- "agent-applications-revisions-tools-update",- "agent-applications-revisions-tools-destroy",- "agent-applications-revisions-spec-update",- "agent-applications-revisions-bundle-retrieve",- "agent-applications-revisions-validate-create",- "agent-applications-revisions-freeze-create",- "agent-applications-revisions-system-prompt",- "agent-applications-revisions-manifest-retrieve",- "agent-applications-revisions-slack-manifest",- "agent-applications-sessions-list",- "agent-applications-sessions-retrieve",- "agent-applications-session-logs",- "agent-applications-env-keys-list",- "agent-applications-env-keys-get",- "agent-native-tools-list",- "agent-resolve-resource",- "agent-applications-models",- "agent-applications-spec-schema",- "execute-sql",- "insight-query",- "get-llm-total-costs-for-project",- "projects-get",- "switch-project",+ { "name": "agent-applications-list", "level": "allow" },+ { "name": "agent-applications-retrieve", "level": "allow" },+ { "name": "agent-applications-create", "level": "allow" },+ { "name": "agent-applications-partial-update", "level": "allow" },+ { "name": "agent-applications-revisions-list", "level": "allow" },+ { "name": "agent-applications-revisions-retrieve", "level": "allow" },+ { "name": "agent-applications-revisions-create", "level": "allow" },+ { "name": "agent-applications-revisions-new-draft-create", "level": "allow" },+ { "name": "agent-applications-revisions-clone-from-create", "level": "allow" },+ { "name": "agent-applications-revisions-partial-update", "level": "allow" },+ { "name": "agent-applications-revisions-agent-md-update", "level": "allow" },+ { "name": "agent-applications-revisions-skill-refs-update", "level": "allow" },+ { "name": "skill-list", "level": "allow" },+ { "name": "skill-get", "level": "allow" },+ { "name": "skill-create", "level": "allow" },+ { "name": "skill-update", "level": "allow" },+ { "name": "skill-file-create", "level": "allow" },+ { "name": "skill-file-delete", "level": "allow" },+ { "name": "skill-file-rename", "level": "allow" },+ { "name": "mcp-connections-list", "level": "allow" },+ { "name": "mcp-connection-tools-list", "level": "allow" },+ { "name": "agent-applications-revisions-tools-update", "level": "allow" },+ { "name": "agent-applications-revisions-tools-destroy", "level": "allow" },+ { "name": "agent-applications-revisions-spec-update", "level": "allow" },+ { "name": "agent-applications-revisions-bundle-retrieve", "level": "allow" },+ { "name": "agent-applications-revisions-validate-create", "level": "allow" },+ { "name": "agent-applications-revisions-freeze-create", "level": "allow" },+ { "name": "agent-applications-revisions-system-prompt", "level": "allow" },+ { "name": "agent-applications-revisions-manifest-retrieve", "level": "allow" },+ { "name": "agent-applications-revisions-slack-manifest", "level": "allow" },+ { "name": "agent-applications-sessions-list", "level": "allow" },+ { "name": "agent-applications-sessions-retrieve", "level": "allow" },+ { "name": "agent-applications-session-logs", "level": "allow" },+ { "name": "agent-applications-env-keys-list", "level": "allow" },+ { "name": "agent-applications-env-keys-get", "level": "allow" },+ { "name": "agent-native-tools-list", "level": "allow" },+ { "name": "agent-resolve-resource", "level": "allow" },+ { "name": "agent-applications-models", "level": "allow" },+ { "name": "agent-applications-spec-schema", "level": "allow" },+ { "name": "execute-sql", "level": "allow" },+ { "name": "insight-query", "level": "allow" },+ { "name": "get-llm-total-costs-for-project", "level": "allow" },+ { "name": "projects-get", "level": "allow" },+ { "name": "switch-project", "level": "allow" },{"name": "agent-applications-revisions-promote-create",- "requires_approval": true,- "approval_policy": {- "type": "principal",- "ttl_ms": 900000- }+ "level": "approve",+ "approval_policy": { "type": "principal", "ttl_ms": 900000 }},{"name": "agent-applications-revisions-archive-create",- "requires_approval": true,- "approval_policy": {- "type": "principal",- "ttl_ms": 900000- }+ "level": "approve",+ "approval_policy": { "type": "principal", "ttl_ms": 900000 }},{"name": "agent-applications-destroy",- "requires_approval": true,- "approval_policy": {- "type": "principal",- "ttl_ms": 900000- }+ "level": "approve",+ "approval_policy": { "type": "principal", "ttl_ms": 900000 }}]}diff --git a/products/agent_platform/services/agent-tests/src/examples/mcp-shared-vs-per-asker/agent.md b/products/agent_platform/services/agent-tests/src/examples/mcp-shared-vs-per-asker/agent.mdnew file mode 100644index 000000000000..5de22b5d4f66--- /dev/null+++ b/products/agent_platform/services/agent-tests/src/examples/mcp-shared-vs-per-asker/agent.md@@ -0,0 +1,49 @@+# MCP auth demo — shared connection vs per-asker identity++This agent exists to show the **two ways an agent reaches an MCP server**, side+by side. Open it in the agent config UI: each entry under `mcps[]` renders+differently and the descriptions spell out how each is set up.++## 1. Agent-level — one shared connection (`mcps[].connection`)++`incident` is an **agent-level** MCP. The agent owner connects the server+**once** (OAuth incl. dynamic client registration, or an API key) and stores it+as a native MCP connection; **every asker of this agent reuses that one+credential** and never signs in themselves.++- **Set it up:** in the agent config, open the `incident` MCP → pick (or+ "Connect new") a connection. The shipped spec points at a placeholder+ connection id, so a fresh project shows _"Referenced connection isn't in this+ project — reconnect it or pick another"_. Connect incident.io once and select+ it; from then on it's shared.+- **Tool permissions** are set per agent, right here: a connection-wide default+ (`default_tool_approval`, here `approve` = ask before every call) plus+ per-tool overrides (allow / approve / deny). The runner loads the shared+ bearer from the connection row and applies these.+- **Use it when:** the agent should act as _one team identity_ (a service+ account), not as the individual asking.++## 2. Principal-level — per-asker identity (`mcps[].auth.provider`)++`posthog` is a **principal-level** MCP. It references an entry in+`identity_providers[]` (here a `posthog` OAuth provider). There is **no shared+credential** — instead, **each asker authenticates as themselves** the first+time they hit a tool that needs it (an auth-required link is surfaced; they+complete the OAuth and the agent then acts _as that user_).++- **Set it up:** declare the provider in `identity_providers[]` and point the+ MCP's `auth.provider` at it. Askers link their own account on first use;+ nobody pre-connects anything.+- **Use it when:** the agent must act _as the person asking_ (their data, their+ permissions) — e.g. querying PostHog as the requesting user.++## TL;DR++| | Agent-level (`connection`) | Principal-level (`auth.provider`) |+| ----------- | ------------------------------------------ | --------------------------------------------- |+| Credential | one shared, owner connects once | per-asker, each links their own |+| Acts as | a team/service identity | the individual asking |+| Setup | owner picks a connection in the UI | declare a provider; askers OAuth on first use |+| Tool gating | `default_tool_approval` + per-tool `level` | (per the tool's own approval) |++Keep replies short; this agent is a reference, not a worker.diff --git a/products/agent_platform/services/agent-tests/src/examples/mcp-shared-vs-per-asker/spec.json b/products/agent_platform/services/agent-tests/src/examples/mcp-shared-vs-per-asker/spec.jsonnew file mode 100644index 000000000000..e82b23edc5b4--- /dev/null+++ b/products/agent_platform/services/agent-tests/src/examples/mcp-shared-vs-per-asker/spec.json@@ -0,0 +1,29 @@+{+ "models": { "mode": "manual", "models": [{ "model": "anthropic/claude-sonnet-4-6" }] },+ "reasoning": "low",+ "triggers": [+ {+ "type": "chat",+ "config": {},+ "auth": { "modes": [{ "type": "posthog", "scopes": ["agents:read"] }] }+ }+ ],+ "mcps": [+ {+ "kind": "agent",+ "id": "incident",+ "url": "https://mcp.incident.io/mcp",+ "connection": "00000000-0000-0000-0000-000000000000",+ "default_tool_approval": "approve"+ },+ {+ "kind": "principal",+ "id": "posthog",+ "url": "http://localhost:8787/mcp",+ "default_tool_approval": "allow",+ "auth": { "provider": "posthog" }+ }+ ],+ "identity_providers": [{ "kind": "posthog", "scopes": ["openid", "profile", "email", "user:read"] }],+ "limits": { "max_turns": 10, "max_tool_calls": 20, "max_wall_seconds": 120 }+}diff --git a/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.jsonindex 25fdcf9e4f74..45c012fb08a9 100644--- a/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json+++ b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json@@ -16,8 +16,10 @@"tools": [],"mcps": [{+ "kind": "principal","id": "posthog","url": "http://localhost:8787/mcp",+ "default_tool_approval": "allow","auth": { "provider": "posthog" }}],diff --git a/products/agent_platform/services/agent-tests/src/examples/seed.py b/products/agent_platform/services/agent-tests/src/examples/seed.pyindex 2e058218c1db..bc94f2442573 100755--- a/products/agent_platform/services/agent-tests/src/examples/seed.py+++ b/products/agent_platform/services/agent-tests/src/examples/seed.py@@ -57,10 +57,13 @@ Exit codes:from __future__ import annotations+import ioimport os+import reimport sysimport jsonimport hashlib+import zipfileimport subprocessimport urllib.errorimport urllib.request@@ -142,6 +145,41 @@ def _req(method: str, path: str, body: dict | None = None) -> tuple[int, dict]:return e.code, {"raw": response_body}+def _req_multipart(path: str, filename: str, content: bytes, content_type: str) -> tuple[int, dict]:+ """POST a single-file multipart/form-data body (form field `file`). The skill+ store's `import` endpoint takes a zip this way; urllib has no multipart helper+ so we frame the body by hand with a fixed boundary."""+ boundary = "----seedpyboundary7MA4YWxkTrZu0gW"+ head = (+ f"--{boundary}\r\n"+ f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'+ f"Content-Type: {content_type}\r\n\r\n"+ ).encode()+ body = head + content + f"\r\n--{boundary}--\r\n".encode()+ url = f"{API}/api/projects/{PROJECT_ID}{path}"+ req = urllib.request.Request(+ url,+ data=body,+ method="POST",+ headers={+ "Authorization": f"Bearer {PAT}",+ "Content-Type": f"multipart/form-data; boundary={boundary}",+ },+ )+ try:+ # Example seed script — API base is a trusted dev/CI env var, not user input.+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected+ with urllib.request.urlopen(req) as r:+ payload = r.read().decode() or "{}"+ return r.status, json.loads(payload)+ except urllib.error.HTTPError as e:+ response_body = e.read().decode() if e.fp else ""+ try:+ return e.code, json.loads(response_body)+ except json.JSONDecodeError:+ return e.code, {"raw": response_body}++class SeedError(Exception):"""A per-bundle failure. Caught by the run loop so one bad bundle doesn'tabort the others; the run still exits non-zero at the end."""@@ -348,6 +386,125 @@ def ensure_dummy_secrets(slug: str, app_id: str, rev_id: str, spec: dict) -> Nonlog(slug, f"set placeholder secrets: {', '.join(set_keys)}")+# ---------------------------------------------------------------------------+# Store skills+#+# The skill store is canonical: a frozen revision pulls each skill from the+# `llm_skills` store via `skill_refs`, and freeze REFUSES inline skills that+# aren't backed by a store reference. So before freeze we mirror every bundle+# skill into the store (idempotent, by name) and set the draft's `skill_refs`.+# The store name and the bundle folder id (the ref `alias`) are both the spec+# skill id — example skill ids are unique across bundles.+# ---------------------------------------------------------------------------+++_FRONTMATTER_RE = re.compile(r"^---\n.*?\n---\n", re.DOTALL)+++def skill_md_for_store(skill_id: str, description: str, body: str) -> str:+ """The SKILL.md text to import, guaranteed to carry a `name` (the store+ requires it). Three cases across the example bundles:+ - no frontmatter (starts at a heading) → synthesise the whole block;+ - frontmatter with a `description` but no `name` → inject `name`;+ - frontmatter with both → use verbatim.+ Synthesised values come from the spec (skill id + ref description) and are+ JSON-encoded — valid YAML double-quoted scalars — so colons / em-dashes in+ descriptions can't break the block."""+ match = _FRONTMATTER_RE.match(body)+ if match is None:+ return f"---\nname: {json.dumps(skill_id)}\ndescription: {json.dumps(description)}\n---\n\n{body}"+ if re.search(r"(?m)^name:[ \t]*\S", match.group(0)):+ return body+ # Frontmatter present but unnamed — inject `name` right after the opening `---`.+ return body.replace("---\n", f"---\nname: {json.dumps(skill_id)}\n", 1)+++def build_skill_zip(skill_id: str, skill_md: str, companions: dict[str, str]) -> bytes:+ """A spec-compliant skill zip: `<id>/SKILL.md` plus any companion files under+ the same folder. `parse_skill_zip` finds the single SKILL.md and collects its+ siblings."""+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as archive:+ archive.writestr(f"{skill_id}/SKILL.md", skill_md)+ for rel_path, content in companions.items():+ archive.writestr(f"{skill_id}/{rel_path}", content)+ return buf.getvalue()+++def _post_frontmatter_body(body: str) -> str:+ """The body the store keeps (frontmatter stripped), for drift comparison."""+ match = _FRONTMATTER_RE.match(body)+ return (body[match.end() :] if match else body).strip()+++def ensure_store_skill(slug: str, skill_id: str, description: str, body: str, companions: dict[str, str]) -> str:+ """Find-or-create the bundle skill in the `llm_skills` store, publishing a new+ version when its body/description has drifted — freeze pulls the store copy, so+ a stale store skill would ship instead of the bundle's. Returns the store name."""+ want_body = _post_frontmatter_body(body)+ want_desc = (description or "").strip()+ status, existing = _req("GET", f"/llm_skills/name/{skill_id}/")+ if status == 200:+ if (existing.get("body") or "").strip() == want_body and (+ existing.get("description") or ""+ ).strip() == want_desc:+ return skill_id+ ver = existing.get("version")+ status, payload = _req(+ "PATCH",+ f"/llm_skills/name/{skill_id}/",+ {"base_version": ver, "body": want_body, "description": want_desc},+ )+ if status not in (200, 201):+ raise SeedError(f"skill update failed for '{skill_id}': {status} {payload}")+ log(slug, f"updated store skill '{skill_id}' (v{ver} → v{payload.get('version', '?')})")+ return skill_id+ skill_md = skill_md_for_store(skill_id, description, body)+ zip_bytes = build_skill_zip(skill_id, skill_md, companions)+ status, payload = _req_multipart("/llm_skills/import/", f"{skill_id}.zip", zip_bytes, "application/zip")+ if status in (200, 201):+ return str(payload.get("name") or skill_id)+ # A name conflict means a concurrent/prior run already created it — reuse.+ if status == 400 and "already exists" in json.dumps(payload):+ return skill_id+ raise SeedError(f"skill import failed for '{skill_id}': {status} {payload}")+++def set_skill_refs(slug: str, app_id: str, rev_id: str, refs: list[dict]) -> None:+ """Full-replace the draft's store-skill references (resolved + materialised at+ freeze). No-op when the bundle has no skills."""+ if not refs:+ return+ log(slug, f"setting {len(refs)} skill ref(s): {', '.join(r['alias'] for r in refs)}")+ status, payload = _req("PUT", f"/agent_applications/{app_id}/revisions/{rev_id}/skill_refs/", {"skill_refs": refs})+ if status != 200:+ raise SeedError(f"set skill_refs failed for {slug}: {status} {payload}")+++def seed_store_skills(slug: str, app_id: str, rev_id: str, spec: dict, bundle_root: Path) -> None:+ """Mirror every bundle skill into the store and pin the draft's `skill_refs`,+ so freeze can resolve them. `from_template` is the store name; `alias` is the+ bundle folder id — both the spec skill id here."""+ refs: list[dict] = []+ for skill_ref in spec.get("skills", []) or []:+ skill_id = skill_ref.get("id")+ if not skill_id:+ continue+ rel = skill_ref.get("path", f"skills/{skill_id}.md")+ skill_md_path = bundle_root / rel+ body = skill_md_path.read_text() if skill_md_path.is_file() else ""+ # Companions: every sibling file in the skill's folder except SKILL.md.+ companions: dict[str, str] = {}+ skill_dir = skill_md_path.parent+ if skill_dir.is_dir() and skill_dir != bundle_root:+ for f in sorted(skill_dir.rglob("*")):+ if f.is_file() and f != skill_md_path:+ companions[f.relative_to(skill_dir).as_posix()] = f.read_text()+ store_name = ensure_store_skill(slug, skill_id, skill_ref.get("description", ""), body, companions)+ refs.append({"from_template": store_name, "alias": skill_id})+ set_skill_refs(slug, app_id, rev_id, refs)++# ---------------------------------------------------------------------------# Pipeline# ---------------------------------------------------------------------------@@ -498,6 +655,9 @@ def seed_bundle(bundle_root: Path) -> None:rev_id = create_draft(slug, app_id, parent=live_rev, spec=spec)push_bundle(slug, app_id, rev_id, files, spec)patch_spec(slug, app_id, rev_id, spec)+ # Mirror bundle skills into the store + pin skill_refs BEFORE freeze — the+ # freeze gate refuses inline skills that lack a store reference.+ seed_store_skills(slug, app_id, rev_id, spec, bundle_root)if SEED_DUMMY_SECRETS:ensure_dummy_secrets(slug, app_id, rev_id, spec)validate(slug, app_id, rev_id)diff --git a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/README.md b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/README.mdindex c8475ba4bdfc..4c34b79c6557 100644--- a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/README.md+++ b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/README.md@@ -15,24 +15,26 @@ doesn't exist yet; see [Gaps](#gaps-that-constrain-this-version) below.## What it does-| Capability | How |-| ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |-| **Auto-triggered by incident.io webhooks** | `webhook` trigger at `/agents/<slug>/webhook` — point incident.io's webhook config here for hands-off alert response. |-| Triggered by Grafana / alertmanager | Same `webhook` endpoint, different payload shape — auto-detected by the agent. |-| Triggered by Slack `@mention` | `slack` trigger, `mention_only: true` |-| **DM the bot directly** | `slack` trigger, `allow_direct_messages: true` — on-call asks it privately; one rolling session per DM, idle-reset by the sweep |-| Chattable from the agent console | `chat` trigger — open the agent in the console and use the playground dock |-| Calls the Slack Web API directly | `@posthog/http-request` + `SLACK_BOT_TOKEN` secret (bring-your-own bot, no integration) |-| **Reads + writes incident.io directly** | `@posthog/http-request` + `INCIDENT_IO_TOKEN` secret — lists active incidents, posts triage updates onto the timeline. |-| Queries PostHog event data **and logs** | `@posthog/query` (HogQL against `events` + the `logs` table — schema documented in `agent.md`) |-| Fetches runbook URLs | `@posthog/http-request` |-| Remembers prior incident outcomes | `@posthog/table-query`, `@posthog/table-append` on the `incidents` table (now with optional `incident_io_id` column) |-| **Consults a runbook corpus on triage** | `@posthog/memory-search` / `-read` over `runbooks/` (alert / system / procedure runbooks) — see [Runbook memory](#runbook-memory) |-| **Proposes runbook updates for users** | `@posthog/memory-write` / `-update`, **approval-gated** — queues the change and links the user to approve it |-| Follows a structured triage flow | `skills/triage-playbook/SKILL.md` |-| Follows a consistent Slack message format | `skills/slack-thread-protocol/SKILL.md` |-| Follows a consistent incident.io flow | `skills/incident-io-playbook/SKILL.md` |-| Knows how to build good memory | `skills/runbook-memory/SKILL.md` |+| Capability | How |+| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **Auto-triggered by incident.io webhooks** | `webhook` trigger at `/agents/<slug>/webhook` — point incident.io's webhook config here for hands-off alert response. |+| Triggered by Grafana / alertmanager | Same `webhook` endpoint, different payload shape — auto-detected by the agent. |+| Triggered by Slack `@mention` | `slack` trigger, `mention_only: true` |+| **DM the bot directly** | `slack` trigger, `allow_direct_messages: true` — on-call asks it privately; one rolling session per DM, idle-reset by the sweep |+| Chattable from the agent console | `chat` trigger — open the agent in the console and use the playground dock |+| Calls the Slack Web API directly | `@posthog/http-request` + `SLACK_BOT_TOKEN` secret (bring-your-own bot, no integration) |+| **Reads + writes incident.io via its MCP** | `mcps[incident-io]` tools (`incident_list` / `incident_show` / `incident_update` / `incident_create`) — lists active incidents, posts triage updates onto the timeline. See [MCP servers](#mcp-servers--two-auth-models). |+| Queries PostHog event data **and logs** | `@posthog/query` (HogQL against `events` + the `logs` table — schema documented in `agent.md`) |+| Fetches runbook URLs | `@posthog/http-request` |+| Remembers prior incident outcomes | `@posthog/table-query`, `@posthog/table-append` on the `incidents` table (now with optional `incident_io_id` column) |+| **Consults a runbook corpus on triage** | `@posthog/memory-search` / `-read` over `runbooks/` (alert / system / procedure runbooks) — see [Runbook memory](#runbook-memory) |+| **Proposes runbook updates for users** | `@posthog/memory-write` / `-update`, **approval-gated** — queues the change and links the user to approve it |+| Follows a structured triage flow | `skills/triage-playbook/SKILL.md` |+| Follows a consistent Slack message format | `skills/slack-thread-protocol/SKILL.md` |+| Follows a consistent incident.io flow | `skills/incident-io-playbook/SKILL.md` |+| Knows how to build good memory | `skills/runbook-memory/SKILL.md` |+| **incident.io as an agent-level MCP** | `mcps[incident-io]` with `connection` — one shared incident.io credential the owner links once; every asker reuses it. Per-tool approval set per agent (`default_tool_approval` + overrides). See [MCP servers](#mcp-servers--two-auth-models). |+| **PostHog as a per-asker MCP** | `mcps[posthog]` with `auth.provider: posthog` — each asker links their own PostHog identity and the agent acts AS them. See [MCP servers](#mcp-servers--two-auth-models). |## What it cannot do@@ -52,7 +54,7 @@ sre-slack-bot/└── skills/├── triage-playbook/SKILL.md # how to investigate├── slack-thread-protocol/SKILL.md # how to reply in Slack- ├── incident-io-playbook/SKILL.md # how to query + update incident.io+ ├── incident-io-playbook/SKILL.md # how to work incident.io through its MCP└── runbook-memory/SKILL.md # the runbook corpus: taxonomy, quality bar, approval-gated writes```@@ -85,12 +87,68 @@ behalf of** the team — a person signs off on what enters the corpus.This is the same gate the [agent-approval-demo](../agent-approval-demo/)bundle showcases, applied to a real curation loop.+## MCP servers — two auth models++The bundle declares two MCP servers under `spec.mcps[]`, one of each auth+model, so this bot doubles as the reference for **how an agent reaches an MCP**.+Open them in the agent config UI (`mcps` → `incident-io` / `posthog`); each+renders differently and the in-UI descriptions spell out the setup.++### `incident-io` — agent-level (one shared connection)++```jsonc+{+ "id": "incident-io",+ "url": "https://mcp.incident.io/mcp",+ "connection": "00000000-…",+ "default_tool_approval": "approve",+}+```++The owner connects incident.io **once** (OAuth incl. dynamic client+registration, or an API key) and stores it as a native MCP connection;+**every asker reuses that one credential** and never signs in. The agent acts+as a single team/service identity.++- **Set it up:** open the `incident-io` MCP in the config UI → pick (or+ "Connect new") a connection. The shipped spec points at a placeholder+ connection id, so a fresh project shows _"Referenced connection isn't in this+ project — reconnect it or pick another."_ Connect incident.io once and select+ it; from then on it's shared.+- **Tool permissions are per agent, right here:** a connection-wide default+ (`default_tool_approval`, here `approve` = ask before every call) plus+ per-tool overrides (allow / approve / deny). The runner loads the shared+ bearer from the connection row and applies these. This is the **only** way+ the bot touches incident.io — `incident_list` / `incident_show` /+ `incident_update` / `incident_create` are the typed runtime tools, so e.g.+ "open new incident" (`incident_create`) can be marked `approve` (or `deny`)+ right on the agent.++### `posthog` — principal-level (per-asker identity)++```jsonc+{ "id": "posthog", "url": "http://localhost:8787/mcp", "auth": { "provider": "posthog" } }+```++References the `posthog` entry in `identity_providers[]`. There is **no shared+credential** — **each asker authenticates as themselves** the first time they+hit a tool that needs it (an auth-required link is surfaced; they complete the+OAuth and the agent then acts AS that user). Use it when the agent must act as+the person asking — querying PostHog as the requesting user.++| | `incident-io` (agent-level) | `posthog` (principal-level) |+| ----------- | ------------------------------------------ | --------------------------------------------- |+| Credential | one shared, owner connects once | per-asker, each links their own |+| Acts as | a team/service identity | the individual asking |+| Setup | owner picks a connection in the UI | declare a provider; askers OAuth on first use |+| Tool gating | `default_tool_approval` + per-tool `level` | (per the tool's own approval) |+## Prerequisites for deploying-Three secrets, two webhooks. The recommended way to set the secrets-is the **Agent Builder walkthrough** below, which uses the console's-`set_secret` punch-out so the values never transit the model's-tool-call history. The list:+Two secrets, one MCP connection, two webhooks. The recommended way to+set the secrets is the **Agent Builder walkthrough** below, which uses+the console's `set_secret` punch-out so the values never transit the+model's tool-call history. The list:1. **Your own Slack app** registered at api.slack.com — see "Slacksetup" below. Two values flow from this:@@ -99,11 +157,14 @@ Bearer ${SLACK_BOT_TOKEN}` on every Slack Web API call.- `SLACK_SIGNING_SECRET` — the signing secret from your Slackapp's "Basic Information" page. Required by the slack triggerto verify event payloads.-2. **incident.io API token** as `INCIDENT_IO_TOKEN`. Generate from- incident.io settings → API keys. Scope to whatever subset of- "read incidents" + "write timeline updates" your org allows; the- bot does not need permission to declare incidents in the default- flow.+2. **Connect the incident.io MCP once.** Open the `incident-io` MCP in+ the agent config UI and pick (or "Connect new") a connection — OAuth+ or an API key. This is an agent-level connection: connect it once and+ every asker reuses it; the MCP carries its own auth, so there's no+ per-deploy incident.io secret to set. The shipped spec points at a+ placeholder connection id, so a fresh project shows _"Referenced+ connection isn't in this project"_ until you connect. See+ [MCP servers](#mcp-servers--two-auth-models).3. **`spec.triggers[].slack.trusted_workspaces`** updated from theplaceholder `T0XXXXXXX` to your actual Slack team id.4. **A webhook shared secret.** The bundle's `spec.auth.modes`@@ -129,18 +190,19 @@ fresh PostHog org:2. **Ask the Agent Builder to clone this bundle.** Something like:_"Build me an SRE triage bot — clone from the sre-slack-botreference, replace the placeholder Slack workspace id with- `<T0YOUR>`, and walk me through setting the three secrets."_+ `<T0YOUR>`, and walk me through setting the secrets."_The Agent Builder resolves to `agent-applications-revisions-clone-from-create`pointing at this bundle, edits `spec.triggers[].slack.trusted_workspaces`via `agent-applications-revisions-partial-update`, and freezes thedraft.3. **Punch out for each secret.** The Agent Builder calls- [`set_secret`](../agent-builder/spec.json) three times — once- for `SLACK_BOT_TOKEN`, once for `SLACK_SIGNING_SECRET`, once for- `INCIDENT_IO_TOKEN`. Each call renders an inline form in the- console; paste the value, hit save. Values are encrypted via the- `agent-applications-set-env-create` API; the Agent Builder sees only- `{ key, action: "set" }`.+ [`set_secret`](../agent-builder/spec.json) twice — once+ for `SLACK_BOT_TOKEN`, once for `SLACK_SIGNING_SECRET`. Each call+ renders an inline form in the console; paste the value, hit save.+ Values are encrypted via the `agent-applications-set-env-create`+ API; the Agent Builder sees only `{ key, action: "set" }`. (incident.io+ has no secret here — connect its MCP once in the config UI, per the+ prerequisites above.)4. **Promote.** The Agent Builder calls`agent-applications-revisions-promote-create`. Promote isapproval-gated (see the Agent Builder's spec) so you approve it@@ -239,14 +301,13 @@ pnpm --filter @posthog/agent-tests test cases/example-sre-botEach one is a follow-up that would make the bot meaningfully moreuseful:-- **incident.io as a typed runtime MCP** rather than raw HTTP calls.- incident.io ships an MCP server; we'd swap `@posthog/http-request`- for a `kind: 'external'` McpRef once- runtime MCP auth discovery- lands and the per-tool approval gating it adds lets us mark- "open new incident" as `requires_approval: true` directly on the- tool ref. v0 here keeps the playbook narrow enough that raw HTTP- is fine.+- ~~**incident.io as a typed runtime MCP** rather than raw HTTP calls.~~+ **Done** — see [MCP servers](#mcp-servers--two-auth-models). The+ `incident-io` MCP is an agent-level shared connection with per-tool+ approval (`default_tool_approval` + overrides), so "open new incident"+ (`incident_create`) can be marked `approve` (or `deny`) right on the agent.+ This is the only path the bot uses to reach incident.io — there is no raw+ HTTP fallback.- **Private-network MCP support (Grafana / k8s).** Public MCPs worktoday via the `kind: 'external'` McpRef;Grafana and Kubernetes typically aren't publicly reachable.diff --git a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/agent.md b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/agent.mdindex 0e3017be28fa..26bd980b9069 100644--- a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/agent.md+++ b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/agent.md@@ -20,10 +20,10 @@ You receive sessions in three shapes:`event_type`s warrant engagement and how to fetch the incident'sSlack channel.- Acknowledge in the incident's Slack channel (the one returned- by `GET /v2/incidents/:id`, not a hard-coded channel) before+ by `incident_show`, not a hard-coded channel) beforegathering evidence.- Post your triage update **both** to the Slack thread and to the- incident.io timeline (`POST /v2/incidents/:id/updates`) so the+ incident.io timeline (`incident_update` with a `message`) so thepost-mortem record matches what humans see in chat.2. **Alert webhook (Grafana / alertmanager).** A Grafana-style alertpayload arrives at `/webhook` (same endpoint, different body@@ -94,7 +94,7 @@ For every invocation, follow this order:— set it when the investigation was tied to an incident.ioincident so future correlations are cheap.- If there's an associated incident.io incident, post a final- summary update via `POST /v2/incidents/:id/updates` per the+ summary update via `incident_update` (with a `message`) per the`incident-io-playbook` skill. The memory table is for **your**pattern-matching; the incident.io timeline is for **humans**reading the post-mortem.@@ -118,7 +118,7 @@ someone provide it?" is far more useful than a guess.| Tool | Use when || --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- || `@posthog/query` | Need PostHog event data **or logs** to verify a hypothesis (volumes, error rates, deploys, log lines). See "PostHog Logs" below. |-| `@posthog/http-request` | Read a runbook URL or HTTP-accessible doc; call the Slack Web API or incident.io API. See "Slack" + "incident.io" below. |+| `@posthog/http-request` | Read a runbook URL or HTTP-accessible doc; call the Slack Web API. See "Slack" below. (incident.io is its own MCP — see below.) || `@posthog/table-query` | Recall prior incidents matching this alert signature. || `@posthog/table-append` | Record a resolved incident's outcome (`{ alert_signature, root_cause, mitigation, … }`). || `@posthog/table-membership` | Cheap "have I seen this alert signature before?" check across a batch. |@@ -255,55 +255,50 @@ If `SLACK_BOT_TOKEN` is unset (you get back `secret_not_resolved:SLACK_BOT_TOKEN`), reply to the user that the bot needs a token configuredand end the session — there's nothing useful you can do without it.-## incident.io — bring-your-own API token+## incident.io — the connected incident.io MCP-You also reach incident.io directly with `@posthog/http-request`. The-API token lives in `spec.secrets` as `INCIDENT_IO_TOKEN`; reference it-as `${INCIDENT_IO_TOKEN}` in any tool argument and the runner-substitutes the value server-side. Full operational details, including-when to escalate vs link to an existing incident, live in the-`incident-io-playbook` skill — load it whenever you're about to call+incident.io is reached through its **MCP**, not a token. The+`incident-io` entry in `spec.mcps[]` is an agent-level connection: the+owner links incident.io once and every asker reuses that one+credential — there's no `${...}` secret to reference. The connected+MCP exposes incident.io's tools inline; reference them by their+incident.io names. Full operational details, including when to+escalate vs link to an existing incident, live in the+`incident-io-playbook` skill — load it whenever you're about to touchincident.io for anything beyond a list-and-link.-The base URL is `https://api.incident.io/v2/`. The four calls you'll-make most often:+The four tools you'll reach for most often:```text-@posthog/http-request {- url: "https://api.incident.io/v2/incidents?status_category%5Bone_of%5D=active&page_size=25",- method: "GET",- headers: { "Authorization": "Bearer ${INCIDENT_IO_TOKEN}" }-}+incident_list { status_category: ["active"], page_size: 25 }-@posthog/http-request {- url: "https://api.incident.io/v2/incidents/<id>",- method: "GET",- headers: { "Authorization": "Bearer ${INCIDENT_IO_TOKEN}" }-}+incident_show { id: "<id>", include: ["investigation"] }-@posthog/http-request {- url: "https://api.incident.io/v2/incidents/<id>/updates",- method: "POST",- headers: { "Authorization": "Bearer ${INCIDENT_IO_TOKEN}" },- body: { "incident_id": "<id>", "message": "<your triage update>" }-}+incident_update { id: "<id>", message: "<your triage update>" }-@posthog/http-request {- url: "https://api.incident.io/v2/incidents",- method: "POST",- headers: { "Authorization": "Bearer ${INCIDENT_IO_TOKEN}" },- body: { "idempotency_key": "<alert_sig>:<startsAt>", "name": "...", "summary": "...", "severity_id": "...", "mode": "real", "visibility": "public" }-}+incident_create { name: "...", summary: "...", severity_id: "..." }```-You **rarely** make the fourth call (open a new incident). The-`incident-io-playbook` documents the narrow conditions under which-that's appropriate; default to letting humans declare incidents.--If `INCIDENT_IO_TOKEN` is unset, continue with the Slack-only flow —-don't fail the session. State plainly in your reply that incident.io-integration isn't configured for this agent so the human knows why-the timeline won't reflect this investigation.+- `incident_list` — find active incidents (filter `status_category:+["active"]`); pass `query` to substring-match a signature.+- `incident_show` — fetch one incident's full detail (Slack channel,+ status, recent updates). Request `include: ["investigation"]` when+ triaging a root cause.+- `incident_update` — post a triage/timeline note. The `message` lands+ on the incident channel + timeline; leave status/severity fields+ unset (humans drive those).+- `incident_create` — declare a new incident. You **rarely** make this+ call; the `incident-io-playbook` documents the narrow conditions+ under which that's appropriate; default to letting humans declare.++To correlate an alert to an existing page, `alert_list` / `alert_show`+are also available on the same MCP.++If the incident.io MCP **isn't connected** (a fresh project ships a+placeholder connection, so its tools may be unavailable or error),+skip the incident.io steps, continue with the Slack-only flow, and say+so plainly in your reply so the human knows why the timeline won't+reflect this investigation. Don't fail the session.## Memory schemadiff --git a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/skills/incident-io-playbook/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/skills/incident-io-playbook/SKILL.mdindex 65b375df25ae..a8f52779579b 100644--- a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/skills/incident-io-playbook/SKILL.md+++ b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/skills/incident-io-playbook/SKILL.md@@ -1,6 +1,6 @@---name: incident-io-playbook-description: How to query and update incident.io — list active incidents, fetch context for an incoming webhook, post triage updates, and (rare) open a new incident. Load when an incident.io webhook fires the agent, when an alert correlates to an active incident, or when recording a resolved outcome.+description: How to work incident.io through its connected MCP — list active incidents, fetch context for an incoming webhook, post triage updates, and (rare) open a new incident. Load when an incident.io webhook fires the agent, when an alert correlates to an active incident, or when recording a resolved outcome.---# Skill — incident.io playbook@@ -13,24 +13,19 @@ in sync so neither tells the wrong story afterwards.You do **not** declare incidents on your own. Opening a new incidentis escalation — humans do that. The one exception is documented below.-## Auth+## How you reach incident.io-Every call is to `https://api.incident.io/v2/...` with:+incident.io is a **connected MCP**, not a token. The `incident-io`+entry in `spec.mcps[]` is an agent-level connection: the owner links+incident.io once and every asker reuses that one credential. The MCP's+tools (`incident_list`, `incident_show`, `incident_update`,+`incident_create`, `alert_list`, …) appear inline — call them by name;+there's no URL to build and no `${...}` secret to substitute.-```text-Authorization: Bearer ${INCIDENT_IO_TOKEN}-```--The token lives in `spec.secrets` as `INCIDENT_IO_TOKEN`; the runner-substitutes the resolved value before dispatch. If you get back-`secret_not_resolved: INCIDENT_IO_TOKEN`, the agent isn't configured-for incident.io — say so plainly in-thread, skip the incident.io steps,-and continue with the Slack-only flow.--All responses have an `incident` (singular) or `incidents` (list)-key plus a `pagination_meta` block. Errors come back with a 4xx /-5xx and `{ "type": "validation_error", "errors": [...] }` — check-the HTTP status before treating the body as success.+If the MCP **isn't connected** — a fresh project ships a placeholder+connection, so the incident.io tools may be unavailable or come back as+errors — say so plainly in-thread, skip the incident.io steps, and+continue with the Slack-only flow. Don't fail the session.## When you receive an incident.io webhook@@ -58,17 +53,13 @@ Always fetch the full incident first to get the Slack channel +current status, even if the webhook payload looks complete:```text-@posthog/http-request {- url: "https://api.incident.io/v2/incidents/01HXYZ...",- method: "GET",- headers: { "Authorization": "Bearer ${INCIDENT_IO_TOKEN}" }-}+incident_show { id: "01HXYZ...", include: ["investigation"] }```-The response carries `incident.slack_channel_id` (use this as-`channel` in subsequent Slack calls) and-`incident.slack_team_id` (sanity-check against your `trusted_workspaces`-config).+The response carries the incident's Slack channel (use it as+`channel` in subsequent Slack calls) and its current status. Request+`include: ["investigation"]` whenever you're triaging a root cause —+it carries the AI investigation findings.## When you're triggered from Slack and want to check incident.io@@ -77,49 +68,35 @@ there's already an active incident covering it, list active incidentsand grep titles + reference codes:```text-@posthog/http-request {- url: "https://api.incident.io/v2/incidents?status_category%5Bone_of%5D=active&page_size=25",- method: "GET",- headers: { "Authorization": "Bearer ${INCIDENT_IO_TOKEN}" }-}+incident_list { status_category: ["active"], page_size: 25 }```-> **URL-encoding note.** incident.io's filter syntax uses square-> brackets (`status_category[one_of]`). The `@posthog/http-request`-> tool runs the URL through strict URI validation, which rejects raw-> `[` / `]` — percent-encode them as `%5B` / `%5D` (as shown above).-> Same rule for any filter param: `?incident_role[one_of]=lead`-> becomes `?incident_role%5Bone_of%5D=lead`.+You can narrow with `query` (a free-text search across incident+names), or enrich each result with `include: ["summary"]` to match on+the summary without a follow-up `incident_show`.If one matches your alert signature (substring match on `name`,-`summary`, or any of the `incident_role_assignments`), mention it-in your reply with the `reference` field (e.g. `INC-42`) so the-human can jump straight to the existing incident. **Don't open a-new one** — the right move is to link.+`summary`, or the role assignments), mention it in your reply with the+`reference` field (e.g. `INC-42`) so the human can jump straight to the+existing incident. **Don't open a new one** — the right move is to link.## Posting a triage update to an incidentThis is the main write you do. Use it when you've finished gatheringevidence and want the hypothesis on the incident timeline (not just-the Slack thread):+the Slack thread). `incident_update` takes a `message` that posts to+the incident channel + timeline:```text-@posthog/http-request {- url: "https://api.incident.io/v2/incidents/01HXYZ.../updates",- method: "POST",- headers: { "Authorization": "Bearer ${INCIDENT_IO_TOKEN}" },- body: {- "incident_id": "01HXYZ...",- "message": "Triage from the SRE bot:\n\n*TL;DR:* ingest 500s correlate with kafka consumer lag (5x baseline since 14:32 UTC).\n\n*Evidence:* error rate 0.2%→4.7% at 14:32; consumer-lag query in PostHog shows lag climbing from 1k→18k msgs on `events-main`; runbook https://runbooks.internal/ingestion-500s names this exact pattern.\n\n*Suggested next step:* scale `events-main` consumer group from 12 → 18 pods. cc @oncall.",- "new_incident_status_id": null,- "severity_id": null- }+incident_update {+ id: "01HXYZ...",+ message: "Triage from the SRE bot:\n\n*TL;DR:* ingest 500s correlate with kafka consumer lag (5x baseline since 14:32 UTC).\n\n*Evidence:* error rate 0.2%→4.7% at 14:32; consumer-lag query in PostHog shows lag climbing from 1k→18k msgs on `events-main`; runbook https://runbooks.internal/ingestion-500s names this exact pattern.\n\n*Suggested next step:* scale `events-main` consumer group from 12 → 18 pods. cc @oncall."}```-Keep `new_incident_status_id` and `severity_id` as `null` unless a-human has explicitly asked you to transition the incident. You-provide information; humans drive status.+Pass **only** `message` — leave `incident_status_id` and `severity_id`+unset unless a human has explicitly asked you to transition the+incident. You provide information; humans drive status.The same content also goes in your Slack reply per`slack-thread-protocol`. Don't pick one over the other — they have@@ -132,18 +109,13 @@ do **two** things:1. Append a row to the `incidents` memory table (as documented in`agent.md`) — this is for **your** future pattern-matching.-2. Post a final update to the incident.io timeline summarising the- root cause + mitigation:+2. Post a final `incident_update` to the incident.io timeline+ summarising the root cause + mitigation:```text-@posthog/http-request {- url: "https://api.incident.io/v2/incidents/01HXYZ.../updates",- method: "POST",- headers: { "Authorization": "Bearer ${INCIDENT_IO_TOKEN}" },- body: {- "incident_id": "01HXYZ...",- "message": "*Resolved.*\n\n*Root cause:* kafka consumer-group `events-main` was under-provisioned after the morning deploy bumped consumer concurrency.\n\n*Mitigation:* scaled the group 12→18 pods; lag drained in 4m; error rate back to baseline by 14:42 UTC.\n\n*Follow-ups:* (1) raise the autoscaler floor for `events-main`; (2) add a pre-deploy check that compares advertised vs configured concurrency."- }+incident_update {+ id: "01HXYZ...",+ message: "*Resolved.*\n\n*Root cause:* kafka consumer-group `events-main` was under-provisioned after the morning deploy bumped consumer concurrency.\n\n*Mitigation:* scaled the group 12→18 pods; lag drained in 4m; error rate back to baseline by 14:42 UTC.\n\n*Follow-ups:* (1) raise the autoscaler floor for `events-main`; (2) add a pre-deploy check that compares advertised vs configured concurrency."}```@@ -164,51 +136,46 @@ scoped:In that case:```text-@posthog/http-request {- url: "https://api.incident.io/v2/incidents",- method: "POST",- headers: { "Authorization": "Bearer ${INCIDENT_IO_TOKEN}" },- body: {- "idempotency_key": "<alert_signature>:<startsAt>",- "name": "<alert name> — auto-opened by SRE bot",- "summary": "<one-paragraph context from the alert>",- "severity_id": "<critical-severity-id-from-config>",- "mode": "real",- "visibility": "public",- "incident_type_id": null- }+incident_create {+ name: "<alert name> — auto-opened by SRE bot",+ summary: "<one-paragraph context from the alert>",+ severity_id: "<critical-severity-id-from-config>"}```Two things to note:-- The `idempotency_key` is critical — without it, retries from the- webhook would duplicate incidents. Derive it deterministically- from the alert signature + start time.-- `severity_id` and `incident_type_id` are organisation-specific- IDs. Read them from `@posthog/memory-read incident-io-config.md`- if that file exists; otherwise reply in Slack with "I would open- an incident but I'm missing the severity-id config" and stop.- Don't guess.+- `incident_create` defaults to **triage** if you omit `severity_id`,+ and **never invent a severity** — only pass `severity_id` when the+ alert is unambiguously critical and you have the org's id. Leaving it+ unset lets a responder set severity when they accept the incident.+- `severity_id` is organisation-specific. Read it from+ `@posthog/memory-read incident-io-config.md` if that file exists;+ otherwise reply in Slack with "I would open an incident but I'm+ missing the severity-id config" and stop. Don't guess.-The very next thing you do after opening is post a Slack reply-linking to the new incident's `permalink`, so humans can take over.+The very next thing you do after opening is post a Slack reply linking+to the new incident (use its `reference`, e.g. `INC-99`), so humans can+take over.## Errors to handle explicitly-- `401 / authentication_error` — `INCIDENT_IO_TOKEN` is wrong or- revoked. Reply in Slack: "incident.io auth failed, someone needs- to rotate `INCIDENT_IO_TOKEN`" and stop.-- `429` — rate-limited. Back off — the next webhook invocation will- retry. Don't loop.-- `validation_error` — your body shape is wrong. Inspect the- `errors[]` array and fix; don't retry blindly with the same body.+- **MCP not connected / tools unavailable** — the `incident-io`+ connection is still the placeholder, or the link was revoked. Reply+ in Slack that incident.io isn't connected for this agent, skip the+ incident.io steps, and continue Slack-only. Don't fail the session.+- A tool call comes back as an error — inspect the message and fix the+ arguments; don't retry blindly with the same shape. If it's a+ validation error (e.g. a missing required field), the response names+ the field — supply it or hand the link back to a human rather than+ resolving catalog IDs yourself.## What you don't do- **You don't add post-mortem actions.** Those are a human'sreflection, not yours. You record what happened; the team- decides what to learn from it.+ decides what to learn from it. (`follow_up_create` exists on the+ MCP, but adding follow-ups is a human call.)- **You don't assign roles.** `incident_lead`, `comms_lead`, etc.are human-to-human assignments.- **You don't change severity.** If you think the severity isdiff --git a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.jsonindex 77d93960d680..c66e0afbafc6 100644--- a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json+++ b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json@@ -150,10 +150,6 @@"allowed_hosts": ["slack.com"]},"SLACK_SIGNING_SECRET",- {- "name": "INCIDENT_IO_TOKEN",- "allowed_hosts": ["api.incident.io"]- },"WEBHOOK_SECRET"],"skills": [@@ -170,7 +166,7 @@{"id": "incident-io-playbook","path": "skills/incident-io-playbook/SKILL.md",- "description": "How to query and update incident.io \u2014 list active incidents, fetch context for an incoming webhook, post triage updates, and (rare) open a new incident. Load when an incident.io webhook fires the agent, when an alert correlates to an active incident, or when recording a resolved outcome."+ "description": "How to work incident.io through its connected MCP \u2014 list active incidents, fetch context for an incoming webhook, post triage updates, and (rare) open a new incident. Load when an incident.io webhook fires the agent, when an alert correlates to an active incident, or when recording a resolved outcome."},{"id": "runbook-memory",@@ -184,5 +180,26 @@"max_wall_seconds": 600},"reasoning": "high",- "mcps": []+ "mcps": [+ {+ "kind": "agent",+ "id": "incident-io",+ "url": "https://mcp.incident.io/mcp",+ "connection": "00000000-0000-0000-0000-000000000000",+ "default_tool_approval": "approve"+ },+ {+ "kind": "principal",+ "id": "posthog",+ "url": "http://localhost:8787/mcp",+ "default_tool_approval": "allow",+ "auth": { "provider": "posthog" }+ }+ ],+ "identity_providers": [+ {+ "kind": "posthog",+ "scopes": ["openid", "profile", "email", "user:read", "query:read", "insight:read", "error_tracking:read"]+ }+ ]}diff --git a/products/agent_platform/services/agents/scripts/build.ts b/products/agent_platform/services/agents/scripts/build.tsindex d6f3f0c49cec..926043db9a13 100644--- a/products/agent_platform/services/agents/scripts/build.ts+++ b/products/agent_platform/services/agents/scripts/build.ts@@ -44,7 +44,7 @@ await build({external: ['pg-native', 'node-rdkafka'],loader: { '.json': 'json', '.sql': 'text' },define: { 'process.env.NODE_ENV': '"production"' },- // CJS deps (pg, node-pg-migrate, jose) call through to a global+ // CJS deps (pg, jose) call through to a global// `require`. ESM has no `require`; banner injects one. `typescript`// (bundled via the janitor's compile-custom-tools) also reaches for// `__filename` / `__dirname`, which ESM doesn't define — shim both fromdiff --git a/products/mcp_store/mcp/tools.yaml b/products/mcp_store/mcp/tools.yamlnew file mode 100644index 000000000000..3580fea88ba8--- /dev/null+++ b/products/mcp_store/mcp/tools.yaml@@ -0,0 +1,80 @@+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.+# The tool list and operation IDs are kept in sync automatically:+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all+#+# To enable a tool, set enabled: true and add required scopes + annotations.+# All other fields (title, description, enrich_url, etc.) are yours to configure.+category: MCP Store+feature: mcp_store+url_prefix: /settings/environment-mcp-servers+ui_apps: {}+tools:+ mcp-connection-tools-list:+ operation: mcp_server_installations_tools_retrieve+ enabled: true+ scopes:+ - project:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List a connection's tools+ description: >+ Load a connected MCP server's live tool catalog by connection `id` (from mcp-connections-list). Returns each+ tool's `tool_name`, `description`, `input_schema`, and `approval_state`. ALWAYS call this to load a+ connection's REAL tool names before curating per-agent MCP tool permissions (an agent's+ `spec.mcps[].tools[]` with `level` / `default_tool_approval`) — never invent or guess tool names from past+ sessions or skill prose.+ mcp-connection-tools-partial-update:+ operation: mcp_server_installations_tools_partial_update+ enabled: false+ mcp-connection-tools-refresh-create:+ operation: mcp_server_installations_tools_refresh_create+ enabled: false+ mcp-connections-authorize-retrieve:+ operation: mcp_server_installations_authorize_retrieve+ enabled: false+ mcp-connections-create:+ operation: mcp_server_installations_create+ enabled: false+ mcp-connections-destroy:+ operation: mcp_server_installations_destroy+ enabled: false+ mcp-connections-install-custom-create:+ operation: mcp_server_installations_install_custom_create+ enabled: false+ mcp-connections-install-template-create:+ operation: mcp_server_installations_install_template_create+ enabled: false+ mcp-connections-list:+ operation: mcp_server_installations_list+ enabled: true+ scopes:+ - project:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List MCP connections+ description: >+ List the MCP servers connected to this project (the "connections"). Each entry returns its `id` (the+ connection id you pass to mcp-connection-tools-list), `display_name`, `url`, and status fields+ (`is_enabled`, `needs_reauth`, `pending_oauth`) plus `tool_count`. Use this to discover which connections+ exist before loading a connection's live tool catalog with mcp-connection-tools-list.+ mcp-connections-partial-update:+ operation: mcp_server_installations_partial_update+ enabled: false+ mcp-connections-proxy-create:+ operation: mcp_server_installations_proxy_create+ enabled: false+ mcp-connections-retrieve:+ operation: mcp_server_installations_retrieve+ enabled: false+ mcp-connections-update:+ operation: mcp_server_installations_update+ enabled: false+ mcp-servers-list:+ operation: mcp_servers_list+ enabled: falsediff --git a/services/mcp/playbooks/authoring-new-agents/SKILL.md b/services/mcp/playbooks/authoring-new-agents/SKILL.mdindex cfbd5f3de283..df9120484d6e 100644--- a/services/mcp/playbooks/authoring-new-agents/SKILL.md+++ b/services/mcp/playbooks/authoring-new-agents/SKILL.md@@ -27,7 +27,7 @@ will throw away.1. discover — what's available, what already exists2. design — write the spec3. create — application + empty draft-4. configure — wire secrets / integrations (punch-out)+4. configure — wire secrets (punch-out)5. write — agent.md, skills, custom tools6. validate — structural check7. freeze + test — sandboxed runs, self-eval@@ -75,8 +75,6 @@ calling any create endpoint. Cover:- **`skills[]`** — usually 0-3 for v0. Plan one per "domain ofknowledge"; don't pre-create skills for ideas the agent mightreach for.-- **`integrations[]`** — list any team-wide OAuth integrations- (e.g. `"slack"`).- **`secrets[]`** — list any per-application keys the agent's toolsread (e.g. `"STRIPE_API_KEY"`). Trigger-required keys are handledseparately — see the note after this list.@@ -157,7 +155,7 @@ If you need to amend the spec on a draft:posthog__agent-applications-revisions-partial-update revision_id=<rid> spec=<json>```-## Phase 4 — configure secrets / integrations+## Phase 4 — configure secretsFor each item in `spec.secrets[]`, you cannot accept the valuedirectly. Load the `secrets-and-integrations` playbook and follow the@@ -170,11 +168,6 @@ endpoint refuses if any are missing; catch them here so the userisn't surprised at the end. See the `secrets-and-integrations` playbook→ "Trigger-required secrets" for the registry + punch-out flow.-For each item in `spec.integrations[]`, check whether the team-already has that integration installed. If not, tell the user to-install it from the PostHog integrations UI — you can't do this-for them.-When the new agent must call PostHog or a third-party API as theuser, load the `authenticating-as-the-user` playbook to wire its identityprovider + scopes.diff --git a/services/mcp/playbooks/platform-mental-model/SKILL.md b/services/mcp/playbooks/platform-mental-model/SKILL.mdindex edc760a3ebfc..bcdc10017718 100644--- a/services/mcp/playbooks/platform-mental-model/SKILL.md+++ b/services/mcp/playbooks/platform-mental-model/SKILL.md@@ -44,8 +44,6 @@ the revision row. It declares:- `mcps[]` — runtime MCP servers the agent connects to at sessionstart (these expose remote tools)- `skills[]` — markdown skills the model can load on demand-- `integrations[]` — team-level integrations the agent expects- (e.g. `slack`)- `secrets[]` — names of encrypted env keys the agent uses- `limits` — per-session caps (`max_turns`, `max_tool_calls`,`max_wall_seconds`)@@ -148,15 +146,30 @@ The skill body is in the bundle at the declared `path`. Skills canbe short (a few hundred lines) because the platform pays for themonly when loaded. Push depth into skills, keep `agent.md` lean.-## Secrets vs integrations+Store skills are canonical. To edit a skill's body, use `skill-update`+(PATCH) and manage its bundled files with `skill-file-create` /+`skill-file-delete` / `skill-file-rename` — the inline+`skills/<id>/SKILL.md` you see in a revision's bundle is a snapshot,+not the editable source. Reference a store skill from a revision with+`agent-applications-revisions-skill-refs-set`; browse and read store+skills via `skill-list` / `skill-get`.++## Secrets and remote credentials- **Secrets** (`spec.secrets[]`) are per-application encrypted envvalues the agent uses (e.g. a specific Stripe API key). Set viathe punch-out flow — you never see the value.-- **Integrations** (`spec.integrations[]`) are team-wide OAuth- connections (e.g. `slack`). Resolved at session start from the- team's integration table. You don't issue them; the team- installs them via the PostHog integrations UI.+- For a remote service the agent talks to, connect an MCP server and+ reference it with `mcps[].connection` (one shared credential the+ owner connects once), or wire an `identity_providers[]` entry for+ per-asker OAuth. There is no team-wide `integrations[]` spec field.++When you curate a connection-based MCP's per-agent tool permissions+(`spec.mcps[].tools[].level` + `default_tool_approval`), FIRST call+`mcp-connection-tools-list` with the connection id (discover ids via+`mcp-connections-list`) to load that connection's REAL tool names.+Never guess tool names from a past session or from skill prose — the+catalog is the only authority for what the server actually exposes.## Revisions vs sessions — the lifetime distinctiondiff --git a/services/mcp/playbooks/secrets-and-integrations/SKILL.md b/services/mcp/playbooks/secrets-and-integrations/SKILL.mdindex b44e7cf18952..07e92d2fa837 100644--- a/services/mcp/playbooks/secrets-and-integrations/SKILL.md+++ b/services/mcp/playbooks/secrets-and-integrations/SKILL.md@@ -225,20 +225,17 @@ The only exception is when the user has explicitly told you tothe value — set it once and we'll rotate it after"), and eventhen warn them about the trace before complying.-## Setting an integration--For systems that DO use team integrations (not Slack), you don't-set them — the team admin does, via PostHog's integrations UI.-You can:--- Check whether an integration is installed by reading the team's- integrations from PostHog. (No dedicated MCP tool for this today- — surface as a known gap, ask the user to confirm in the UI.)-- Reference an integration in `spec.integrations[]`. The runner- resolves it at session start.-- Tell the user "this agent needs an X integration on this team; an- admin can install it at <link>" — the link is a PostHog URL the- user follows manually.+## Connecting a third-party service++There is no `spec.integrations[]` field. For a third-party service+the agent should call:++- **MCP server** — connect it once (OAuth/DCR or api-key) and+ reference it with `mcps[].connection`; every asker of the agent+ shares that one owner-connected credential.+- **Per-asker OAuth** — wire an `identity_providers[]` entry plus an+ `auth.provider` on the MCP/tool so each asker authenticates as+ themselves. See `skills/authenticating-as-the-user`.> Slack is **not** one of these. Use `SLACK_BOT_TOKEN` +> `SLACK_SIGNING_SECRET` on the agent's `encrypted_env` via thediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 75bcd127a8d6..c4ae1c8ec747 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5525,6 +5525,34 @@"requires_ai_consent": true,"feature_flag": "mcp-analytics"},+ "mcp-connection-tools-list": {+ "description": "Load a connected MCP server's live tool catalog by connection `id` (from mcp-connections-list). Returns each tool's `tool_name`, `description`, `input_schema`, and `approval_state`. ALWAYS call this to load a connection's REAL tool names before curating per-agent MCP tool permissions (an agent's `spec.mcps[].tools[]` with `level` / `default_tool_approval`) — never invent or guess tool names from past sessions or skill prose.",+ "category": "MCP Store",+ "feature": "mcp_store",+ "summary": "List a connection's tools",+ "title": "List a connection's tools",+ "required_scopes": ["project:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "mcp-connections-list": {+ "description": "List the MCP servers connected to this project (the \"connections\"). Each entry returns its `id` (the connection id you pass to mcp-connection-tools-list), `display_name`, `url`, and status fields (`is_enabled`, `needs_reauth`, `pending_oauth`) plus `tool_count`. Use this to discover which connections exist before loading a connection's live tool catalog with mcp-connection-tools-list.",+ "category": "MCP Store",+ "feature": "mcp_store",+ "summary": "List MCP connections",+ "title": "List MCP connections",+ "required_scopes": ["project:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"mcp-feedback-submit": {"description": "Submit qualitative feedback about the current MCP workflow, tool result, or product experience. Use this when the available tools worked but the experience was confusing, incomplete, or could be improved.","category": "MCP analytics",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex f2017b9cabac..d04d8d75fd09 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5961,6 +5961,34 @@"requires_ai_consent": true,"feature_flag": "mcp-analytics"},+ "mcp-connection-tools-list": {+ "description": "Load a connected MCP server's live tool catalog by connection `id` (from mcp-connections-list). Returns each tool's `tool_name`, `description`, `input_schema`, and `approval_state`. ALWAYS call this to load a connection's REAL tool names before curating per-agent MCP tool permissions (an agent's `spec.mcps[].tools[]` with `level` / `default_tool_approval`) — never invent or guess tool names from past sessions or skill prose.",+ "category": "MCP Store",+ "feature": "mcp_store",+ "summary": "List a connection's tools",+ "title": "List a connection's tools",+ "required_scopes": ["project:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "mcp-connections-list": {+ "description": "List the MCP servers connected to this project (the \"connections\"). Each entry returns its `id` (the connection id you pass to mcp-connection-tools-list), `display_name`, `url`, and status fields (`is_enabled`, `needs_reauth`, `pending_oauth`) plus `tool_count`. Use this to discover which connections exist before loading a connection's live tool catalog with mcp-connection-tools-list.",+ "category": "MCP Store",+ "feature": "mcp_store",+ "summary": "List MCP connections",+ "title": "List MCP connections",+ "required_scopes": ["project:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"mcp-feedback-submit": {"description": "Submit qualitative feedback about the current MCP workflow, tool result, or product experience. Use this when the available tools worked but the experience was confusing, incomplete, or could be improved.","category": "MCP analytics",diff --git a/services/mcp/src/generated/mcp_store/api.ts b/services/mcp/src/generated/mcp_store/api.tsnew file mode 100644index 000000000000..de06d72a665d--- /dev/null+++ b/services/mcp/src/generated/mcp_store/api.ts@@ -0,0 +1,31 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * MCP service uses these Zod schemas for generated tool handlers.+ * To regenerate: hogli build:openapi+ *+ * PostHog API - MCP 2 enabled ops+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++export const McpServerInstallationsListParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const McpServerInstallationsListQueryParams = /* @__PURE__ */ zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++export const McpServerInstallationsToolsRetrieveParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this mcp server installation.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.tsindex c1854e47e4e8..723913250dd0 100644--- a/services/mcp/src/tools/generated/index.ts+++ b/services/mcp/src/tools/generated/index.ts@@ -31,6 +31,7 @@ import { GENERATED_TOOLS as integrations } from './integrations'import { GENERATED_TOOLS as logs } from './logs'import { GENERATED_TOOLS as marketing_analytics } from './marketing_analytics'import { GENERATED_TOOLS as mcp_analytics } from './mcp_analytics'+import { GENERATED_TOOLS as mcp_store } from './mcp_store'import { GENERATED_TOOLS as metrics } from './metrics'import { GENERATED_TOOLS as notebooks } from './notebooks'import { GENERATED_TOOLS as persons } from './persons'@@ -84,6 +85,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =...logs,...marketing_analytics,...mcp_analytics,+ ...mcp_store,...metrics,...notebooks,...persons,diff --git a/services/mcp/src/tools/generated/mcp_store.ts b/services/mcp/src/tools/generated/mcp_store.tsnew file mode 100644index 000000000000..3615b7095d66--- /dev/null+++ b/services/mcp/src/tools/generated/mcp_store.ts@@ -0,0 +1,55 @@+// AUTO-GENERATED from products/mcp_store/mcp/tools.yaml + OpenAPI — do not edit+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import {+ McpServerInstallationsListQueryParams,+ McpServerInstallationsToolsRetrieveParams,+} from '@/generated/mcp_store/api'+import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'++const McpConnectionToolsListSchema = McpServerInstallationsToolsRetrieveParams.omit({ project_id: true })++const mcpConnectionToolsList = (): ToolBase<+ typeof McpConnectionToolsListSchema,+ WithPostHogUrl<Schemas.PaginatedMCPServerInstallationToolList>+> => ({+ name: 'mcp-connection-tools-list',+ schema: McpConnectionToolsListSchema,+ handler: async (context: Context, params: z.infer<typeof McpConnectionToolsListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedMCPServerInstallationToolList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/mcp_server_installations/${encodeURIComponent(String(params.id))}/tools/`,+ })+ return await withPostHogUrl(context, result, '/settings/environment-mcp-servers')+ },+})++const McpConnectionsListSchema = McpServerInstallationsListQueryParams++const mcpConnectionsList = (): ToolBase<+ typeof McpConnectionsListSchema,+ WithPostHogUrl<Schemas.PaginatedMCPServerInstallationList>+> => ({+ name: 'mcp-connections-list',+ schema: McpConnectionsListSchema,+ handler: async (context: Context, params: z.infer<typeof McpConnectionsListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedMCPServerInstallationList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/mcp_server_installations/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ return await withPostHogUrl(context, result, '/settings/environment-mcp-servers')+ },+})++export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'mcp-connection-tools-list': mcpConnectionToolsList,+ 'mcp-connections-list': mcpConnectionsList,+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/mcp-connection-tools-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/mcp-connection-tools-list.jsonnew file mode 100644index 000000000000..390d848ce3cb--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/mcp-connection-tools-list.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this mcp server installation.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/mcp-connections-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/mcp-connections-list.jsonnew file mode 100644index 000000000000..8331b796ac73--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/mcp-connections-list.json@@ -0,0 +1,14 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "limit": {+ "description": "Number of results to return per page.",+ "type": "number"+ },+ "offset": {+ "description": "The initial index from which to return the results.",+ "type": "number"+ }+ },+ "type": "object"+}