Skip to content

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

fix(mcp): stop telling PostHog app users to reauthorize for scopes (#120550)

Richard Solomou074089461876
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 84e4f584b6de..beb6d021d7b9 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -986,6 +986,7 @@ export class ToolExecutor {
flagGatedTools: state.flagGatedTools,
...(state.heldTools ? { heldTools: state.heldTools } : {}),
builtInSkillHint: this.builtInSkillHint(state),
+ oauthClientId: state.oauthClientId,
...(state.gatewayToolsEnabled
? {
gatewayToolsProvider: () => this.gatewayToolsFor(state),
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 59a48bef79a3..132675ec544e 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -17,6 +17,7 @@ import {
import { estimateTokens } from '@/lib/estimate-tokens'
import { GATEWAY_TOOL_SEPARATOR, isGatewayToolName } from '@/lib/gateway-tools'
import { findIgnoredInputKeys, withIgnoredInputKeys } from '@/lib/ignored-input-keys'
+import { isChatGptAppConnection } from '@/lib/oauth-constants'
import type { RequestProperties } from '@/lib/request-properties'
import { formatResponse } from '@/lib/response'
import { API_KEY_CACHE_TTL_MS } from '@/lib/StateManager'
@@ -256,6 +257,7 @@ export interface ExecToolOptions {
* is the case where an agent has no way to reach a built-in skill at all.
*/
builtInSkillHint?: BuiltInSkillHint
+ oauthClientId?: string | undefined
/**
* The tools a scout run with a picked tool list holds. A catalog or connected tool outside this
* set is refused as `tool_not_granted`, so the agent does not search for another way to reach it.
@@ -1659,7 +1661,10 @@ function flagGatedToolMessage(gated: FlagGatedTool, tools: Tool<ZodObjectAny>[])
return `Tool "${gated.name}" is retired on this PostHog connection. Use ${successors} instead.${hint}`
}
-function missingScopeRecovery(context: Context | undefined): string {
+function missingScopeRecovery(context: Context | undefined, oauthClientId: string | undefined): string {
+ if (isChatGptAppConnection(oauthClientId)) {
+ return 'The PostHog app in ChatGPT and Codex does not request every PostHog scope, so reconnecting it adds these scopes only if the app asks for them. If the user already reconnected and approved all access, this tool is not available through the app yet. Continue with the other tools.'
+ }
switch (classifyAuthMethod(context?.api.config.apiToken)) {
case 'oauth':
return 'Reauthorize the PostHog MCP connection and approve these scopes.'
@@ -1676,7 +1681,8 @@ function findTool(
flagGatedTools: FlagGatedTool[],
name: string,
context: Context | undefined,
- isNotGranted: (name: string) => boolean
+ isNotGranted: (name: string) => boolean,
+ oauthClientId: string | undefined
): Tool<ZodObjectAny> {
const tool = tools.find((t) => t.name === name)
if (!tool) {
@@ -1691,7 +1697,7 @@ function findTool(
const scopeGatedTool = scopeGatedTools.find((candidate) => candidate.name === name)
if (scopeGatedTool) {
throw new ExecCommandError(
- `Tool "${name}" exists, but this MCP connection is missing the required scope(s): ${scopeGatedTool.missingScopes.join(', ')}. ${missingScopeRecovery(context)} Logging in to PostHog in a browser does not update MCP permissions.`,
+ `Tool "${name}" exists, but this MCP connection is missing the required scope(s): ${scopeGatedTool.missingScopes.join(', ')}. ${missingScopeRecovery(context, oauthClientId)} Logging in to PostHog in a browser does not update MCP permissions.`,
'missing_scope'
)
}
@@ -1877,7 +1883,7 @@ export function createExecTool(
})),
hint:
`These tools also match but are hidden because the API key is missing the ` +
- `required scope(s): ${requiredScopes.join(', ')}. ${missingScopeRecovery(context)}`,
+ `required scope(s): ${requiredScopes.join(', ')}. ${missingScopeRecovery(context, options.oauthClientId)}`,
})
}
if (matches.length === 0) {
@@ -1921,7 +1927,8 @@ export function createExecTool(
flagGatedTools,
infoArgs,
context,
- isNotGranted
+ isNotGranted,
+ options.oauthClientId
)
// `io: 'input'` mirrors the advertised `tools/list` schema and the executor's
// validation: fields with a Zod `.default()` (e.g. a query `kind` discriminator)
@@ -1973,7 +1980,8 @@ export function createExecTool(
flagGatedTools,
schemaToolName,
context,
- isNotGranted
+ isNotGranted,
+ options.oauthClientId
)
// See the `info` command: `io: 'input'` keeps this in sync with the advertised
// schema and validation, so `.default()` fields aren't shown as required.
@@ -2037,7 +2045,8 @@ export function createExecTool(
flagGatedTools,
toolName,
context,
- isNotGranted
+ isNotGranted,
+ options.oauthClientId
)
if (options.requireDestructiveConfirmation && tool.annotations.destructiveHint && !confirmed) {
throw new ExecCommandError(
diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.ts
index bb5101ebfa78..2e42f87e6a25 100644
--- a/services/mcp/tests/unit/exec.test.ts
+++ b/services/mcp/tests/unit/exec.test.ts
@@ -8,6 +8,7 @@ import { PostHogApiError, ToolInputValidationError } from '@/lib/errors'
import { estimateTokens } from '@/lib/estimate-tokens'
import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instructions'
import { InstructionsFormatter } from '@/lib/instructions-formatter'
+import { CHATGPT_APP_OAUTH_CLIENT_ID } from '@/lib/oauth-constants'
import { formatResponse } from '@/lib/response'
import { SessionManager } from '@/lib/SessionManager'
import { OrganizationSetActiveSchema, ReadDataSchemaSchema } from '@/schema/tool-inputs'
@@ -2060,9 +2061,15 @@ describe('exec tool', () => {
apiToken: 'unrecognized-token',
recovery: 'Reauthorize the PostHog MCP connection, or add these scopes to the personal API key.',
},
+ {
+ apiToken: 'pha_test',
+ oauthClientId: CHATGPT_APP_OAUTH_CLIENT_ID,
+ recovery:
+ 'If the user already reconnected and approved all access, this tool is not available through the app yet.',
+ },
])(
- 'gives the scope recovery step for the connection credential ($apiToken)',
- async ({ apiToken, recovery }) => {
+ 'gives the scope recovery step for the connection credential ($apiToken, $oauthClientId)',
+ async ({ apiToken, oauthClientId, recovery }) => {
const context = { ...mockContext, api: { config: { apiToken } } } as unknown as Context
const scopeGated = [
{
@@ -2072,7 +2079,18 @@ describe('exec tool', () => {
missingScopes: ['endpoint:write'],
},
]
- const exec = createExecTool([makeMockTool()], context, 'desc', 'cmd', undefined, undefined, scopeGated)
+ const exec = createExecTool(
+ [makeMockTool()],
+ context,
+ 'desc',
+ 'cmd',
+ undefined,
+ undefined,
+ scopeGated,
+ {
+ oauthClientId,
+ }
+ )
await expect(exec.handler(context, { command: 'call endpoint-create {}' })).rejects.toThrow(recovery)
const search = JSON.parse(