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(oauth): preload MCP scopes server-side on consent page (#65601)

Matt Brookerfd55d9cc2d25
diff --git a/Dockerfile b/Dockerfile
index 78702ec28bfc..c4e760408d4d 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -392,6 +392,10 @@ COPY --chown=posthog:posthog common/hogvm common/hogvm/
COPY --chown=posthog:posthog common/migration_utils common/migration_utils/
COPY --chown=posthog:posthog common/alerting common/alerting/
COPY --chown=posthog:posthog products products/
+# Generated MCP tool catalog, read at runtime from BASE_DIR by the OAuth consent page
+# (posthog/api/oauth/mcp_resource_scopes.py) and the tasks permission broker. The rest of
+# services/ is a Node build (Dockerfile.node) and deliberately stays out of this image.
+COPY --chown=posthog:posthog services/mcp/schema services/mcp/schema/
# Validate the Playwright client library (used to drive the remote browserless service over CDP —
# no browser binary ships in this image).
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index f1ebaa9ea686..282bf09fc619 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -326,36 +326,6 @@ export const PROJECT_SECRET_API_KEY_SCOPE_PRESETS: ProjectSecretAPIKeyScopePrese
export const DEFAULT_OAUTH_SCOPES = ['openid', 'email', 'profile']
-// Scopes required by the PostHog MCP server (https://mcp.posthog.com)
-// These match the scopes_supported in the MCP server's OAuth protected resource metadata
-export const MCP_SERVER_OAUTH_SCOPES = [
- 'openid',
- 'profile',
- 'email',
- 'introspection',
- 'user:read',
- 'user:write',
- 'organization:read',
- 'project:read',
- 'project:write',
- 'feature_flag:read',
- 'feature_flag:write',
- 'experiment:read',
- 'experiment:write',
- 'insight:read',
- 'insight:write',
- 'dashboard:read',
- 'dashboard:write',
- 'query:read',
- 'survey:read',
- 'survey:write',
- 'event_definition:read',
- 'event_definition:write',
- 'error_tracking:read',
- 'logs:read',
- 'tracing:read',
-]
-
export const getScopeDescription = (scope: string): string | undefined => {
if (scope === '*') {
return 'Read and write access to all PostHog data'
diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
index 17768e87598f..26fa7c7d0969 100644
--- a/frontend/src/scenes/oauth/OAuthAuthorize.tsx
+++ b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
@@ -146,7 +146,6 @@ export const OAuthAuthorize = (): JSX.Element => {
redirectUrl,
scopesWereDefaulted,
isMcpResource,
- resourceScopesLoading,
showCreateProject,
newProjectLoading,
selectedOrganization,
@@ -293,7 +292,7 @@ export const OAuthAuthorize = (): JSX.Element => {
{scopesWereDefaulted && isMcpResource && (
<LemonBanner type="info" className="mb-4">
<strong>No permissions requested.</strong> This application didn't request specific permissions.
- Showing all permissions supported by this resource.
+ Showing all permissions the PostHog MCP server supports.
</LemonBanner>
)}
@@ -407,63 +406,52 @@ export const OAuthAuthorize = (): JSX.Element => {
</div>
)}
</div>
- {resourceScopesLoading ? (
- <div className="flex items-center gap-2 py-2">
- <Spinner className="text-muted" />
- <span className="text-muted">Loading permissions...</span>
- </div>
- ) : (
- <>
- {(identityScopeDescriptions.length > 0 || requiredScopeRows.length > 0) && (
- <ul className="space-y-2">
- {identityScopeDescriptions.map((description, idx) => (
- <li key={idx} className="flex items-center space-x-2">
- <IconCheck color="var(--success)" className="shrink-0" />
- <span className="font-medium">{description}</span>
- </li>
- ))}
- {requiredScopeRows.map((row) => (
- <li key={row.key} className="flex items-center space-x-2">
- <IconCheck color="var(--success)" className="shrink-0" />
- <span className="font-medium">{row.description}</span>
- {!allScopesRequired && (
- <Tooltip title={`${appName} requires this permission`}>
- <LemonTag>Required</LemonTag>
- </Tooltip>
- )}
- </li>
- ))}
- </ul>
- )}
- {adjustableScopeRows.length > 0 && (
- <div className="flex flex-col">
- {adjustableScopeRows.map((row) => (
- <ScopeAccessRow
- key={row.key}
- label={row.label}
- info={row.info}
- muted={row.value === 'none'}
- value={row.value}
- onChange={(value) =>
- setScopeAccess(row.key, value as ScopeAccessLevel)
- }
- noneDisabledReason={
- row.minLevel !== 'none'
- ? `${appName} requires at least ${row.minLevel} access`
- : undefined
- }
- writeDisabledReason={
- row.maxLevel !== 'write'
- ? `Not requested by ${appName}`
- : undefined
- }
- warning={row.warning}
- />
- ))}
- </div>
- )}
- </>
- )}
+ <>
+ {(identityScopeDescriptions.length > 0 || requiredScopeRows.length > 0) && (
+ <ul className="space-y-2">
+ {identityScopeDescriptions.map((description, idx) => (
+ <li key={idx} className="flex items-center space-x-2">
+ <IconCheck color="var(--success)" className="shrink-0" />
+ <span className="font-medium">{description}</span>
+ </li>
+ ))}
+ {requiredScopeRows.map((row) => (
+ <li key={row.key} className="flex items-center space-x-2">
+ <IconCheck color="var(--success)" className="shrink-0" />
+ <span className="font-medium">{row.description}</span>
+ {!allScopesRequired && (
+ <Tooltip title={`${appName} requires this permission`}>
+ <LemonTag>Required</LemonTag>
+ </Tooltip>
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ {adjustableScopeRows.length > 0 && (
+ <div className="flex flex-col">
+ {adjustableScopeRows.map((row) => (
+ <ScopeAccessRow
+ key={row.key}
+ label={row.label}
+ info={row.info}
+ muted={row.value === 'none'}
+ value={row.value}
+ onChange={(value) => setScopeAccess(row.key, value as ScopeAccessLevel)}
+ noneDisabledReason={
+ row.minLevel !== 'none'
+ ? `${appName} requires at least ${row.minLevel} access`
+ : undefined
+ }
+ writeDisabledReason={
+ row.maxLevel !== 'write' ? `Not requested by ${appName}` : undefined
+ }
+ warning={row.warning}
+ />
+ ))}
+ </div>
+ )}
+ </>
</div>
{redirectDomain && (
@@ -507,9 +495,7 @@ export const OAuthAuthorize = (): JSX.Element => {
? 'Authorizing...'
: isCanceling
? 'Processing...'
- : resourceScopesLoading
- ? 'Loading permissions...'
- : undefined
+ : undefined
}
onClick={() => submitOauthAuthorization()}
>
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
index 2cd886cc1438..830405645037 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
@@ -5,13 +5,7 @@ import { router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import {
- API_SCOPES,
- DEFAULT_OAUTH_SCOPES,
- MCP_SERVER_OAUTH_SCOPES,
- getMinimumEquivalentScopes,
- getScopeDescription,
-} from 'lib/scopes'
+import { API_SCOPES, DEFAULT_OAUTH_SCOPES, getMinimumEquivalentScopes, getScopeDescription } from 'lib/scopes'
import { getAppContext } from 'lib/utils/getAppContext'
import { userLogic } from 'scenes/userLogic'
@@ -165,8 +159,6 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
setTeamHint: (teamId: number | null) => ({ teamId }),
setScopesWereDefaulted: (scopesWereDefaulted: boolean) => ({ scopesWereDefaulted }),
setIsMcpResource: (isMcpResource: boolean) => ({ isMcpResource }),
- loadResourceScopes: (resourceUrl: string) => ({ resourceUrl }),
- setResourceScopesLoading: (loading: boolean) => ({ loading }),
cancel: () => ({}),
setCanceling: (canceling: boolean) => ({ canceling }),
setAuthorizationComplete: (complete: boolean) => ({ complete }),
@@ -228,31 +220,6 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
actions.setCanceling(false)
}
},
- loadResourceScopes: async ({ resourceUrl }) => {
- // Fetch scopes from the OAuth Protected Resource Metadata endpoint
- // Per RFC 9728, the metadata is at /.well-known/oauth-protected-resource
- actions.setResourceScopesLoading(true)
- try {
- const url = new URL(resourceUrl)
- const metadataUrl = `${url.origin}/.well-known/oauth-protected-resource`
- const response = await fetch(metadataUrl)
- if (!response.ok) {
- throw new Error(`Failed to fetch protected resource metadata: ${response.status}`)
- }
- const metadata = await response.json()
- if (metadata.scopes_supported && Array.isArray(metadata.scopes_supported)) {
- actions.setScopes(metadata.scopes_supported)
- return
- }
- } catch (e) {
- // Fall back to hardcoded scopes on any error
- console.warn('Failed to fetch resource scopes, using fallback:', e)
- } finally {
- actions.setResourceScopesLoading(false)
- }
- // Fallback to hardcoded MCP scopes
- actions.setScopes(MCP_SERVER_OAUTH_SCOPES)
- },
createNewProject: async ({ name }) => {
actions.setNewProjectLoading(true)
try {
@@ -321,12 +288,6 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
setIsMcpResource: (_, { isMcpResource }) => isMcpResource,
},
],
- resourceScopesLoading: [
- false,
- {
- setResourceScopesLoading: (_, { loading }) => loading,
- },
- ],
isCanceling: [
false,
{
@@ -659,21 +620,8 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
urlToAction(({ actions }) => {
const handleAuthorize = (_: Record<string, any>, searchParams: Record<string, any>): void => {
const requestedScopes = searchParams['scope']?.split(' ')?.filter((scope: string) => scope.length) ?? []
- const resourceParam = searchParams['resource'] as string | undefined
+ const oauthMcpConsent = getAppContext()?.oauth_mcp_consent
- // Check if this is an MCP server request with no scopes specified
- // Per MCP spec, when clients don't specify scopes, they should use all scopes_supported
- // from the Protected Resource Metadata. We default to MCP scopes for known MCP resources.
- let isMcpResource = false
- if (resourceParam) {
- try {
- const resourceUrl = new URL(resourceParam)
- // Strict hostname check to prevent URL manipulation attacks
- isMcpResource = resourceUrl.hostname === 'mcp.posthog.com'
- } catch {
- // Invalid URL, not an MCP resource
- }
- }
const scopesWereDefaulted = requestedScopes.length === 0
const rawRequiredAccessLevel = searchParams['required_access_level'] as 'organization' | 'project' | null
@@ -685,19 +633,19 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
const teamHint = Number.isInteger(teamIdParam) && teamIdParam > 0 ? teamIdParam : null
actions.setScopesWereDefaulted(scopesWereDefaulted)
- actions.setIsMcpResource(isMcpResource)
actions.setTeamHint(teamHint)
actions.setRequiredAccessLevel(requiredAccessLevel || null)
actions.loadOAuthApplication()
actions.loadAllTeams()
- if (scopesWereDefaulted && isMcpResource && resourceParam) {
- // Fetch scopes dynamically from the protected resource metadata
- actions.loadResourceScopes(resourceParam)
+ if (scopesWereDefaulted && oauthMcpConsent?.is_mcp_resource) {
+ actions.setIsMcpResource(true)
+ actions.setScopes(oauthMcpConsent.scopes ?? DEFAULT_OAUTH_SCOPES)
} else if (scopesWereDefaulted) {
- // Fallback to minimal OIDC scopes for non-MCP clients
+ actions.setIsMcpResource(false)
actions.setScopes(DEFAULT_OAUTH_SCOPES)
} else {
+ actions.setIsMcpResource(false)
actions.setScopes(requestedScopes)
}
}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 1ce9856228c2..b1793d7c9b86 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5023,6 +5023,8 @@ export interface AppContext {
suggested_users_with_access?: UserBasicType[]
livestream_host?: string
oauth_application?: OAuthApplicationPublicMetadata
+ /** Server-resolved MCP scopes for OAuth consent when the client omits `scope`. */
+ oauth_mcp_consent?: OAuthMcpConsentContext
/** The user's configured homepage for the current team, bootstrapped so navigation can honor it on first paint. */
homepage?: SceneTab | null
}
@@ -7491,6 +7493,11 @@ export interface ProjectTreeRef {
ref: string | null
}
+export type OAuthMcpConsentContext = {
+ is_mcp_resource: boolean
+ scopes?: string[]
+}
+
export type OAuthApplicationPublicMetadata = {
name: string
client_id: string
diff --git a/playwright/e2e/oauth-mcp-consent.spec.ts b/playwright/e2e/oauth-mcp-consent.spec.ts
new file mode 100644
index 000000000000..2100e013372b
--- /dev/null
+++ b/playwright/e2e/oauth-mcp-consent.spec.ts
@@ -0,0 +1,39 @@
+import { expect, test, testWithWorkspace } from '../utils/workspace-test-base'
+
+const CLIENT_ID = 'e2e_mcp_consent_client_id'
+const CODE_CHALLENGE = 'UI2rDDeC_UEA-4FbZQEa6BwaHxrXvWfXUTju4YEJ5xY'
+
+testWithWorkspace.describe('OAuth MCP consent', () => {
+ testWithWorkspace(
+ 'shows full MCP scope catalog when scope param is omitted',
+ async ({ page, workspace, playwrightSetup }) => {
+ await test.step('seed OAuth app and log in', async () => {
+ await playwrightSetup.callSetupEndpoint('oauth_application', {})
+ await playwrightSetup.login(page, workspace)
+ })
+
+ const authorizeUrl =
+ '/oauth/authorize/' +
+ `?client_id=${CLIENT_ID}` +
+ '&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback' +
+ '&response_type=code' +
+ `&code_challenge=${CODE_CHALLENGE}` +
+ '&code_challenge_method=S256' +
+ '&resource=https%3A%2F%2Fmcp.posthog.com%2Fmcp'
+
+ await test.step('load consent page', async () => {
+ await page.goto(authorizeUrl)
+ await expect(page.getByRole('button', { name: 'Authorize E2E MCP Consent Test App' })).toBeVisible({
+ timeout: 30_000,
+ })
+ })
+
+ await test.step('assert server-preloaded MCP scopes', async () => {
+ await expect(page.getByText('Showing all permissions the PostHog MCP server supports')).toBeVisible()
+ // notebook scopes are absent from the old static fallback, so their
+ // presence proves the server derived the full catalog.
+ await expect(page.getByText('Notebook', { exact: true })).toBeVisible()
+ })
+ }
+ )
+})
diff --git a/posthog/api/oauth/mcp_resource_scopes.py b/posthog/api/oauth/mcp_resource_scopes.py
new file mode 100644
index 000000000000..8fd6bbf3661c
--- /dev/null
+++ b/posthog/api/oauth/mcp_resource_scopes.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+import os
+import json
+from functools import lru_cache
+from typing import TypedDict
+from urllib.parse import urlparse
+
+import structlog
+
+from posthog.cloud_utils import is_dev_mode
+from posthog.scopes import get_oauth_scopes_supported
+from posthog.settings.base_variables import BASE_DIR
+
+logger = structlog.get_logger(__name__)
+
+# The MCP server builds its RFC 9728 `scopes_supported` from this same committed
+# artifact (services/mcp/src/tools/toolDefinitions.ts reads it too). Deriving the
+# consent list from it here keeps the authorization server's promise sourced from
+# its own state instead of a runtime fetch to the resource server.
+_TOOL_DEFINITIONS_PATH = os.path.join(BASE_DIR, "services", "mcp", "schema", "generated-tool-definitions.json")
+
+# Keep in sync with services/mcp/src/lib/routing.ts regional MCP hostnames.
+PRODUCTION_MCP_HOSTS = frozenset(
+ {
+ "mcp.posthog.com",
+ "mcp.us.posthog.com",
+ "mcp.eu.posthog.com",
+ "mcp-eu.posthog.com",
+ }
+)
+LOCAL_MCP_HOSTS = frozenset({"localhost", "127.0.0.1"})
+
+
+class OAuthMcpConsentContext(TypedDict, total=False):
+ is_mcp_resource: bool
+ scopes: list[str]
+
+
+def is_trusted_posthog_mcp_resource(resource_url: str) -> bool:
+ try:
+ parsed = urlparse(resource_url)
+ except ValueError:
+ return False
+
+ if parsed.scheme not in {"https", "http"}:
+ return False
+
+ hostname = (parsed.hostname or "").lower()
+ if hostname in PRODUCTION_MCP_HOSTS:
+ return parsed.scheme == "https"
+
+ if is_dev_mode() and hostname in LOCAL_MCP_HOSTS:
+ return parsed.scheme == "http"
+
+ return False
+
+
+@lru_cache(maxsize=1)
+def _tool_required_scopes() -> frozenset[str]:
+ with open(_TOOL_DEFINITIONS_PATH) as definitions_file:
+ definitions = json.load(definitions_file)
+
+ return frozenset(
+ scope for definition in definitions.values() for scope in (definition.get("required_scopes") or [])
+ )
+
+
+def mcp_advertised_scopes() -> list[str]:
+ """The scopes an MCP client gets when it omits `scope` on `/oauth/authorize`.
+
+ Mirrors the MCP server's `getAdvertisedOAuthScopes()`: every identity scope
+ (no `:`) plus the resource scopes some tool actually requires, both drawn from
+ the authorization server's own supported set so nothing advertised is later
+ rejected at `/authorize`.
+ """
+ required = _tool_required_scopes()
+ return [scope for scope in get_oauth_scopes_supported() if ":" not in scope or scope in required]
+
+
+def build_oauth_mcp_consent_context(resource_url: str | None) -> OAuthMcpConsentContext | None:
+ if not resource_url or not is_trusted_posthog_mcp_resource(resource_url):
+ return None
+
+ return OAuthMcpConsentContext(is_mcp_resource=True, scopes=mcp_advertised_scopes())
diff --git a/posthog/api/oauth/test_mcp_resource_scopes.py b/posthog/api/oauth/test_mcp_resource_scopes.py
new file mode 100644
index 000000000000..fe9c28dac58b
--- /dev/null
+++ b/posthog/api/oauth/test_mcp_resource_scopes.py
@@ -0,0 +1,70 @@
+from unittest.mock import patch
+
+from django.test import SimpleTestCase, override_settings
+
+from posthog.api.oauth.mcp_resource_scopes import (
+ _tool_required_scopes,
+ build_oauth_mcp_consent_context,
+ is_trusted_posthog_mcp_resource,
+ mcp_advertised_scopes,
+)
+
+
+class TestMcpResourceScopes(SimpleTestCase):
+ def test_is_trusted_posthog_mcp_resource_production(self):
+ for host in (
+ "mcp.posthog.com",
+ "mcp.us.posthog.com",
+ "mcp.eu.posthog.com",
+ "mcp-eu.posthog.com",
+ ):
+ self.assertTrue(is_trusted_posthog_mcp_resource(f"https://{host}/mcp"))
+ self.assertFalse(is_trusted_posthog_mcp_resource(f"http://{host}/mcp"))
+ self.assertFalse(is_trusted_posthog_mcp_resource("https://evil.posthog.com/mcp"))
+ # A userinfo-smuggled host must resolve to the real hostname, not the allowlisted prefix.
+ self.assertFalse(is_trusted_posthog_mcp_resource("https://[email protected]/mcp"))
+
+ @override_settings(DEBUG=True)
+ def test_is_trusted_posthog_mcp_resource_local_dev(self):
+ self.assertTrue(is_trusted_posthog_mcp_resource("http://localhost:8787/mcp"))
+ self.assertTrue(is_trusted_posthog_mcp_resource("http://127.0.0.1:8787/mcp"))
+
+ @override_settings(DEBUG=False)
+ def test_local_mcp_host_blocked_outside_dev(self):
+ self.assertFalse(is_trusted_posthog_mcp_resource("http://localhost:8787/mcp"))
+
+ @patch(
+ "posthog.api.oauth.mcp_resource_scopes.get_oauth_scopes_supported",
+ return_value=["openid", "profile", "notebook:read", "notebook:write", "webhook:write"],
+ )
+ @patch(
+ "posthog.api.oauth.mcp_resource_scopes._tool_required_scopes",
+ return_value=frozenset({"notebook:read", "notebook:write"}),
+ )
+ def test_advertised_scopes_keeps_identity_and_tool_required_only(self, _mock_required, _mock_supported):
+ # Identity scopes (no `:`) always ride; resource scopes only if a tool needs them.
+ # `webhook:write` is grantable but exercised by no tool, so it must not be advertised.
+ self.assertEqual(
+ mcp_advertised_scopes(),
+ ["openid", "profile", "notebook:read", "notebook:write"],
+ )
+
+ def test_advertised_scopes_derives_from_real_committed_catalog(self):
+ # Guards the cross-service artifact path and shape: if
+ # services/mcp/schema/generated-tool-definitions.json moves or changes
+ # structure, this fails loudly instead of silently advertising nothing.
+ _tool_required_scopes.cache_clear()
+ scopes = mcp_advertised_scopes()
+ self.assertIn("openid", scopes)
+ self.assertIn("notebook:read", scopes)
+ self.assertGreater(len(scopes), 50)
+
+ def test_build_oauth_mcp_consent_context_success(self):
+ context = build_oauth_mcp_consent_context("https://mcp.posthog.com/mcp")
+
+ assert context is not None
+ self.assertTrue(context["is_mcp_resource"])
+ self.assertIn("notebook:read", context["scopes"])
+
+ def test_build_oauth_mcp_consent_context_ignores_untrusted_resource(self):
+ self.assertIsNone(build_oauth_mcp_consent_context("https://evil.example.com/mcp"))
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 08a8dace507d..b0a724fd0579 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -186,6 +186,37 @@ class TestOAuthAPI(APIBaseTest):
response = self.client.get(self.base_authorization_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
+ @patch("posthog.api.oauth.views.render_template")
+ @patch("posthog.api.oauth.mcp_resource_scopes.mcp_advertised_scopes")
+ def test_authorize_injects_mcp_scopes_when_resource_omits_scope(self, mock_scopes, mock_render):
+ mock_scopes.return_value = ["openid", "notebook:read", "notebook:write", "query:read"]
+ mock_render.return_value = HttpResponse(status=status.HTTP_200_OK)
+
+ auth_url = f"{self.base_authorization_url}&resource=https%3A%2F%2Fmcp.posthog.com%2Fmcp"
+ response = self.client.get(auth_url)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ mock_render.assert_called_once()
+ template_context = mock_render.call_args.kwargs["context"]
+ self.assertEqual(
+ template_context["oauth_mcp_consent"],
+ {
+ "is_mcp_resource": True,
+ "scopes": ["openid", "notebook:read", "notebook:write", "query:read"],
+ },
+ )
+
+ @patch("posthog.api.oauth.views.render_template")
+ def test_authorize_omits_mcp_consent_for_untrusted_resource(self, mock_render):
+ mock_render.return_value = HttpResponse(status=status.HTTP_200_OK)
+
+ auth_url = f"{self.base_authorization_url}&resource=https%3A%2F%2Fevil.example.com%2Fmcp"
+ response = self.client.get(auth_url)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ template_context = mock_render.call_args.kwargs["context"]
+ self.assertNotIn("oauth_mcp_consent", template_context)
+
def test_first_party_app_auto_approves_with_org_scoped_grant(self):
first_party_app = OAuthApplication.objects.create(
name="First Party App",
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index ca9604c9d8e3..6f136df75024 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -47,6 +47,7 @@ from posthog.api.oauth.cimd import (
get_or_create_cimd_application,
is_cimd_client_id,
)
+from posthog.api.oauth.mcp_resource_scopes import build_oauth_mcp_consent_context
from posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_session
from posthog.middleware import is_read_only_impersonation
from posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, User
@@ -1005,25 +1006,29 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
except OAuthToolkitError as error:
return self.error_response(error, application, state=request.query_params.get("state"))
- return render_template(
- "index.html",
- request,
- context={
- "oauth_application": {
- "name": application.name,
- "client_id": application.client_id,
- "is_verified": application.is_verified,
- "logo_uri": application.logo_uri,
- "required_scopes": application.required_scopes,
- # The read-only form of a `*` grant, computed from the same ceiling
- # resolution `validate_scopes` enforces — the frontend's scope list
- # drifts from the server's (both over- and under-granting otherwise).
- "wildcard_read_scopes": sorted(
- scope for scope in effective_ceiling(application.ceiling_scopes) if scope.endswith(":read")
- ),
- }
- },
- )
+ template_context: dict[str, object] = {
+ "oauth_application": {
+ "name": application.name,
+ "client_id": application.client_id,
+ "is_verified": application.is_verified,
+ "logo_uri": application.logo_uri,
+ "required_scopes": application.required_scopes,
+ # The read-only form of a `*` grant, computed from the same ceiling
+ # resolution `validate_scopes` enforces — the frontend's scope list
+ # drifts from the server's (both over- and under-granting otherwise).
+ "wildcard_read_scopes": sorted(
+ scope for scope in effective_ceiling(application.ceiling_scopes) if scope.endswith(":read")
+ ),
+ }
+ }
+
+ requested_scope = (request.query_params.get("scope") or "").strip()
+ if not requested_scope:
+ oauth_mcp_consent = build_oauth_mcp_consent_context(request.query_params.get("resource"))
+ if oauth_mcp_consent is not None:
+ template_context["oauth_mcp_consent"] = oauth_mcp_consent
+
+ return render_template("index.html", request, context=template_context)
def post(self, request, *args, **kwargs):
serializer = OAuthAuthorizationSerializer(data=request.data, context={"user": request.user})
diff --git a/posthog/test/playwright_setup_functions.py b/posthog/test/playwright_setup_functions.py
index aa01642af691..a8f87742d8eb 100644
--- a/posthog/test/playwright_setup_functions.py
+++ b/posthog/test/playwright_setup_functions.py
@@ -562,6 +562,50 @@ def create_hog_function_template(
return PlaywrightHogFunctionTemplateResult(template_id=data.template_id, created=False)
+class PlaywrightOAuthApplicationData(BaseModel):
+ client_id: str = "e2e_mcp_consent_client_id"
+ name: str = "E2E MCP Consent Test App"
+ redirect_uris: str = "https://example.com/callback"
+
+
+class PlaywrightOAuthApplicationResult(BaseModel):
+ client_id: str
+ name: str
+ created: bool
+
+
+def create_oauth_application(data: PlaywrightOAuthApplicationData) -> PlaywrightOAuthApplicationResult:
+ """Seed an OAuth application for consent-page e2e tests.
+
+ OAuth apps are global (not team-scoped). Idempotent via get_or_create on client_id.
+ """
+ from posthog.models.oauth import OAuthApplication
+
+ app, created = OAuthApplication.objects.get_or_create(
+ client_id=data.client_id,
+ defaults={
+ "name": data.name,
+ "client_secret": "",
+ "client_type": OAuthApplication.CLIENT_PUBLIC,
+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ "redirect_uris": data.redirect_uris,
+ "algorithm": "RS256",
+ },
+ )
+ if not created:
+ update_fields: list[str] = []
+ if app.name != data.name:
+ app.name = data.name
+ update_fields.append("name")
+ if app.redirect_uris != data.redirect_uris:
+ app.redirect_uris = data.redirect_uris
+ update_fields.append("redirect_uris")
+ if update_fields:
+ app.save(update_fields=update_fields)
+
+ return PlaywrightOAuthApplicationResult(client_id=app.client_id, name=app.name, created=created)
+
+
@dataclass(frozen=True)
class SetupFunctionConfig:
function: PlaywrightSetupFunction
@@ -580,4 +624,9 @@ PLAYWRIGHT_SETUP_FUNCTIONS: dict[str, SetupFunctionConfig] = {
input_model=PlaywrightHogFunctionTemplateData,
description="Seeds a single HogFunctionTemplate row (templates are global, not team-scoped)",
),
+ "oauth_application": SetupFunctionConfig(
+ function=create_oauth_application, # type: ignore
+ input_model=PlaywrightOAuthApplicationData,
+ description="Seeds an OAuth application for consent-page e2e tests (global, idempotent on client_id)",
+ ),
}
diff --git a/posthog/utils.py b/posthog/utils.py
index e5a82438c25f..49bad398fb34 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -659,6 +659,8 @@ def _build_template_context(
# Merge caller-provided keys into posthog_app_context (e.g. oauth_application from the authorize view)
if "oauth_application" in context:
posthog_app_context["oauth_application"] = context.pop("oauth_application")
+ if "oauth_mcp_consent" in context:
+ posthog_app_context["oauth_mcp_consent"] = context.pop("oauth_mcp_consent")
# JSON dumps here since there may be objects like Queries
# that are not serializable by Django's JSON serializer
diff --git a/services/mcp/src/hono/public-routes.ts b/services/mcp/src/hono/public-routes.ts
index bca2ef51a06d..315b1fab6f6f 100644
--- a/services/mcp/src/hono/public-routes.ts
+++ b/services/mcp/src/hono/public-routes.ts
@@ -2,6 +2,7 @@ import { serveStatic } from '@hono/node-server/serve-static'
import type { Hono } from 'hono'
import { isLocalApi } from '@/lib/constants'
+import { corsHeadersForOAuthMetadata, oauthMetadataPreflightResponse } from '@/lib/oauth-metadata-cors'
import { buildRedirectUrl, getPublicUrl, matchAuthServerRedirect } from '@/lib/routing'
import { getAdvertisedOAuthScopes } from '@/tools/toolDefinitions'
@@ -48,6 +49,11 @@ function readyzHandler(redis: RedisWithPing, lifecycle: Lifecycle) {
// the client connected on, so we derive it from the request rather than
// hard-coding the host.
const wellKnownHandler = (c: HonoCtx): Response => {
+ const preflight = oauthMetadataPreflightResponse(c.req.raw)
+ if (preflight) {
+ return preflight
+ }
+
const url = new URL(c.req.url)
const resourcePath = url.pathname.slice(WELL_KNOWN_PREFIX.length) || '/'
const resourceUrl = getPublicUrl(c.req.raw)
@@ -62,7 +68,7 @@ const wellKnownHandler = (c: HonoCtx): Response => {
bearer_methods_supported: ['header'],
},
200,
- { 'Cache-Control': 'public, max-age=3600' }
+ { 'Cache-Control': 'public, max-age=3600', ...corsHeadersForOAuthMetadata(c.req.raw) }
)
}
diff --git a/services/mcp/src/index.ts b/services/mcp/src/index.ts
index f93f39b831f6..b263e1467158 100644
--- a/services/mcp/src/index.ts
+++ b/services/mcp/src/index.ts
@@ -3,6 +3,7 @@ import { MCP_DOCS_URL, getAuthorizationServerUrl } from '@/lib/constants'
import { isIdJagAccessToken } from '@/lib/id-jag'
import { RequestLogger, withLogging } from '@/lib/logging'
import { extractClientInfoFromBody } from '@/lib/mcp-client-info'
+import { corsHeadersForOAuthMetadata, oauthMetadataPreflightResponse } from '@/lib/oauth-metadata-cors'
import { RequestProperties } from '@/lib/request-properties'
import { buildRedirectUrl, matchAuthServerRedirect } from '@/lib/routing'
import { extractBearerToken, hash, parseMcpMode, sanitizeHeaderValue } from '@/lib/utils'
@@ -154,6 +155,11 @@ const handleRequest = async (
// 5. Client reconnects to MCP with the access token
const wellKnownPrefix = '/.well-known/oauth-protected-resource'
if (url.pathname.startsWith(wellKnownPrefix)) {
+ const preflight = oauthMetadataPreflightResponse(request)
+ if (preflight) {
+ return preflight
+ }
+
// Extract the resource path from after the well-known prefix
// e.g., /.well-known/oauth-protected-resource/mcp → /mcp
const resourcePath = url.pathname.slice(wellKnownPrefix.length) || '/'
@@ -176,6 +182,7 @@ const handleRequest = async (
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'public, max-age=3600',
+ ...corsHeadersForOAuthMetadata(request),
},
}
)
diff --git a/services/mcp/src/lib/oauth-metadata-cors.ts b/services/mcp/src/lib/oauth-metadata-cors.ts
new file mode 100644
index 000000000000..6e274a292e58
--- /dev/null
+++ b/services/mcp/src/lib/oauth-metadata-cors.ts
@@ -0,0 +1,34 @@
+/** PostHog app origins that render the OAuth consent page and fetch MCP metadata in-browser. */
+export const OAUTH_CONSENT_PAGE_ORIGINS = [
+ 'https://us.posthog.com',
+ 'https://eu.posthog.com',
+ 'http://localhost:8000',
+ 'http://127.0.0.1:8000',
+ 'http://localhost:8010',
+ 'http://127.0.0.1:8010',
+ 'http://localhost:8080',
+ 'http://127.0.0.1:8080',
+] as const
+
+export function corsHeadersForOAuthMetadata(request: Request): Record<string, string> {
+ const origin = request.headers.get('Origin')
+ if (!origin || !OAUTH_CONSENT_PAGE_ORIGINS.includes(origin as (typeof OAUTH_CONSENT_PAGE_ORIGINS)[number])) {
+ return {}
+ }
+ return {
+ 'Access-Control-Allow-Origin': origin,
+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',
+ 'Access-Control-Allow-Headers': 'Content-Type',
+ 'Access-Control-Max-Age': '3600',
+ Vary: 'Origin',
+ }
+}
+
+/** OPTIONS preflight for RFC 9728 metadata — shared by Hono and Cloudflare Workers. */
+export function oauthMetadataPreflightResponse(request: Request): Response | null {
+ if (request.method !== 'OPTIONS') {
+ return null
+ }
+ const headers = corsHeadersForOAuthMetadata(request)
+ return new Response(null, { status: 204, headers })
+}
diff --git a/services/mcp/tests/hono/app-routes.test.ts b/services/mcp/tests/hono/app-routes.test.ts
index 033c5d54098e..bbd4ee06a5e1 100644
--- a/services/mcp/tests/hono/app-routes.test.ts
+++ b/services/mcp/tests/hono/app-routes.test.ts
@@ -154,6 +154,29 @@ describe('Hono App Routes', () => {
const res = await app.request('/.well-known/oauth-protected-resource/mcp')
expect(res.headers.get('Cache-Control')).toBe('public, max-age=3600')
})
+
+ it('should allow CORS from PostHog app origins for consent-page metadata fetch', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/.well-known/oauth-protected-resource/mcp', {
+ headers: { Origin: 'https://us.posthog.com' },
+ })
+ expect(res.status).toBe(200)
+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('https://us.posthog.com')
+ expect(res.headers.get('Vary')).toBe('Origin')
+ })
+
+ it('should answer OPTIONS preflight for PostHog app origins', async () => {
+ const { app } = createApp(mockRedis)
+ const res = await app.request('/.well-known/oauth-protected-resource/mcp', {
+ method: 'OPTIONS',
+ headers: {
+ Origin: 'https://us.posthog.com',
+ 'Access-Control-Request-Method': 'GET',
+ },
+ })
+ expect(res.status).toBe(204)
+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('https://us.posthog.com')
+ })
})
describe('hostname-based region detection', () => {
diff --git a/services/mcp/tests/workers/mcp-protocol.test.ts b/services/mcp/tests/workers/mcp-protocol.test.ts
index bc5a946532ee..83c8987b09d2 100644
--- a/services/mcp/tests/workers/mcp-protocol.test.ts
+++ b/services/mcp/tests/workers/mcp-protocol.test.ts
@@ -30,6 +30,29 @@ describe('MCP HTTP entry point (Cloudflare Workers)', () => {
const body = (await response.json()) as Record<string, unknown>
expect(body.resource).toBe('https://mcp.posthog.com/sse')
})
+
+ it('allows CORS from PostHog app origins for consent-page metadata fetch', async () => {
+ const response = await SELF.fetch('https://mcp.posthog.com/.well-known/oauth-protected-resource/mcp', {
+ headers: { Origin: 'https://us.posthog.com' },
+ })
+
+ expect(response.status).toBe(200)
+ expect(response.headers.get('Access-Control-Allow-Origin')).toBe('https://us.posthog.com')
+ expect(response.headers.get('Vary')).toBe('Origin')
+ })
+
+ it('answers OPTIONS preflight for PostHog app origins', async () => {
+ const response = await SELF.fetch('https://mcp.posthog.com/.well-known/oauth-protected-resource/mcp', {
+ method: 'OPTIONS',
+ headers: {
+ Origin: 'https://us.posthog.com',
+ 'Access-Control-Request-Method': 'GET',
+ },
+ })
+
+ expect(response.status).toBe(204)
+ expect(response.headers.get('Access-Control-Allow-Origin')).toBe('https://us.posthog.com')
+ })
})
describe('Authentication challenges', () => {