: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): seed chat credentials before queueing (#71781)
Dylan Martin1b7d6e0ad4cd
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.tsindex 3c033dcc4275..c703264a5c0a 100644--- a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts+++ b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.test.ts@@ -364,6 +364,7 @@ describe('enqueueOrResume', () => {seed: { role: 'user', content: 'first', timestamp: 1 },})+ const prepareSession = vi.fn(async () => ({ rollback: async (): Promise<void> => undefined }))const second = await enqueueOrResume({ queue },{@@ -373,17 +374,53 @@ describe('enqueueOrResume', () => {idempotencyKey: 'k1',// Deliberately different seed to prove it's discarded.seed: { role: 'user', content: 'second', timestamp: 2 },+ prepareSession,})expect(second.sessionId).toBe(first.sessionId)expect(second.kind).toBe('created')expect(second.isResume).toBe(false)+ expect(prepareSession).not.toHaveBeenCalled()// The first call's seed is preserved; the duplicate's seed is dropped.const session = await queue.get(first.sessionId)expect(session!.conversation).toHaveLength(1)expect((session!.conversation[0] as { content: string }).content).toBe('first')})+ it('does not prepare an existing session for a different principal', async () => {+ const queue = new PgSessionQueue(pool)+ const { app, rev } = makePair()+ const first = await enqueueOrResume(+ { queue },+ {+ application: app,+ revision: rev,+ externalKey: null,+ idempotencyKey: 'principal-bound',+ principal: ALICE,+ seed: { role: 'user', content: 'first', timestamp: 1, sender: ALICE },+ }+ )+ const prepareSession = vi.fn(async () => ({ rollback: async (): Promise<void> => undefined }))++ const replay = await enqueueOrResume(+ { queue },+ {+ application: app,+ revision: rev,+ externalKey: null,+ idempotencyKey: 'principal-bound',+ principal: BOB,+ seed: { role: 'user', content: 'replay', timestamp: 2, sender: BOB },+ prepareSession,+ }+ )++ expect(replay.kind).toBe('elevation_required')+ expect(replay.sessionId).toBe(first.sessionId)+ expect(prepareSession).not.toHaveBeenCalled()+ })+it('stamps trigger_metadata on the session row when supplied', async () => {const queue = new PgSessionQueue(pool)const { app, rev } = makePair()diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.tsindex 87ba59534e93..29aac2bba708 100644--- a/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts+++ b/products/agent_platform/services/agent-ingress/src/enqueue/enqueue.ts@@ -26,6 +26,7 @@ import { randomUUID } from 'crypto'import {AgentApplication,AgentRevision,+ AgentSession,ConversationMessage,EMPTY_USAGE_TOTAL,SessionPrincipal,@@ -40,6 +41,10 @@ export interface EnqueueDeps {queue: SessionQueue}+export interface SessionPreparation {+ rollback(): Promise<void>+}+export interface EnqueueInput {application: AgentApplicationrevision: AgentRevision@@ -66,8 +71,9 @@ export interface EnqueueInput {** If a session with this key already exists, this call no-ops and* returns `{ kind: 'created', isResume: false }` with the original- * session id. The principal + seed message of the duplicate request- * are discarded — same shape Stripe's idempotency contract follows.+ * session id. The principal, seed message, and session preparation of+ * the duplicate request are discarded — same shape Stripe's idempotency+ * contract follows.*/idempotencyKey?: string/**@@ -95,6 +101,11 @@ export interface EnqueueInput {* for audit. Defaults to false (owner-only, the fail-closed behaviour).*/bypassOwnerAcl?: boolean+ /**+ * Prepare per-session dependencies before making the session claimable.+ * Chat uses this to write credentials before a worker can claim the row.+ */+ prepareSession?: (sessionId: string) => Promise<SessionPreparation>}export type EnqueueOutcome =@@ -124,6 +135,51 @@ export async function enqueueOrResume(deps: EnqueueDeps, input: EnqueueInput): P}}+async function withPreparedSession(+ input: EnqueueInput,+ sessionId: string,+ operation: () => Promise<void>+): Promise<void> {+ const preparation = await input.prepareSession?.(sessionId)+ try {+ await operation()+ } catch (err) {+ if (preparation) {+ try {+ await preparation.rollback()+ } catch (rollbackError) {+ throw new AggregateError([err, rollbackError], 'session preparation rollback failed')+ }+ }+ throw err+ }+}++async function elevationIfDenied(+ deps: EnqueueDeps,+ input: EnqueueInput,+ existing: AgentSession+): Promise<Extract<EnqueueOutcome, { kind: 'elevation_required' }> | null> {+ const incoming = input.principal ?? null+ const check = input.bypassOwnerAcl ? ({ kind: 'allowed' } as const) : requireAclAccess(existing, incoming)+ if (check.kind === 'allowed') {+ return null+ }+ const request = await recordElevationRequest(deps.queue, existing, {+ requester: incoming,+ requesterDisplay: input.requesterDisplay ?? principalDisplay(incoming),+ trigger: input.trigger ?? 'chat',+ proposedMessage: input.seed,+ })+ return {+ kind: 'elevation_required',+ sessionId: existing.id,+ isResume: false,+ elevationRequestId: request.id,+ existingPrincipalDisplay: principalDisplay(existing.principal),+ }+}+async function enqueueOrResumeInner(deps: EnqueueDeps, input: EnqueueInput): Promise<EnqueueOutcome> {// Idempotency check first — independent of externalKey. A duplicate// request returns the original session id unchanged; the principal +@@ -133,6 +189,10 @@ async function enqueueOrResumeInner(deps: EnqueueDeps, input: EnqueueInput): Proif (input.idempotencyKey) {const existing = await deps.queue.findByIdempotencyKey(input.application.id, input.idempotencyKey)if (existing) {+ const denied = await elevationIfDenied(deps, input, existing)+ if (denied) {+ return denied+ }return { kind: 'created', sessionId: existing.id, isResume: false }}}@@ -144,25 +204,14 @@ async function enqueueOrResumeInner(deps: EnqueueDeps, input: EnqueueInput): Pro// the same external_key stay isolated.const existing = await deps.queue.findByExternalKey(input.application.id, input.externalKey, input.revision.id)if (existing && existing.state !== 'closed' && existing.state !== 'failed') {- const incoming = input.principal ?? null- const check = input.bypassOwnerAcl ? ({ kind: 'allowed' } as const) : requireAclAccess(existing, incoming)- if (check.kind === 'denied') {- const req = await recordElevationRequest(deps.queue, existing, {- requester: incoming,- requesterDisplay: input.requesterDisplay ?? principalDisplay(incoming),- trigger: input.trigger ?? 'chat',- proposedMessage: input.seed,- })- return {- kind: 'elevation_required',- sessionId: existing.id,- isResume: false,- elevationRequestId: req.id,- existingPrincipalDisplay: principalDisplay(existing.principal),- }+ const denied = await elevationIfDenied(deps, input, existing)+ if (denied) {+ return denied}- await deps.queue.appendPendingInput(existing.id, input.seed)- await deps.queue.update(existing.id, { state: 'queued' })+ await withPreparedSession(input, existing.id, async () => {+ await deps.queue.appendPendingInput(existing.id, input.seed)+ await deps.queue.update(existing.id, { state: 'queued' })+ })return { kind: 'resumed', sessionId: existing.id, isResume: true }}}@@ -189,7 +238,7 @@ async function enqueueOrResumeInner(deps: EnqueueDeps, input: EnqueueInput): Proupdated_at: new Date().toISOString(),}try {- await deps.queue.enqueue(session)+ await withPreparedSession(input, session.id, async () => deps.queue.enqueue(session))} catch (err) {// Race-window safety net: between the `findByIdempotencyKey` check// above and this INSERT, a concurrent writer could have created a@@ -200,6 +249,10 @@ async function enqueueOrResumeInner(deps: EnqueueDeps, input: EnqueueInput): Proif (input.idempotencyKey && isUniqueViolation(err)) {const existing = await deps.queue.findByIdempotencyKey(input.application.id, input.idempotencyKey)if (existing) {+ const denied = await elevationIfDenied(deps, input, existing)+ if (denied) {+ return denied+ }return { kind: 'created', sessionId: existing.id, isResume: false }}}diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.test.ts b/products/agent_platform/services/agent-ingress/src/routing/server.test.tsindex c1ae4e64ee96..2e1adb42c544 100644--- a/products/agent_platform/services/agent-ingress/src/routing/server.test.ts+++ b/products/agent_platform/services/agent-ingress/src/routing/server.test.ts@@ -171,6 +171,7 @@ describe('ingress HTTP server (path mode)', () => {revisions: PgRevisionStorequeue: PgSessionQueueapprovals: PgApprovalStore+ credentialBroker: PgCredentialBrokerbus: RedisSessionEventBusapp: ReturnType<typeof buildApp>} {@@ -210,7 +211,7 @@ describe('ingress HTTP server (path mode)', () => {},},})- return { revisions, queue, approvals, bus, app }+ return { revisions, queue, approvals, credentialBroker, bus, app }}it('GET /healthz returns ok', async () => {@@ -236,6 +237,72 @@ describe('ingress HTTP server (path mode)', () => {expect(session!.conversation[0]).toMatchObject({ role: 'user', content: 'hi' })})+ it('makes credentials available before a chat session becomes claimable', async () => {+ const { revisions, queue, credentialBroker, app } = mk(undefined, { withAuth: true })+ await seedPosthogApp(revisions, 'credential-ordering')++ const enqueue = queue.enqueue.bind(queue)+ vi.spyOn(queue, 'enqueue').mockImplementation(async (session) => {+ await expect(credentialBroker.resolve(session.id, 'posthog_api')).resolves.toEqual({+ kind: 'posthog_bearer',+ token: OWNER_TOKEN,+ })+ await enqueue(session)+ })++ const run = await request(app)+ .post('/agents/credential-ordering/run')+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ .send({ message: 'first' })+ expect(run.status).toBe(200)++ const sessionId = run.body.session_id+ await credentialBroker.clear(sessionId)+ const update = queue.update.bind(queue)+ vi.spyOn(queue, 'update').mockImplementation(async (id, patch) => {+ if (patch.state === 'queued') {+ await expect(credentialBroker.resolve(id, 'posthog_api')).resolves.toEqual({+ kind: 'posthog_bearer',+ token: OWNER_TOKEN,+ })+ }+ await update(id, patch)+ })++ const send = await request(app)+ .post('/agents/credential-ordering/send')+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ .send({ session_id: sessionId, message: 'second' })+ expect(send.status).toBe(200)+ })++ it('restores prior credentials when a send fails before requeue', async () => {+ const { revisions, queue, credentialBroker, app } = mk(undefined, { withAuth: true })+ await seedPosthogApp(revisions, 'credential-rollback')++ const run = await request(app)+ .post('/agents/credential-rollback/run')+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ .send({ message: 'first' })+ expect(run.status).toBe(200)+ const sessionId = run.body.session_id+ await credentialBroker.write(sessionId, {+ posthog_api: { kind: 'posthog_bearer', token: 'prior-token' },+ })++ vi.spyOn(queue, 'update').mockRejectedValueOnce(new Error('queue update failed'))+ const send = await request(app)+ .post('/agents/credential-rollback/send')+ .set('Authorization', `Bearer ${OWNER_TOKEN}`)+ .send({ session_id: sessionId, message: 'second' })++ expect(send.status).toBe(500)+ await expect(credentialBroker.resolve(sessionId, 'posthog_api')).resolves.toEqual({+ kind: 'posthog_bearer',+ token: 'prior-token',+ })+ })+it('POST /send buffers into pending_inputs (drained by runner at next turn)', async () => {const { revisions, queue, app } = mk()await seedApp(revisions, 'x')diff --git a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts b/products/agent_platform/services/agent-ingress/src/triggers/chat.tsindex 3c0d1622dead..1c7409236fae 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/chat.ts@@ -118,6 +118,7 @@ async function runHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatRunBodySchema>>kind: 'chat',...(supportedClientTools?.length ? { supported_client_tools: supportedClientTools } : {}),},+ prepareSession: (sessionId) => deps.broker.writeWithRollback(sessionId, ctx.credentials),})if (outcome.kind === 'elevation_required') {@@ -129,10 +130,6 @@ async function runHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatRunBodySchema>>})return}- // Write per-session auth materials into the broker keyed by the freshly- // minted session id. Tools resolve through this at call time; nothing- // token-bearing lands on the session row.- await deps.broker.write(outcome.sessionId, ctx.credentials)res.json({ok: true,session_id: outcome.sessionId,@@ -195,32 +192,42 @@ async function sendHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatSendBodySchemareturn}}- if (client_tool_result) {- const payload = client_tool_result.error- ? { call_id: client_tool_result.call_id, error: client_tool_result.error }- : {- call_id: client_tool_result.call_id,- result: (client_tool_result.result ?? {}) as Record<string, unknown>,- }- await deps.queue.appendPendingInput(sessionId, {- role: 'user',- content: buildClientToolResultMarker(payload),- timestamp: Date.now(),- sender: incomingPrincipal,- })- } else {- await deps.queue.appendPendingInput(sessionId, {- role: 'user',- content: message!,- timestamp: Date.now(),- sender: incomingPrincipal,- })+ // Refresh credentials before re-queueing so a worker can never claim this+ // turn in the gap between the state transition and the broker write. If a+ // queue mutation fails, restore the previous map only while this write is+ // still current, so a concurrent successful refresh is never overwritten.+ const credentialWrite = await deps.broker.writeWithRollback(sessionId, ctx.credentials)+ try {+ if (client_tool_result) {+ const payload = client_tool_result.error+ ? { call_id: client_tool_result.call_id, error: client_tool_result.error }+ : {+ call_id: client_tool_result.call_id,+ result: (client_tool_result.result ?? {}) as Record<string, unknown>,+ }+ await deps.queue.appendPendingInput(sessionId, {+ role: 'user',+ content: buildClientToolResultMarker(payload),+ timestamp: Date.now(),+ sender: incomingPrincipal,+ })+ } else {+ await deps.queue.appendPendingInput(sessionId, {+ role: 'user',+ content: message!,+ timestamp: Date.now(),+ sender: incomingPrincipal,+ })+ }+ await deps.queue.update(sessionId, { state: 'queued' })+ } catch (err) {+ try {+ await credentialWrite.rollback()+ } catch (rollbackError) {+ throw new AggregateError([err, rollbackError], 'credential rollback failed')+ }+ throw err}- await deps.queue.update(sessionId, { state: 'queued' })- // Refresh broker creds with whatever the client just supplied — OAuth- // tokens may have rotated since /run, and the worker may have evicted the- // prior entry.- await deps.broker.write(sessionId, ctx.credentials)res.json({ ok: true })}diff --git a/products/agent_platform/services/agent-shared/src/runtime/credential-broker.test.ts b/products/agent_platform/services/agent-shared/src/runtime/credential-broker.test.tsnew file mode 100644index 000000000000..0b8e8442a503--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/credential-broker.test.ts@@ -0,0 +1,27 @@+import { MemoryCredentialBroker } from './credential-broker'++describe('MemoryCredentialBroker rollback receipts', () => {+ it('restores the previous credential without overwriting a newer refresh', async () => {+ const broker = new MemoryCredentialBroker()+ await broker.write('session', { posthog_api: { kind: 'posthog_bearer', token: 'original' } })++ const failedWrite = await broker.writeWithRollback('session', {+ posthog_api: { kind: 'posthog_bearer', token: 'failed' },+ })+ await failedWrite.rollback()+ await expect(broker.resolve('session', 'posthog_api')).resolves.toEqual({+ kind: 'posthog_bearer',+ token: 'original',+ })++ const staleRollback = await broker.writeWithRollback('session', {+ posthog_api: { kind: 'posthog_bearer', token: 'stale' },+ })+ await broker.write('session', { posthog_api: { kind: 'posthog_bearer', token: 'newer' } })+ await staleRollback.rollback()+ await expect(broker.resolve('session', 'posthog_api')).resolves.toEqual({+ kind: 'posthog_bearer',+ token: 'newer',+ })+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/credential-broker.ts b/products/agent_platform/services/agent-shared/src/runtime/credential-broker.tsindex f6e4dd600ca8..f7f5647ef5e0 100644--- a/products/agent_platform/services/agent-shared/src/runtime/credential-broker.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/credential-broker.ts@@ -55,6 +55,11 @@ export type Credential =*/export type CredentialMap = Record<string, Credential>+export interface CredentialWriteReceipt {+ /** Restore the previous credential map only if this write is still current. */+ rollback(): Promise<void>+}+export interface CredentialBroker {/*** Write the credential map for a session. Overwrites any prior@@ -62,6 +67,16 @@ export interface CredentialBroker {* automatic expiry on the implementation side; default = 24h.*/write(sessionId: string, credentials: CredentialMap, opts?: { ttlMs?: number }): Promise<void>+ /**+ * Replace credentials and return a conditional rollback receipt. Rollback+ * restores the previous map only while this write remains current, so it+ * cannot overwrite a newer successful refresh.+ */+ writeWithRollback(+ sessionId: string,+ credentials: CredentialMap,+ opts?: { ttlMs?: number }+ ): Promise<CredentialWriteReceipt>/*** Resolve a credential for `(session, target)`. Returns null when* the session has no creds, the target isn't bound, or the entry@@ -90,8 +105,30 @@ export class MemoryCredentialBroker implements CredentialBroker {private readonly entries = new Map<string, MemoryEntry>()async write(sessionId: string, credentials: CredentialMap, opts: { ttlMs?: number } = {}): Promise<void> {+ await this.writeWithRollback(sessionId, credentials, opts)+ }++ async writeWithRollback(+ sessionId: string,+ credentials: CredentialMap,+ opts: { ttlMs?: number } = {}+ ): Promise<CredentialWriteReceipt> {+ const previous = this.entries.get(sessionId)const ttlMs = opts.ttlMs ?? DEFAULT_CREDENTIAL_TTL_MS- this.entries.set(sessionId, { credentials, expires_at: Date.now() + ttlMs })+ const current = { credentials, expires_at: Date.now() + ttlMs }+ this.entries.set(sessionId, current)+ return {+ rollback: async (): Promise<void> => {+ if (this.entries.get(sessionId) !== current) {+ return+ }+ if (previous) {+ this.entries.set(sessionId, previous)+ } else {+ this.entries.delete(sessionId)+ }+ },+ }}async resolve(sessionId: string, target: string): Promise<Credential | null> {diff --git a/products/agent_platform/services/agent-shared/src/runtime/pg-credential-broker.ts b/products/agent_platform/services/agent-shared/src/runtime/pg-credential-broker.tsindex 673e75cd6946..963f7beca647 100644--- a/products/agent_platform/services/agent-shared/src/runtime/pg-credential-broker.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/pg-credential-broker.ts@@ -21,9 +21,15 @@* build time (see `buildCluster` in agent-tests).*/-import type { Pool } from 'pg'+import type { Pool, PoolClient } from 'pg'-import { Credential, CredentialBroker, CredentialMap, DEFAULT_CREDENTIAL_TTL_MS } from './credential-broker'+import {+ Credential,+ CredentialBroker,+ CredentialMap,+ CredentialWriteReceipt,+ DEFAULT_CREDENTIAL_TTL_MS,+} from './credential-broker'import { EncryptedFields } from './encryption'interface EncryptedRow {@@ -31,6 +37,10 @@ interface EncryptedRow {expires_at: Date}+async function lockSession(client: PoolClient, sessionId: string): Promise<void> {+ await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [sessionId])+}+export class PgCredentialBroker implements CredentialBroker {private readonly fields: EncryptedFields@@ -47,18 +57,64 @@ export class PgCredentialBroker implements CredentialBroker {}async write(sessionId: string, credentials: CredentialMap, opts: { ttlMs?: number } = {}): Promise<void> {+ await this.writeWithRollback(sessionId, credentials, opts)+ }++ async writeWithRollback(+ sessionId: string,+ credentials: CredentialMap,+ opts: { ttlMs?: number } = {}+ ): Promise<CredentialWriteReceipt> {+ const client = await this.pool.connect()const ttlMs = opts.ttlMs ?? DEFAULT_CREDENTIAL_TTL_MSconst expiresAt = new Date(Date.now() + ttlMs)const ciphertext = this.fields.encrypt(JSON.stringify(credentials))- await this.pool.query(- `INSERT INTO agent_session_credential (session_id, encrypted_credentials, expires_at)- VALUES ($1, $2, $3)- ON CONFLICT (session_id) DO UPDATE SET- encrypted_credentials = EXCLUDED.encrypted_credentials,- expires_at = EXCLUDED.expires_at,- updated_at = NOW()`,- [sessionId, ciphertext, expiresAt]- )+ let previous: EncryptedRow | null = null+ try {+ await client.query('BEGIN')+ await lockSession(client, sessionId)+ const existing = await client.query<EncryptedRow>(+ `SELECT encrypted_credentials, expires_at+ FROM agent_session_credential+ WHERE session_id = $1`,+ [sessionId]+ )+ previous = existing.rows[0] ?? null+ await client.query(+ `INSERT INTO agent_session_credential (session_id, encrypted_credentials, expires_at)+ VALUES ($1, $2, $3)+ ON CONFLICT (session_id) DO UPDATE SET+ encrypted_credentials = EXCLUDED.encrypted_credentials,+ expires_at = EXCLUDED.expires_at,+ updated_at = NOW()`,+ [sessionId, ciphertext, expiresAt]+ )+ await client.query('COMMIT')+ } catch (err) {+ await client.query('ROLLBACK').catch(() => undefined)+ throw err+ } finally {+ client.release()+ }++ return {+ rollback: async (): Promise<void> => {+ if (previous) {+ await this.pool.query(+ `UPDATE agent_session_credential+ SET encrypted_credentials = $2, expires_at = $3, updated_at = NOW()+ WHERE session_id = $1 AND encrypted_credentials = $4`,+ [sessionId, previous.encrypted_credentials, previous.expires_at, ciphertext]+ )+ } else {+ await this.pool.query(+ `DELETE FROM agent_session_credential+ WHERE session_id = $1 AND encrypted_credentials = $2`,+ [sessionId, ciphertext]+ )+ }+ },+ }}async resolve(sessionId: string, target: string): Promise<Credential | null> {diff --git a/products/agent_platform/services/agent-tests/src/cases/posthog-tool-auth.test.ts b/products/agent_platform/services/agent-tests/src/cases/posthog-tool-auth.test.tsindex 31c084856350..83dd6d4cc274 100644--- a/products/agent_platform/services/agent-tests/src/cases/posthog-tool-auth.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/posthog-tool-auth.test.ts@@ -1,5 +1,5 @@/**- * Auth methodology for the native `@posthog/*` data tools.+ * Auth methodology for native `@posthog/*` tools and the first-party PostHog MCP.** These tools act **as the connected PostHog user**: they target an EXPLICIT* `project_id` the agent passes (resolved via the `get_context` client tool or@@ -13,16 +13,28 @@* bearer — never the agent's owning team.*/+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 request from 'supertest'import { vi } from 'vitest'import { AuthProvider, publicVerifier, readBearer } from '@posthog/agent-ingress'+import type { McpTransportFactory } from '@posthog/agent-runner'import { buildCluster, closeSharedPool, Cluster, fauxCallTool, fauxText } from '../harness'const AGENT_TEAM = 100const CALLER_TEAM = 200+function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise+ })+ return { promise, resolve }+}+// A user from CALLER_TEAM authenticating with a bearer. The principal carries// the caller's team; the bearer flows to tools as the `posthog_api` credential.const callerProvider: AuthProvider = {@@ -45,7 +57,7 @@ const callerProvider: AuthProvider = {],}-describe('@posthog/* data tools: act as the calling user, not the agent team', () => {+describe('PostHog tools: act as the calling user, not the agent team', () => {let c: Clusterconst fetchMock = vi.fn(async (_url: string | URL, _init?: RequestInit) =>@@ -96,4 +108,91 @@ describe('@posthog/* data tools: act as the calling user, not the agent team', (})expect(authHeaders).toContain('Bearer caller-token')})++ it('opens the PostHog MCP with the caller bearer when a worker is already polling', async () => {+ const mcpTargets: Array<{ url: string; headers: Record<string, string> }> = []+ 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+ }++ await c.teardown()+ c = await buildCluster({+ authProvider: callerProvider,+ mcpTransportFactory,+ teamId: AGENT_TEAM,+ })+ c.setScript([fauxCallTool('posthog__agent-applications-list', { project_id: CALLER_TEAM }), fauxText('listed')])+ await c.deployAgent({+ slug: 'polling-worker',+ teamId: AGENT_TEAM,+ spec: {+ auth: { modes: [{ type: 'posthog' }] },+ tools: [+ {+ kind: 'client',+ id: 'get_context',+ description: 'Read the current PostHog Code context.',+ args_schema: { type: 'object', properties: {}, additionalProperties: false },+ },+ ],+ mcps: [+ {+ kind: 'principal',+ id: 'posthog',+ url: 'http://localhost:8787/mcp',+ auth: { provider: 'posthog' },+ default_tool_approval: 'allow',+ tools: [{ name: 'agent-applications-list', level: 'allow' }],+ },+ ],+ },+ })++ const credentialWriteStarted = deferred<void>()+ const firstClaimFinished = deferred<boolean>()+ const credentialResolveFinished = deferred<void>()+ const originalClaim = c.queue.claim.bind(c.queue)+ const originalWrite = c.credentialBroker.writeWithRollback.bind(c.credentialBroker)+ const originalResolve = c.credentialBroker.resolve.bind(c.credentialBroker)++ vi.spyOn(c.queue, 'claim').mockImplementationOnce(async (timeoutMs) => {+ await credentialWriteStarted.promise+ const session = await originalClaim(timeoutMs)+ firstClaimFinished.resolve(session !== null)+ return session+ })+ vi.spyOn(c.credentialBroker, 'writeWithRollback').mockImplementationOnce(async (...args) => {+ credentialWriteStarted.resolve()+ if (await firstClaimFinished.promise) {+ await credentialResolveFinished.promise+ }+ return originalWrite(...args)+ })+ vi.spyOn(c.credentialBroker, 'resolve').mockImplementationOnce(async (...args) => {+ const credential = await originalResolve(...args)+ credentialResolveFinished.resolve()+ return credential+ })++ const workerLoop = c.worker.loop({ iterations: 1, claimTimeoutMs: 10 })+ const runRequest = request(c.ingress)+ .post('/agents/polling-worker/run')+ .set('authorization', 'Bearer caller-token')+ .send({ message: 'list my agents', supported_client_tools: ['get_context'] })+ .then((response) => response)+ const [res] = await Promise.all([runRequest, workerLoop])++ expect(res.status).toBe(200)+ expect(mcpTargets).toHaveLength(1)+ expect(mcpTargets[0].headers.Authorization).toBe('Bearer caller-token')+ })})