: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
fix(agent-platform): require and preserve builder user auth (#72027)
Dylan Martinda1bd5289e4c
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts b/products/agent_platform/services/agent-ingress/src/triggers/mcp.tsindex d6264a11ca69..b77097481fe3 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/mcp.ts@@ -213,13 +213,23 @@ async function mcpHandler(ctx: CustomAuthRouteCtx): Promise<void> {res.json(errReply(RPC_UNAUTHORIZED, JSON.stringify(buildElevationResponse(existing, elevationReq))))return}- await deps.queue.appendPendingInput(continuationId, {- role: 'user',- content: message,- timestamp: Date.now(),- sender: principal,- })- await deps.queue.update(continuationId, { state: 'queued' })+ const credentialWrite = await deps.broker.writeWithRollback(continuationId, auth.credentials)+ try {+ await deps.queue.appendPendingInput(continuationId, {+ role: 'user',+ content: message,+ timestamp: Date.now(),+ sender: principal,+ })+ await deps.queue.update(continuationId, { state: 'queued' })+ } catch (err) {+ try {+ await credentialWrite.rollback()+ } catch (rollbackError) {+ throw new AggregateError([err, rollbackError], 'credential rollback failed')+ }+ throw err+ }res.json(reply({content: [@@ -246,6 +256,7 @@ async function mcpHandler(ctx: CustomAuthRouteCtx): Promise<void> {principal: principal,trigger: 'mcp',requesterDisplay: principalDisplay(principal),+ prepareSession: (sessionId) => deps.broker.writeWithRollback(sessionId, auth.credentials),})if (freshOutcome.kind === 'elevation_required') {diff --git a/products/agent_platform/services/agent-ingress/src/triggers/types.ts b/products/agent_platform/services/agent-ingress/src/triggers/types.tsindex db3bc0c68569..e0f696681660 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/types.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/types.ts@@ -58,7 +58,7 @@ export interface TriggerDeps {*/approvals?: ApprovalStore/**- * Per-session credential broker. Chat trigger consumes it on /run + /send;+ * Per-session credential broker. Chat and MCP triggers persist caller credentials before queueing;* other triggers ignore it. Required — prod wires `PgCredentialBroker`,* tests wire the same against the test DB.*/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 9ff7b298a3fc..21f4b9ba5bf7 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@@ -46,7 +46,8 @@ type ToolRefInput = z.input<typeof ToolRefSchema>function makeRev(toolRefs: ToolRefInput[],skills: AgentRevision['spec']['skills'] = [],- mcps: McpRef[] = []+ mcps: McpRef[] = [],+ identityProviders: AgentRevision['spec']['identity_providers'] = []): AgentRevision {return {id: 'rev1',@@ -57,7 +58,13 @@ function makeRev(state: 'live',bundle_uri: 's3://',bundle_sha256: null,- spec: AgentSpecSchema.parse({ model: 'test/x', tools: toolRefs, skills, mcps }),+ spec: AgentSpecSchema.parse({+ model: 'test/x',+ tools: toolRefs,+ skills,+ mcps,+ identity_providers: identityProviders,+ }),encrypted_env: null,}}@@ -202,14 +209,14 @@ describe('buildAgentTools', () => {expect(withSkills.tools.map((t) => t.label)).toContain('@posthog/load-skill')})- it('auto-includes @posthog/identity-connect when the agent has a linkable identity', async () => {+ it('auto-includes @posthog/identity-connect only for declared linkable identities', async () => {// No identity surface → no connect tool (it would just error on use).const none = await buildAgentTools(makeRev([]), makeDeps(makeRev([])))expect(none.tools.map((t) => t.label)).not.toContain('@posthog/identity-connect')- // An MCP that authenticates through a provider makes connect available so- // the agent can hand the user a (re)link on demand.- const rev = makeRev(+ // An MCP can use the implicit seed-only PostHog provider. It authenticates+ // from the trigger bearer and deliberately has no OAuth connect flow.+ const seedOnly = makeRev([],[],[@@ -223,8 +230,14 @@ describe('buildAgentTools', () => {},])- const built = await buildAgentTools(rev, makeDeps(rev))- expect(built.tools.map((t) => t.label)).toContain('@posthog/identity-connect')+ const seedOnlyBuilt = await buildAgentTools(seedOnly, makeDeps(seedOnly))+ expect(seedOnlyBuilt.tools.map((t) => t.label)).not.toContain('@posthog/identity-connect')++ const linkable = makeRev([], [], seedOnly.spec.mcps, [+ { kind: 'posthog', id: 'posthog', scopes: ['user:read'], binding: 'principal' },+ ])+ const linkableBuilt = await buildAgentTools(linkable, makeDeps(linkable))+ expect(linkableBuilt.tools.map((t) => t.label)).toContain('@posthog/identity-connect')})describe('@posthog/web-search gating', () => {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 b001de12975c..c500fa868c21 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@@ -220,10 +220,10 @@ export async function buildAgentTools(rev: AgentRevision, deps: AgentToolDeps):alwaysOn.push('@posthog/load-skill')}// `@posthog/identity-connect` lets the agent mint a connect/reconnect link on- // demand — included whenever the agent has any linkable identity (declared- // providers, or an MCP that authenticates through one), so the agent can hand- // the user a link proactively instead of only after a tool/MCP auth failure.- if (rev.spec.identity_providers.length > 0 || rev.spec.mcps.some((m) => m.auth?.provider)) {+ // demand. Only declared providers are linkable: an MCP can reference the+ // implicit seed-only PostHog provider used by chat/MCP trigger passthrough,+ // and offering a reconnect flow for that provider is both useless and wrong.+ if (rev.spec.identity_providers.length > 0) {alwaysOn.push('@posthog/identity-connect')}const all = [...alwaysOn.map((id) => ({ kind: 'native' as const, id })), ...rev.spec.tools]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 cd594afa8e45..16eae9821233 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@@ -653,16 +653,16 @@ describe('driver runSession', () => {expect(rows[0].state).toBe('queued')})- // ── Proxy-mode gating (large connection: >40 tools → helper tools) ──+ // ── Proxy-mode gating (large connection: >50 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`+ // the `call_tool` args. Build a 52-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++) {+ for (let i = 0; i < 52; i++) {tools[`tool_${i}`] = { description: `tool ${i}`, result: { ok: true } }}return toolsdiff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.tsindex f62625ca45d5..8ddf182f8f01 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts@@ -303,6 +303,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps// language instead of calling a slack tool).const slackReply = session.trigger_metadata?.kind === 'slack' ? session.trigger_metadata : nullconst system = await buildSystemPrompt(rev, deps.bundle, {+ availableMcps: (deps.mcpClients ?? []).map((client) => client.prefix),unavailableMcps: (deps.mcpFailures ?? []).map((f) => ({id: f.ref.id,category: f.category,diff --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 5c867b9cfa9b..816049c146e8 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@@ -291,6 +291,7 @@ describe('openMcpClients', () => {secrets: {},transportFactory: factory,identity: { resolve },+ linkableProviders: new Set(['github']),})expect(clients).toEqual([])expect(failures[0].category).toBe('auth')@@ -302,6 +303,37 @@ describe('openMcpClients', () => {await closePairs(pairs)})+ it('does not advertise a seed-only provider auth failure as reconnectable', async () => {+ const { factory, pairs } = await buildEchoFactory()+ const refs: McpRef[] = [+ {+ kind: 'principal',+ default_tool_approval: 'allow',+ id: 'posthog',+ url: 'https://example.com/mcp',+ secrets: [],+ auth: { provider: 'posthog' },+ },+ ]+ const { clients, failures, close } = await openMcpClients(refs, {+ secrets: {},+ transportFactory: factory,+ identity: {+ resolve: async () => ({+ kind: 'unavailable',+ provider: 'posthog',+ reason: 'identity_not_connected',+ }),+ },+ linkableProviders: new Set(),+ })+ expect(clients).toEqual([])+ expect(failures[0].category).toBe('auth')+ expect(failures[0].provider).toBeUndefined()+ await close()+ await closePairs(pairs)+ })+it('auth.provider linked-but-rejected does not initiate reconnect during startup', async () => {const failingFactory: McpTransportFactory = () =>({@@ -326,6 +358,7 @@ describe('openMcpClients', () => {const { clients, failures } = await openMcpClients(refs, {secrets: {},transportFactory: failingFactory,+ linkableProviders: new Set(['posthog']),identity: {resolve: async () => ({kind: 'ok',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 939ab030e034..5ce9f5e1c753 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@@ -223,6 +223,10 @@ export interface OpenMcpClientsDeps {identity?: {resolve(provider: string, scopes?: string[], options?: { initiate?: boolean }): Promise<IdentityResolution>}+ /** Provider ids backed by declared, linkable `identity_providers[]` entries.+ * Auth failures for implicit seed-only providers must not be advertised as+ * repairable through `@posthog/identity-connect`. */+ linkableProviders?: ReadonlySet<string>/*** Agent-level shared-credential resolver (`ref.connection` → a native* `mcp_store` installation), team-bound by the worker. Returns the upstream@@ -303,7 +307,10 @@ export async function openMcpClients(ref,category,devReason: err.message,- provider: category === 'auth' ? ref.auth?.provider : undefined,+ provider:+ category === 'auth' && ref.auth?.provider && deps.linkableProviders?.has(ref.auth.provider)+ ? ref.auth.provider+ : undefined,})log('warn', 'mcp.open.failed', { prefix: ref.id, category, devReason: err.message })}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.tsindex 6d2a0846f5bc..7603f018902b 100644--- 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.ts@@ -22,6 +22,7 @@ function makeCatalog(count: number, schemaFields: number, descWords: number): Reconst richCatalog = makeCatalog(600, 50, 6) // ~3M serialized charsconst smallCatalog = makeCatalog(38, 4, 3)+const agentBuilderCatalog = makeCatalog(47, 4, 3)describe('MCP exposure decision', () => {it('a rich surface exceeds the budget → proxy', () => {@@ -43,6 +44,12 @@ describe('MCP exposure decision', () => {expect(decideMcpExposure(richCatalog.slice(0, 10)).mode).toBe('inline')})+ it('the Agent Builder-sized curated surface stays inline', () => {+ const decision = decideMcpExposure(agentBuilderCatalog)+ expect(decision.mode).toBe('inline')+ expect(decision.reasons).toEqual([])+ })+it('proxying collapses the surface to ~constant cost regardless of N', () => {const PROXY_BLOCK_CHARS = 2_000expect(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.tsindex f7da38d552db..169fd4d96b82 100644--- 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.ts@@ -12,9 +12,9 @@ export interface McpExposureBudget {maxInlineChars: number}-/** incident.io (38 tools, ~85k chars) stays inline; the PostHog MCP (603, ~2.7M) proxies. */+/** Curated catalogs up to 50 tools stay inline; the PostHog MCP (603 tools, ~2.7M chars) proxies. */export const DEFAULT_MCP_EXPOSURE_BUDGET: McpExposureBudget = {- maxInlineTools: 40,+ maxInlineTools: 50,maxInlineChars: 100_000,}diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.ts b/products/agent_platform/services/agent-runner/src/workers/worker.tsindex 4af6cbb9a6b6..8dbb2a42979c 100644--- a/products/agent_platform/services/agent-runner/src/workers/worker.ts+++ b/products/agent_platform/services/agent-runner/src/workers/worker.ts@@ -523,6 +523,7 @@ export class Worker {secretAllowedHosts: (name) => getSecretAllowedHosts(rev.spec, name),transportFactory: this.deps.mcpTransportFactory,identity: mcpIdentity,+ linkableProviders: new Set(rev.spec.identity_providers.map((provider) => provider.id)),connections: mcpConnections,devMcpBearerToken: this.deps.devMcpBearerToken,log: (level, msg, meta) => sLog[level](meta ?? {}, msg),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 83bb55a2e57d..f5424565cb1c 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,19 @@ describe('buildSystemPrompt', () => {expect(prompt).toMatch(/do NOT paste raw error messages/)})+ it('identifies MCPs that opened successfully', async () => {+ await bundle.write('rev1', 'agent.md', 'x')+ const spec = AgentSpecSchema.parse({ model: 'test/x' })+ const prompt = await buildSystemPrompt(makeRev(spec), bundle, {+ availableMcps: ['posthog'],+ })++ expect(prompt).toContain('Connected MCP servers')+ expect(prompt).toContain('- `posthog`')+ expect(prompt).toMatch(/opened successfully/)+ expect(prompt).toMatch(/Do not claim.*disconnected/)+ })+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' })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 f265618dbe66..9e6c5d370c74 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@@ -37,6 +37,10 @@ export interface UnavailableMcp {}export interface BuildSystemPromptOpts {+ /** MCP refs that opened successfully for this session. Positive runtime+ * state keeps the model from guessing connection status from its own+ * imperfect recollection of the tool declarations. */+ availableMcps?: readonly string[]/*** MCP refs that failed to open for this session. Rendered as a brief* "unavailable capabilities" section so the model can shape its reply@@ -94,6 +98,21 @@ export async function buildSystemPrompt(parts.push(lines.join('\n'))}+ const available = opts.availableMcps ?? []+ if (available.length > 0) {+ const lines = ['\n\n---\n\n## Connected MCP servers', '']+ lines.push('These MCP servers opened successfully for this session:')+ lines.push('')+ for (const id of available) {+ lines.push(`- \`${id}\``)+ }+ lines.push('')+ lines.push(+ 'Their tools allowed by the agent spec are callable. Do not claim one of these servers is disconnected based on whether you can enumerate or recall every tool declaration. Only a server listed under an unavailable-capabilities section failed to open.'+ )+ parts.push(lines.join('\n'))+ }+const unavailable = opts.unavailableMcps ?? []// Shared connections need an owner/admin to reconnect them. Principal auth// failures retain provider metadata for a later explicit connect action;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 fbe0b90a88ef..8a8e78c79b82 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@@ -2,7 +2,7 @@* Example bundle wiring check — `services/agent-tests/src/examples/agent-builder/`.** The Agent Builder authors + operates other agents through the PostHog MCP- * (one `spec.mcps[]` entry authed by the `posthog` identity provider), acting+ * (one `spec.mcps[]` entry authed by the trigger-edge PostHog bearer), acting* as the asking user. 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[]`@@ -13,16 +13,23 @@* Faux net — wiring, not inference quality.*/+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'+import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'import { execFile } from 'node:child_process'import { cp, mkdir, mkdtemp, readdir, readFile, rm } from 'node:fs/promises'import { tmpdir } from 'node:os'import { dirname, join, resolve } from 'node:path'import { fileURLToPath } from 'node:url'import { promisify } from 'node:util'+import request from 'supertest'+import type { McpTransportFactory } from '@posthog/agent-runner'import { AgentSpecSchema } from '@posthog/agent-shared'import { listNativeTools } from '@posthog/agent-tools'+import { buildCluster, closeSharedPool, Cluster, fakeAuthProvider, fauxText } from '../harness'+const __dirname = dirname(fileURLToPath(import.meta.url))const BUNDLE_ROOT = resolve(__dirname, '../examples/agent-builder')const execFileAsync = promisify(execFile)@@ -58,14 +65,20 @@ describe('example: agent-builder bundle', () => {expect(files['agent.md'].length).toBeGreaterThan(500)})- it('authors via ONE PostHog MCP authed by the posthog identity provider', async () => {- const { spec } = await loadBundle()+ it('authors through one direct-tools PostHog MCP authed by the trigger-edge bearer', async () => {+ const { spec, files } = await loadBundle()const parsed = AgentSpecSchema.parse(spec)expect(parsed.mcps).toHaveLength(1)expect(parsed.mcps[0].id).toBe('posthog')expect(parsed.mcps[0].auth?.provider).toBe('posthog')+ // Unknown MCP clients default to the single `exec` tool. The builder+ // allow-lists direct authoring operations, so it must request tools mode.+ expect(parsed.mcps[0].headers?.['x-posthog-mcp-mode']).toBe('tools')// The curated allow-list keeps the surface to authoring + data tools.expect(parsed.mcps[0].tools?.length ?? 0).toBeGreaterThan(20)+ expect(files['agent.md']).toContain('top-level `posthog__<name>` tools')+ expect(files['agent.md']).toContain('There is no `posthog__call_tool`')+ expect(files['agent.md']).not.toContain('pass them to `call_tool`')})it('keeps only its own runtime natives (memory + web-search) — no native agent-applications tools', async () => {@@ -94,15 +107,20 @@ describe('example: agent-builder bundle', () => {expect(types).not.toContain('slack')})- it('declares a posthog identity provider with the scopes authoring needs', async () => {- const { spec } = await loadBundle()+ it('uses trigger-edge PostHog auth without provisioning a second OAuth connection', async () => {+ const { spec, files } = await loadBundle()const parsed = AgentSpecSchema.parse(spec)- const posthog = parsed.identity_providers.find((p) => p.kind === 'posthog')- expect(posthog).not.toBeUndefined()- const scopes = posthog?.scopes ?? []- // user:read backs the MCP's /api/users/@me/ bootstrap; agents:write backs- // authoring other agents. Both are load-bearing — pin them.- expect(scopes).toEqual(expect.arrayContaining(['user:read', 'agents:read', 'agents:write']))+ // PostHog Code already seeds `posthog_api` from trigger auth. An empty+ // list selects the implicit seed-only provider instead of offering a+ // redundant OAuth connection that cannot improve the session identity.+ expect(parsed.identity_providers).toEqual([])+ const chat = parsed.triggers.find((trigger) => trigger.type === 'chat')+ const posthogMode = chat?.type === 'chat' ? chat.auth?.modes.find((mode) => mode.type === 'posthog') : undefined+ expect(posthogMode?.type === 'posthog' ? posthogMode.scopes : []).toEqual(+ expect.arrayContaining(['agents:read', 'agents:write', 'agent_session:read'])+ )+ expect(files['agent.md']).toContain('Never ask the user to connect or reconnect PostHog')+ expect(files['agent.md']).toMatch(/Never claim\s+the PostHog MCP is disconnected/)})it('declares the client tools the console UI implements', async () => {@@ -125,15 +143,139 @@ describe('example: agent-builder bundle', () => {])})- it('tries the user PostHog bearer before the internal fallback', async () => {+ it('requires the user PostHog bearer on both entrypoints', async () => {const { spec } = await loadBundle()const parsed = AgentSpecSchema.parse(spec)const modesFor = (type: string): string[] => {const t = parsed.triggers.find((x) => x.type === type)return t && 'auth' in t && t.auth ? (t.auth.modes?.map((m) => m.type) ?? []) : []}- expect(modesFor('chat')).toEqual(['posthog', 'posthog_internal'])- expect(modesFor('mcp')).toEqual(['posthog', 'posthog_internal'])+ expect(modesFor('chat')).toEqual(['posthog'])+ expect(modesFor('mcp')).toEqual(['posthog'])+ })++ describe('entrypoint auth behavior', () => {+ const userBearer = 'phx_builder_user'+ const internalSecret = 'builder-internal-secret'+ let cluster: Cluster+ let mcpTargets: Array<{ url: string; headers: Record<string, string> }>++ beforeEach(async () => {+ mcpTargets = []+ const mcpTransportFactory: McpTransportFactory = (target): Transport => {+ mcpTargets.push(target)+ const server = new McpServer({ name: 'posthog', version: '1.0.0' })+ server.registerTool(+ 'agent-applications-list',+ { description: 'List agents', inputSchema: {} },+ async () => ({ content: [{ type: 'text' as const, text: JSON.stringify({ results: [] }) }] })+ )+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair()+ void server.server.connect(serverTransport)+ return clientTransport+ }+ cluster = await buildCluster({+ authProvider: fakeAuthProvider({ posthog: userBearer, internal: internalSecret }),+ mcpTransportFactory,+ })+ cluster.setScript([fauxText('ready')])+ })++ afterEach(async () => {+ if (cluster) {+ await cluster.teardown()+ }+ })++ afterAll(async () => {+ await closeSharedPool()+ })++ it('rejects service-only auth and opens the nested MCP in direct tools mode', async () => {+ const { spec, files } = await loadBundle()+ await cluster.deployAgent({ slug: 'agent-builder-auth', spec, files })++ const internalChat = await request(cluster.ingress)+ .post('/agents/agent-builder-auth/run')+ .set('x-posthog-internal', internalSecret)+ .send({ message: 'create an agent' })+ expect(internalChat.status).toBe(401)++ const userChat = await request(cluster.ingress)+ .post('/agents/agent-builder-auth/run')+ .set('authorization', `Bearer ${userBearer}`)+ .send({ message: 'create an agent' })+ expect(userChat.status).toBe(200)+ expect(userChat.body.principal.kind).toBe('posthog')+ await cluster.drain()+ expect(mcpTargets).toHaveLength(1)+ expect(mcpTargets[0].headers.Authorization).toBe(`Bearer ${userBearer}`)++ const internalMcp = await request(cluster.ingress)+ .post('/agents/agent-builder-auth/mcp')+ .set('x-posthog-internal', internalSecret)+ .send({ jsonrpc: '2.0', id: 1, method: 'tools/list' })+ expect(internalMcp.body.error?.code).toBe(-32001)++ const userMcp = await request(cluster.ingress)+ .post('/agents/agent-builder-auth/mcp')+ .set('authorization', `Bearer ${userBearer}`)+ .send({ jsonrpc: '2.0', id: 2, method: 'tools/list' })+ expect(userMcp.body.result?.tools).toEqual(+ expect.arrayContaining([expect.objectContaining({ name: 'ask' })])+ )++ const userMcpCall = await request(cluster.ingress)+ .post('/agents/agent-builder-auth/mcp')+ .set('authorization', `Bearer ${userBearer}`)+ .send({+ jsonrpc: '2.0',+ id: 3,+ method: 'tools/call',+ params: { name: 'ask', arguments: { message: 'create another agent' } },+ })+ expect(userMcpCall.body.error).toBeUndefined()+ await cluster.drain()+ expect(mcpTargets).toHaveLength(2)++ const resumableMcpCall = await request(cluster.ingress)+ .post('/agents/agent-builder-auth/mcp')+ .set('authorization', `Bearer ${userBearer}`)+ .send({+ jsonrpc: '2.0',+ id: 4,+ method: 'tools/call',+ params: { name: 'ask', arguments: { message: 'start editing' } },+ })+ expect(resumableMcpCall.body.error).toBeUndefined()+ const resumableMcpSession = JSON.parse(resumableMcpCall.body.result.content[0].text) as {+ session_id: string+ }+ await cluster.queue.update(resumableMcpSession.session_id, { state: 'running' })+ await cluster.credentialBroker.clear(resumableMcpSession.session_id)+ const userMcpContinuation = await request(cluster.ingress)+ .post('/agents/agent-builder-auth/mcp')+ .set('authorization', `Bearer ${userBearer}`)+ .send({+ jsonrpc: '2.0',+ id: 5,+ method: 'tools/call',+ params: {+ name: 'ask',+ arguments: { message: 'continue editing', session_id: resumableMcpSession.session_id },+ },+ })+ expect(userMcpContinuation.body.error).toBeUndefined()+ await cluster.drain()+ expect(mcpTargets).toHaveLength(3)+ expect(+ mcpTargets.every(+ (target) =>+ target.headers.Authorization === `Bearer ${userBearer}` &&+ target.headers['x-posthog-mcp-mode'] === 'tools'+ )+ ).toBe(true)+ })})it('enables resume so multi-step flows can span days', async () => {diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.mdindex ab60bc66f8c9..9ef8ffd3a5be 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.md@@ -89,33 +89,37 @@ agent-builder/## Auth modelAuth is configured **per trigger** — there is no top-level-`spec.auth`. Each of the Agent Builder's triggers sets-`auth.modes: [posthog, posthog_internal]` (an array), so both entry-points map to the same effective auth:+`spec.auth`. Both Agent Builder entrypoints require the user-scoped+`posthog` mode:1. **PostHog Code** — user signs into the PostHog Code app via- PostHog OAuth; the app mints a short-lived session-principal- token from the OAuth session and attaches it to the chat trigger.- Every tool call runs as the user without a separate MCP connection.+ PostHog OAuth. The app sends that OAuth access token to the chat+ trigger. Every tool call runs as the user without a separate MCP+ sign-in.2. **MCP** — user attaches their PostHog PAT in their MCP clientconfig. The runner resolves the PAT to a principal once atsession start, threads it through identically.The Agent Builder holds no fallback credential.-Mode order is load-bearing. `posthog` must remain first so a request carrying-the signed-in user's bearer resolves the user-scoped `posthog_api` credential.-`posthog_internal` is only the trusted service fallback and does not supply a-user credential for MCP calls.+The Agent Builder accepts only `posthog` auth on both chat and MCP entrypoints.+For chat, PostHog Code sends the signed-in user's OAuth bearer on `/run` and+`/send`; ingress validates it and stores it as the session's `posthog_api`+credential. The runner forwards that same bearer to the first-party MCP, so+there is no second interactive OAuth flow. A browser session cookie cannot be+forwarded to the MCP host, and `posthog_internal` authenticates only a service+call, not the asking user. Allowing that mode on either entrypoint could create+a session without the user credential required by the nested authoring MCP, so+the bundle fails closed instead.The PostHog MCP is a first-party implementation detail of the builder, not a-connection the user configures. MCP startup only reuses an existing trigger or-linked credential; it never starts OAuth or reconnects automatically. The-identity-connect tool remains available for agents that intentionally support-account linking, but startup never invokes it.+connection the user configures. The Builder does not declare a PostHog identity+provider. Its MCP resolves the trigger-edge `posthog_api` credential through the+platform's seed-only PostHog provider, so there is no account-linking path and no+second OAuth flow.The Agent Builder chat therefore does not use the ingress OAuth callback route.-PostHog Code supplies the signed-in user's short-lived bearer at the trigger+PostHog Code supplies the signed-in user's OAuth access token at the triggeredge, and the runner passes that credential to the first-party MCP. The`/link/<provider>/callback` flow exists for agents that intentionally supportconnecting an additional identity.@@ -134,7 +138,7 @@ These are platform-side, not bundle-side — and they're in place:`set_secret` entries parse and validate.2. **Runtime MCP support** — the runner opens the clients declared in`spec.mcps` at session start. (The Agent Builder declares exactly- one — the PostHog MCP, authed by the `posthog` identity provider —+ one — the PostHog MCP, authed by the trigger-edge PostHog bearer —which carries its whole authoring surface.)3. **OAuth principal threading** — the session principal threadsthrough every tool call, so writes attribute to the user.@@ -177,10 +181,9 @@ agent-applications-revisions-promote-create revision_id=<rid>The Agent Builder lives in **PostHog's primary org** so it'savailable to every team via the standard MCP / chat ingress. Each-trigger's `auth.modes: [posthog, posthog_internal]` means it's not-callable as a random external bot — only PostHog Code's signed-session-principal token (`posthog_internal`) + verified user PATs-(`posthog`) get through.+trigger's `auth.modes: [posthog]` means every request must carry a+verified user credential. PostHog Code supplies the user's OAuth+access token to chat; standalone MCP clients supply a user PAT.## Regression test@@ -197,6 +200,8 @@ loads the bundle from disk and asserts:- Both `chat` and `mcp` triggers are declared — and NO `slack` trigger(no dedicated Slack app exists, and a slack trigger blocks promoteuntil its required secrets are set)+- Both entrypoints reject service-only `posthog_internal` auth, while+ accepting the user bearer required by the nested authoring MCP- The `kind: "client"` tools (`focus_*`, `toast`, `get_context`,`set_secret`, `connect_mcp`) are present, and the destructive MCPauthoring tools (`promote`, `archive`, `destroy`) are gated withdiff --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 d72f829c7270..fce108188ce3 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@@ -118,9 +118,11 @@ one, refuse and explain why.1. **Act as the asking user — never as PostHog.** Every PostHog MCPcall runs with the asking user's PostHog identity. You holdno fallback credential. In PostHog Code / MCP the bearer passes- through from the trigger (see "Acting as the user"). If a call- returns 403, that is the user's permissions speaking — surface- it, don't work around it.+ through from the trigger (see "Acting as the user").+ Never ask the user to connect or reconnect PostHog for the Builder's+ own MCP. If its tools are absent, report that the authoring capability failed to+ start for this session. If a call returns 403, that is the user's+ permissions speaking — surface it, don't work around it.2. **Never accept raw secrets in chat.** API keys, OAuth tokens,passwords. If the user pastes one, tell them not to and resetthe secret to whatever you'd have used the punch-out flow for.@@ -220,15 +222,14 @@ 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.+The PostHog MCP is pinned to direct-tools mode. Its allowed tools appear as+top-level `posthog__<name>` tools with their argument schemas attached, so call+them directly. There is no `posthog__call_tool`, `posthog__get_tool_schema`, or+`posthog__explore_tools` wrapper in this mode. The runtime's connected and+unavailable MCP sections are authoritative for connection status. Never claim+the PostHog MCP is disconnected based on whether you can enumerate or recall its+tool declarations. The non-PostHog entries below (`@posthog/*` natives, client+tools) are also called directly.| Class | Examples | When you use it || ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |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 4cdc2235270b..13350dcda44a 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@@ -13,9 +13,6 @@"type": "posthog","scopes": ["agents:read", "agents:write", "agent_session:read"],"audience": "organization"- },- {- "type": "posthog_internal"}]}@@ -30,9 +27,6 @@{"type": "posthog","audience": "organization"- },- {- "type": "posthog_internal"}]}@@ -256,6 +250,9 @@"auth": {"provider": "posthog"},+ "headers": {+ "x-posthog-mcp-mode": "tools"+ },"default_tool_approval": "deny","tools": [{ "name": "agent-applications-list", "level": "allow" },@@ -320,21 +317,7 @@]}],- "identity_providers": [- {- "kind": "posthog",- "scopes": [- "openid",- "profile",- "email",- "user:read",- "agents:read",- "agents:write",- "query:read",- "insight:read"- ]- }- ],+ "identity_providers": [],"secrets": [],"limits": {"max_turns": 80,