: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): keep MCP startup from initiating OAuth (#71348)
Dylan Martin90acc7082c08
diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.tsindex eee28b05f12c..f62625ca45d5 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts@@ -306,7 +306,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsunavailableMcps: (deps.mcpFailures ?? []).map((f) => ({id: f.ref.id,category: f.category,- authorizeUrl: f.authorizeUrl,+ provider: f.provider,})),slackReplyRelay: slackReply !== null,})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 ef1a69d2c3a7..5c867b9cfa9b 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@@ -270,7 +270,7 @@ describe('openMcpClients', () => {await closePairs(pairs)})- it('auth.provider unlinked → ref fails to open in the auth category', async () => {+ it('auth.provider unlinked → lookup-only failure without initiating authorization', async () => {const { factory, pairs } = await buildEchoFactory()const refs: McpRef[] = [{@@ -282,26 +282,27 @@ describe('openMcpClients', () => {auth: { provider: 'github' },},]+ const resolve = vi.fn(async () => ({+ kind: 'unavailable' as const,+ provider: 'github',+ reason: 'identity_not_connected',+ }))const { clients, failures, close } = await openMcpClients(refs, {secrets: {},transportFactory: factory,- identity: {- resolve: async () => ({ kind: 'link_required', provider: 'github', authorizeUrl: 'https://gh/oauth' }),- },+ identity: { resolve },})expect(clients).toEqual([])expect(failures[0].category).toBe('auth')- expect(failures[0].devReason).toMatch(/mcp_identity_link_required: github/)- // The authorize URL rides on the failure so the system prompt can relay it.- expect(failures[0].authorizeUrl).toBe('https://gh/oauth')+ expect(failures[0].provider).toBe('github')+ expect(failures[0].devReason).toMatch(/mcp_identity_unavailable: github \(identity_not_connected\)/)+ expect(failures[0]).not.toHaveProperty('authorizeUrl')+ expect(resolve).toHaveBeenCalledWith('github', [], { initiate: false })await close()await closePairs(pairs)})- it('auth.provider linked-but-rejected (e.g. missing scope) → offers a reconnect link via relink', async () => {- // Resolve succeeds (the asker IS linked), but the MCP rejects the grant- // at open with a scope error. The failure must carry a reconnect URL so- // the agent can relay it — not dead-end as "unavailable".+ it('auth.provider linked-but-rejected does not initiate reconnect during startup', async () => {const failingFactory: McpTransportFactory = () =>({async start() {@@ -322,7 +323,6 @@ describe('openMcpClients', () => {auth: { provider: 'posthog' },},]- const relink = vi.fn(async () => 'https://app.posthog.test/oauth/authorize/?reconnect=1')const { clients, failures } = await openMcpClients(refs, {secrets: {},transportFactory: failingFactory,@@ -332,14 +332,12 @@ describe('openMcpClients', () => {credential: { kind: 'posthog_bearer', token: 'linked-but-underscoped' },allowedHosts: ['example.com'],}),- relink,},})expect(clients).toEqual([])- // Scope rejection classifies as auth (not unknown), which gates the reconnect offer.expect(failures[0].category).toBe('auth')- expect(failures[0].authorizeUrl).toBe('https://app.posthog.test/oauth/authorize/?reconnect=1')- expect(relink).toHaveBeenCalledWith('posthog')+ expect(failures[0].provider).toBe('posthog')+ expect(failures[0]).not.toHaveProperty('authorizeUrl')})it('auth.provider refuses a host outside the resolved credential allowlist', async () => {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 1e0beb3aa7d2..939ab030e034 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@@ -12,7 +12,8 @@* - `auth.provider` → resolve the asker's linked identity via `ctx.identity`* → `Authorization: Bearer <token>`. Host-bound by the provider's own* `allowedHosts()` so a spec author can't redirect a user's OAuth token to- * an arbitrary URL; an unlinked asker surfaces a relayable authorize link.+ * an arbitrary URL. Startup is lookup-only: it never initiates OAuth or+ * reconnects. Authorization starts only through an explicit connect tool.* - `secrets[]` → resolve each name via `secrets[NAME]`; substitute* `${NAME}` placeholders in the URL + author-supplied headers before* opening the transport. Each substitution is gated on the secret's@@ -110,27 +111,14 @@ export type McpFailureCategory = 'connection_dead' | 'auth' | 'network' | 'not_fexport interface McpOpenFailure {ref: McpRefcategory: McpFailureCategory+ /** Identity provider that can repair an auth failure through an explicit+ * `@posthog/identity-connect` call. Metadata only: startup never initiates+ * authorization or mints a link. */+ provider?: string/** The raw error message. Server-side observability only — never to be* forwarded to the chat UI or the model's view of the world. The agent* owner reads this via `log_entries` on the session detail page. */devReason: string- /** Set when the open failed because the asker hasn't linked the MCP's- * `auth.provider` identity yet. The model relays this so the user can- * connect (vs a dead "temporarily unavailable"). Safe to surface — it's a- * per-asker authorize link, not a secret. */- authorizeUrl?: string-}--/** Thrown by `resolveTarget` when an `auth.provider` MCP can't open because the- * asker is unlinked. Carries the authorize URL so `openMcpClients` can surface- * it as a relayable link rather than an opaque "unavailable". */-class McpIdentityLinkRequiredError extends Error {- constructor(- readonly provider: string,- readonly authorizeUrl: string- ) {- super(`mcp_identity_link_required: ${provider}`)- }}/**@@ -233,11 +221,7 @@ export interface OpenMcpClientsDeps {* host allowlist). Absent → any `auth.provider` ref is refused at open time.*/identity?: {- resolve(provider: string, scopes?: string[]): Promise<IdentityResolution>- /** Force a reconnect link for an already-linked provider — used when the- * resolved bearer is rejected at open (e.g. missing scope). See- * `openMcpClients`'s failure handling. */- relink?(provider: string): Promise<string | null>+ resolve(provider: string, scopes?: string[], options?: { initiate?: boolean }): Promise<IdentityResolution>}/*** Agent-level shared-credential resolver (`ref.connection` → a native@@ -315,16 +299,12 @@ export async function openMcpClients(const err = r.reason instanceof Error ? r.reason : new Error(String(r.reason))const ref = refs[i]const category = categorizeMcpOpenError(err)- let authorizeUrl = err instanceof McpIdentityLinkRequiredError ? err.authorizeUrl : undefined- // Reconnect path: an `auth.provider` MCP that resolved a bearer but was- // rejected at open (a revoked or under-scoped linked grant) surfaces as- // an `auth` failure WITHOUT a link. Offer a fresh authorize URL so the- // asker can re-authorize, instead of a dead "unavailable" the agent- // can't act on. A never-linked asker already carries the URL above.- if (!authorizeUrl && category === 'auth' && ref.auth?.provider && deps.identity?.relink) {- authorizeUrl = (await deps.identity.relink(ref.auth.provider)) ?? undefined- }- failures.push({ ref, category, devReason: err.message, authorizeUrl })+ failures.push({+ ref,+ category,+ devReason: err.message,+ provider: category === 'auth' ? ref.auth?.provider : undefined,+ })log('warn', 'mcp.open.failed', { prefix: ref.id, category, devReason: err.message })}@@ -447,9 +427,9 @@ async function resolveTarget(if (!deps.identity) {throw new Error(`mcp_identity_not_wired: ${ref.auth.provider}`)}- const res = await deps.identity.resolve(ref.auth.provider)+ const res = await deps.identity.resolve(ref.auth.provider, [], { initiate: false })if (res.kind === 'link_required') {- throw new McpIdentityLinkRequiredError(ref.auth.provider, res.authorizeUrl)+ throw new Error(`mcp_identity_not_connected: ${ref.auth.provider}`)}if (res.kind === 'unavailable') {throw new Error(`mcp_identity_unavailable: ${ref.auth.provider} (${res.reason})`)diff --git a/products/agent_platform/services/agent-shared/src/runtime/identity-gate.test.ts b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.test.tsindex 3d28353b2145..3d3a88af25b2 100644--- a/products/agent_platform/services/agent-shared/src/runtime/identity-gate.test.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.test.ts@@ -100,6 +100,16 @@ describe('createToolIdentity.resolve', () => {})})+ it('does not initiate authorization when resolution is lookup-only', async () => {+ const provider = fakeProvider()+ const { toolIdentity } = deps({ provider })++ const res = await toolIdentity.resolve('posthog', [], { initiate: false })++ expect(res).toEqual({ kind: 'unavailable', provider: 'posthog', reason: 'identity_not_connected' })+ expect(provider.initiate).not.toHaveBeenCalled()+ })+it('fails closed in a shared session WITHOUT consulting the seed (T1 confused-deputy guard)', async () => {const provider = fakeProvider()const seed = { resolve: vi.fn(async () => OK_CRED) }diff --git a/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.tsindex 521bf7290167..b81be83467db 100644--- a/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts@@ -168,7 +168,7 @@ export interface ToolIdentityDeps {}export function createToolIdentity(deps: ToolIdentityDeps): {- resolve(provider: string, scopes?: string[]): Promise<IdentityResolution>+ resolve(provider: string, scopes?: string[], options?: { initiate?: boolean }): Promise<IdentityResolution>relink(provider: string): Promise<string | null>} {return {@@ -207,7 +207,7 @@ export function createToolIdentity(deps: ToolIdentityDeps): {return null}},- async resolve(providerId, scopes = []): Promise<IdentityResolution> {+ async resolve(providerId, scopes = [], options = {}): Promise<IdentityResolution> {// One session-log line per resolution: the credential source + decision, never the token.const emit = (res: IdentityResolution, source: string, binding?: string): IdentityResolution => {deps.log?.('info', 'identity.resolved', {@@ -270,6 +270,13 @@ export function createToolIdentity(deps: ToolIdentityDeps): {provider.binding)}+ if (options.initiate === false) {+ return emit(+ { kind: 'unavailable', provider: providerId, reason: 'identity_not_connected' },+ 'unavailable',+ provider.binding+ )+ }const { authorizeUrl } = await provider.initiate({...args,redirectUri: deps.redirectUriFor(providerId),diff --git a/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.test.ts b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.test.tsindex 762cbb005625..f9b411e0bbe6 100644--- a/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.test.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.test.ts@@ -35,6 +35,29 @@ describe('posthog provider credential target', () => {expect(p.credentialTarget).toBe('posthog_api')})+ it.each([+ ['https://us.posthog.com', ['us.posthog.com', 'mcp.us.posthog.com']],+ ['https://app.posthog.com', ['app.posthog.com', 'mcp.us.posthog.com']],+ ['https://eu.posthog.com', ['eu.posthog.com', 'mcp.eu.posthog.com']],+ ['https://posthog.com', ['posthog.com', 'mcp.posthog.com']],+ ])('allows the matching first-party MCP host for %s', (baseUrl, expectedHosts) => {+ const managedProvider = new PostHogAuthProvider({+ config: {+ id: 'posthog',+ authorizeUrl: `${baseUrl}/oauth/authorize/`,+ tokenUrl: `${baseUrl}/oauth/token/`,+ clientId: 'c',+ },+ links: {} as IdentityLinkStateStore,+ credentials: {} as IdentityCredentialStore,+ http: {} as HttpFetcher,+ })+ const seedOnlyProvider = new SeedOnlyPostHogProvider('posthog', baseUrl)++ expect(managedProvider.allowedHosts()).toEqual(expectedHosts)+ expect(seedOnlyProvider.allowedHosts()).toEqual(expectedHosts)+ })+it('SeedOnlyPostHogProvider surfaces the seed target + host but cannot link', async () => {const p = new SeedOnlyPostHogProvider('posthog', BASE)expect(p.credentialTarget).toBe('posthog_api')diff --git a/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.ts b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.tsindex 5d62065589b1..7d3811cde977 100644--- a/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.ts@@ -30,6 +30,30 @@ import type {} from './identity-provider'import { Oauth2AuthProvider } from './oauth2-identity-provider'+function posthogMcpHost(host: string): string | null {+ if (host === 'us.posthog.com' || host === 'app.posthog.com') {+ return 'mcp.us.posthog.com'+ }+ if (host === 'eu.posthog.com') {+ return 'mcp.eu.posthog.com'+ }+ if (host === 'posthog.com') {+ return 'mcp.posthog.com'+ }+ return null+}++function withPosthogMcpHost(hosts: string[]): string[] {+ const allowedHosts = new Set(hosts)+ for (const host of hosts) {+ const mcpHost = posthogMcpHost(host)+ if (mcpHost) {+ allowedHosts.add(mcpHost)+ }+ }+ return [...allowedHosts]+}+export class PostHogAuthProvider extends Oauth2AuthProvider {// Linking proves WHO the principal is; `complete()` stamps the userinfo `sub`// (read by the inherited `fetchSubject`) as the credential subject.@@ -40,6 +64,10 @@ export class PostHogAuthProvider extends Oauth2AuthProvider {override get credentialTarget(): string {return 'posthog_api'}++ override allowedHosts(): string[] {+ return withPosthogMcpHost(super.allowedHosts())+ }}/**@@ -66,7 +94,7 @@ export class SeedOnlyPostHogProvider implements IdentityProvider {}allowedHosts(): string[] {- return [this.host]+ return withPosthogMcpHost([this.host])}async initiate(_input: IdentityInitiateInput): Promise<IdentityInitiateResult> {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 dca42cb0dfba..83bb55a2e57d 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@@ -192,20 +192,19 @@ describe('buildSystemPrompt', () => {expect(prompt).not.toMatch(/Bearer|http/)})- it('renders a link-required MCP under "Connect required" with the URL, not as "unavailable"', async () => {+ it('keeps auth failures passive until the user explicitly asks to connect', async () => {await bundle.write('rev1', 'agent.md', 'x')const spec = AgentSpecSchema.parse({ model: 'test/x' })const prompt = await buildSystemPrompt(makeRev(spec), bundle, {- unavailableMcps: [- { id: 'posthog', category: 'auth', authorizeUrl: 'https://app.posthog.test/oauth/authorize/?x=1' },- ],+ unavailableMcps: [{ id: 'github', category: 'auth', provider: 'github-user' }],})- expect(prompt).toContain('Connect required')- // Rendered as a markdown link (not a bare URL) so the model relays a clickable link.- expect(prompt).toContain('`posthog`: [Connect posthog](https://app.posthog.test/oauth/authorize/?x=1)')- expect(prompt).toMatch(/markdown link/)- // A linkable failure must NOT land in the dead-end "Unavailable" block.- expect(prompt).not.toContain('Unavailable capabilities')++ expect(prompt).toContain('Connections available on request')+ expect(prompt).toContain('`github`: provider `github-user`')+ expect(prompt).toContain('@posthog/identity-connect')+ expect(prompt).toMatch(/Do not start authorization merely because session startup/i)+ expect(prompt).toMatch(/If the user asks to use or connect/i)+ expect(prompt).not.toMatch(/https?:\/\//)})it('reasoning hint only fires for high / xhigh', async () => {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 0686f0f6a255..f265618dbe66 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@@ -31,10 +31,9 @@ export interface UnavailableMcp {/** Spec ref id — same string the model sees as the tool-name prefix. */id: stringcategory: UnavailableMcpCategory- /** Set when the MCP didn't open because the asker hasn't linked its- * identity provider yet. The model relays this connect link rather than- * reporting a dead "temporarily unavailable". */- authorizeUrl?: string+ /** Identity provider to pass to `@posthog/identity-connect` after the user+ * explicitly asks to use or connect this capability. */+ provider?: string}export interface BuildSystemPromptOpts {@@ -96,35 +95,35 @@ export async function buildSystemPrompt(}const unavailable = opts.unavailableMcps ?? []- // 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 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', '']+ // Shared connections need an owner/admin to reconnect them. Principal auth+ // failures retain provider metadata for a later explicit connect action;+ // startup itself never initiates OAuth.+ const dead = unavailable.filter((u) => u.category === 'connection_dead')+ const connectable = unavailable.filter(+ (u): u is UnavailableMcp & { provider: string } => u.category === 'auth' && !!u.provider+ )+ const broken = unavailable.filter((u) => u.category !== 'connection_dead' && !(u.category === 'auth' && u.provider))+ if (dead.length > 0) {+ const lines = ['\n\n---\n\n## Disconnected integrations', '']lines.push(- "These capabilities need the user to connect (or reconnect) their account before you can use them — the connection is either not set up yet or no longer has the access it needs. When they ask for something one powers (including asking to reconnect), relay the link below as a **markdown link** with a short friendly label (never the bare URL), ask them to click it, then re-ask — don't say it's unavailable:"+ "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 linkable) {- lines.push(`- \`${u.id}\`: [Connect ${u.id}](${u.authorizeUrl})`)+ 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 (dead.length > 0) {- const lines = ['\n\n---\n\n## Disconnected integrations', '']+ if (connectable.length > 0) {+ const lines = ['\n\n---\n\n## Connections available on request', '']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:"+ 'These MCP servers need the asking user to connect or reconnect an account. Do not start authorization merely because session startup found them disconnected. If the user asks to use or connect one of these capabilities, call `@posthog/identity-connect` with the listed provider, relay its `authorize_url` as a markdown link, and ask the user to continue after completing authorization:')lines.push('')- for (const u of dead) {- lines.push(`- \`${u.id}\``)+ for (const u of connectable) {+ lines.push(`- \`${u.id}\`: provider \`${u.provider}\``)}lines.push('')lines.push('Do NOT paste raw error messages, transport URLs, or stack traces into the conversation.')diff --git a/products/agent_platform/services/agent-shared/src/spec/tool.ts b/products/agent_platform/services/agent-shared/src/spec/tool.tsindex a1c546a2e50d..bd3316c540f0 100644--- a/products/agent_platform/services/agent-shared/src/spec/tool.ts+++ b/products/agent_platform/services/agent-shared/src/spec/tool.ts@@ -128,7 +128,7 @@ export interface ToolContext {* Wired from spec.identity_providers; absent when none are configured.*/identity?: {- resolve(provider: string, scopes?: string[]): Promise<IdentityResolution>+ resolve(provider: string, scopes?: string[], options?: { initiate?: boolean }): Promise<IdentityResolution>/** Force a fresh authorize link for an already-linked provider (reconnect)* — used when a resolved credential is rejected downstream (revoked, or* missing a scope the resource server now requires). Null when no link isdiff --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 65775c11e30c..3ee7a54b02ec 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@@ -121,15 +121,15 @@ describe('example: agent-builder bundle', () => {])})- it('accepts posthog + posthog_internal auth on its chat and mcp triggers', async () => {+ it('tries the user PostHog bearer before the internal fallback', 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(expect.arrayContaining(['posthog', 'posthog_internal']))- expect(modesFor('mcp')).toEqual(expect.arrayContaining(['posthog', 'posthog_internal']))+ expect(modesFor('chat')).toEqual(['posthog', 'posthog_internal'])+ expect(modesFor('mcp')).toEqual(['posthog', 'posthog_internal'])})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 bb8bbd073c58..ab60bc66f8c9 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@@ -95,14 +95,36 @@ points map to the same effective auth:1. **PostHog Code** — user signs into the PostHog Code app viaPostHog OAuth; the app mints a short-lived session-principal- token from the OAuth session, attaches it as the chat trigger's- principal field. Every tool call runs as the user.+ token from the OAuth session and attaches it to the chat trigger.+ Every tool call runs as the user without a separate MCP connection.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 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.++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+edge, and the runner passes that credential to the first-party MCP. The+`/link/<provider>/callback` flow exists for agents that intentionally support+connecting an additional identity.++The checked-in MCP URL is the local development endpoint. `seed.py` rewrites+PostHog-authenticated MCP entries to the target region, so the production US+deployment uses `https://mcp.us.posthog.com/mcp` rather than localhost. The+PostHog identity provider explicitly allows that matching regional MCP host.+## Platform pieces it relies on (all shipped)These are platform-side, not bundle-side — and they're in place: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 b59536184c65..d72f829c7270 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@@ -162,7 +162,11 @@ account. Every `posthog__*` MCP call is signed with that user's PostHogidentity, so what you can see and change is exactly what they can.On both of your surfaces (PostHog Code and MCP / IDE) the user's PostHogbearer passes through from the trigger — they're already authenticated,-nothing to link.+nothing to link. Never tell a PostHog Code user to connect the PostHog MCP;+if the PostHog MCP reports an auth failure there, explain that the builder's+auth passthrough is broken rather than presenting connection as expected setup.+The PostHog MCP is your first-party authoring transport, not a connection the+user adds to the agent they are building.This is also the single most important thing to get right in the agents youbuild: an agent that calls PostHog (or any third-party API) on a user'sdiff --git a/services/mcp/playbooks/authenticating-as-the-user/SKILL.md b/services/mcp/playbooks/authenticating-as-the-user/SKILL.mdindex 7da11aeb97d0..d312bc4eda90 100644--- a/services/mcp/playbooks/authenticating-as-the-user/SKILL.md+++ b/services/mcp/playbooks/authenticating-as-the-user/SKILL.md@@ -79,10 +79,11 @@ seam — don't use it.)Every identity-gated call resolves to one of three outcomes:- **`ok`** — a bearer was available; the call runs as the user.-- **`link_required`** — the user hasn't linked yet. The tool/MCP returns a- connect link (an `auth_required` payload, or the MCP degrades with one). The- agent **relays it as a markdown link** ("Connect your PostHog account: [link]"),- asks the user to click, then retries — it is NOT an error or a dead capability.+- **`link_required`** — an explicitly invoked identity-gated tool found that+ the user hasn't linked yet. The tool returns a connect link in an+ `auth_required` payload. The agent **relays it as a markdown link**+ ("Connect your PostHog account: [link]"), asks the user to click, then+ retries. MCP startup is lookup-only and never initiates this flow.- **`unavailable`** — can't link here (e.g. a shared thread, or ananonymous principal). Surface plainly.@@ -94,10 +95,11 @@ Where the bearer comes from depends on the surface:persisted per-user and reused.**`@posthog/identity-connect`** mints a connect/reconnect link on demand for any-declared provider — use it to proactively hand the user a link ("connect my-PostHog account") rather than waiting for a call to fail. If a linked grant is-later missing a scope the service now requires, the same path offers a-**reconnect** link (re-authorize with the updated scopes).+declared provider. The runtime makes it available when the agent declares an+identity provider or an identity-backed MCP. Use it for an explicit connection+need such as "connect my PostHog account"; merely opening an MCP never invokes+it. If a linked grant is later missing a scope the service now requires, the+same path offers a **reconnect** link (re-authorize with the updated scopes).## Choosing scopes