: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
feat(mcp_store): turn the MCP store into a team gateway (#72409)
Chris Volzer3d0287f058b2
diff --git a/.gitignore b/.gitignoreindex 233dbe220e88..95d2985b95a1 100644--- a/.gitignore+++ b/.gitignore@@ -226,3 +226,6 @@ rust/cohort-stream-processor/cohort-store/# Local TLS certs (e.g. mkcert) — never commit private keys*.pem++# Redis persistence snapshot dropped by a locally running redis-server+dump.rdbdiff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 8a5ca8be9ea9..cc40993cc1fa 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -161,6 +161,7 @@ rules:|FeatureFlag|TeamExperimentsConfig|TeamFeatureFlagDefaultsConfig+ |TeamMCPGatewayConfig|TeamSessionSummariesConfig|TeamWorkflowsConfig|FieldNote@@ -214,9 +215,16 @@ rules:|Metric|RelationshipProposal|MCPAnalyticsSubmission+ |MCPAuditEvent+ |MCPGatewayServer|MCPIntentClusterSnapshot|MCPIntentEmbeddingCache+ |MCPMemberServerRevocation+ |MCPOrgRule+ |MCPServiceAccount+ |MCPServiceAccountServerAccess|MCPSession+ |MCPToolPolicy|Opportunity|OptOutSyncConfig|Node@@ -486,6 +494,7 @@ rules:|FeatureFlag|TeamExperimentsConfig|TeamFeatureFlagDefaultsConfig+ |TeamMCPGatewayConfig|TeamSessionSummariesConfig|TeamWorkflowsConfig|FieldNote@@ -533,9 +542,16 @@ rules:|MessageTemplate|Metric|RelationshipProposal+ |MCPAuditEvent+ |MCPGatewayServer|MCPIntentClusterSnapshot|MCPIntentEmbeddingCache+ |MCPMemberServerRevocation+ |MCPOrgRule+ |MCPServiceAccount+ |MCPServiceAccountServerAccess|MCPSession+ |MCPToolPolicy|Opportunity|OptOutSyncConfig|Nodediff --git a/ee/hogai/tools/call_mcp_server/installations.py b/ee/hogai/tools/call_mcp_server/installations.pyindex 03fe335d44fe..a724b838e31c 100644--- a/ee/hogai/tools/call_mcp_server/installations.py+++ b/ee/hogai/tools/call_mcp_server/installations.py@@ -1,9 +1,12 @@from __future__ import annotations+from uuid import UUID+from django.db.models import Qfrom posthog.models import Team, User+from products.mcp_store.backend.facade.api import resolve_member_tool_statesfrom products.mcp_store.backend.models import MCPServerInstallation, MCPServerInstallationToolfrom products.mcp_store.backend.oauth import refresh_installation_token@@ -30,6 +33,10 @@ def _get_installations(team: Team, user: User) -> list[dict]:dict(row)for row in MCPServerInstallation.objects.filter(team=team, is_enabled=True).filter(Q(scope="shared") | Q(user=user))+ # Gateway layer: servers disabled for the team, or turned off for this+ # member by an admin, are invisible to the agent too.+ .filter(Q(gateway_server__isnull=True) | Q(gateway_server__is_team_enabled=True))+ .exclude(gateway_server__member_revocations__user=user).values("id","display_name",@@ -37,6 +44,7 @@ def _get_installations(team: Team, user: User) -> list[dict]:"auth_type","sensitive_configuration","scope",+ "gateway_server_id",)]ready_shared_by_url = {row["url"]: row for row in rows if row["scope"] == "shared" and _is_row_ready(row)}@@ -56,34 +64,38 @@ def _get_cached_tools(installation_id: str) -> list[dict]:Each row is shaped to match the `tools/list` payload the MCP client wouldreturn, so the agent code can format it identically whether the data came- from Postgres or from a fresh upstream call. `approval_state` rides along- so callers don't need a second query to filter/annotate."""+ from Postgres or from a fresh upstream call. Approval states are deliberately+ not included: effective states come from `_get_tool_approval_states`, which+ resolves through the gateway policy engine."""rows = MCPServerInstallationTool.objects.filter(installation_id=installation_id, removed_at__isnull=True).values(- "tool_name", "description", "input_schema", "approval_state"+ "tool_name", "description", "input_schema")return [{"name": row["tool_name"],"description": row["description"] or "No description","inputSchema": row["input_schema"] or {},- "approval_state": row["approval_state"],}for row in rows]-def _get_tool_approval_states(installation_id: str) -> dict[str, str]:- """Return a {tool_name: approval_state} map for an installation.-- Rows with `removed_at` set surface as `"do_not_use"` so the agent can't- call them even if the cached approval state was previously `approved` —- if the tool is gone upstream, it's gone. Anything not in the map is- treated as `needs_approval` by the caller (explicit opt-in for freshly- discovered tools)."""- rows = MCPServerInstallationTool.objects.filter(installation_id=installation_id).values(- "tool_name", "approval_state", "removed_at"+def _get_tool_approval_states(+ installation_id: str,+ team_id: int,+ gateway_server_id: UUID | None,+ user: User | None = None,+) -> dict[str, str]:+ """Return a {tool_name: effective_state} map for an installation.++ See `resolve_member_tool_states` on the mcp_store facade for the resolution+ semantics (gateway policy engine vs. cached per-tool approval state)."""+ return resolve_member_tool_states(+ installation_id,+ team_id,+ gateway_server_id,+ user_id=user.id if user is not None else None,)- return {row["tool_name"]: ("do_not_use" if row["removed_at"] else row["approval_state"]) for row in rows}def _mark_needs_reauth_sync(installation_id: str) -> None:diff --git a/ee/hogai/tools/call_mcp_server/test/test_tool.py b/ee/hogai/tools/call_mcp_server/test/test_tool.pyindex 4edbb8ed795a..13c94725d013 100644--- a/ee/hogai/tools/call_mcp_server/test/test_tool.py+++ b/ee/hogai/tools/call_mcp_server/test/test_tool.py@@ -10,12 +10,21 @@ from asgiref.sync import sync_to_asyncfrom langchain_core.runnables import RunnableConfigfrom parameterized import parameterized-from products.mcp_store.backend.models import MCPServerInstallation, MCPServerInstallationTool+from products.mcp_store.backend.models import (+ MCPGatewayServer,+ MCPServerInstallation,+ MCPServerInstallationTool,+ TeamMCPGatewayConfig,+)from products.mcp_store.backend.oauth import TokenRefreshErrorfrom ee.hogai.context.context import AssistantContextManagerfrom ee.hogai.tool_errors import MaxToolFatalError, MaxToolRetryableError-from ee.hogai.tools.call_mcp_server.installations import _build_server_headers, _get_installations+from ee.hogai.tools.call_mcp_server.installations import (+ _build_server_headers,+ _get_installations,+ _get_tool_approval_states,+)from ee.hogai.tools.call_mcp_server.mcp_client import MCPClientErrorfrom ee.hogai.tools.call_mcp_server.tool import CallMCPServerToolfrom ee.hogai.utils.types.base import AssistantState, NodePath@@ -315,6 +324,87 @@ class TestCallTool(TestCallMCPServerTool):self.assertIn("Failed to connect", str(ctx.exception))+class TestGetToolApprovalStates(BaseTest):+ def test_gateway_policy_uses_cached_tool_annotations(self) -> None:+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Issue server",+ url="https://mcp.issue-policy.example.com/mcp",+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name=server.name,+ url=server.url,+ gateway_server=server,+ )+ MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name="manage_issue",+ annotations={"destructiveHint": True},+ last_seen_at=timezone.now(),+ )+ TeamMCPGatewayConfig.objects.for_team(self.team.id).create(+ team=self.team,+ member_default_preset="block",+ )++ with self.assertNumQueries(5):+ states = _get_tool_approval_states(str(installation.id), self.team.id, server.id, self.user)++ assert states == {"manage_issue": "do_not_use"}+++class TestCachedToolListGatewayPolicy(TestCallMCPServerTool):+ async def test_cached_tool_list_resolves_states_through_gateway_policy(self) -> None:+ def _setup():+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Issue server",+ url="https://mcp.example.com/mcp",+ )+ installation = self._install_server()+ installation.gateway_server = server+ installation.save()+ for tool_name, description in (+ ("delete_issue", "Deletes an issue permanently."),+ ("read_issue", "Reads an issue."),+ ):+ MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name=tool_name,+ description=description,+ approval_state="approved",+ last_seen_at=timezone.now(),+ )+ TeamMCPGatewayConfig.objects.for_team(self.team.id).create(+ team=self.team,+ member_default_preset="block",+ )+ return installation, server++ installation, server = await sync_to_async(_setup)()+ tool = self._create_tool(+ installations=[+ {+ "id": str(installation.id),+ "display_name": "Test Server",+ "url": installation.url,+ "gateway_server_id": server.id,+ }+ ]+ )++ listing = await tool._get_cached_tool_list(installation.url)++ assert listing is not None+ assert "read_issue" in listing+ # The legacy per-installation state says approved, but the team's+ # "block destructive" preset must gate the cached list too.+ assert "delete_issue" not in listing+ assert tool._approval_cache[installation.url]["delete_issue"] == "do_not_use"++class TestGetInstallations(TestCallMCPServerTool):def _create_teammate(self, email="[email protected]"):from posthog.models import Userdiff --git a/ee/hogai/tools/call_mcp_server/tool.py b/ee/hogai/tools/call_mcp_server/tool.pyindex fb2a17f41921..9ded480c5a7a 100644--- a/ee/hogai/tools/call_mcp_server/tool.py+++ b/ee/hogai/tools/call_mcp_server/tool.py@@ -84,7 +84,8 @@ class CallMCPServerTool(MaxTool):_installations: list_installations_by_url: dict[str, dict]_server_headers: dict[str, dict[str, str]]- # {server_url: {tool_name: approval_state}} — lazily populated to minimize DB reads; also seeded by _get_cached_tool_list to avoid double lookup when calling __list_tools__+ # {server_url: {tool_name: effective_state}} — lazily populated via+ # _get_approval_states so every path holds gateway-policy-resolved states._approval_cache: dict[str, dict[str, str]]@classmethod@@ -136,7 +137,12 @@ class CallMCPServerTool(MaxTool):if cached is not None:return cachedinst = self._get_installation(server_url)- states = await database_sync_to_async(_get_tool_approval_states)(str(inst["id"]))+ states = await database_sync_to_async(_get_tool_approval_states)(+ str(inst["id"]),+ self._team.id,+ inst.get("gateway_server_id"),+ self._user,+ )self._approval_cache[server_url] = statesreturn states@@ -195,9 +201,10 @@ class CallMCPServerTool(MaxTool):rows = await database_sync_to_async(_get_cached_tools)(str(inst["id"]))if not rows:return None- approval_states = {row["name"]: row["approval_state"] for row in rows}- # Seed the approval cache so a subsequent `tools/call` doesn't re-query.- self._approval_cache.setdefault(server_url, dict(approval_states))+ # Resolve through the gateway policy engine (and warm the shared cache),+ # never the raw per-installation flags — a team ceiling or org rule must+ # gate the cached list exactly like a fresh tools/list.+ approval_states = await self._get_approval_states(server_url)return self._format_tool_list(server_url, rows, approval_states)async def _call_server(self, server_url: str, tool_name: str, arguments: dict | None) -> str:diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 009a3d4ca0ce..7b4e0430d12c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7119,9 +7119,9 @@ snapshots:scenes-app-settings-user--settings-user-danger-zone--light:hash: v1.k794b7964.96846d7823357e89a9d91350f6f435373fe287f713250b59ccce2dbd31b6f69c.kl21kygOhH1SlNOJ6VekMMlGUuyNg5Ka7NXFoHcG6M0scenes-app-settings-user--settings-user-navigation--dark:- hash: v1.k794b7964.68e19b6597e184cfa2953dc29e234545cf800d0b82cb7d1f29b1fc0d56802c25.0jGd_KRf9U-UvFIdYhGpFZBnIjnD9NP-9oIvIJ9QFjs+ hash: v1.k794b7964.cbe8a7155a74500ce61596851359605e3a86c6b8d627dd2a1a065ebac9e77faa.FMw128N8fWYGkBwDnXgRyOXaK-Q4FZhUm-T5MAEmkDIscenes-app-settings-user--settings-user-navigation--light:- hash: v1.k794b7964.78cc9b0da938b3d09c8053de11dc396961b566d87a27e7c07134457ce23aea82.x1XNnjEtqJ9scvL7-t_t0MvTFXeuveiQImx1NUWptqE+ hash: v1.k794b7964.234c39e18037876ab898373ce69b5f6d0071fd285f0b46e7ee0c589a85942c1c.y8lk5o0Yj_Ju0CfpKDnweF8s92xxNdsqmq2JkrOX-kUscenes-app-settings-user--settings-user-notifications--dark:hash: v1.k794b7964.a09a57f1c0bbcebf82942edebeba7772b2f684ba235bcef3a816aec2beb4cbce.AtQZhdZeeMVvpcmyBhPvprSMZawliTZaIFE5G8M_MVgscenes-app-settings-user--settings-user-notifications--light:diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.tsindex 6a9fad5e23a8..9009fd804345 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts@@ -370,6 +370,7 @@ export interface accessControlsLogicActions {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -508,6 +509,7 @@ export interface accessControlsLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -650,6 +652,7 @@ export interface accessControlsLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -765,6 +768,7 @@ export interface accessControlsLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.tsindex 2452308157e7..ee92f4878888 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts@@ -86,6 +86,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -205,6 +206,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -316,6 +318,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -440,6 +443,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -569,6 +573,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -700,6 +705,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -811,6 +817,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -961,6 +968,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -1074,6 +1082,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -1186,6 +1195,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -1298,6 +1308,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -1411,6 +1422,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -1523,6 +1535,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -1646,6 +1659,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -1758,6 +1772,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.tsindex e64c4af6e32c..07eb08065e8f 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts@@ -126,6 +126,7 @@ export interface accessControlLogicValues {| 'logs'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -371,6 +372,7 @@ export interface accessControlLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -476,6 +478,7 @@ export interface accessControlLogicMeta {| 'logs'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -585,6 +588,7 @@ export interface accessControlLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -697,6 +701,7 @@ export interface accessControlLogicMeta {| 'loop'| 'marketing_analytics'| 'mcp_analytics'+ | 'mcp_builtin_agent'| 'metrics'| 'notebook'| 'organization'@@ -970,6 +975,7 @@ export const accessControlLogic = kea<accessControlLogicType>([| 'llm_skill'| 'logs'| 'marketing_analytics'+ | 'mcp_builtin_agent'| 'mcp_analytics'| 'metrics'| 'notebook'@@ -1080,6 +1086,7 @@ export const accessControlLogic = kea<accessControlLogicType>([| 'llm_skill'| 'logs'| 'marketing_analytics'+ | 'mcp_builtin_agent'| 'mcp_analytics'| 'metrics'| 'notebook'@@ -1205,6 +1212,7 @@ export const accessControlLogic = kea<accessControlLogicType>([| 'llm_skill'| 'logs'| 'marketing_analytics'+ | 'mcp_builtin_agent'| 'mcp_analytics'| 'metrics'| 'notebook'diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 80c4db8f007c..80d1fbfb45f1 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -389,6 +389,7 @@ export const FEATURE_FLAGS = {MAX_WEB_ANALYTICS_NUDGE: 'posthog-ai-web-analytics-nudge', // owner: @jordanm-posthog #team-web-analyticsMCP_ANALYTICS: 'mcp-analytics', // owner: #project-mcp-analyticsMCP_ANALYTICS_INTENT_ROUTING: 'mcp-analytics-intent-routing', // owner: #project-mcp-analytics+ MCP_GATEWAY: 'mcp-gateway', // owner: #team-self-driving — gates the MCP gateway UI AND backend enforcement of built-in agent MCP access (delegated-only installs + restricted sandbox token scope); roll out by organizationMCP_SERVERS: 'mcp-servers', // owner: #team-posthog-aiMESSAGING_SES: 'messaging-ses', // owner #team-workflowsMETRICS: 'metrics', // owner: #team-apm (@jonmcwest, @frankh)diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 14ae04cb1991..1b8971556d4a 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -234,6 +234,7 @@ export const API_SCOPES_OMITTED_FROM_MODAL: Partial<Record<APIScopeObject, strin// INTERNAL_API_SCOPE_OBJECTS — server-minted only, never user-grantable.clickhouse_test_cluster_perf: 'Internal: minted programmatically only.',internal_run: 'Internal: marks a server-minted sandbox/agent run credential.',+ mcp_builtin_agent: 'Internal: identifies a trusted built-in agent credential.',signal_scout_internal: 'Internal: sandbox-only writes for the headless Signals agent.',signal_scout_report: 'Internal: sandbox-only writes for the scout report channel.',// OAUTH_HIDDEN_SCOPE_OBJECTS — pasteable into a PAT, but never advertised via OAuth/CLI/MCP.diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex a91bf626a333..963965c94ba9 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -107,6 +107,10 @@ export const productScenes: Record<string, () => Promise<any>> = {ManagedMigrationNew: () => import('../../products/managed_migrations/frontend/ManagedMigration'),MCPAnalytics: () => import('../../products/mcp_analytics/frontend/MCPAnalyticsScene'),MCPAnalyticsToolDetail: () => import('../../products/mcp_analytics/frontend/MCPAnalyticsToolDetail'),+ McpGateway: () => import('../../products/mcp_store/frontend/gateway/McpGatewayScene'),+ McpGatewayServer: () => import('../../products/mcp_store/frontend/gateway/GatewayServerScene'),+ McpGatewayAgent: () => import('../../products/mcp_store/frontend/gateway/GatewayAgentScene'),+ McpGatewayMember: () => import('../../products/mcp_store/frontend/gateway/GatewayMemberScene'),Metrics: () => import('../../products/metrics/frontend/MetricsScene'),TaskTracker: () => import('../../products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker'),Pulse: () => import('../../products/pulse/frontend/PulseScene'),diff --git a/frontend/src/products.json b/frontend/src/products.jsonindex 1f56a0ec98bd..fee86c683bfd 100644--- a/frontend/src/products.json+++ b/frontend/src/products.json@@ -184,6 +184,7 @@"type": "mcp_analytics","intents": ["mcp_analytics"]},+ { "path": "MCP servers", "category": "AI engineering", "iconType": "tools", "type": null, "intents": [] },{"path": "Metrics","category": "App monitoring",diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 031789442c8d..f90201033a59 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -180,6 +180,11 @@ export const productRoutes: Record<string, [string, string]> = {'/mcp-analytics/tool-quality/:toolName': ['MCPAnalyticsToolDetail', 'mcpAnalyticsTool'],'/mcp-analytics/intent-clustering': ['MCPAnalytics', 'mcpAnalyticsIntentClustering'],'/mcp-analytics/notifications': ['MCPAnalytics', 'mcpAnalyticsNotifications'],+ '/mcp-servers/server/:id': ['McpGatewayServer', 'mcpGatewayServer'],+ '/mcp-servers/agent/:id': ['McpGatewayAgent', 'mcpGatewayAgent'],+ '/mcp-servers/member/:id': ['McpGatewayMember', 'mcpGatewayMember'],+ '/mcp-servers': ['McpGateway', 'mcpGateway'],+ '/mcp-servers/:tab': ['McpGateway', 'mcpGatewayTab'],'/metrics': ['Metrics', 'metrics'],'/tasks': ['TaskTracker', 'taskTracker'],'/tasks/:taskId': ['TaskTracker', 'taskDetail'],@@ -719,6 +724,17 @@ export const productConfiguration: Record<string, any> = {layout: 'app-container',iconType: 'mcp_analytics',},+ McpGateway: {+ projectBased: true,+ name: 'MCP servers',+ description:+ 'Route every MCP server your team uses through one gateway: shared credentials, per-tool policies, agent identities, and an audit log.',+ layout: 'app-container',+ iconType: 'tools',+ },+ McpGatewayServer: { projectBased: true, name: 'MCP server' },+ McpGatewayAgent: { projectBased: true, name: 'MCP agent' },+ McpGatewayMember: { projectBased: true, name: 'MCP member access' },Metrics: {name: 'Metrics',projectBased: true,@@ -1207,6 +1223,12 @@ export const productUrls = {mcpAnalyticsTool: (toolName: string): string => `/mcp-analytics/tool-quality/${encodeURIComponent(toolName)}`,mcpAnalyticsIntentClustering: (): string => '/mcp-analytics/intent-clustering',mcpAnalyticsNotifications: (): string => '/mcp-analytics/notifications',+ mcpGateway: (): string => '/mcp-servers',+ mcpGatewayTab: (tab: string): string => `/mcp-servers/${tab}`,+ mcpGatewayServer: (id: string, scope?: string): string =>+ `/mcp-servers/server/${id}${scope ? `?scope=${encodeURIComponent(scope)}` : ''}`,+ mcpGatewayAgent: (id: string): string => `/mcp-servers/agent/${id}`,+ mcpGatewayMember: (id: string | number): string => `/mcp-servers/member/${id}`,metrics: (): string => '/metrics',notebooks: (): string => '/notebooks',notebook: (shortId: string): string => `/notebooks/${shortId}`,@@ -2080,6 +2102,17 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [sceneKey: 'MCPAnalytics',sceneKeys: ['MCPAnalytics', 'MCPAnalyticsToolDetail'],},+ {+ path: 'MCP servers',+ intents: [],+ category: ProductItemCategory.AI_ENGINEERING,+ href: urls.mcpGateway(),+ iconType: 'tools',+ flag: FEATURE_FLAGS.MCP_GATEWAY,+ tags: ['alpha'],+ sceneKey: 'McpGateway',+ sceneKeys: ['McpGateway', 'McpGatewayServer', 'McpGatewayAgent', 'McpGatewayMember'],+ },{path: 'Marketing analytics',intents: [ProductKey.MARKETING_ANALYTICS],diff --git a/frontend/src/scenes/inbox/components/config/AgentsTab.tsx b/frontend/src/scenes/inbox/components/config/AgentsTab.tsxindex 0be5822065ef..2ca8e9c44f03 100644--- a/frontend/src/scenes/inbox/components/config/AgentsTab.tsx+++ b/frontend/src/scenes/inbox/components/config/AgentsTab.tsx@@ -121,10 +121,7 @@ export function AgentsTab(): JSX.Element {)}{featureFlags[FEATURE_FLAGS.MCP_SERVERS] && (- <Subsection- title="MCP servers"- description="External tools agents can read from. PostHog data is always available; this is everything else."- >+ <Subsection title="MCP servers" description="Shared external tools that scheduled Scouts can use."><McpServersSection /></Subsection>)}diff --git a/frontend/src/scenes/inbox/components/config/McpServersSection.tsx b/frontend/src/scenes/inbox/components/config/McpServersSection.tsxindex 4e51fa42aa94..7dc69af7a908 100644--- a/frontend/src/scenes/inbox/components/config/McpServersSection.tsx+++ b/frontend/src/scenes/inbox/components/config/McpServersSection.tsx@@ -1,25 +1,81 @@+import { useMountedLogic, useValues } from 'kea'+import { IconChevronRight, IconServer } from '@posthog/icons'-import { Link } from '@posthog/lemon-ui'+import { LemonTag, LemonTagType, Link, Spinner } from '@posthog/lemon-ui'+import { ServerIcon } from '@posthog/products-mcp-store/frontend/scene/icons'import { urls } from 'scenes/urls'+import type { MCPServiceAccountServerApi } from 'products/mcp_store/frontend/generated/api.schemas'++import { scoutMcpServersLogic } from '../../logics/scoutMcpServersLogic'++const CONNECTION_STATE: Record<+ MCPServiceAccountServerApi['connection_state'],+ { label: string; tagType: LemonTagType }+> = {+ ready: { label: 'Connection ready', tagType: 'success' },+ pending_oauth: { label: 'Pending OAuth', tagType: 'warning' },+ needs_reauth: { label: 'Reconnect', tagType: 'danger' },+ disabled: { label: 'Disabled', tagType: 'muted' },+ missing_credential: { label: 'Needs connection', tagType: 'warning' },+}+export function McpServersSection(): JSX.Element {+ useMountedLogic(scoutMcpServersLogic)+ const { scoutAccount, scoutServers, scoutServersLoading } = useValues(scoutMcpServersLogic)++ if (scoutServersLoading && scoutAccount === null) {+ return (+ <div className="flex items-center gap-2 rounded border border-dashed px-3 py-4 text-sm text-secondary">+ <Spinner /> Loading Scout MCP servers...+ </div>+ )+ }+return (- <Link- to={urls.settings('mcp-servers')}- className="group flex items-center justify-between gap-3 rounded border bg-bg-light px-3 py-2.5 no-underline transition-colors hover:border-primary-3000 hover:bg-bg-3000"- >- <div className="flex items-start gap-3 min-w-0">- <IconServer className="size-5 shrink-0 mt-0.5 text-secondary" />- <div className="min-w-0">- <div className="font-medium text-sm text-default">Manage MCP servers</div>- <p className="text-xs text-secondary mt-0.5 mb-0 max-w-xl">- External tools agents can read from. PostHog data is always available; this is everything else —- connect or disconnect Notion, PagerDuty, Linear, Zendesk, GitHub, anything that speaks MCP.- </p>+ <div className="rounded border bg-bg-light overflow-hidden">+ {scoutServers.length === 0 ? (+ <div className="flex items-start gap-3 px-3 py-3">+ <IconServer className="size-5 shrink-0 mt-0.5 text-secondary" />+ <div className="min-w-0">+ <div className="font-medium text-sm text-default">No MCP servers shared with Scout</div>+ <p className="text-xs text-secondary mt-0.5 mb-0">+ A project admin can share a connection with the Scout agent.+ </p>+ </div></div>- </div>- <IconChevronRight className="size-4 shrink-0 text-muted transition-colors group-hover:text-default" />- </Link>+ ) : (+ <div className="divide-y">+ {scoutServers.map((server) => {+ const state = CONNECTION_STATE[server.connection_state]+ return (+ <div key={server.id} className="flex items-center gap-3 px-3 py-2.5">+ <ServerIcon iconDomain={server.icon_domain} size={28} />+ <div className="min-w-0 flex-1">+ <div className="font-medium text-sm text-default truncate">{server.name}</div>+ {server.description && (+ <div className="text-xs text-secondary truncate">{server.description}</div>+ )}+ </div>+ <LemonTag type={state.tagType} size="small">+ {state.label}+ </LemonTag>+ </div>+ )+ })}+ </div>+ )}+ <Link+ to={urls.settings('mcp-servers')}+ className="group flex items-center justify-between gap-3 border-t px-3 py-2 text-xs no-underline transition-colors hover:bg-bg-3000"+ >+ <span className="text-secondary group-hover:text-default">View MCP server settings</span>+ <IconChevronRight className="size-4 shrink-0 text-muted transition-colors group-hover:text-default" />+ </Link>+ {scoutAccount?.status === 'paused' ? (+ <div className="border-t px-3 py-2 text-xs text-secondary">Scout MCP access is paused.</div>+ ) : null}+ </div>)}diff --git a/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsx b/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsxindex b4de80dc8392..3241ffb93480 100644--- a/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsx+++ b/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsx@@ -2,7 +2,6 @@ import { useActions, useMountedLogic, useValues } from 'kea'import { IconBolt, IconCheckCircle, IconChevronRight, IconCompass, IconGithub, IconServer } from '@posthog/icons'import { LemonModal, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'-import { mcpStoreLogic } from '@posthog/products-mcp-store/frontend/mcpStoreLogic'import { ServerIcon } from '@posthog/products-mcp-store/frontend/scene/icons'import { FEATURE_FLAGS } from 'lib/constants'@@ -14,9 +13,11 @@ import { cn } from 'lib/utils/css-classes'import { urls } from 'scenes/urls'import { scoutFleetLogic } from '../../logics/scoutFleetLogic'+import { scoutMcpServersLogic } from '../../logics/scoutMcpServersLogic'import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'import { userAutonomyLogic } from '../../logics/userAutonomyLogic'import { signalSourcesLogic } from '../../signalSourcesLogic'+import { McpServersSection } from '../config/McpServersSection'import { ScoutsFleetSection } from '../config/scouts/ScoutsFleetSection'import { SelfDrivingSection } from '../config/SelfDrivingSection'import { SignalSourcesPanel } from '../config/SignalSourcesPanel'@@ -218,30 +219,44 @@ function CodeAccessWidget(): JSX.Element {}function McpServersWidget(): JSX.Element {- useMountedLogic(mcpStoreLogic)- const { installations, installationsLoading } = useValues(mcpStoreLogic)- const count = installations.length+ useMountedLogic(scoutMcpServersLogic)+ const { availableScoutServers, scoutAccount, scoutServers, scoutServersLoading, scoutServersNeedingSetup } =+ useValues(scoutMcpServersLogic)+ const { openSetupModal } = useActions(agentSetupModalLogic)+ const availableCount = availableScoutServers.length+ const needsSetupCount = scoutServersNeedingSetup.length+ let status = 'Share external tools'+ let tone: WidgetTone = 'neutral'+ if (scoutAccount?.status === 'paused') {+ status = 'MCP access paused'+ } else if (availableCount > 0 && needsSetupCount > 0) {+ status = `${availableCount} available · ${needsSetupCount} need setup`+ tone = 'done'+ } else if (availableCount > 0) {+ status = `${availableCount} available to Scout`+ tone = 'done'+ } else if (needsSetupCount > 0) {+ status = `${needsSetupCount} need setup`+ tone = 'todo'+ }return (<SetupWidgetCardicon={<IconServer />}title="MCP servers"size="md"- tone={count > 0 ? 'done' : 'neutral'}- loading={installationsLoading && count === 0}- status={count > 0 ? `${count} connected` : 'Connect external tools'}- to={urls.settings('mcp-servers')}+ tone={tone}+ loading={scoutServersLoading && scoutServers.length === 0}+ status={status}+ onClick={() => openSetupModal('mcp-servers')}>- {count > 0 && (+ {scoutServers.length > 0 && (<div className="flex items-center gap-1 pt-1">- {installations.slice(0, 6).map((installation) => (- <ServerIcon- key={installation.id}- iconDomain={installation.icon_domain}- serverUrl={installation.url}- size={16}- />+ {scoutServers.slice(0, 6).map((server) => (+ <ServerIcon key={server.id} iconDomain={server.icon_domain} size={16} />))}- {count > 6 && <span className="text-[11px] text-muted">+{count - 6}</span>}+ {scoutServers.length > 6 && (+ <span className="text-[11px] text-muted">+{scoutServers.length - 6}</span>+ )}</div>)}</SetupWidgetCard>@@ -310,6 +325,12 @@ const SETUP_MODALS: Record<width: 560,body: <SlackNotificationsSection />,},+ 'mcp-servers': {+ title: 'MCP servers',+ description: 'Shared external tools available to scheduled Scouts.',+ width: 560,+ body: <McpServersSection />,+ },}function SetupModal(): JSX.Element {@@ -332,8 +353,8 @@ function SetupModal(): JSX.Element {/*** The agent-setup widgets, grouped into Agents / Connections. Each widget shows* status and nudges the user to finish that part of the setup. Signal sources and Scout troop- * (most edited) are largest; connections medium. Code access and MCP link- * out to settings; the rest open a management modal.+ * (most edited) are largest; connections medium. Code access links out to settings;+ * the rest open a management modal.** Rendered two ways: `rail` (a column to the right of the tabs on wide viewports) and* `stacked` (the Configuration tab body on narrow viewports).diff --git a/frontend/src/scenes/inbox/components/shell/agentSetupModalLogic.ts b/frontend/src/scenes/inbox/components/shell/agentSetupModalLogic.tsindex b591bf25ba8f..f785e9b71d7f 100644--- a/frontend/src/scenes/inbox/components/shell/agentSetupModalLogic.ts+++ b/frontend/src/scenes/inbox/components/shell/agentSetupModalLogic.ts@@ -1,7 +1,7 @@import { MakeLogicType, actions, kea, path, reducers } from 'kea'-/** Setup widgets whose management UI opens in a modal. GitHub and MCP servers link out instead. */-export type AgentSetupModalKey = 'signal-sources' | 'scout-troop' | 'slack'+/** Setup widgets whose management UI opens in a modal. */+export type AgentSetupModalKey = 'signal-sources' | 'scout-troop' | 'slack' | 'mcp-servers'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface agentSetupModalLogicValues {diff --git a/frontend/src/scenes/inbox/logics/scoutMcpServersLogic.test.ts b/frontend/src/scenes/inbox/logics/scoutMcpServersLogic.test.tsnew file mode 100644index 000000000000..8038f4c79bfa--- /dev/null+++ b/frontend/src/scenes/inbox/logics/scoutMcpServersLogic.test.ts@@ -0,0 +1,112 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type {+ ConnectionStateEnumApi,+ MCPServiceAccountApi,+ MCPServiceAccountServerApi,+} from 'products/mcp_store/frontend/generated/api.schemas'++import { scoutMcpServersLogic } from './scoutMcpServersLogic'++function server(id: string, name: string, connectionState: ConnectionStateEnumApi): MCPServiceAccountServerApi {+ return {+ id,+ name,+ description: `${name} workspace`,+ icon_key: name.toLowerCase(),+ icon_domain: `${name.toLowerCase()}.com`,+ connection_state: connectionState,+ }+}++function account(+ agentKey: MCPServiceAccountApi['agent_key'],+ servers: MCPServiceAccountServerApi[],+ { status = 'active' }: { status?: MCPServiceAccountApi['status'] } = {}+): MCPServiceAccountApi {+ return {+ id: `${agentKey}-id`,+ name: agentKey,+ description: `${agentKey} agent`,+ handle: `svc-${agentKey}`,+ agent_key: agentKey,+ status,+ server_ids: servers.map(({ id }) => id),+ servers,+ last_active_at: null,+ created_at: '2026-07-22T00:00:00Z',+ updated_at: '2026-07-22T00:00:00Z',+ }+}++describe('scoutMcpServersLogic', () => {+ let logic: ReturnType<typeof scoutMcpServersLogic.build> | undefined++ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('shows Scout grants and separates servers that still need setup', async () => {+ const notion = server('notion-id', 'Notion', 'missing_credential')+ const linear = server('linear-id', 'Linear', 'ready')+ const zendesk = server('zendesk-id', 'Zendesk', 'ready')+ useMocks({+ get: {+ '/api/projects/:team_id/mcp_gateway/service_accounts/': () => [+ 200,+ {+ count: 2,+ next: null,+ previous: null,+ results: [account('support', [zendesk]), account('scout', [notion, linear])],+ },+ ],+ },+ })++ logic = scoutMcpServersLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.scoutServers).toEqual([notion, linear])+ expect(logic.values.isScoutMcpAccessEnabled).toBe(true)+ expect(logic.values.readyScoutServers).toEqual([linear])+ expect(logic.values.availableScoutServers).toEqual([linear])+ expect(logic.values.scoutServersNeedingSetup).toEqual([notion])+ })++ it('does not expose ready servers when MCP access is paused', async () => {+ const linear = server('linear-id', 'Linear', 'ready')+ useMocks({+ get: {+ '/api/projects/:team_id/mcp_gateway/service_accounts/': () => [+ 200,+ {+ count: 1,+ next: null,+ previous: null,+ results: [account('scout', [linear], { status: 'paused' })],+ },+ ],+ },+ })++ logic = scoutMcpServersLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.scoutServers).toEqual([linear])+ expect(logic.values.isScoutMcpAccessEnabled).toBe(false)+ expect(logic.values.readyScoutServers).toEqual([linear])+ expect(logic.values.availableScoutServers).toEqual([])+ expect(logic.values.scoutServersNeedingSetup).toEqual([])+ })+})diff --git a/frontend/src/scenes/inbox/logics/scoutMcpServersLogic.ts b/frontend/src/scenes/inbox/logics/scoutMcpServersLogic.tsnew file mode 100644index 000000000000..8788d46ddf1c--- /dev/null+++ b/frontend/src/scenes/inbox/logics/scoutMcpServersLogic.ts@@ -0,0 +1,129 @@+import { MakeLogicType, connect, kea, path, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'++import { teamLogic } from 'scenes/teamLogic'++import { mcpGatewayServiceAccountsList } from 'products/mcp_store/frontend/generated/api'+import type {+ MCPServiceAccountApi,+ MCPServiceAccountServerApi,+} from 'products/mcp_store/frontend/generated/api.schemas'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scoutMcpServersLogicValues {+ currentTeamId: number | null // teamLogic+ availableScoutServers: MCPServiceAccountServerApi[]+ isScoutMcpAccessEnabled: boolean+ readyScoutServers: MCPServiceAccountServerApi[]+ scoutAccount: MCPServiceAccountApi | null+ scoutServers: MCPServiceAccountServerApi[]+ scoutServersLoading: boolean+ scoutServersNeedingSetup: MCPServiceAccountServerApi[]+ serviceAccounts: MCPServiceAccountApi[]+ serviceAccountsLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scoutMcpServersLogicActions {+ loadServiceAccounts: () => any+ loadServiceAccountsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadServiceAccountsSuccess: (+ serviceAccounts: MCPServiceAccountApi[],+ payload?: any+ ) => {+ serviceAccounts: MCPServiceAccountApi[]+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scoutMcpServersLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ scoutAccount: (serviceAccounts: MCPServiceAccountApi[]) => MCPServiceAccountApi | null+ isScoutMcpAccessEnabled: (scoutAccount: MCPServiceAccountApi | null) => boolean+ scoutServers: (scoutAccount: MCPServiceAccountApi | null) => MCPServiceAccountServerApi[]+ readyScoutServers: (scoutServers: MCPServiceAccountServerApi[]) => MCPServiceAccountServerApi[]+ availableScoutServers: (+ readyScoutServers: MCPServiceAccountServerApi[],+ isScoutMcpAccessEnabled: boolean+ ) => MCPServiceAccountServerApi[]+ scoutServersNeedingSetup: (scoutServers: MCPServiceAccountServerApi[]) => MCPServiceAccountServerApi[]+ scoutServersLoading: (serviceAccountsLoading: boolean) => boolean+ }+}++export type scoutMcpServersLogicType = MakeLogicType<+ scoutMcpServersLogicValues,+ scoutMcpServersLogicActions,+ Record<string, any>,+ scoutMcpServersLogicMeta+>++export const scoutMcpServersLogic = kea<scoutMcpServersLogicType>([+ path(['scenes', 'inbox', 'logics', 'scoutMcpServersLogic']),+ connect({+ values: [teamLogic, ['currentTeamId']],+ }),+ loaders(({ values }) => ({+ serviceAccounts: [+ [] as MCPServiceAccountApi[],+ {+ loadServiceAccounts: async () => {+ if (values.currentTeamId === null) {+ return []+ }+ const response = await mcpGatewayServiceAccountsList(String(values.currentTeamId), { limit: 500 })+ return response.results+ },+ },+ ],+ })),+ selectors({+ scoutAccount: [+ (s) => [s.serviceAccounts],+ (serviceAccounts: MCPServiceAccountApi[]): MCPServiceAccountApi | null =>+ serviceAccounts.find((account) => account.agent_key === 'scout') ?? null,+ ],+ isScoutMcpAccessEnabled: [+ (s) => [s.scoutAccount],+ (scoutAccount: MCPServiceAccountApi | null): boolean => scoutAccount?.status === 'active',+ ],+ scoutServers: [+ (s) => [s.scoutAccount],+ (scoutAccount: MCPServiceAccountApi | null): MCPServiceAccountServerApi[] => [+ ...(scoutAccount?.servers ?? []),+ ],+ ],+ readyScoutServers: [+ (s) => [s.scoutServers],+ (scoutServers: MCPServiceAccountServerApi[]): MCPServiceAccountServerApi[] =>+ scoutServers.filter((server) => server.connection_state === 'ready'),+ ],+ availableScoutServers: [+ (s) => [s.readyScoutServers, s.isScoutMcpAccessEnabled],+ (+ readyScoutServers: MCPServiceAccountServerApi[],+ isScoutMcpAccessEnabled: boolean+ ): MCPServiceAccountServerApi[] => (isScoutMcpAccessEnabled ? readyScoutServers : []),+ ],+ scoutServersNeedingSetup: [+ (s) => [s.scoutServers],+ (scoutServers: MCPServiceAccountServerApi[]): MCPServiceAccountServerApi[] =>+ scoutServers.filter((server) => server.connection_state !== 'ready'),+ ],+ scoutServersLoading: [+ (s) => [s.serviceAccountsLoading],+ (serviceAccountsLoading: boolean): boolean => serviceAccountsLoading,+ ],+ }),+ subscriptions(({ actions }) => ({+ currentTeamId: () => actions.loadServiceAccounts(),+ })),+])diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 85cf5b88bf73..a937fa7a6431 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -102,6 +102,10 @@ export enum Scene {Login2FA = 'Login2FA',MaterializedColumns = 'MaterializedColumns',Max = 'Max',+ McpGateway = 'McpGateway',+ McpGatewayAgent = 'McpGatewayAgent',+ McpGatewayMember = 'McpGatewayMember',+ McpGatewayServer = 'McpGatewayServer',Models = 'Models',NodeDetail = 'NodeDetail',MoveToPostHogCloud = 'MoveToPostHogCloud',diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex eba4a9fb80b3..63e4328c68d6 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5784,6 +5784,7 @@ export const API_SCOPE_OBJECTS = ['logs','loop','marketing_analytics',+ 'mcp_builtin_agent','mcp_analytics','metrics','notebook',diff --git a/posthog/permissions.py b/posthog/permissions.pyindex cb30a58405e2..4380eb05ec4d 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -30,7 +30,12 @@ from posthog.constants import AvailableFeaturefrom posthog.exceptions import Conflict, EnterpriseFeatureException, PaidFeatureExceptionfrom posthog.models import Organization, OrganizationMembership, Team, Userfrom posthog.rbac.user_access_control import AccessControlLevel, UserAccessControl, ordered_access_levels-from posthog.scopes import INTERNAL_API_SCOPE_OBJECTS, APIScopeObject, APIScopeObjectOrNotSupported+from posthog.scopes import (+ INTERNAL_API_SCOPE_OBJECTS,+ MCP_BUILT_IN_AGENT_SCOPE,+ APIScopeObject,+ APIScopeObjectOrNotSupported,+)from posthog.session.reauth import sensitive_action_reference, step_up_requiredfrom posthog.utils import get_can_create_org@@ -1049,3 +1054,22 @@ class UserCanCreateProjectPermission(BasePermission):return Falsereturn bool(organization.members_can_create_projects)+++def is_mcp_built_in_agent_oauth_request(request: Request) -> bool:+ """Whether the request authenticated with an OAuth token minted for one of+ PostHog's built-in agents (carries the server-only `mcp_builtin_agent` scope)."""+ authenticator = request.successful_authenticator+ if not isinstance(authenticator, OAuthAccessTokenAuthentication):+ return False+ return MCP_BUILT_IN_AGENT_SCOPE in authenticator.access_token.scope.split()+++class DenyMCPBuiltInAgentOAuth(BasePermission):+ """Denies built-in agent sandbox tokens on human/member surfaces they must+ not reach — their access goes through explicit MCP gateway grants instead."""++ message = "Built-in agents must use their explicitly granted MCP gateway connections."++ def has_permission(self, request: Request, view: APIView) -> bool:+ return not is_mcp_built_in_agent_oauth_request(request)diff --git a/posthog/scopes.py b/posthog/scopes.pyindex e5dad0dce3df..b7cebc7a57d9 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -78,6 +78,7 @@ APIScopeObject = Literal["logs","loop","marketing_analytics",+ "mcp_builtin_agent","mcp_analytics","metrics","notebook",@@ -125,6 +126,11 @@ APIScopeObject = Literal["wizard_session",]++# Server-only provenance marker for OAuth tokens minted for PostHog's built-in+# agents. It is hidden from user-controlled scope selectors below.+MCP_BUILT_IN_AGENT_SCOPE = "mcp_builtin_agent:read"+APIScopeActions = Literal["read","write",@@ -149,6 +155,10 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(# it on the internal products that share the PostHog Desktop OAuth app so a user's# own credential can't reach them — see services/llm-gateway products/config.py."internal_run",+ # Marks a sandbox OAuth token as belonging to a trusted built-in agent.+ # MCP Store uses it to deny the human/member control plane and force the+ # agent through its own explicit gateway grants.+ "mcp_builtin_agent",# Sandbox-only writes for the headless Signals agent (memory create/delete,# finding emit). Read access for the same surface lives on the public# `signal_scout` object so user-grantable PAKs can still inspect runs/memory.diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex d1d673bbaa1d..3ce77b7095f7 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -593,6 +593,14 @@ SPECTACULAR_SETTINGS = {# Shared by ConversionGoalSummary.kind and GoalExplanation.kind (same choice set)."ConversionGoalKindEnum": "products.marketing_analytics.backend.hogql_queries.constants.CONVERSION_GOAL_KIND_CHOICES","MCPInstallationScopeEnum": ["personal", "shared"],+ "MCPServiceAccountStatusEnum": "products.mcp_store.backend.models.SERVICE_ACCOUNT_STATUS_CHOICES",+ "MCPServerCategoryEnum": "products.mcp_store.backend.models.CATEGORY_CHOICES",+ "MCPToolApprovalStateEnum": "products.mcp_store.backend.models.APPROVAL_STATES",+ "MCPPolicyPresetEnum": "products.mcp_store.backend.models.POLICY_PRESET_CHOICES",+ "MCPAuditDecisionEnum": "products.mcp_store.backend.models.AUDIT_DECISION_CHOICES",+ # Keeps agent_platform's approval-request enum on its pre-collision name now+ # that mcp_store also has a "decision" field.+ "DecisionEnum": ["approve", "reject"],# Disambiguates from data_modeling's node_type (table/view/matview/endpoint)."NotebookSQLV2NodeTypeEnum": ["hogql", "python"],"NotebookSQLV2RefKindEnum": ["hogql", "local"],diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex eecc09a29e92..9a8baba20556 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -6,7 +6,13 @@ from django.utils import timezonefrom posthog.models import OAuthAccessToken, OAuthApplicationfrom posthog.models.utils import generate_random_oauth_access_token-from posthog.scopes import API_SCOPE_OBJECTS, INTERNAL_API_SCOPE_OBJECTS, OAUTH_HIDDEN_SCOPE_OBJECTS, resolve_ceiling+from posthog.scopes import (+ API_SCOPE_OBJECTS,+ INTERNAL_API_SCOPE_OBJECTS,+ MCP_BUILT_IN_AGENT_SCOPE,+ OAUTH_HIDDEN_SCOPE_OBJECTS,+ resolve_ceiling,+)from posthog.utils import get_instance_regionARRAY_APP_CLIENT_ID_US = "HCWoE0aRFMYxIxFNTTwkOORn5LBjOt2GVDzwSw5W"@@ -51,7 +57,6 @@ INTERNAL_SCOPES: list[str] = ["internal_run:read",]-# Writes for the Signals scout harness — sandbox-only because the scope object is in# `INTERNAL_API_SCOPE_OBJECTS` and so cannot be minted via the personal API key UI or# granted through the OAuth consent flow. Reads use the public `signal_scout:read` scope.@@ -231,9 +236,15 @@ def create_oauth_access_token_for_user(*,scopes: PosthogMcpScopes = "read_only",include_internal_scopes: bool = True,+ include_mcp_builtin_agent_scope: bool = False,application: SandboxOAuthApplication = "array",) -> str:resolved = resolve_scopes(scopes, include_internal_scopes=include_internal_scopes)+ if include_mcp_builtin_agent_scope:+ # Provenance marker: the MCP Store uses it to deny the human/member+ # surface and route the agent through its explicit gateway grants. It+ # does not narrow the token's other scopes.+ resolved.append(MCP_BUILT_IN_AGENT_SCOPE)app = get_sandbox_oauth_app(application)return _mint_oauth_access_token(user, team_id, app=app, scopes=list(resolved))diff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.pyindex 4d31bba042f1..af7b552da7d9 100644--- a/posthog/temporal/tests/test_oauth.py+++ b/posthog/temporal/tests/test_oauth.py@@ -3,7 +3,9 @@ from django.test import SimpleTestCase, TestCase, override_settingsfrom parameterized import parameterizedfrom posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, User+from posthog.scopes import MCP_BUILT_IN_AGENT_SCOPEfrom posthog.temporal.oauth import (+ ARRAY_APP_CLIENT_ID_DEV,INTERNAL_SCOPES,MCP_READ_SCOPES,MCP_WRITE_SCOPES,@@ -169,6 +171,23 @@ class TestCreateOAuthAccessTokenForUser(TestCase):with self.assertRaisesRegex(RuntimeError, "PostHog AI app not found"):create_oauth_access_token_for_user(user, team.id, application="posthog_ai")+ @override_settings(CLOUD_DEPLOYMENT="DEV")+ def test_built_in_agent_scope_is_added_without_narrowing_scopes(self) -> None:+ self._create_oauth_app(ARRAY_APP_CLIENT_ID_DEV, "Array Dev App")+ user, team = self._create_user_and_team()++ token = create_oauth_access_token_for_user(+ user,+ team.id,+ include_mcp_builtin_agent_scope=True,+ )++ scopes = set(OAuthAccessToken.objects.get(token=token).scope.split())+ assert MCP_BUILT_IN_AGENT_SCOPE in scopes+ # The marker is provenance only: built-in agents keep the task tools.+ assert "task:read" in scopes+ assert "task:write" in scopes+class TestCreateWizardOAuthAccessTokenForUser(TestCase):def _create_wizard_app(self, scopes: list[str]) -> OAuthApplication:diff --git a/products/conversations/backend/temporal/ai_reply/activities/draft.py b/products/conversations/backend/temporal/ai_reply/activities/draft.pyindex d7462f7e66d8..32bd835f985b 100644--- a/products/conversations/backend/temporal/ai_reply/activities/draft.py+++ b/products/conversations/backend/temporal/ai_reply/activities/draft.py@@ -234,6 +234,7 @@ Return your response as a JSON object with keys: reply, citations, confidence, smodel=SupportReplyDraft,step_name="support_reply",origin_product=tasks_facade.TaskOriginProduct.SUPPORT_REPLY,+ mcp_builtin_agent_key="support",internal=True,max_poll_seconds=DRAFT_POLL_SECONDS,)diff --git a/products/mcp_store/backend/agents.py b/products/mcp_store/backend/agents.pynew file mode 100644index 000000000000..120dbe6ec9e2--- /dev/null+++ b/products/mcp_store/backend/agents.py@@ -0,0 +1,192 @@+from __future__ import annotations++from dataclasses import dataclass+from typing import Literal++from django.conf import settings+from django.core import signing+from django.utils import timezone++import structlog+import posthoganalytics++from posthog.models import Team+from posthog.models.scoping.manager import TeamScopeError+from posthog.models.utils import hash_key_value++from .models import MCPServiceAccount++logger = structlog.get_logger(__name__)++BuiltInAgentKey = Literal["support", "scout"]++GATEWAY_AGENT_TOKEN_PREFIX = "mcp_gw_"+GATEWAY_AGENT_TOKEN_SALT = "mcp_store.gateway_agent"+GATEWAY_AGENT_TOKEN_MAX_AGE_SECONDS = 6 * 60 * 60+++@dataclass(frozen=True)+class BuiltInAgentSpec:+ key: BuiltInAgentKey+ name: str+ description: str+ handle: str+++BUILT_IN_AGENTS: tuple[BuiltInAgentSpec, ...] = (+ BuiltInAgentSpec(+ key="support",+ name="Support agent",+ description="Drafts grounded replies and investigates customer support tickets.",+ handle="posthog-support",+ ),+ BuiltInAgentSpec(+ key="scout",+ name="Scout agent",+ description="Proactively investigates your product and reports useful findings.",+ handle="posthog-scout",+ ),+)++_SPEC_BY_KEY = {spec.key: spec for spec in BUILT_IN_AGENTS}+_SPEC_BY_HANDLE = {spec.handle: spec for spec in BUILT_IN_AGENTS}++_TASK_ORIGIN_TO_AGENT: dict[str, BuiltInAgentKey] = {+ "support_reply": "support",+ "signals_scout": "scout",+}+# Signal report tasks may be created through the public Tasks API, so they+# remain member-scoped instead of inheriting Scout's MCP grants.+++def built_in_agent_handles() -> tuple[str, ...]:+ return tuple(spec.handle for spec in BUILT_IN_AGENTS)+++def built_in_agent_key_for_task_origin(origin_product: str) -> BuiltInAgentKey | None:+ return _TASK_ORIGIN_TO_AGENT.get(origin_product)+++MCP_GATEWAY_FEATURE_FLAG = "mcp-gateway"+++def is_builtin_agent_enforcement_enabled(team_id: int) -> bool:+ """Per-team rollout gate for built-in agent MCP enforcement.++ Until `mcp-gateway` is enabled for the team's organization, built-in agent+ tasks keep the legacy member resolution (team-shared installations and a+ member-capable sandbox token). The Store facade and the sandbox token+ minter both key off this check — they must agree, or a legacy-resolved+ task gets a token the member proxy rejects. Fails closed to legacy so a+ flag-evaluation hiccup behaves like a not-yet-rolled-out team.++ DEBUG bypasses the flag: the analytics SDK is disabled in local dev, where+ gateway work needs enforcement on to be exercisable at all.+ """+ if settings.DEBUG:+ return True+ try:+ team = Team.objects.only("uuid", "organization_id").get(id=team_id)+ return bool(+ posthoganalytics.feature_enabled(+ MCP_GATEWAY_FEATURE_FLAG,+ str(team.uuid),+ groups={"organization": str(team.organization_id)},+ group_properties={"organization": {"id": str(team.organization_id)}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.exception("mcp_gateway_enforcement_flag_check_failed", team_id=team_id)+ return False+++def get_built_in_agent_spec(account: MCPServiceAccount) -> BuiltInAgentSpec | None:+ return _SPEC_BY_HANDLE.get(account.handle)+++def sync_built_in_agents(team: Team) -> list[MCPServiceAccount]:+ accounts: list[MCPServiceAccount] = []+ changed: list[MCPServiceAccount] = []++ for spec in BUILT_IN_AGENTS:+ token_hash = hash_key_value(f"built-in-mcp-agent:{team.id}:{spec.key}")+ account, created = MCPServiceAccount.objects.for_team(team.id).get_or_create(+ team_id=team.id,+ token_hash=token_hash,+ defaults={+ "name": spec.name,+ "description": spec.description,+ "handle": spec.handle,+ "status": "active",+ },+ )+ if not created:+ account_changed = False+ if account.handle != spec.handle:+ account.handle = spec.handle+ account_changed = True+ if account.name != spec.name:+ account.name = spec.name+ account_changed = True+ if account.description != spec.description:+ account.description = spec.description+ account_changed = True+ if account_changed:+ account.updated_at = timezone.now()+ changed.append(account)+ accounts.append(account)++ if changed:+ MCPServiceAccount.objects.for_team(team.id).bulk_update(+ changed,+ ["name", "description", "handle", "updated_at"],+ )++ return accounts+++def get_built_in_agent(team_id: int, agent_key: str) -> MCPServiceAccount | None:+ spec = next((candidate for candidate in BUILT_IN_AGENTS if candidate.key == agent_key), None)+ if spec is None:+ return None+ try:+ team = Team.objects.select_related("organization").get(id=team_id)+ except Team.DoesNotExist:+ return None+ return next(account for account in sync_built_in_agents(team) if account.handle == spec.handle)+++def create_gateway_agent_token(account: MCPServiceAccount) -> str:+ payload = {"service_account_id": str(account.id), "team_id": account.team_id}+ return GATEWAY_AGENT_TOKEN_PREFIX + signing.dumps(payload, salt=GATEWAY_AGENT_TOKEN_SALT)+++def resolve_gateway_agent_token(token: str) -> MCPServiceAccount | None:+ if not token.startswith(GATEWAY_AGENT_TOKEN_PREFIX):+ return None+ signed_value = token.removeprefix(GATEWAY_AGENT_TOKEN_PREFIX)+ try:+ payload = signing.loads(+ signed_value,+ salt=GATEWAY_AGENT_TOKEN_SALT,+ max_age=GATEWAY_AGENT_TOKEN_MAX_AGE_SECONDS,+ )+ except signing.BadSignature:+ return None+ if not isinstance(payload, dict):+ return None+ account_id = payload.get("service_account_id")+ team_id = payload.get("team_id")+ if not account_id or not isinstance(team_id, int):+ return None+ try:+ # TeamScopeError: the token can outlive its team — treat a deleted team+ # like any other invalid token instead of erroring at the auth layer.+ return MCPServiceAccount.objects.for_team(team_id).get(+ id=account_id,+ handle__in=built_in_agent_handles(),+ )+ except (MCPServiceAccount.DoesNotExist, TeamScopeError, ValueError):+ return Nonediff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.pyindex 2616d1a80898..926ad37ec22f 100644--- a/products/mcp_store/backend/facade/api.py+++ b/products/mcp_store/backend/facade/api.py@@ -11,12 +11,62 @@ from django.db.models import Qimport structlog+from products.mcp_store.backend.agents import (+ built_in_agent_key_for_task_origin,+ create_gateway_agent_token,+ get_built_in_agent,+ is_builtin_agent_enforcement_enabled,+)from products.mcp_store.backend.facade.contracts import ActiveInstallationInfo-from products.mcp_store.backend.models import MCPServerInstallation+from products.mcp_store.backend.models import (+ MCPServerInstallation,+ MCPServerInstallationTool,+ MCPServiceAccountServerAccess,+)+from products.mcp_store.backend.policy import GatewayCaller, PolicyContextlogger = structlog.get_logger(__name__)+def resolve_member_tool_states(+ installation_id: str,+ team_id: int,+ gateway_server_id: uuid.UUID | None,+ user_id: int | None = None,+) -> dict[str, str]:+ """Return a {tool_name: effective_state} map for an installation.++ States resolve through the gateway policy engine when the installation is+ registered with a gateway (org rules → team default → the user's scope);+ unregistered installations fall back to the cached per-tool approval state.+ Rows with `removed_at` set surface as `"do_not_use"` so the agent can't+ call them even if the cached approval state was previously `approved` —+ if the tool is gone upstream, it's gone. Anything not in the map is+ treated as `needs_approval` by the caller (explicit opt-in for freshly+ discovered tools)."""+ rows = MCPServerInstallationTool.objects.filter(installation_id=installation_id).values(+ "tool_name", "annotations", "approval_state", "removed_at"+ )+ legacy = {row["tool_name"]: ("do_not_use" if row["removed_at"] else row["approval_state"]) for row in rows}++ if gateway_server_id is None or user_id is None:+ return legacy++ context = PolicyContext(+ team_id=team_id,+ caller=GatewayCaller(kind="member", user_id=user_id),+ gateway_server_id=gateway_server_id,+ legacy_rows={row["tool_name"]: row["approval_state"] for row in rows if row["removed_at"] is None},+ )+ resolved: dict[str, str] = {}+ for row in rows:+ if row["removed_at"]:+ resolved[row["tool_name"]] = "do_not_use"+ else:+ resolved[row["tool_name"]] = context.resolve(row["tool_name"], row["annotations"]).state+ return resolved++def unauthorized_installation_ids(team_id: int, user_id: int, candidate_ids: Iterable[str]) -> list[str]:"""Return the subset of `candidate_ids` the caller must REJECT — installationids not owned by this (team, user). Ownership is keyed by `(team_id, user_id)`@@ -68,12 +118,23 @@ def _is_oauth_ready(installation: MCPServerInstallation) -> bool:return True-def _to_info(installation: MCPServerInstallation, team_id: int) -> ActiveInstallationInfo:+def _to_info(+ installation: MCPServerInstallation,+ team_id: int,+ *,+ agent_proxy_token: str | None = None,+) -> ActiveInstallationInfo:+ if agent_proxy_token is not None and installation.gateway_server_id is not None:+ proxy_path = f"/api/mcp_store/gateway/servers/{installation.gateway_server_id}/proxy/"+ else:+ proxy_path = f"/api/environments/{team_id}/mcp_server_installations/{installation.id}/proxy/"+return ActiveInstallationInfo(id=str(installation.id),name=_resolve_name(installation),- proxy_path=f"/api/environments/{team_id}/mcp_server_installations/{installation.id}/proxy/",+ proxy_path=proxy_path,scope=installation.scope,+ proxy_token=agent_proxy_token,)@@ -86,9 +147,10 @@ def get_active_installations(team_id: int, user_id: int) -> list[ActiveInstallattry:# list() evaluates the lazy queryset here so DB errors hit this handler.installations = list(- MCPServerInstallation.objects.filter(- team_id=team_id, user_id=user_id, is_enabled=True, scope="personal"- ).select_related("template")+ MCPServerInstallation.objects.filter(team_id=team_id, user_id=user_id, is_enabled=True, scope="personal")+ .filter(Q(gateway_server__isnull=True) | Q(gateway_server__is_team_enabled=True))+ .exclude(gateway_server__member_revocations__user_id=user_id)+ .select_related("template"))except Exception as e:logger.warning("Error fetching MCP installations", error=str(e), team_id=team_id)@@ -113,27 +175,86 @@ def get_installations_for_sandbox(*,user_id: int | None = None,include_personal: bool = False,+ task_origin: str | None = None,+ task_agent_key: str | None = None,) -> list[ActiveInstallationInfo]:"""Return MCP installations for sandbox agent use.- Always includes shared (team-wide) installations. Optionally includes- the user's personal installations when ``include_personal`` is True- and a ``user_id`` is provided. When the user has a ready personal- installation for the same URL as a shared one, only the personal one is- returned — the user acts as themselves rather than through the shared- credential.+ Generic tasks retain the legacy team-shared installation behavior. A+ server-stamped built-in agent task gets only the credentials explicitly+ delegated through its service-account grants, and only while the gateway+ server stays enabled for the team. Origin alone is not trusted:+ the persisted task agent key must match the origin mapping. A mapped origin+ without that marker gets no MCP Store installations. Built-in agent+ handling is gated per team on the `mcp-gateway` rollout flag; teams+ without it resolve mapped origins like unmapped tasks. Unmapped origins+ retain the legacy member behavior and optionally include the user's+ personal installations when ``include_personal`` is True and a ``user_id``+ is provided. When the user has a ready personal installation for the same+ URL as a shared one, only the personal one is returned — the user acts as+ themselves rather than through the shared credential."""try:- scope_filter = Q(scope="shared")- if include_personal and user_id is not None:- scope_filter = scope_filter | Q(scope="personal", user_id=user_id)-- # list() evaluates the lazy queryset here so DB errors hit this handler.- installations = list(- MCPServerInstallation.objects.filter(team_id=team_id, is_enabled=True)- .filter(scope_filter)- .select_related("template")+ base_queryset = MCPServerInstallation.objects.filter(team_id=team_id, is_enabled=True).select_related(+ "template", "gateway_server")++ mapped_agent_key = built_in_agent_key_for_task_origin(task_origin or "")+ if mapped_agent_key is not None and not is_builtin_agent_enforcement_enabled(team_id):+ # Rollout gate: until the gateway ships for this team, built-in+ # agent origins keep the legacy member resolution below.+ mapped_agent_key = None+ if mapped_agent_key is not None and task_agent_key != mapped_agent_key:+ logger.warning(+ "Refusing MCP installations for an unstamped built-in agent task",+ team_id=team_id,+ task_origin=task_origin,+ )+ return []++ agent_key = mapped_agent_key+ agent_account = get_built_in_agent(team_id, agent_key) if agent_key is not None else None+ if agent_key is not None and agent_account is not None and agent_account.status != "active":+ return []++ if agent_key is not None:+ if agent_account is None:+ installations = []+ else:+ access_rows = list(+ MCPServiceAccountServerAccess.objects.for_team(team_id)+ .filter(service_account=agent_account)+ .values_list("installation_id", "gateway_server_id")+ )+ bound_servers = {+ installation_id: gateway_server_id+ for installation_id, gateway_server_id in access_rows+ if installation_id is not None+ }+ # The admin kill switch overrides grants: a server turned off+ # for the team is withheld from agents too.+ candidates = list(base_queryset.filter(id__in=bound_servers, gateway_server__is_team_enabled=True))+ installations = [+ installation+ for installation in candidates+ if bound_servers.get(installation.id) == installation.gateway_server_id+ ]+ else:+ shared_queryset = base_queryset.filter(scope="shared")+ shared_queryset = shared_queryset.filter(+ Q(gateway_server__isnull=True) | Q(gateway_server__is_team_enabled=True)+ )+ if user_id is not None:+ shared_queryset = shared_queryset.exclude(gateway_server__member_revocations__user_id=user_id)+ # list() evaluates the lazy querysets here so DB errors hit this handler.+ installations = list(shared_queryset)+ if include_personal and user_id is not None:+ personal_queryset = (+ base_queryset.filter(scope="personal", user_id=user_id)+ .filter(Q(gateway_server__isnull=True) | Q(gateway_server__is_team_enabled=True))+ .exclude(gateway_server__member_revocations__user_id=user_id)+ )+ installations.extend(personal_queryset)except Exception as e:logger.warning("Error fetching MCP installations for sandbox", error=str(e), team_id=team_id)return []@@ -147,12 +268,22 @@ def get_installations_for_sandbox(if installation.scope == "personal" or installation.url not in personal_urls]- results = [_to_info(installation, team_id) for installation in ready]+ agent_proxy_token = create_gateway_agent_token(agent_account) if agent_account is not None and ready else None+ results = [+ _to_info(+ installation,+ team_id,+ agent_proxy_token=agent_proxy_token if agent_account is not None else None,+ )+ for installation in ready+ ]logger.debug("Found MCP installations for sandbox",count=len(results),team_id=team_id,include_personal=include_personal,+ task_origin=task_origin,+ has_trusted_agent_key=agent_key is not None,)return resultsdiff --git a/products/mcp_store/backend/facade/contracts.py b/products/mcp_store/backend/facade/contracts.pyindex f302d31ea256..1e5120a27d6e 100644--- a/products/mcp_store/backend/facade/contracts.py+++ b/products/mcp_store/backend/facade/contracts.py@@ -5,7 +5,7 @@ Stable, framework-free frozen dataclasses that define what this productexposes to the rest of the codebase. No Django imports."""-from dataclasses import dataclass+from dataclasses import dataclass, field@dataclass(frozen=True)@@ -16,3 +16,6 @@ class ActiveInstallationInfo:name: strproxy_path: strscope: str = "personal"+ # Set only for credentials delegated to a built-in agent. Kept out of reprs so the+ # short-lived bearer cannot accidentally land in logs.+ proxy_token: str | None = field(default=None, repr=False)diff --git a/products/mcp_store/backend/gateway.py b/products/mcp_store/backend/gateway.pynew file mode 100644index 000000000000..26f05759b5b4--- /dev/null+++ b/products/mcp_store/backend/gateway.py@@ -0,0 +1,104 @@+"""Keeps the gateway registry (`MCPGatewayServer`) in sync with installations.++The registry is sparse: a row exists only once someone touched the server.+Every credential row registers its (team, url) with the gateway at the success+points of the install/share/OAuth-start flows, and admins materialize a row for+an untouched catalog template when they toggle it (the gateway API's+set_template_enabled action). Servers with no row follow the team's+`default_servers_enabled` posture."""++import structlog++from posthog.models import User++from .models import MCPGatewayServer, MCPServerInstallation, MCPServiceAccountServerAccess, TeamMCPGatewayConfig++logger = structlog.get_logger(__name__)++_GATEWAY_SERVER_NAME_MAX_LENGTH = 200+++def members_can_manage_agent_access(team_id: int) -> bool:+ """Whether regular members may grant MCP access to agents and tune it."""+ config = TeamMCPGatewayConfig.objects.for_team(team_id).first()+ return config is None or config.allow_member_agent_access+++def server_disabled_reason(team_id: int, url: str) -> str | None:+ """Resolve enablement for one server URL: an explicit registration wins;+ otherwise the team's default posture applies (enabled when never set).+ Returns None when enabled, else the layer that disabled it+ ("row_disabled" or "default_disabled")."""+ server = MCPGatewayServer.objects.for_team(team_id).filter(url=url).only("id", "is_team_enabled").first()+ if server is not None:+ return None if server.is_team_enabled else "row_disabled"+ config = TeamMCPGatewayConfig.objects.for_team(team_id).only("id", "default_servers_enabled").first()+ if config is None or config.default_servers_enabled:+ return None+ return "default_disabled"+++def link_installation_to_gateway(installation: MCPServerInstallation, created_by: User | None) -> MCPGatewayServer:+ """Ensure a gateway registration exists for the installation's (team, url)+ and point the installation at it. Idempotent."""+ template = installation.template+ server, _ = MCPGatewayServer.objects.for_team(installation.team_id).get_or_create(+ url=installation.url,+ defaults={+ "team_id": installation.team_id,+ "name": (installation.display_name or (template.name if template else installation.url))[+ :_GATEWAY_SERVER_NAME_MAX_LENGTH+ ],+ "description": installation.description,+ "template": template,+ "category": template.category if template else "dev",+ "created_by": created_by,+ },+ )++ update_fields: list[str] = []+ if template is not None and server.template_id is None:+ server.template = template+ update_fields.append("template")+ if update_fields:+ server.save(update_fields=[*update_fields, "updated_at"])++ if installation.gateway_server_id != server.id:+ installation.gateway_server = server+ installation.save(update_fields=["gateway_server", "updated_at"])++ return server+++def installation_for_agent_grant(+ team_id: int, gateway_server: MCPGatewayServer, user_id: int+) -> MCPServerInstallation | None:+ """Choose the credential delegated by an agent-access action: the+ requesting user's own connection to the server. An agent never rides a+ credential its granter didn't connect themselves.+ """+ return (+ MCPServerInstallation.objects.filter(+ team_id=team_id,+ gateway_server=gateway_server,+ user_id=user_id,+ scope="personal",+ )+ .order_by("created_at")+ .first()+ )+++def installation_for_agent_access(access: MCPServiceAccountServerAccess) -> MCPServerInstallation | None:+ """Resolve the exact credential bound to an access row."""+ installation = access.installation+ if installation is None:+ return None+ if installation.team_id != access.team_id or installation.gateway_server_id != access.gateway_server_id:+ logger.warning(+ "Refusing mismatched agent MCP credential",+ access_id=str(access.id),+ installation_id=str(installation.id),+ )+ return None+ return installationdiff --git a/products/mcp_store/backend/migrations/0016_mcp_gateway_models.py b/products/mcp_store/backend/migrations/0016_mcp_gateway_models.pynew file mode 100644index 000000000000..23df44338f26--- /dev/null+++ b/products/mcp_store/backend/migrations/0016_mcp_gateway_models.py@@ -0,0 +1,657 @@+# Generated by Django 5.2.14 on 2026-07-20 19:14++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("mcp_store", "0015_backfill_mcp_template_icon_domains"),+ ("posthog", "1260_activitylog_idx_alog_org_created_at_and_more"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AddField(+ model_name="mcpoauthstate",+ name="web_return_path",+ field=models.TextField(blank=True, db_default="", default=""),+ ),+ migrations.AddField(+ model_name="mcpserverinstallation",+ name="last_used_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.CreateModel(+ name="MCPGatewayServer",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("name", models.CharField(max_length=200)),+ ("url", models.URLField(max_length=2048)),+ ("description", models.TextField(blank=True, default="")),+ (+ "category",+ models.CharField(+ choices=[+ ("business", "Business Operations"),+ ("data", "Data & Analytics"),+ ("design", "Design & Content"),+ ("dev", "Developer Tools & APIs"),+ ("infra", "Infrastructure"),+ ("productivity", "Productivity & Collaboration"),+ ],+ default="dev",+ max_length=20,+ ),+ ),+ ("is_team_enabled", models.BooleanField(default=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="gateway_servers",+ to="posthog.team",+ ),+ ),+ (+ "template",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="gateway_servers",+ to="mcp_store.mcpservertemplate",+ ),+ ),+ ],+ options={+ "db_table": "mcp_store_mcpgatewayserver",+ },+ ),+ migrations.AddField(+ model_name="mcpserverinstallation",+ name="gateway_server",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="installations",+ to="mcp_store.mcpgatewayserver",+ ),+ ),+ migrations.CreateModel(+ name="MCPMemberServerRevocation",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "gateway_server",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="member_revocations",+ to="mcp_store.mcpgatewayserver",+ ),+ ),+ (+ "revoked_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "user",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ],+ options={+ "db_table": "mcp_store_mcpmemberserverrevocation",+ },+ ),+ migrations.CreateModel(+ name="MCPOrgRule",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("name", models.CharField(max_length=200)),+ ("description", models.TextField(blank=True, default="")),+ (+ "applies_to",+ models.CharField(+ choices=[+ ("everyone", "Everyone"),+ ("members", "Members"),+ ("agents", "Agents"),+ ],+ default="everyone",+ max_length=20,+ ),+ ),+ (+ "effect",+ models.CharField(+ choices=[+ ("needs_approval", "Require approval"),+ ("do_not_use", "Block"),+ ],+ default="do_not_use",+ max_length=20,+ ),+ ),+ (+ "tool_pattern",+ models.CharField(blank=True, default="", max_length=400),+ ),+ ("enabled", models.BooleanField(default=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="org_rules",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "mcp_store_mcporgrule",+ },+ ),+ migrations.CreateModel(+ name="MCPServiceAccount",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("name", models.CharField(max_length=200)),+ ("description", models.TextField(blank=True, default="")),+ ("handle", models.CharField(max_length=200)),+ (+ "status",+ models.CharField(+ choices=[("active", "Active"), ("paused", "Paused")],+ default="active",+ max_length=20,+ ),+ ),+ ("token_hash", models.CharField(max_length=128, unique=True)),+ ("token_mask", models.CharField(blank=True, default="", max_length=64)),+ ("last_active_at", models.DateTimeField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="mcp_service_accounts",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "mcp_store_mcpserviceaccount",+ },+ ),+ migrations.CreateModel(+ name="MCPAuditEvent",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "actor_label",+ models.CharField(blank=True, default="", max_length=254),+ ),+ (+ "server_name",+ models.CharField(blank=True, default="", max_length=200),+ ),+ ("tool_name", models.CharField(blank=True, default="", max_length=200)),+ (+ "decision",+ models.CharField(+ choices=[+ ("auto", "Auto-approved"),+ ("approved", "Approved"),+ ("pending", "Awaiting approval"),+ ("blocked", "Blocked"),+ ],+ max_length=20,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "actor_user",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "installation",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="mcp_store.mcpserverinstallation",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "gateway_server",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="audit_events",+ to="mcp_store.mcpgatewayserver",+ ),+ ),+ (+ "actor_service_account",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="audit_events",+ to="mcp_store.mcpserviceaccount",+ ),+ ),+ ],+ options={+ "db_table": "mcp_store_mcpauditevent",+ },+ ),+ migrations.CreateModel(+ name="MCPServiceAccountServerAccess",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "gateway_server",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="agent_access",+ to="mcp_store.mcpgatewayserver",+ ),+ ),+ (+ "granted_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "service_account",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="server_access",+ to="mcp_store.mcpserviceaccount",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "mcp_store_mcpserviceaccountserveraccess",+ },+ ),+ migrations.CreateModel(+ name="MCPToolPolicy",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("tool_name", models.CharField(max_length=200)),+ (+ "scope_type",+ models.CharField(+ choices=[+ ("team", "Team default"),+ ("member", "Member"),+ ("agent", "Agent"),+ ],+ max_length=20,+ ),+ ),+ (+ "state",+ models.CharField(+ choices=[+ ("approved", "Approved"),+ ("needs_approval", "Needs approval"),+ ("do_not_use", "Do not use"),+ ],+ default="needs_approval",+ max_length=20,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "gateway_server",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="tool_policies",+ to="mcp_store.mcpgatewayserver",+ ),+ ),+ (+ "scope_service_account",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="tool_policies",+ to="mcp_store.mcpserviceaccount",+ ),+ ),+ (+ "scope_user",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "mcp_store_mcptoolpolicy",+ },+ ),+ migrations.CreateModel(+ name="TeamMCPGatewayConfig",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("allow_custom_servers", models.BooleanField(default=True)),+ (+ "member_default_preset",+ models.CharField(+ blank=True,+ choices=[+ ("allow", "Allow all"),+ ("user", "Member decides"),+ ("ask", "Ask for destructive"),+ ("block", "Block destructive"),+ ],+ default="",+ max_length=20,+ ),+ ),+ (+ "agent_default_preset",+ models.CharField(+ blank=True,+ choices=[+ ("allow", "Allow all"),+ ("user", "Member decides"),+ ("ask", "Ask for destructive"),+ ("block", "Block destructive"),+ ],+ default="",+ max_length=20,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.OneToOneField(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="mcp_gateway_config",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "mcp_store_teammcpgatewayconfig",+ },+ ),+ migrations.AddConstraint(+ model_name="mcpgatewayserver",+ constraint=models.UniqueConstraint(fields=("team", "url"), name="uniq_gateway_server_per_team_url"),+ ),+ migrations.AddConstraint(+ model_name="mcpmemberserverrevocation",+ constraint=models.UniqueConstraint(fields=("gateway_server", "user"), name="uniq_member_server_revocation"),+ ),+ migrations.AddConstraint(+ model_name="mcpserviceaccount",+ constraint=models.UniqueConstraint(fields=("team", "handle"), name="uniq_service_account_handle_per_team"),+ ),+ migrations.AddIndex(+ model_name="mcpauditevent",+ index=models.Index(fields=["team", "-created_at"], name="mcp_store_m_team_id_e98417_idx"),+ ),+ migrations.AddIndex(+ model_name="mcpauditevent",+ index=models.Index(+ fields=["team", "decision", "-created_at"],+ name="mcp_store_m_team_id_79feb4_idx",+ ),+ ),+ migrations.AddIndex(+ model_name="mcpauditevent",+ index=models.Index(+ fields=["team", "actor_service_account", "-created_at"],+ name="mcp_store_m_team_id_161c46_idx",+ ),+ ),+ migrations.AddConstraint(+ model_name="mcpserviceaccountserveraccess",+ constraint=models.UniqueConstraint(+ fields=("service_account", "gateway_server"),+ name="uniq_agent_server_access",+ ),+ ),+ migrations.AddIndex(+ model_name="mcptoolpolicy",+ index=models.Index(+ fields=["gateway_server", "scope_type"],+ name="mcp_store_m_gateway_d897e6_idx",+ ),+ ),+ migrations.AddConstraint(+ model_name="mcptoolpolicy",+ constraint=models.UniqueConstraint(+ condition=models.Q(("scope_type", "team")),+ fields=("gateway_server", "tool_name"),+ name="uniq_team_tool_policy",+ ),+ ),+ migrations.AddConstraint(+ model_name="mcptoolpolicy",+ constraint=models.UniqueConstraint(+ condition=models.Q(("scope_type", "member")),+ fields=("gateway_server", "tool_name", "scope_user"),+ name="uniq_member_tool_policy",+ ),+ ),+ migrations.AddConstraint(+ model_name="mcptoolpolicy",+ constraint=models.UniqueConstraint(+ condition=models.Q(("scope_type", "agent")),+ fields=("gateway_server", "tool_name", "scope_service_account"),+ name="uniq_agent_tool_policy",+ ),+ ),+ migrations.AddConstraint(+ model_name="mcptoolpolicy",+ constraint=models.CheckConstraint(+ condition=models.Q(+ models.Q(+ ("scope_service_account__isnull", True),+ ("scope_type", "team"),+ ("scope_user__isnull", True),+ ),+ models.Q(+ ("scope_service_account__isnull", True),+ ("scope_type", "member"),+ ("scope_user__isnull", False),+ ),+ models.Q(+ ("scope_service_account__isnull", False),+ ("scope_type", "agent"),+ ("scope_user__isnull", True),+ ),+ _connector="OR",+ ),+ name="tool_policy_scope_matches_type",+ ),+ ),+ ]diff --git a/products/mcp_store/backend/migrations/0017_backfill_gateway_servers.py b/products/mcp_store/backend/migrations/0017_backfill_gateway_servers.pynew file mode 100644index 000000000000..eaa5b4e90812--- /dev/null+++ b/products/mcp_store/backend/migrations/0017_backfill_gateway_servers.py@@ -0,0 +1,62 @@+from typing import Any++from django.db import migrations++GATEWAY_SERVER_NAME_MAX_LENGTH = 200+++def backfill_gateway_servers(apps, schema_editor):+ """Create a gateway registration for every (team, url) with installations,+ and point the installations at it.++ Registrations start enabled: pre-gateway behavior is preserved by the+ per-installation is_enabled flag, which keeps gating the proxy as before.+ """+ MCPServerInstallation = apps.get_model("mcp_store", "MCPServerInstallation")+ MCPGatewayServer = apps.get_model("mcp_store", "MCPGatewayServer")++ servers_by_key: dict[tuple[int, str], Any] = {}+ installations = (+ MCPServerInstallation.objects.filter(gateway_server__isnull=True)+ .select_related("team", "template")+ .order_by("id")+ .iterator(chunk_size=500)+ )+ pending_links: list[Any] = []+ for installation in installations:+ canonical_team_id = installation.team.parent_team_id or installation.team_id+ key = (canonical_team_id, installation.url)+ server = servers_by_key.get(key)+ if server is None:+ server, _ = MCPGatewayServer.objects.get_or_create(+ team_id=canonical_team_id,+ url=installation.url,+ defaults={+ "name": (+ installation.display_name+ or (installation.template.name if installation.template else installation.url)+ )[:GATEWAY_SERVER_NAME_MAX_LENGTH],+ "description": installation.description,+ "template": installation.template,+ "category": installation.template.category if installation.template else "dev",+ "created_by": installation.user,+ },+ )+ servers_by_key[key] = server+ installation.gateway_server = server+ pending_links.append(installation)+ if len(pending_links) >= 500:+ MCPServerInstallation.objects.bulk_update(pending_links, ["gateway_server"])+ pending_links = []+ if pending_links:+ MCPServerInstallation.objects.bulk_update(pending_links, ["gateway_server"])+++class Migration(migrations.Migration):+ dependencies = [+ ("mcp_store", "0016_mcp_gateway_models"),+ ]++ operations = [+ migrations.RunPython(backfill_gateway_servers, migrations.RunPython.noop),+ ]diff --git a/products/mcp_store/backend/migrations/0018_bind_agent_access_credential.py b/products/mcp_store/backend/migrations/0018_bind_agent_access_credential.pynew file mode 100644index 000000000000..4e301fa0694c--- /dev/null+++ b/products/mcp_store/backend/migrations/0018_bind_agent_access_credential.py@@ -0,0 +1,24 @@+# Generated by Django 5.2.14 on 2026-07-22 20:08++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("mcp_store", "0017_backfill_gateway_servers"),+ ]++ operations = [+ migrations.AddField(+ model_name="mcpserviceaccountserveraccess",+ name="installation",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="agent_grants",+ to="mcp_store.mcpserverinstallation",+ ),+ ),+ ]diff --git a/products/mcp_store/backend/migrations/0019_allow_member_agent_access.py b/products/mcp_store/backend/migrations/0019_allow_member_agent_access.pynew file mode 100644index 000000000000..31fbb3e1df93--- /dev/null+++ b/products/mcp_store/backend/migrations/0019_allow_member_agent_access.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-07-23 15:27++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("mcp_store", "0018_bind_agent_access_credential"),+ ]++ operations = [+ migrations.AddField(+ model_name="teammcpgatewayconfig",+ name="allow_member_agent_access",+ field=models.BooleanField(default=True),+ ),+ ]diff --git a/products/mcp_store/backend/migrations/0020_default_servers_enabled.py b/products/mcp_store/backend/migrations/0020_default_servers_enabled.pynew file mode 100644index 000000000000..972732c6790c--- /dev/null+++ b/products/mcp_store/backend/migrations/0020_default_servers_enabled.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-07-29 00:00++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("mcp_store", "0019_allow_member_agent_access"),+ ]++ operations = [+ migrations.AddField(+ model_name="teammcpgatewayconfig",+ name="default_servers_enabled",+ field=models.BooleanField(default=True),+ ),+ ]diff --git a/products/mcp_store/backend/migrations/0021_mcpserverinstallationtool_annotations.py b/products/mcp_store/backend/migrations/0021_mcpserverinstallationtool_annotations.pynew file mode 100644index 000000000000..f3524fa1f620--- /dev/null+++ b/products/mcp_store/backend/migrations/0021_mcpserverinstallationtool_annotations.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("mcp_store", "0020_default_servers_enabled"),+ ]++ operations = [+ migrations.AddField(+ model_name="mcpserverinstallationtool",+ name="annotations",+ field=models.JSONField(blank=True, default=dict),+ ),+ ]diff --git a/products/mcp_store/backend/migrations/max_migration.txt b/products/mcp_store/backend/migrations/max_migration.txtindex 08632c5c75f9..b6efd88b9ff6 100644--- a/products/mcp_store/backend/migrations/max_migration.txt+++ b/products/mcp_store/backend/migrations/max_migration.txt@@ -1 +1 @@-0015_backfill_mcp_template_icon_domains+0021_mcpserverinstallationtool_annotationsdiff --git a/products/mcp_store/backend/models.py b/products/mcp_store/backend/models.pyindex 4ba2ce271580..a35e78e40051 100644--- a/products/mcp_store/backend/models.py+++ b/products/mcp_store/backend/models.py@@ -5,6 +5,7 @@ from django.db import modelsfrom django.db.models import Qfrom posthog.helpers.encrypted_fields import EncryptedJSONField+from posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModelAUTH_TYPE_CHOICES = [@@ -35,6 +36,46 @@ SCOPE_CHOICES = [("shared", "Shared"),]+SERVICE_ACCOUNT_STATUS_CHOICES = [+ ("active", "Active"),+ ("paused", "Paused"),+]++# Team-level policy baselines. They derive a default per-tool state for tools+# that have no explicit policy row (see policy.member_preset_team_state).+POLICY_PRESET_CHOICES = [+ ("allow", "Allow all"),+ ("user", "Member decides"),+ ("ask", "Ask for destructive"),+ ("block", "Block destructive"),+]++POLICY_SCOPE_TYPE_CHOICES = [+ ("team", "Team default"),+ ("member", "Member"),+ ("agent", "Agent"),+]++ORG_RULE_APPLIES_TO_CHOICES = [+ ("everyone", "Everyone"),+ ("members", "Members"),+ ("agents", "Agents"),+]++ORG_RULE_EFFECT_CHOICES = [+ ("needs_approval", "Require approval"),+ ("do_not_use", "Block"),+]++# How the gateway decided a proxied tool call. "pending" is an agent call that+# hit a needs_approval tool and was rejected awaiting a human.+AUDIT_DECISION_CHOICES = [+ ("auto", "Auto-approved"),+ ("approved", "Approved"),+ ("pending", "Awaiting approval"),+ ("blocked", "Blocked"),+]+class SensitiveConfig(TypedDict, total=False):api_key: str@@ -133,6 +174,13 @@ class MCPServerInstallation(CreatedMetaFields, UpdatedMetaFields, UUIDModel):oauth_issuer_url = models.URLField(max_length=2048, blank=True, default="")oauth_metadata = models.JSONField(default=dict, blank=True)sensitive_configuration = EncryptedJSONField(default=dict, blank=True)+ # The team-level gateway registration this credential belongs to. Null for+ # rows that predate the gateway until the backfill links them; the proxy+ # falls back to pre-gateway behavior when unset.+ gateway_server = models.ForeignKey(+ "MCPGatewayServer", on_delete=models.SET_NULL, related_name="installations", null=True, blank=True+ )+ last_used_at = models.DateTimeField(null=True, blank=True)class Meta:db_table = "mcp_store_mcpserverinstallation"@@ -161,6 +209,9 @@ class MCPServerInstallationTool(CreatedMetaFields, UpdatedMetaFields, UUIDModel)display_name = models.CharField(max_length=200, blank=True, default="")description = models.TextField(blank=True, default="")input_schema = models.JSONField(default=dict, blank=True)+ # MCP spec tool annotations (destructiveHint etc.) as declared by the+ # upstream server. Untrusted hints: policy lets them escalate, never loosen.+ annotations = models.JSONField(default=dict, blank=True)approval_state = models.CharField(max_length=20, choices=APPROVAL_STATES, default="needs_approval")last_seen_at = models.DateTimeField()# Set when the tool is absent from a fresh tools/list. Cleared on reappearance.@@ -185,6 +236,12 @@ class MCPOAuthState(CreatedMetaFields, UpdatedMetaFields, UUIDModel):)install_source = models.CharField(max_length=20, choices=INSTALL_SOURCE_CHOICES, default="posthog")posthog_code_callback_url = models.TextField(blank=True, default="", db_column="twig_callback_url")+ # In-app path to land back on after the OAuth round-trip (e.g. the gateway+ # page that initiated the connect). Validated as a same-app relative path+ # before any redirect — see `_is_valid_web_return_path`. db_default keeps a+ # real Postgres DEFAULT so inserts from code predating this column (old+ # pods during a rolling deploy) don't hit the NOT NULL.+ web_return_path = models.TextField(blank=True, default="", db_default="")pkce_verifier = models.CharField(max_length=255, blank=True, default="")expires_at = models.DateTimeField()consumed_at = models.DateTimeField(null=True, blank=True)@@ -195,3 +252,250 @@ class MCPOAuthState(CreatedMetaFields, UpdatedMetaFields, UUIDModel):models.Index(fields=["expires_at"]),models.Index(fields=["consumed_at"]),]+++class TeamMCPGatewayConfig(TeamScopedRootMixin, UUIDModel):+ """Team-wide gateway settings (a Team extension — not fields on Team)."""++ team = models.OneToOneField(+ "posthog.Team", on_delete=models.CASCADE, related_name="mcp_gateway_config", db_constraint=False+ )+ allow_custom_servers = models.BooleanField(default=True)+ allow_member_agent_access = models.BooleanField(default=True)+ # Enablement fallback for servers with no MCPGatewayServer row (including+ # catalog templates published later). A row's is_team_enabled always wins.+ default_servers_enabled = models.BooleanField(default=True)+ # Blank until an admin applies a preset from Team settings; the policy+ # engine treats blank as "no baseline".+ member_default_preset = models.CharField(max_length=20, choices=POLICY_PRESET_CHOICES, blank=True, default="")+ agent_default_preset = models.CharField(max_length=20, choices=POLICY_PRESET_CHOICES, blank=True, default="")+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "mcp_store_teammcpgatewayconfig"+++class MCPGatewayServer(TeamScopedRootMixin, UUIDModel):+ """A team-level registration of one MCP server URL in the gateway.++ Everything the gateway controls hangs off this row: enablement, per-scope+ tool policies, agent access, member revocations, and the audit trail.+ Credentials stay on `MCPServerInstallation` rows that point here."""++ team = models.ForeignKey(+ "posthog.Team", on_delete=models.CASCADE, related_name="gateway_servers", db_constraint=False+ )+ name = models.CharField(max_length=200)+ url = models.URLField(max_length=2048)+ description = models.TextField(blank=True, default="")+ category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default="dev")+ # Team-wide kill switch: when off, neither members nor agents can call the+ # server. Agent access additionally requires an explicit+ # MCPServiceAccountServerAccess grant.+ is_team_enabled = models.BooleanField(default=True)+ template = models.ForeignKey(+ MCPServerTemplate, on_delete=models.SET_NULL, related_name="gateway_servers", null=True, blank=True+ )+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "mcp_store_mcpgatewayserver"+ constraints = [+ models.UniqueConstraint(fields=["team", "url"], name="uniq_gateway_server_per_team_url"),+ ]+++class MCPMemberServerRevocation(TeamScopedRootMixin, UUIDModel):+ """An admin turned one server off for one member. Presence = revoked."""++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)+ gateway_server = models.ForeignKey(MCPGatewayServer, on_delete=models.CASCADE, related_name="member_revocations")+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)+ revoked_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ db_table = "mcp_store_mcpmemberserverrevocation"+ constraints = [+ models.UniqueConstraint(fields=["gateway_server", "user"], name="uniq_member_server_revocation"),+ ]+++class MCPOrgRule(TeamScopedRootMixin, UUIDModel):+ """A team guardrail evaluated before any scope policy. A matching enabled+ rule locks the tool's state for its audience — no scope can loosen it."""++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="org_rules", db_constraint=False)+ name = models.CharField(max_length=200)+ description = models.TextField(blank=True, default="")+ applies_to = models.CharField(max_length=20, choices=ORG_RULE_APPLIES_TO_CHOICES, default="everyone")+ effect = models.CharField(max_length=20, choices=ORG_RULE_EFFECT_CHOICES, default="do_not_use")+ # fnmatch-style pattern matched against the tool name (e.g. "delete_*" or+ # "*"). Blank means the rule matches destructive tools heuristically —+ # see policy.is_destructive_tool.+ tool_pattern = models.CharField(max_length=400, blank=True, default="")+ enabled = models.BooleanField(default=True)+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "mcp_store_mcporgrule"+++class MCPServiceAccount(TeamScopedRootMixin, UUIDModel):+ """A fixed PostHog agent identity with independent MCP access policies."""++ team = models.ForeignKey(+ "posthog.Team", on_delete=models.CASCADE, related_name="mcp_service_accounts", db_constraint=False+ )+ name = models.CharField(max_length=200)+ description = models.TextField(blank=True, default="")+ # Stable internal identity handle shown in audit trails.+ handle = models.CharField(max_length=200)+ status = models.CharField(max_length=20, choices=SERVICE_ACCOUNT_STATUS_CHOICES, default="active")+ # Reserved unique identity material for the built-in catalog. Runtime+ # authentication uses short-lived signed tokens instead.+ token_hash = models.CharField(max_length=128, unique=True)+ token_mask = models.CharField(max_length=64, blank=True, default="")+ last_active_at = models.DateTimeField(null=True, blank=True)+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "mcp_store_mcpserviceaccount"+ constraints = [+ models.UniqueConstraint(fields=["team", "handle"], name="uniq_service_account_handle_per_team"),+ ]+++class MCPServiceAccountServerAccess(TeamScopedRootMixin, UUIDModel):+ """Grant row: this agent may call this gateway server using one credential."""++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)+ service_account = models.ForeignKey(MCPServiceAccount, on_delete=models.CASCADE, related_name="server_access")+ gateway_server = models.ForeignKey(MCPGatewayServer, on_delete=models.CASCADE, related_name="agent_access")+ # Null preserves the grant when its exact credential is deleted, so the UI+ # can surface that the agent needs a new connection.+ installation = models.ForeignKey(+ MCPServerInstallation,+ on_delete=models.SET_NULL,+ related_name="agent_grants",+ null=True,+ blank=True,+ )+ granted_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ created_at = models.DateTimeField(auto_now_add=True)++ def save(self, *args, **kwargs) -> None:+ # Join rows are always created via their parents; derive the tenant key+ # so get_or_create call sites don't have to thread it through.+ if not self.team_id and self.gateway_server_id:+ self.team_id = self.gateway_server.team_id+ super().save(*args, **kwargs)++ class Meta:+ db_table = "mcp_store_mcpserviceaccountserveraccess"+ constraints = [+ models.UniqueConstraint(fields=["service_account", "gateway_server"], name="uniq_agent_server_access"),+ ]+++class MCPToolPolicy(TeamScopedRootMixin, UUIDModel):+ """One tool's state for one scope: the team default, one member, or one+ agent. Resolution order lives in policy.PolicyContext."""++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)+ gateway_server = models.ForeignKey(MCPGatewayServer, on_delete=models.CASCADE, related_name="tool_policies")+ tool_name = models.CharField(max_length=200)+ scope_type = models.CharField(max_length=20, choices=POLICY_SCOPE_TYPE_CHOICES)+ scope_user = models.ForeignKey(+ "posthog.User", on_delete=models.CASCADE, null=True, blank=True, related_name="+", db_constraint=False+ )+ scope_service_account = models.ForeignKey(+ MCPServiceAccount, on_delete=models.CASCADE, null=True, blank=True, related_name="tool_policies"+ )+ state = models.CharField(max_length=20, choices=APPROVAL_STATES, default="needs_approval")+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ def save(self, *args, **kwargs) -> None:+ if not self.team_id and self.gateway_server_id:+ self.team_id = self.gateway_server.team_id+ super().save(*args, **kwargs)++ class Meta:+ db_table = "mcp_store_mcptoolpolicy"+ indexes = [models.Index(fields=["gateway_server", "scope_type"])]+ constraints = [+ models.UniqueConstraint(+ fields=["gateway_server", "tool_name"],+ condition=Q(scope_type="team"),+ name="uniq_team_tool_policy",+ ),+ models.UniqueConstraint(+ fields=["gateway_server", "tool_name", "scope_user"],+ condition=Q(scope_type="member"),+ name="uniq_member_tool_policy",+ ),+ models.UniqueConstraint(+ fields=["gateway_server", "tool_name", "scope_service_account"],+ condition=Q(scope_type="agent"),+ name="uniq_agent_tool_policy",+ ),+ models.CheckConstraint(+ check=(+ Q(scope_type="team", scope_user__isnull=True, scope_service_account__isnull=True)+ | Q(scope_type="member", scope_user__isnull=False, scope_service_account__isnull=True)+ | Q(scope_type="agent", scope_user__isnull=True, scope_service_account__isnull=False)+ ),+ name="tool_policy_scope_matches_type",+ ),+ ]+++class MCPAuditEvent(TeamScopedRootMixin, UUIDModel):+ """One proxied tool call and how the gateway decided it. Metadata only —+ never request/response bodies. Actor fields are denormalized so the trail+ survives account or server deletion."""++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)+ gateway_server = models.ForeignKey(+ MCPGatewayServer, on_delete=models.SET_NULL, null=True, blank=True, related_name="audit_events"+ )+ installation = models.ForeignKey(+ MCPServerInstallation, on_delete=models.SET_NULL, null=True, blank=True, related_name="+"+ )+ actor_user = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ actor_service_account = models.ForeignKey(+ MCPServiceAccount, on_delete=models.SET_NULL, null=True, blank=True, related_name="audit_events"+ )+ actor_label = models.CharField(max_length=254, blank=True, default="")+ server_name = models.CharField(max_length=200, blank=True, default="")+ tool_name = models.CharField(max_length=200, blank=True, default="")+ decision = models.CharField(max_length=20, choices=AUDIT_DECISION_CHOICES)+ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ db_table = "mcp_store_mcpauditevent"+ indexes = [+ models.Index(fields=["team", "-created_at"]),+ models.Index(fields=["team", "decision", "-created_at"]),+ models.Index(fields=["team", "actor_service_account", "-created_at"]),+ ]diff --git a/products/mcp_store/backend/policy.py b/products/mcp_store/backend/policy.pynew file mode 100644index 000000000000..2d4b346cf386--- /dev/null+++ b/products/mcp_store/backend/policy.py@@ -0,0 +1,424 @@+"""Gateway policy engine.++Resolves the effective state of one tool for one caller. Team policy is a+ceiling: a caller may choose the same state or a more restrictive state, but+can never make a tool more permissive than the team allows.++1. Org rules — enabled team guardrails; a match locks the state.+2. The stricter of the caller's own choice and the team ceiling. The caller's+ choice comes from its scope row, or for members from the legacy+ per-installation state. The ceiling comes from the explicit team row, then+ the audience preset.+3. `needs_approval` — freshly discovered tools are opt-in when neither side+ has made a choice.++Every consumer (member proxy, agent proxy, Max, the gateway UI) resolves+through this module so their answers can't drift apart.+"""++import re+from collections.abc import Iterable+from dataclasses import dataclass+from fnmatch import fnmatch+from typing import Any, Literal+from uuid import UUID++from django.db.models import Q++from posthog.models.scoping.manager import resolve_effective_team_id++from .models import MCPGatewayServer, MCPOrgRule, MCPServerInstallation, MCPToolPolicy, TeamMCPGatewayConfig++# What tool sync stamps on every freshly discovered row (see tools.py). Only+# members have this legacy layer, so a row still sitting at the sync default+# would invent a member preference that no one chose — and because a caller's+# own choice beats a laxer ceiling, that phantom undercuts the team baseline.+# The result was incoherent: team and agent scopes saw the baseline while the+# member saw needs_approval on the same tool.+#+# Safe to ignore because an explicit choice is recorded elsewhere: the legacy+# toggle mirrors every write into a member MCPToolPolicy row+# (views._mirror_tool_approval_to_gateway), and scope rows outrank legacy ones.+# The gap is a pre-gateway member who explicitly picked needs_approval and was+# never mirrored. That only changes behaviour on teams whose admin has set a+# permissive preset — with no preset the resolve() fallback is needs_approval+# anyway — so the loosening is limited to teams that asked for it.+SYNC_DEFAULT_APPROVAL_STATE = "needs_approval"++# Exact verb forms that indicate a tool mutates or destroys state. Matched+# against the tool name only — descriptions are prose, where verbs like+# "archived" or "removes" show up in read-only tools. Deliberately the strong+# set only: an over-broad heuristic would make the "ask"/"block" presets gate+# nearly every tool.+_DESTRUCTIVE_TOKENS = frozenset(+ {+ "archive",+ "archived",+ "archives",+ "archiving",+ "ban",+ "banned",+ "banning",+ "bans",+ "cancel",+ "canceled",+ "canceling",+ "cancelled",+ "cancelling",+ "cancels",+ "delete",+ "deleted",+ "deletes",+ "deleting",+ "destroy",+ "destroyed",+ "destroying",+ "destroys",+ "drop",+ "dropped",+ "dropping",+ "drops",+ "erase",+ "erased",+ "erases",+ "erasing",+ "overwrite",+ "overwritten",+ "overwrites",+ "overwriting",+ "overwrote",+ "purge",+ "purged",+ "purges",+ "purging",+ "remove",+ "removed",+ "removes",+ "removing",+ "reset",+ "resets",+ "resetting",+ "revoke",+ "revoked",+ "revokes",+ "revoking",+ "suspend",+ "suspended",+ "suspending",+ "suspends",+ "terminate",+ "terminated",+ "terminates",+ "terminating",+ "truncate",+ "truncated",+ "truncates",+ "truncating",+ "wipe",+ "wiped",+ "wipes",+ "wiping",+ }+)++_CAMEL_CASE_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")+_WORD_SPLIT = re.compile(r"[^a-z0-9]+")+++def _word_tokens(value: str) -> set[str]:+ normalized = _CAMEL_CASE_BOUNDARY.sub(" ", value).lower()+ return {token for token in _WORD_SPLIT.split(normalized) if token}+++def is_destructive_tool(tool_name: str, annotations: dict[str, Any] | None = None) -> bool:+ """Heuristic used by presets and pattern-less org rules: destructive verb+ tokens in the tool name, or the server's own MCP ``destructiveHint``+ annotation. Annotations are untrusted upstream input, so a hint can only+ escalate — ``destructiveHint: false`` never clears a name match."""+ if annotations is not None and annotations.get("destructiveHint") is True:+ return True+ return bool(_word_tokens(tool_name) & _DESTRUCTIVE_TOKENS)+++def member_preset_team_state(preset: str, tool_name: str, annotations: dict[str, Any] | None = None) -> str | None:+ """The default state a policy preset implies for a tool, or None when the+ preset is unset and imposes nothing."""+ if preset == "allow":+ return "approved"+ if preset == "user":+ return "needs_approval"+ if preset == "ask":+ return "needs_approval" if is_destructive_tool(tool_name, annotations) else "approved"+ if preset == "block":+ return "do_not_use" if is_destructive_tool(tool_name, annotations) else "approved"+ return None+++@dataclass(frozen=True)+class GatewayCaller:+ kind: Literal["member", "agent"]+ user_id: int | None = None+ service_account_id: str | None = None+++@dataclass(frozen=True)+class ResolvedPolicy:+ state: str+ # Which layer decided: "rule" | "scope" | "team" | "preset" | "legacy" | "default"+ decided_by: str+ # What the team-level chain (row or preset) would yield, ignoring the+ # caller's own scope. None when the team imposes nothing.+ team_state: str | None = None+ rule_name: str = ""+ rule_description: str = ""++ @property+ def locked(self) -> bool:+ """A rule match can't be loosened by any scope."""+ return self.decided_by == "rule"+++@dataclass(frozen=True)+class _PolicyInputs:+ rules: tuple[MCPOrgRule, ...]+ policies: tuple[MCPToolPolicy, ...]+ preset: str+++_STRICTNESS = {"do_not_use": 2, "needs_approval": 1, "approved": 0}+++def is_policy_state_allowed(state: str, ceiling: str | None) -> bool:+ """Whether ``state`` is at least as restrictive as ``ceiling``."""+ if ceiling is None:+ return True+ return _STRICTNESS[state] >= _STRICTNESS[ceiling]+++class PolicyContext:+ """Preloads every policy input for one (team, caller, server) so `resolve`+ is a pure in-memory lookup — callers resolve many tools in a loop."""++ def __init__(+ self,+ *,+ team_id: int,+ caller: GatewayCaller,+ gateway_server: MCPGatewayServer | None = None,+ gateway_server_id: UUID | None = None,+ installation: MCPServerInstallation | None = None,+ legacy_rows: dict[str, str] | None = None,+ _preloaded: _PolicyInputs | None = None,+ ) -> None:+ if gateway_server is not None:+ gateway_server_id = gateway_server.id+ if gateway_server_id is None:+ raise ValueError("PolicyContext requires a gateway server or gateway server ID")++ self.team_id = team_id+ self.caller = caller+ self.gateway_server = gateway_server+ self.gateway_server_id = gateway_server_id++ audience = "members" if caller.kind == "member" else "agents"+ # for_team: policy resolution also runs outside request scope (Max,+ # the agent proxy), where the fail-closed manager has no context.+ if _preloaded is None:+ canonical_team_id = resolve_effective_team_id(team_id)+ self._rules = tuple(+ MCPOrgRule.objects.for_team(canonical_team_id, canonical=True).filter(+ enabled=True,+ applies_to__in=("everyone", audience),+ )+ )+ else:+ canonical_team_id = team_id+ self._rules = _preloaded.rules++ policy_scope = Q(scope_type="team")+ if caller.kind == "member" and caller.user_id is not None:+ policy_scope |= Q(scope_type="member", scope_user_id=caller.user_id)+ elif caller.kind == "agent" and caller.service_account_id is not None:+ policy_scope |= Q(scope_type="agent", scope_service_account_id=caller.service_account_id)+ policies: Iterable[MCPToolPolicy] = (+ MCPToolPolicy.objects.for_team(canonical_team_id, canonical=True).filter(+ policy_scope, gateway_server_id=gateway_server_id+ )+ if _preloaded is None+ else _preloaded.policies+ )+ self._team_rows: dict[str, str] = {}+ self._scope_rows: dict[str, str] = {}+ for policy in policies:+ if policy.scope_type == "team":+ self._team_rows[policy.tool_name] = policy.state+ elif (+ policy.scope_type == "member"+ and caller.kind == "member"+ and caller.user_id is not None+ and policy.scope_user_id == caller.user_id+ ):+ self._scope_rows[policy.tool_name] = policy.state+ elif (+ policy.scope_type == "agent"+ and caller.kind == "agent"+ and caller.service_account_id is not None+ and str(policy.scope_service_account_id) == str(caller.service_account_id)+ ):+ self._scope_rows[policy.tool_name] = policy.state++ if _preloaded is not None:+ self.preset = _preloaded.preset+ else:+ config = TeamMCPGatewayConfig.objects.for_team(canonical_team_id, canonical=True).first()+ if config is None:+ self.preset = ""+ else:+ self.preset = config.member_default_preset if caller.kind == "member" else config.agent_default_preset++ raw_legacy = dict(legacy_rows or {}) if caller.kind == "member" else {}+ if legacy_rows is None and installation is not None and caller.kind == "member":+ for row in installation.tools.filter(removed_at__isnull=True).values("tool_name", "approval_state"):+ raw_legacy[row["tool_name"]] = row["approval_state"]+ self._legacy_rows = {+ tool_name: state for tool_name, state in raw_legacy.items() if state != SYNC_DEFAULT_APPROVAL_STATE+ }++ @classmethod+ def for_agent_servers(+ cls,+ *,+ team_id: int,+ service_account_id: str,+ gateway_servers: Iterable[MCPGatewayServer],+ ) -> dict[UUID, "PolicyContext"]:+ """Load policy inputs once for an agent's server catalog."""+ servers_by_id = {server.id: server for server in gateway_servers}+ if not servers_by_id:+ return {}++ canonical_team_id = resolve_effective_team_id(team_id)+ caller = GatewayCaller(kind="agent", service_account_id=service_account_id)+ rules = tuple(+ MCPOrgRule.objects.for_team(canonical_team_id, canonical=True).filter(+ enabled=True,+ applies_to__in=("everyone", "agents"),+ )+ )+ policies_by_server: dict[UUID, list[MCPToolPolicy]] = {}+ relevant_policies = (+ MCPToolPolicy.objects.for_team(canonical_team_id, canonical=True)+ .filter(gateway_server_id__in=servers_by_id)+ .filter(+ Q(scope_type="team")+ | Q(+ scope_type="agent",+ scope_service_account_id=service_account_id,+ )+ )+ )+ for policy in relevant_policies:+ policies_by_server.setdefault(policy.gateway_server_id, []).append(policy)++ config = TeamMCPGatewayConfig.objects.for_team(canonical_team_id, canonical=True).first()+ preset = config.agent_default_preset if config is not None else ""+ return {+ server_id: cls(+ team_id=team_id,+ caller=caller,+ gateway_server=server,+ _preloaded=_PolicyInputs(+ rules=rules,+ policies=tuple(policies_by_server.get(server_id, ())),+ preset=preset,+ ),+ )+ for server_id, server in servers_by_id.items()+ }++ def _matching_rule(self, tool_name: str, annotations: dict[str, Any] | None) -> MCPOrgRule | None:+ matches = [+ rule+ for rule in self._rules+ if (+ fnmatch(tool_name, rule.tool_pattern)+ if rule.tool_pattern+ else is_destructive_tool(tool_name, annotations)+ )+ ]+ if not matches:+ return None+ return max(matches, key=lambda rule: _STRICTNESS.get(rule.effect, 0))++ def team_policy(self, tool_name: str, annotations: dict[str, Any] | None = None) -> tuple[str, str] | None:+ if tool_name in self._team_rows:+ return self._team_rows[tool_name], "team"+ preset_state = member_preset_team_state(self.preset, tool_name, annotations)+ return (preset_state, "preset") if preset_state is not None else None++ def team_state(self, tool_name: str, annotations: dict[str, Any] | None = None) -> str | None:+ team_policy = self.team_policy(tool_name, annotations)+ return team_policy[0] if team_policy is not None else None++ def resolve_team(self, tool_name: str, annotations: dict[str, Any] | None = None) -> ResolvedPolicy:+ """Resolve the editable team ceiling itself, rather than a caller under it."""+ team_policy = self.team_policy(tool_name, annotations)+ team_state = team_policy[0] if team_policy is not None else None++ rule = self._matching_rule(tool_name, annotations)+ if rule is not None:+ return ResolvedPolicy(+ state=rule.effect,+ decided_by="rule",+ team_state=team_state,+ rule_name=rule.name,+ rule_description=rule.description,+ )++ if team_policy is not None:+ state, decided_by = team_policy+ return ResolvedPolicy(state=state, decided_by=decided_by, team_state=state)++ return ResolvedPolicy(state="approved", decided_by="default", team_state=None)++ def resolve(self, tool_name: str, annotations: dict[str, Any] | None = None) -> ResolvedPolicy:+ team_policy = self.team_policy(tool_name, annotations)+ team_state = team_policy[0] if team_policy is not None else None++ rule = self._matching_rule(tool_name, annotations)+ if rule is not None:+ return ResolvedPolicy(+ state=rule.effect,+ decided_by="rule",+ team_state=team_state,+ rule_name=rule.name,+ rule_description=rule.description,+ )++ preference: tuple[str, str] | None = None+ if tool_name in self._scope_rows:+ preference = self._scope_rows[tool_name], "scope"+ elif tool_name in self._legacy_rows:+ preference = self._legacy_rows[tool_name], "legacy"++ if preference is not None:+ preference_state, preference_source = preference+ if team_policy is not None:+ ceiling_state, ceiling_source = team_policy+ if not is_policy_state_allowed(preference_state, ceiling_state):+ return ResolvedPolicy(+ state=ceiling_state,+ decided_by=ceiling_source,+ team_state=ceiling_state,+ )+ return ResolvedPolicy(+ state=preference_state,+ decided_by=preference_source,+ team_state=team_state,+ )++ if team_policy is not None:+ ceiling_state, ceiling_source = team_policy+ return ResolvedPolicy(state=ceiling_state, decided_by=ceiling_source, team_state=ceiling_state)++ return ResolvedPolicy(state="needs_approval", decided_by="default", team_state=team_state)diff --git a/products/mcp_store/backend/presentation/agent_views.py b/products/mcp_store/backend/presentation/agent_views.pynew file mode 100644index 000000000000..7fa1fcc73e7f--- /dev/null+++ b/products/mcp_store/backend/presentation/agent_views.py@@ -0,0 +1,233 @@+"""Agent-facing gateway surface, authenticated by service-account tokens.++Agents call this root-level API with `Authorization: Bearer mcp_gw_...`; the+token resolves the team, so there is no project in the URL. Deliberately+outside the OpenAPI spec (like the OAuth redirect): it is an external token+surface, not part of the app schema.++Each grant binds the credential its administrator delegated to the agent.+Every tools/call resolves through the same policy engine as members, under the+agent's own scope.+"""++from collections import defaultdict+from datetime import timedelta+from typing import Any, cast+from uuid import UUID++from django.http import HttpResponse+from django.http.response import HttpResponseBase+from django.utils import timezone++import structlog+from rest_framework import viewsets+from rest_framework.authentication import BaseAuthentication+from rest_framework.decorators import action+from rest_framework.exceptions import AuthenticationFailed+from rest_framework.permissions import BasePermission+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.throttling import SimpleRateThrottle+from rest_framework.views import APIView++from posthog.rate_limit import MCPProxyBurstThrottle, MCPProxySustainedThrottle++from ..agents import resolve_gateway_agent_token+from ..gateway import installation_for_agent_access+from ..models import MCPServerInstallationTool, MCPServiceAccount, MCPServiceAccountServerAccess+from ..policy import GatewayCaller, PolicyContext+from ..proxy import proxy_mcp_request, validate_installation_auth+from .views import MCPProxyRenderer++logger = structlog.get_logger(__name__)+++class _MCPGatewayAgentThrottle(SimpleRateThrottle):+ def get_cache_key(self, request: Request, view: APIView) -> str | None:+ account = request.auth+ if not isinstance(account, MCPServiceAccount):+ return None+ return self.cache_format % {"scope": self.scope, "ident": account.id}+++class MCPGatewayAgentBurstThrottle(_MCPGatewayAgentThrottle):+ scope = "mcp_gateway_agent_burst"+ rate = MCPProxyBurstThrottle.rate+++class MCPGatewayAgentSustainedThrottle(_MCPGatewayAgentThrottle):+ scope = "mcp_gateway_agent_sustained"+ rate = MCPProxySustainedThrottle.rate+++class GatewayAgentAuthentication(BaseAuthentication):+ """Resolves `Authorization: Bearer mcp_gw_...` to an active service account.++ Returns no user — the agent is the principal; downstream code reads it from+ `request.auth`."""++ def authenticate(self, request: Request) -> tuple[Any, MCPServiceAccount] | None:+ header = request.headers.get("Authorization", "")+ if not header.startswith("Bearer "):+ return None+ token = header.split(" ", 1)[1].strip()+ account = resolve_gateway_agent_token(token)+ if account is None:+ raise AuthenticationFailed("Invalid gateway token.")+ if account.status != "active":+ raise AuthenticationFailed("This agent is paused.")+ return (None, account)++ def authenticate_header(self, request: Request) -> str:+ return "Bearer"+++class GatewayAgentPermission(BasePermission):+ message = "A valid gateway token is required."++ def has_permission(self, request: Request, view: Any) -> bool:+ return isinstance(request.auth, MCPServiceAccount)+++class MCPGatewayAgentViewSet(viewsets.ViewSet):+ """What an agent can see and call through the gateway."""++ authentication_classes = [GatewayAgentAuthentication]+ permission_classes = [GatewayAgentPermission]+ throttle_classes = [MCPGatewayAgentBurstThrottle, MCPGatewayAgentSustainedThrottle]++ def _accessible_server_access(self, account: MCPServiceAccount) -> list[MCPServiceAccountServerAccess]:+ # The admin kill switch overrides grants: a server turned off for the+ # team disappears from the agent catalog like it does for members.+ return list(+ MCPServiceAccountServerAccess.objects.for_team(account.team_id)+ .filter(service_account=account, gateway_server__is_team_enabled=True)+ .select_related("gateway_server__template", "installation")+ .order_by("gateway_server__name")+ )++ def _touch(self, account: MCPServiceAccount) -> None:+ now = timezone.now()+ if account.last_active_at is None or now - account.last_active_at > timedelta(hours=1):+ MCPServiceAccount.objects.for_team(account.team_id).filter(pk=account.pk).update(last_active_at=now)++ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """The agent's server catalog: every enabled server it has access to,+ with each tool's effective policy state."""+ account = cast(MCPServiceAccount, request.auth)+ catalog_entries = [+ (access, installation_for_agent_access(access)) for access in self._accessible_server_access(account)+ ]+ active_entries = [+ (access, installation)+ for access, installation in catalog_entries+ if installation is not None and installation.is_enabled+ ]+ policy_contexts = PolicyContext.for_agent_servers(+ team_id=account.team_id,+ service_account_id=str(account.id),+ gateway_servers=(access.gateway_server for access, _installation in active_entries),+ )+ tools_by_installation: dict[UUID, list[MCPServerInstallationTool]] = defaultdict(list)+ active_installation_ids = [installation.id for _access, installation in active_entries]+ for tool in (+ MCPServerInstallationTool.objects.filter(+ installation_id__in=active_installation_ids,+ removed_at__isnull=True,+ )+ .order_by("installation_id", "tool_name", "-last_seen_at", "-id")+ .only("installation_id", "tool_name", "description", "input_schema", "annotations")+ ):+ tools_by_installation[tool.installation_id].append(tool)++ results = []+ for access, installation in catalog_entries:+ server = access.gateway_server+ tools = []+ seen: set[str] = set()+ tool_rows: list[MCPServerInstallationTool] = []+ if installation is not None and installation.is_enabled:+ tool_rows = tools_by_installation.get(installation.id, [])+ for tool in tool_rows:+ if tool.tool_name in seen:+ continue+ seen.add(tool.tool_name)+ tools.append(+ {+ "name": tool.tool_name,+ "description": tool.description or "",+ "input_schema": tool.input_schema or {},+ "state": policy_contexts[server.id]+ .resolve(+ tool.tool_name,+ tool.annotations,+ )+ .state,+ }+ )+ results.append(+ {+ "id": str(server.id),+ "name": server.name,+ "url": server.url,+ "description": server.description,+ "proxy_path": f"/api/mcp_store/gateway/servers/{server.id}/proxy/",+ "tools": tools,+ }+ )+ self._touch(account)+ return Response({"results": results})++ @action(detail=True, methods=["post"], url_path="proxy", renderer_classes=[MCPProxyRenderer])+ def proxy(self, request: Request, pk: str | None = None, *args: Any, **kwargs: Any) -> HttpResponseBase:+ """Proxy one MCP request to the server as this agent."""+ account = cast(MCPServiceAccount, request.auth)+ if not pk:+ return HttpResponse('{"error": "Server not found"}', content_type="application/json", status=404)+ try:+ access = (+ MCPServiceAccountServerAccess.objects.for_team(account.team_id)+ .select_related("gateway_server", "installation")+ .get(service_account=account, gateway_server_id=pk)+ )+ except (MCPServiceAccountServerAccess.DoesNotExist, ValueError):+ return HttpResponse(+ '{"error": "Server not found or not shared with this agent"}',+ content_type="application/json",+ status=404,+ )+ server = access.gateway_server+ if not server.is_team_enabled:+ return HttpResponse(+ '{"error": "Server is disabled for this team"}',+ content_type="application/json",+ status=403,+ )+ installation = installation_for_agent_access(access)+ if installation is None:+ return HttpResponse(+ '{"error": "This server has no credential shared with this agent"}',+ content_type="application/json",+ status=409,+ )++ logger.info(+ "mcp_gateway agent proxy request",+ team_id=account.team_id,+ gateway_server_id=str(server.id),+ service_account_id=str(account.id),+ )++ ok, error_response = validate_installation_auth(installation)+ if not ok and error_response is not None:+ return error_response++ self._touch(account)+ caller = GatewayCaller(kind="agent", service_account_id=str(account.id))+ return proxy_mcp_request(+ request,+ installation,+ caller=caller,+ gateway_server=server,+ actor_label=account.handle,+ )diff --git a/products/mcp_store/backend/presentation/gateway_views.py b/products/mcp_store/backend/presentation/gateway_views.pynew file mode 100644index 000000000000..1fba664cf8f1--- /dev/null+++ b/products/mcp_store/backend/presentation/gateway_views.py@@ -0,0 +1,1540 @@+"""Gateway API — the team control plane for MCP servers.++Registrations (`MCPGatewayServer`) are the unit everything hangs off:+enablement, per-scope tool policies, agent access, member revocations, org+rules, and the audit log. Personal/shared credentials stay on+`MCPServerInstallation` (see views.py); this module only adds the team layer.+"""++from collections.abc import Sequence+from functools import cached_property+from typing import Any, cast++from django.db import transaction+from django.db.models import Case, Count, IntegerField, Prefetch, Q, QuerySet, When, prefetch_related_objects+from django.utils import timezone++import structlog+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field, extend_schema_serializer+from rest_framework import mixins, serializers, status, viewsets+from rest_framework.authentication import SessionAuthentication+from rest_framework.decorators import action+from rest_framework.exceptions import NotFound, PermissionDenied+from rest_framework.permissions import IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.mixins import validated_request+from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.shared import UserBasicSerializer+from posthog.event_usage import report_user_action+from posthog.models import User+from posthog.models.organization import OrganizationMembership+from posthog.permissions import DenyMCPBuiltInAgentOAuth++from ..agents import built_in_agent_handles, get_built_in_agent_spec, sync_built_in_agents+from ..gateway import installation_for_agent_access, installation_for_agent_grant, members_can_manage_agent_access+from ..models import (+ APPROVAL_STATES,+ AUTH_TYPE_CHOICES,+ POLICY_PRESET_CHOICES,+ POLICY_SCOPE_TYPE_CHOICES,+ SERVICE_ACCOUNT_STATUS_CHOICES,+ MCPAuditEvent,+ MCPGatewayServer,+ MCPMemberServerRevocation,+ MCPOrgRule,+ MCPServerInstallation,+ MCPServerInstallationTool,+ MCPServerTemplate,+ MCPServiceAccount,+ MCPServiceAccountServerAccess,+ MCPToolPolicy,+ TeamMCPGatewayConfig,+)+from ..policy import GatewayCaller, PolicyContext, is_policy_state_allowed++logger = structlog.get_logger(__name__)++RESOLVED_DECIDED_BY_CHOICES = ["rule", "scope", "team", "preset", "legacy", "default"]++AUDIT_QUICK_FILTER_CHOICES = ["all", "agents", "approvals", "blocked"]++# The UI sends whole catalogs, so keep headroom while bounding per-entry writes.+MAX_TOOL_POLICIES_PER_REQUEST = 1_000++AGENT_SERVER_CONNECTION_STATE_CHOICES = [+ "ready",+ "pending_oauth",+ "needs_reauth",+ "disabled",+ "missing_credential",+]+++def get_gateway_config(team_id: int) -> TeamMCPGatewayConfig | None:+ return TeamMCPGatewayConfig.objects.for_team(team_id).first()+++def _ordered_gateway_tool_rows(+ server: MCPGatewayServer,+ *,+ tool_names: list[str] | None = None,+ include_removed_fallback: bool = False,+) -> QuerySet[MCPServerInstallationTool]:+ """Order rows so the first per tool is the newest active row, then the newest removed row."""+ queryset = MCPServerInstallationTool.objects.filter(installation__gateway_server=server)+ if tool_names is not None:+ queryset = queryset.filter(tool_name__in=tool_names)+ if include_removed_fallback:+ return queryset.annotate(+ removed_rank=Case(+ When(removed_at__isnull=True, then=0),+ default=1,+ output_field=IntegerField(),+ )+ ).order_by("tool_name", "removed_rank", "-last_seen_at", "-id")+ return queryset.filter(removed_at__isnull=True).order_by("tool_name", "-last_seen_at", "-id")+++def policy_entries_above_team_ceiling(+ *,+ team_id: int,+ server: MCPGatewayServer,+ caller: GatewayCaller,+ entries: list[dict[str, Any]],+) -> list[str]:+ """Return entries that try to make a caller scope more permissive than its team ceiling."""+ context = PolicyContext(team_id=team_id, caller=caller, gateway_server=server)+ annotations_by_tool: dict[str, dict[str, Any]] = {}+ tool_rows = _ordered_gateway_tool_rows(+ server,+ tool_names=[entry["tool_name"] for entry in entries],+ include_removed_fallback=True,+ ).values_list("tool_name", "annotations")+ for tool_name, annotations in tool_rows:+ annotations_by_tool.setdefault(tool_name, annotations or {})+ return [+ entry["tool_name"]+ for entry in entries+ if not is_policy_state_allowed(+ entry["policy_state"],+ context.team_state(entry["tool_name"], annotations_by_tool.get(entry["tool_name"])),+ )+ ]+++def raise_for_policies_above_team_ceiling(tool_names: list[str]) -> None:+ if tool_names:+ raise serializers.ValidationError(+ {+ "policies": (+ "A team admin set a stricter ceiling for: "+ + ", ".join(sorted(tool_names))+ + ". Choose the ceiling or a more restrictive state."+ )+ }+ )+++class GatewayAdminMixin:+ """Admin gate shared by gateway viewsets.++ Mirrors MCPServerInstallationViewSet._is_project_admin: organization+ admins/owners, or users explicitly granted admin on this project.+ `explicit=True` keeps open-project defaults from making every member an+ effective admin.+ """++ def _is_project_admin(self) -> bool:+ if self.user_access_control.is_organization_admin: # type: ignore[attr-defined]+ return True+ return bool(+ self.user_access_control.check_access_level_for_object(self.team, "admin", explicit=True) # type: ignore[attr-defined]+ )++ def _require_project_admin(self) -> None:+ if not self._is_project_admin():+ raise PermissionDenied("Only project admins can manage the MCP gateway.")++ def _can_manage_agent_access(self) -> bool:+ return self._is_project_admin() or members_can_manage_agent_access(self.team_id) # type: ignore[attr-defined]++ def _require_agent_access_manager(self) -> None:+ if not self._can_manage_agent_access():+ raise PermissionDenied("Only project admins can manage agent access for this project.")+++# ---------------------------------------------------------------------------+# Serializers+# ---------------------------------------------------------------------------+++class GatewayConnectionSerializer(serializers.Serializer):+ """One member's personal connection to a gateway server."""++ installation_id = serializers.UUIDField(help_text="Installation row backing this connection.")+ user = UserBasicSerializer(help_text="The member who connected.")+ last_used_at = serializers.DateTimeField(+ allow_null=True, help_text="When this connection last proxied a tool call. Null if never used."+ )+ pending_oauth = serializers.BooleanField(help_text="True when the OAuth round-trip has not completed yet.")+ needs_reauth = serializers.BooleanField(help_text="True when the stored token was invalidated and needs reauth.")+++class GatewayYourConnectionSerializer(serializers.Serializer):+ """The requesting user's own connection to a gateway server."""++ installation_id = serializers.UUIDField(help_text="The caller's installation row for this server.")+ is_enabled = serializers.BooleanField(help_text="Per-connection switch — false when self-disabled.")+ pending_oauth = serializers.BooleanField(help_text="True when the OAuth round-trip has not completed yet.")+ needs_reauth = serializers.BooleanField(help_text="True when the stored token was invalidated and needs reauth.")+ last_used_at = serializers.DateTimeField(+ allow_null=True, help_text="When the caller last proxied a call through this connection."+ )+++class GatewayAgentAccessSerializer(serializers.Serializer):+ """One agent's access to a gateway server."""++ service_account_id = serializers.UUIDField(help_text="Service account granted access.")+ name = serializers.CharField(help_text="Agent display name.")+ handle = serializers.CharField(help_text="Agent identity handle, e.g. posthog-support.")+ status = serializers.ChoiceField(+ choices=SERVICE_ACCOUNT_STATUS_CHOICES, help_text="active, or paused (all access off)."+ )+ last_active_at = serializers.DateTimeField(allow_null=True, help_text="When the agent last made a call.")+ granted_by = UserBasicSerializer(allow_null=True, help_text="Admin who shared this server with the agent.")+++def _installation_pending_oauth(installation: MCPServerInstallation) -> bool:+ if installation.auth_type != "oauth":+ return False+ return not (installation.sensitive_configuration or {}).get("access_token")+++def _installation_needs_reauth(installation: MCPServerInstallation) -> bool:+ if installation.auth_type != "oauth":+ return False+ return bool((installation.sensitive_configuration or {}).get("needs_reauth"))+++def _connection_payload(installation: MCPServerInstallation) -> dict[str, Any]:+ return {+ "installation_id": installation.id,+ "user": UserBasicSerializer(installation.user).data,+ "last_used_at": installation.last_used_at,+ "pending_oauth": _installation_pending_oauth(installation),+ "needs_reauth": _installation_needs_reauth(installation),+ }+++class MCPGatewayServerSerializer(serializers.ModelSerializer):+ """A server registered in the team's gateway, with connection summary."""++ template_auth_type = serializers.ChoiceField(+ choices=AUTH_TYPE_CHOICES,+ source="template.auth_type",+ read_only=True,+ allow_null=True,+ default=None,+ help_text="Fixed authentication type for catalog templates. Null for custom servers, where members choose.",+ )+ icon_key = serializers.CharField(+ source="template.icon_key",+ read_only=True,+ default="",+ help_text="Deprecated brand icon key from the linked template. Empty for custom servers.",+ )+ icon_domain = serializers.CharField(+ source="template.icon_domain",+ read_only=True,+ default="",+ help_text="Brand domain from the linked template. Empty for custom servers.",+ )+ docs_url = serializers.CharField(+ source="template.docs_url", read_only=True, default="", help_text="Documentation URL from the template."+ )+ template_id = serializers.UUIDField(+ source="template.id", read_only=True, allow_null=True, default=None, help_text="Linked catalog template."+ )+ created_by = UserBasicSerializer(+ read_only=True, allow_null=True, help_text="Who registered the server. Null when that user was deleted."+ )+ tool_count = serializers.SerializerMethodField(help_text="Number of live tools known for this server.")+ connections = serializers.SerializerMethodField(+ help_text="Members with a connection to this server. Only project admins receive this list."+ )+ your_connection = serializers.SerializerMethodField(+ help_text="The requesting user's own connection, or null when not connected."+ )+ agents = serializers.SerializerMethodField(help_text="Agents this server is shared with.")+ revoked_user_ids = serializers.SerializerMethodField(+ help_text="Ids of members whose access an admin has turned off. Only project admins receive this list."+ )+ is_revoked_for_you = serializers.SerializerMethodField(+ help_text="True when an admin has turned this server off for the requesting user."+ )++ class Meta:+ model = MCPGatewayServer+ fields = [+ "id",+ "name",+ "url",+ "description",+ "category",+ "template_auth_type",+ "is_team_enabled",+ "icon_key",+ "icon_domain",+ "docs_url",+ "template_id",+ "tool_count",+ "connections",+ "your_connection",+ "agents",+ "revoked_user_ids",+ "is_revoked_for_you",+ "created_by",+ "created_at",+ "updated_at",+ ]+ read_only_fields = [+ "id",+ "name",+ "url",+ "description",+ "category",+ "is_team_enabled",+ "created_at",+ "updated_at",+ ]++ @extend_schema_field(serializers.IntegerField())+ def get_tool_count(self, obj: MCPGatewayServer) -> int:+ annotated = getattr(obj, "tool_count_annotated", None)+ if annotated is not None:+ return annotated+ return (+ MCPServerInstallationTool.objects.filter(installation__gateway_server=obj, removed_at__isnull=True)+ .values("tool_name")+ .distinct()+ .count()+ )++ @extend_schema_field(GatewayConnectionSerializer(many=True))+ def get_connections(self, obj: MCPGatewayServer) -> list[dict[str, Any]]:+ if not self.context.get("is_admin"):+ return []+ return [_connection_payload(installation) for installation in obj.installations.all()]++ @extend_schema_field(GatewayYourConnectionSerializer(allow_null=True))+ def get_your_connection(self, obj: MCPGatewayServer) -> dict[str, Any] | None:+ request = self.context.get("request")+ if request is None:+ return None+ own = [installation for installation in obj.installations.all() if installation.user_id == request.user.id]+ # A personal row wins over a legacy team-shared row the user owns.+ own.sort(key=lambda installation: installation.scope != "personal")+ if not own:+ return None+ installation = own[0]+ return {+ "installation_id": installation.id,+ "is_enabled": installation.is_enabled,+ "pending_oauth": _installation_pending_oauth(installation),+ "needs_reauth": _installation_needs_reauth(installation),+ "last_used_at": installation.last_used_at,+ }++ @extend_schema_field(GatewayAgentAccessSerializer(many=True))+ def get_agents(self, obj: MCPGatewayServer) -> list[dict[str, Any]]:+ return [+ {+ "service_account_id": access.service_account_id,+ "name": access.service_account.name,+ "handle": access.service_account.handle,+ "status": access.service_account.status,+ "last_active_at": access.service_account.last_active_at,+ "granted_by": UserBasicSerializer(access.granted_by).data if access.granted_by else None,+ }+ for access in obj.agent_access.all()+ ]++ @extend_schema_field(serializers.ListField(child=serializers.IntegerField()))+ def get_revoked_user_ids(self, obj: MCPGatewayServer) -> list[int]:+ if not self.context.get("is_admin"):+ return []+ return [revocation.user_id for revocation in obj.member_revocations.all()]++ @extend_schema_field(serializers.BooleanField())+ def get_is_revoked_for_you(self, obj: MCPGatewayServer) -> bool:+ request = self.context.get("request")+ if request is None:+ return False+ return any(revocation.user_id == request.user.id for revocation in obj.member_revocations.all())+++class SetTemplateEnabledSerializer(serializers.Serializer):+ template_id = serializers.UUIDField(help_text="Active catalog template to enable or disable for the team.")+ enabled = serializers.BooleanField(+ help_text="True lets the team see and call the server; false hides it from members and blocks connections."+ )+++class MCPGatewayServerUpdateSerializer(serializers.ModelSerializer):+ class Meta:+ model = MCPGatewayServer+ fields = ["name", "description", "category", "is_team_enabled"]+ extra_kwargs = {+ "name": {"required": False, "help_text": "Display name shown across the gateway."},+ "description": {"required": False, "help_text": "Short description shown on server cards."},+ "category": {"required": False, "help_text": "Catalog category used for filter chips."},+ "is_team_enabled": {+ "required": False,+ "help_text": "Whether the team can see and call the server. Turning it off also blocks agent access.",+ },+ }+++class ToolPolicyEntrySerializer(serializers.Serializer):+ tool_name = serializers.CharField(max_length=200, help_text="Tool to set the policy for, up to 200 characters.")+ policy_state = serializers.ChoiceField(choices=APPROVAL_STATES, help_text="State to apply for this scope.")+++class GatewayPoliciesQuerySerializer(serializers.Serializer):+ scope_type = serializers.ChoiceField(+ choices=POLICY_SCOPE_TYPE_CHOICES,+ required=False,+ default="team",+ help_text="Which scope to resolve: the team default, one member, or one agent.",+ )+ scope_user_id = serializers.IntegerField(+ required=False, help_text="Member scope target. Defaults to the requesting user."+ )+ scope_service_account_id = serializers.UUIDField(+ required=False, help_text="Agent scope target. Required when scope_type is agent."+ )+++class GatewayPoliciesUpsertSerializer(GatewayPoliciesQuerySerializer):+ policies = serializers.ListField(+ child=ToolPolicyEntrySerializer(),+ max_length=MAX_TOOL_POLICIES_PER_REQUEST,+ help_text=f"Per-tool states to upsert for the scope. At most {MAX_TOOL_POLICIES_PER_REQUEST:,} entries per request.",+ )+++@extend_schema_field(OpenApiTypes.OBJECT)+class MCPToolInputSchemaField(serializers.JSONField):+ pass+++class ResolvedToolPolicySerializer(serializers.Serializer):+ """One tool with its effective policy for the requested scope."""++ tool_name = serializers.CharField(help_text="Tool name as exposed by the upstream server.")+ description = serializers.CharField(allow_blank=True, help_text="Tool description from the upstream server.")+ input_schema = MCPToolInputSchemaField(help_text="JSON Schema describing the tool's input arguments.")+ policy_state = serializers.ChoiceField(choices=APPROVAL_STATES, help_text="Effective state for the scope.")+ team_state = serializers.ChoiceField(+ choices=APPROVAL_STATES,+ allow_null=True,+ help_text="What the team-level chain (row or preset) yields, ignoring the scope. Null when the team imposes nothing.",+ )+ locked = serializers.BooleanField(+ help_text="True when no state is editable for this scope (a rule match or a Blocked team ceiling)."+ )+ decided_by = serializers.ChoiceField(+ choices=RESOLVED_DECIDED_BY_CHOICES, help_text="Which policy layer decided the state."+ )+ rule_name = serializers.CharField(allow_blank=True, help_text="Matching org rule name, when decided_by is rule.")+ rule_description = serializers.CharField(+ allow_blank=True, help_text="Matching org rule description, when decided_by is rule."+ )+++# many=False keeps spectacular from wrapping this in an array for the `list` action,+# which returns the team's single config object rather than a collection.+@extend_schema_serializer(many=False)+class TeamMCPGatewayConfigSerializer(serializers.ModelSerializer):+ is_admin = serializers.SerializerMethodField(+ help_text="Whether the requesting user can administer the gateway (org admin or explicit project admin)."+ )++ class Meta:+ model = TeamMCPGatewayConfig+ fields = [+ "allow_custom_servers",+ "allow_member_agent_access",+ "default_servers_enabled",+ "member_default_preset",+ "agent_default_preset",+ "is_admin",+ ]+ extra_kwargs = {+ "allow_custom_servers": {+ "help_text": "Whether non-admin members may register custom MCP servers with the gateway."+ },+ "default_servers_enabled": {+ "help_text": (+ "Whether servers with no gateway registration — including catalog templates published later — "+ "are enabled for the team. A registered server's own toggle always wins."+ )+ },+ "allow_member_agent_access": {+ "help_text": (+ "Whether non-admin members may share their available MCP connections with agents "+ "and manage agent tool policies."+ )+ },+ "member_default_preset": {+ "help_text": "Baseline preset for members. Empty until an admin applies one from Team settings."+ },+ "agent_default_preset": {+ "help_text": "Baseline preset deriving default policies for tools an agent has no explicit row for."+ },+ }++ @extend_schema_field(serializers.BooleanField())+ def get_is_admin(self, obj: TeamMCPGatewayConfig) -> bool:+ return bool(self.context.get("is_admin"))+++class GatewayConfigUpdateSerializer(serializers.Serializer):+ allow_custom_servers = serializers.BooleanField(+ required=False, help_text="Whether non-admin members may register custom MCP servers."+ )+ allow_member_agent_access = serializers.BooleanField(+ required=False,+ help_text=(+ "Whether non-admin members may share their available MCP connections with agents "+ "and manage agent tool policies."+ ),+ )+ default_servers_enabled = serializers.BooleanField(+ required=False,+ help_text=(+ "Whether servers with no gateway registration — including catalog templates published later — "+ "are enabled for the team. A registered server's own toggle always wins."+ ),+ )+ member_default_preset = serializers.ChoiceField(+ choices=POLICY_PRESET_CHOICES, required=False, allow_blank=True, help_text="Baseline preset for members."+ )+ agent_default_preset = serializers.ChoiceField(+ choices=POLICY_PRESET_CHOICES, required=False, allow_blank=True, help_text="Baseline preset for agents."+ )+++class SetAllServersEnabledSerializer(serializers.Serializer):+ enabled = serializers.BooleanField(+ help_text=(+ "True enables every MCP server for the team; false disables them all. Applies to every registered "+ "server and becomes the default for untouched and future catalog servers."+ )+ )+++class ApplyPresetSerializer(serializers.Serializer):+ audience = serializers.ChoiceField(+ choices=["members", "agents"], help_text="Which audience's baseline to overwrite."+ )+ preset = serializers.ChoiceField(choices=POLICY_PRESET_CHOICES, help_text="Preset to apply.")+++class MCPServiceAccountServerSerializer(serializers.Serializer):+ """A credential-safe summary of a server configured for an agent."""++ id = serializers.UUIDField(help_text="Gateway server granted to the agent.")+ name = serializers.CharField(help_text="Server display name.")+ description = serializers.CharField(help_text="Server description.")+ icon_key = serializers.CharField(help_text="Deprecated brand icon key. Empty for custom servers.")+ icon_domain = serializers.CharField(help_text="Brand domain. Empty for custom servers.")+ connection_state = serializers.ChoiceField(+ choices=AGENT_SERVER_CONNECTION_STATE_CHOICES,+ help_text="Whether the credential delegated to the agent is ready to use.",+ )+++class MCPServiceAccountSerializer(serializers.ModelSerializer):+ agent_key = serializers.SerializerMethodField(help_text="Stable PostHog agent identifier.")+ server_ids = serializers.SerializerMethodField(help_text="Gateway servers configured for this agent.")+ servers = serializers.SerializerMethodField(+ help_text="Credential-safe summaries of the gateway servers configured for this agent."+ )++ class Meta:+ model = MCPServiceAccount+ fields = [+ "id",+ "name",+ "description",+ "handle",+ "agent_key",+ "status",+ "server_ids",+ "servers",+ "last_active_at",+ "created_at",+ "updated_at",+ ]+ read_only_fields = [+ "id",+ "name",+ "description",+ "handle",+ "agent_key",+ "status",+ "last_active_at",+ "created_at",+ "updated_at",+ ]+ extra_kwargs = {+ "handle": {"help_text": "Stable internal identity handle for this PostHog agent."},+ "status": {"help_text": "active, or paused (all MCP access off)."},+ "last_active_at": {"help_text": "When the agent last made a call through the gateway."},+ }++ @extend_schema_field(serializers.ChoiceField(choices=["support", "scout"]))+ def get_agent_key(self, obj: MCPServiceAccount) -> str:+ spec = get_built_in_agent_spec(obj)+ return spec.key if spec is not None else ""++ @extend_schema_field(serializers.ListField(child=serializers.UUIDField()))+ def get_server_ids(self, obj: MCPServiceAccount) -> list[str]:+ return [str(access.gateway_server_id) for access in obj.server_access.all()]++ @extend_schema_field(MCPServiceAccountServerSerializer(many=True))+ def get_servers(self, obj: MCPServiceAccount) -> list[dict[str, Any]]:+ servers: list[dict[str, Any]] = []+ for access in obj.server_access.all():+ server = access.gateway_server+ installation = installation_for_agent_access(access)+ connection_state = "ready"+ if installation is None:+ connection_state = "missing_credential"+ elif not installation.is_enabled:+ connection_state = "disabled"+ elif _installation_needs_reauth(installation):+ connection_state = "needs_reauth"+ elif _installation_pending_oauth(installation):+ connection_state = "pending_oauth"++ servers.append(+ {+ "id": server.id,+ "name": server.name,+ "description": server.description,+ "icon_key": server.template.icon_key if server.template else "",+ "icon_domain": server.template.icon_domain if server.template else "",+ "connection_state": connection_state,+ }+ )+ return servers+++class MCPServiceAccountUpdateSerializer(serializers.ModelSerializer):+ class Meta:+ model = MCPServiceAccount+ fields = ["status"]+ extra_kwargs = {+ "status": {"required": False, "help_text": "active, or paused (all MCP access off)."},+ }+++class ServiceAccountAccessUpdateSerializer(serializers.Serializer):+ gateway_server_id = serializers.UUIDField(help_text="Gateway server to grant or revoke.")+ enabled = serializers.BooleanField(help_text="True grants access, false revokes it.")+ policies = serializers.ListField(+ child=ToolPolicyEntrySerializer(),+ max_length=MAX_TOOL_POLICIES_PER_REQUEST,+ required=False,+ default=list,+ help_text=(+ "Optional agent-scope tool policies to set alongside the grant. "+ f"At most {MAX_TOOL_POLICIES_PER_REQUEST:,} entries per request."+ ),+ )+++class MCPOrgRuleSerializer(serializers.ModelSerializer):+ class Meta:+ model = MCPOrgRule+ fields = [+ "id",+ "name",+ "description",+ "applies_to",+ "effect",+ "tool_pattern",+ "enabled",+ "created_at",+ "updated_at",+ ]+ read_only_fields = ["id", "created_at", "updated_at"]+ extra_kwargs = {+ "name": {"help_text": "Short rule name shown wherever the rule locks a tool."},+ "description": {"required": False, "help_text": "Why this guardrail exists."},+ "applies_to": {"required": False, "help_text": "Audience the rule constrains."},+ "effect": {"required": False, "help_text": "State the rule forces on matching tools."},+ "tool_pattern": {+ "required": False,+ "help_text": "fnmatch pattern against tool names. Blank matches destructive tools heuristically.",+ },+ "enabled": {"required": False, "help_text": "Disabled rules are kept but not evaluated."},+ }+++class AuditActorServiceAccountSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="Service account id.")+ name = serializers.CharField(help_text="Agent display name.")+ handle = serializers.CharField(help_text="Agent identity handle.")+++class MCPAuditEventSerializer(serializers.ModelSerializer):+ actor_user = UserBasicSerializer(read_only=True, allow_null=True, help_text="Member who made the call, if any.")+ actor_service_account = serializers.SerializerMethodField(+ help_text="Agent that made the call, if any. Null for member calls."+ )++ class Meta:+ model = MCPAuditEvent+ fields = [+ "id",+ "created_at",+ "server_name",+ "tool_name",+ "decision",+ "actor_user",+ "actor_service_account",+ "actor_label",+ ]+ read_only_fields = ["id", "created_at", "server_name", "tool_name", "decision", "actor_label"]+ extra_kwargs = {+ "server_name": {"help_text": "Gateway server name at call time (denormalized)."},+ "tool_name": {"help_text": "Tool that was called."},+ "decision": {"help_text": "How the gateway decided the call."},+ "actor_label": {"help_text": "Denormalized actor label (email or handle) that survives deletion."},+ }++ @extend_schema_field(AuditActorServiceAccountSerializer(allow_null=True))+ def get_actor_service_account(self, obj: MCPAuditEvent) -> dict[str, Any] | None:+ account = obj.actor_service_account+ if account is None:+ return None+ return {"id": account.id, "name": account.name, "handle": account.handle}+++class AuditQuerySerializer(serializers.Serializer):+ quick_filter = serializers.ChoiceField(+ choices=AUDIT_QUICK_FILTER_CHOICES,+ required=False,+ default="all",+ help_text="all, agents (agent calls only), approvals (approved or pending), or blocked.",+ )+ actor_service_account_id = serializers.UUIDField(+ required=False, help_text="Only calls made by this service account."+ )+++class AuditCountsSerializer(serializers.Serializer):+ all = serializers.IntegerField(help_text="Every audited tool call.")+ agents = serializers.IntegerField(help_text="Calls made by service accounts.")+ approvals = serializers.IntegerField(help_text="Calls that were approved or are awaiting approval.")+ blocked = serializers.IntegerField(help_text="Calls the gateway blocked.")+++class GatewayMemberSummarySerializer(serializers.Serializer):+ """One team member's gateway posture (admin overview)."""++ user = UserBasicSerializer(help_text="The member.")+ is_org_admin = serializers.BooleanField(help_text="Whether the member is an organization admin or owner.")+ connected_server_ids = serializers.ListField(+ child=serializers.UUIDField(), help_text="Gateway servers the member has a personal connection to."+ )+ revoked_server_ids = serializers.ListField(+ child=serializers.UUIDField(), help_text="Gateway servers an admin turned off for this member."+ )+++class MemberAccessUpdateSerializer(serializers.Serializer):+ gateway_server_id = serializers.UUIDField(help_text="Gateway server to toggle for the member.")+ enabled = serializers.BooleanField(help_text="False turns the server off for the member; true restores it.")+++# ---------------------------------------------------------------------------+# Viewsets+# ---------------------------------------------------------------------------+++class MCPGatewayServerViewSet(+ GatewayAdminMixin,+ TeamAndOrgViewSetMixin,+ mixins.ListModelMixin,+ mixins.RetrieveModelMixin,+ mixins.UpdateModelMixin,+ mixins.DestroyModelMixin,+ viewsets.GenericViewSet,+):+ """The team's gateway server registry. The registry is sparse: rows appear+ through the install/share/OAuth-start flows in views.py, or when an admin+ toggles an untouched catalog template here (`set_template_enabled`).+ Servers with no row follow the team config's `default_servers_enabled`."""++ scope_object = "project"+ scope_object_read_actions = ["list", "retrieve", "tools"]+ scope_object_write_actions = ["update", "partial_update", "destroy", "policies", "set_template_enabled"]+ serializer_class = MCPGatewayServerSerializer+ permission_classes = [IsAuthenticated, DenyMCPBuiltInAgentOAuth]+ # Fail-closed manager raises if `.all()` runs at import; the real per-request+ # scoping happens in safely_get_queryset.+ queryset = MCPGatewayServer.objects.unscoped()++ def safely_get_queryset(self, queryset: QuerySet[MCPGatewayServer]) -> QuerySet[MCPGatewayServer]:+ servers = MCPGatewayServer.objects.for_team(self.team_id)+ if not self._is_project_admin():+ user_id = cast(int, self.request.user.id)+ servers = servers.filter(is_team_enabled=True).exclude(member_revocations__user_id=user_id)+ return (+ servers.select_related("template", "created_by")+ .prefetch_related(+ Prefetch(+ "installations",+ queryset=MCPServerInstallation.objects.select_related("user").order_by("created_at"),+ ),+ Prefetch(+ "agent_access",+ queryset=MCPServiceAccountServerAccess.objects.unscoped().select_related(+ "service_account", "granted_by"+ ),+ ),+ "member_revocations",+ )+ .annotate(+ tool_count_annotated=Count(+ "installations__tools__tool_name",+ filter=Q(installations__tools__removed_at__isnull=True),+ distinct=True,+ )+ )+ .order_by("name")+ )++ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:+ if self.action == "policies" and isinstance(request.successful_authenticator, SessionAuthentication):+ return ["project:read"]+ return None++ def get_serializer_class(self) -> type[serializers.BaseSerializer]:+ if self.action in ("update", "partial_update"):+ return MCPGatewayServerUpdateSerializer+ return MCPGatewayServerSerializer++ def get_serializer_context(self) -> dict[str, Any]:+ context = super().get_serializer_context()+ if not getattr(self, "swagger_fake_view", False):+ context["is_admin"] = self._is_project_admin()+ return context++ def perform_update(self, serializer: serializers.BaseSerializer) -> None:+ self._require_project_admin()+ server = cast(MCPGatewayServer, serializer.save())+ report_user_action(+ cast(User, self.request.user),+ "mcp_gateway server updated",+ properties={+ "server_name": server.name,+ "is_team_enabled": server.is_team_enabled,+ },+ team=self.team,+ )++ def perform_destroy(self, instance: MCPGatewayServer) -> None:+ """Disconnect every member (their credentials are disabled) and drop the+ registration. Nothing recreates rows, so the server durably returns to+ the catalog default posture (`default_servers_enabled`)."""+ self._require_project_admin()+ properties = {"server_name": instance.name, "server_url": instance.url}+ with transaction.atomic():+ locked_instance = MCPGatewayServer.objects.for_team(self.team_id).select_for_update().get(pk=instance.pk)+ MCPServerInstallation.objects.filter(team_id=self.team_id, gateway_server=locked_instance).update(+ is_enabled=False, updated_at=timezone.now()+ )+ locked_instance.delete()++ report_user_action(+ cast(User, self.request.user),+ "mcp_gateway server removed",+ properties=properties,+ team=self.team,+ )++ def _resolve_scope(self, data: dict) -> tuple[str, User | None, MCPServiceAccount | None]:+ scope_type = data.get("scope_type", "team")+ if scope_type == "member":+ raw_user_id = data.get("scope_user_id")+ user_id = int(raw_user_id) if raw_user_id is not None else cast(User, self.request.user).id+ membership_exists = OrganizationMembership.objects.filter(+ organization_id=self.team.organization_id, user_id=user_id+ ).exists()+ if not membership_exists:+ raise NotFound("User is not a member of this organization.")+ return "member", User.objects.get(id=user_id), None+ if scope_type == "agent":+ account_id = data.get("scope_service_account_id")+ if not account_id:+ raise serializers.ValidationError("scope_service_account_id is required for agent scope.")+ try:+ account = MCPServiceAccount.objects.for_team(self.team_id).get(id=account_id)+ except MCPServiceAccount.DoesNotExist:+ raise NotFound("Service account not found.")+ return "agent", None, account+ return "team", None, None++ def _require_scope_permission(self, scope_type: str, scope_user: User | None, write: bool = False) -> None:+ """Members may view team defaults and manage their own member scope;+ agent scopes follow the team's agent-access setting."""+ if self._is_project_admin():+ return+ if scope_type == "member" and scope_user is not None and scope_user.id == self.request.user.id:+ return+ if scope_type == "agent" and self._can_manage_agent_access():+ return+ if scope_type == "team" and not write:+ return+ raise PermissionDenied("Only project admins can manage this scope.")++ def _member_installation(self, server: MCPGatewayServer, scope_user: User) -> MCPServerInstallation | None:+ """The credential this member calls the server through.++ Mirrors ``get_your_connection``: a personal row wins over a legacy+ team-shared row the same user happens to own.+ """+ own = [installation for installation in server.installations.all() if installation.user_id == scope_user.id]+ own.sort(key=lambda installation: installation.scope != "personal")+ return own[0] if own else None++ def _resolve_policies_for_scope(+ self,+ server: MCPGatewayServer,+ scope_type: str,+ scope_user: User | None,+ scope_account: MCPServiceAccount | None,+ ) -> list[dict[str, Any]]:+ if scope_type == "agent" and scope_account is not None:+ caller = GatewayCaller(kind="agent", service_account_id=str(scope_account.id))+ else:+ # Team scope resolves as a member with no scope rows of their own.+ caller = GatewayCaller(kind="member", user_id=scope_user.id if scope_user else None)+ # The member's own preference lives in the legacy per-installation+ # column, which PolicyContext only loads when given the installation.+ # The proxy and the installation tools endpoint both pass it, so+ # without it this view would show a laxer state than gets enforced.+ # Team scope resolves the ceiling itself and agent scope has no legacy+ # rows, so neither needs one.+ installation = self._member_installation(server, scope_user) if scope_type == "member" and scope_user else None+ context = PolicyContext(+ team_id=self.team_id,+ caller=caller,+ gateway_server=server,+ installation=installation,+ )++ tools: list[tuple[str, str, dict[str, Any], dict[str, Any]]] = []+ seen: set[str] = set()+ tool_rows = _ordered_gateway_tool_rows(server).values_list(+ "tool_name", "description", "input_schema", "annotations"+ )+ for tool_name, description, input_schema, annotations in tool_rows:+ if tool_name in seen:+ continue+ seen.add(tool_name)+ tools.append((tool_name, description or "", input_schema or {}, annotations or {}))++ rows: list[dict[str, Any]] = []+ for tool_name, description, input_schema, annotations in tools:+ resolved = (+ context.resolve_team(tool_name, annotations)+ if scope_type == "team"+ else context.resolve(tool_name, annotations)+ )+ rows.append(+ {+ "tool_name": tool_name,+ "description": description,+ "input_schema": input_schema,+ "policy_state": resolved.state,+ "team_state": resolved.team_state,+ "locked": resolved.locked or (scope_type != "team" and resolved.team_state == "do_not_use"),+ "decided_by": resolved.decided_by,+ "rule_name": resolved.rule_name,+ "rule_description": resolved.rule_description,+ }+ )+ return rows++ @validated_request(+ request_serializer=SetTemplateEnabledSerializer,+ responses={200: OpenApiResponse(response=MCPGatewayServerSerializer)},+ )+ @action(detail=False, methods=["post"], url_path="set_template_enabled")+ def set_template_enabled(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Enable or disable a catalog template for the team (admin-only),+ materializing its gateway registration on the first toggle."""+ self._require_project_admin()+ data = request.validated_data+ try:+ template = MCPServerTemplate.objects.get(id=data["template_id"], is_active=True)+ except MCPServerTemplate.DoesNotExist:+ raise NotFound("Template not found.")++ enabled = data["enabled"]+ server, created = MCPGatewayServer.objects.for_team(self.team_id).get_or_create(+ url=template.url,+ defaults={+ "team_id": self.team_id,+ "name": template.name,+ "description": template.description,+ "category": template.category,+ "template": template,+ "created_by": cast(User, request.user),+ "is_team_enabled": enabled,+ },+ )+ if not created:+ update_fields: list[str] = []+ if server.is_team_enabled != enabled:+ server.is_team_enabled = enabled+ update_fields.append("is_team_enabled")+ if server.template_id is None:+ server.template = template+ update_fields.append("template")+ if update_fields:+ server.save(update_fields=[*update_fields, "updated_at"])++ report_user_action(+ cast(User, request.user),+ "mcp_gateway server toggled",+ properties={"server_url": server.url, "enabled": enabled},+ team=self.team,+ )+ return Response(MCPGatewayServerSerializer(server, context=self.get_serializer_context()).data)++ @validated_request(+ query_serializer=GatewayPoliciesQuerySerializer,+ responses={200: OpenApiResponse(response=ResolvedToolPolicySerializer(many=True))},+ )+ @action(detail=True, methods=["get"], url_path="tools")+ def tools(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Tool catalog with the resolved policy for a scope."""+ server = self.get_object()+ scope_type, scope_user, scope_account = self._resolve_scope(request.validated_query_data)+ self._require_scope_permission(scope_type, scope_user)+ rows = self._resolve_policies_for_scope(server, scope_type, scope_user, scope_account)+ return Response({"count": len(rows), "next": None, "previous": None, "results": rows})++ @validated_request(+ request_serializer=GatewayPoliciesUpsertSerializer,+ responses={200: OpenApiResponse(response=ResolvedToolPolicySerializer(many=True))},+ )+ @action(detail=True, methods=["post"], url_path="policies")+ def policies(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Upsert per-tool states for a scope, returning the re-resolved catalog."""+ server = self.get_object()+ data = request.validated_data+ scope_type, scope_user, scope_account = self._resolve_scope(data)+ self._require_scope_permission(scope_type, scope_user, write=True)++ if scope_type != "team":+ if scope_type == "agent" and scope_account is not None:+ caller = GatewayCaller(kind="agent", service_account_id=str(scope_account.id))+ else:+ caller = GatewayCaller(kind="member", user_id=scope_user.id if scope_user else None)+ raise_for_policies_above_team_ceiling(+ policy_entries_above_team_ceiling(+ team_id=self.team_id,+ server=server,+ caller=caller,+ entries=data["policies"],+ )+ )++ with transaction.atomic():+ for entry in data["policies"]:+ MCPToolPolicy.objects.update_or_create(+ team_id=self.team_id,+ gateway_server=server,+ tool_name=entry["tool_name"],+ scope_type=scope_type,+ scope_user=scope_user,+ scope_service_account=scope_account,+ defaults={"state": entry["policy_state"]},+ )++ report_user_action(+ cast(User, request.user),+ "mcp_gateway tool policies updated",+ properties={+ "server_name": server.name,+ "scope_type": scope_type,+ "tool_count": len(data["policies"]),+ },+ team=self.team,+ )++ rows = self._resolve_policies_for_scope(server, scope_type, scope_user, scope_account)+ return Response({"count": len(rows), "next": None, "previous": None, "results": rows})+++class MCPServiceAccountViewSet(+ GatewayAdminMixin,+ TeamAndOrgViewSetMixin,+ mixins.ListModelMixin,+ mixins.RetrieveModelMixin,+ mixins.UpdateModelMixin,+ viewsets.GenericViewSet,+):+ """PostHog's built-in agents and their MCP access grants.++ The catalog is fixed. Projects can pause an agent's MCP access and grant or+ revoke servers, but cannot create, rename, rotate, or delete agents.+ """++ scope_object = "project"+ scope_object_read_actions = ["list", "retrieve"]+ scope_object_write_actions = ["update", "partial_update", "access"]+ serializer_class = MCPServiceAccountSerializer+ permission_classes = [IsAuthenticated, DenyMCPBuiltInAgentOAuth]+ queryset = MCPServiceAccount.objects.unscoped()++ @cached_property+ def _synced_built_in_accounts(self) -> list[MCPServiceAccount]:+ return sync_built_in_agents(self.team)++ def _server_access_prefetch(self) -> Prefetch:+ return Prefetch(+ "server_access",+ queryset=MCPServiceAccountServerAccess.objects.for_team(self.team_id)+ .select_related("gateway_server__template", "installation")+ .order_by("gateway_server__name"),+ )++ def safely_get_queryset(self, queryset: QuerySet[MCPServiceAccount]) -> QuerySet[MCPServiceAccount]:+ catalog_order = Case(+ *(When(id=account.id, then=position) for position, account in enumerate(self._synced_built_in_accounts)),+ output_field=IntegerField(),+ )+ accounts_queryset = MCPServiceAccount.objects.for_team(self.team_id).filter(handle__in=built_in_agent_handles())+ if self.action in ("list", "retrieve"):+ accounts_queryset = accounts_queryset.prefetch_related(self._server_access_prefetch())+ return accounts_queryset.order_by(catalog_order)++ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:+ if self.action == "access" and isinstance(request.successful_authenticator, SessionAuthentication):+ return ["project:read"]+ return None++ def get_serializer_class(self) -> type[serializers.BaseSerializer]:+ if self.action in ("update", "partial_update"):+ return MCPServiceAccountUpdateSerializer+ return MCPServiceAccountSerializer++ def perform_update(self, serializer: serializers.BaseSerializer) -> None:+ self._require_project_admin()+ account = cast(MCPServiceAccount, serializer.save())+ report_user_action(+ cast(User, self.request.user),+ "mcp_gateway agent updated",+ properties={"handle": account.handle, "status": account.status},+ team=self.team,+ )++ @validated_request(+ request_serializer=ServiceAccountAccessUpdateSerializer,+ responses={200: OpenApiResponse(response=MCPServiceAccountSerializer)},+ )+ @action(detail=True, methods=["post"], url_path="access")+ def access(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Grant or revoke this agent's access to one gateway server."""+ self._require_agent_access_manager()+ account = self.get_object()+ data = request.validated_data+ try:+ server = MCPGatewayServer.objects.for_team(self.team_id).get(id=data["gateway_server_id"])+ except MCPGatewayServer.DoesNotExist:+ raise NotFound("Gateway server not found.")++ if data["enabled"]:+ policies = data.get("policies") or []+ raise_for_policies_above_team_ceiling(+ policy_entries_above_team_ceiling(+ team_id=self.team_id,+ server=server,+ caller=GatewayCaller(kind="agent", service_account_id=str(account.id)),+ entries=policies,+ )+ )+ installation = installation_for_agent_grant(self.team_id, server, cast(User, request.user).id)+ if installation is None:+ raise serializers.ValidationError(+ {"gateway_server_id": "Connect this server before sharing access with an agent."}+ )+ with transaction.atomic():+ MCPServiceAccountServerAccess.objects.for_team(self.team_id).update_or_create(+ service_account=account,+ gateway_server=server,+ defaults={+ "team_id": self.team_id,+ "installation": installation,+ "granted_by": cast(User, request.user),+ },+ )+ for entry in policies:+ MCPToolPolicy.objects.update_or_create(+ team_id=self.team_id,+ gateway_server=server,+ tool_name=entry["tool_name"],+ scope_type="agent",+ scope_user=None,+ scope_service_account=account,+ defaults={"state": entry["policy_state"]},+ )+ else:+ with transaction.atomic():+ MCPServiceAccountServerAccess.objects.for_team(self.team_id).filter(+ service_account=account,+ gateway_server=server,+ ).delete()+ MCPToolPolicy.objects.for_team(self.team_id).filter(+ gateway_server=server, scope_type="agent", scope_service_account=account+ ).delete()++ report_user_action(+ cast(User, request.user),+ "mcp_gateway agent access changed",+ properties={"handle": account.handle, "server_name": server.name, "enabled": data["enabled"]},+ team=self.team,+ )+ prefetch_related_objects([account], self._server_access_prefetch())+ return Response(MCPServiceAccountSerializer(account, context=self.get_serializer_context()).data)+++class MCPOrgRuleViewSet(GatewayAdminMixin, TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+ """Team guardrails evaluated before any scope policy."""++ scope_object = "project"+ scope_object_read_actions = ["list", "retrieve"]+ scope_object_write_actions = ["create", "update", "partial_update", "destroy"]+ serializer_class = MCPOrgRuleSerializer+ permission_classes = [IsAuthenticated, DenyMCPBuiltInAgentOAuth]+ queryset = MCPOrgRule.objects.unscoped()++ def safely_get_queryset(self, queryset: QuerySet[MCPOrgRule]) -> QuerySet[MCPOrgRule]:+ return MCPOrgRule.objects.for_team(self.team_id).order_by("name")++ def perform_create(self, serializer: serializers.BaseSerializer) -> None:+ self._require_project_admin()+ rule = cast(MCPOrgRule, serializer.save(team_id=self.team_id, created_by=cast(User, self.request.user)))+ report_user_action(+ cast(User, self.request.user),+ "mcp_gateway rule created",+ properties={"rule_name": rule.name, "effect": rule.effect},+ team=self.team,+ )++ def perform_update(self, serializer: serializers.BaseSerializer) -> None:+ self._require_project_admin()+ rule = cast(MCPOrgRule, serializer.save())+ report_user_action(+ cast(User, self.request.user),+ "mcp_gateway rule updated",+ properties={"rule_name": rule.name, "enabled": rule.enabled},+ team=self.team,+ )++ def perform_destroy(self, instance: MCPOrgRule) -> None:+ self._require_project_admin()+ report_user_action(+ cast(User, self.request.user),+ "mcp_gateway rule deleted",+ properties={"rule_name": instance.name},+ team=self.team,+ )+ instance.delete()+++class MCPAuditEventViewSet(+ GatewayAdminMixin,+ TeamAndOrgViewSetMixin,+ mixins.RetrieveModelMixin,+ viewsets.GenericViewSet,+):+ """Read-only trail of proxied tool calls. Admin-only — it exposes what+ every member and agent has been doing."""++ scope_object = "project"+ scope_object_read_actions = ["list", "retrieve", "counts"]+ serializer_class = MCPAuditEventSerializer+ permission_classes = [IsAuthenticated, DenyMCPBuiltInAgentOAuth]+ queryset = MCPAuditEvent.objects.unscoped()++ def safely_get_queryset(self, queryset: QuerySet[MCPAuditEvent]) -> QuerySet[MCPAuditEvent]:+ return (+ MCPAuditEvent.objects.for_team(self.team_id)+ .select_related("actor_user", "actor_service_account")+ .order_by("-created_at")+ )++ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ self._require_project_admin()+ return super().retrieve(request, *args, **kwargs)++ @validated_request(+ query_serializer=AuditQuerySerializer,+ responses={200: OpenApiResponse(response=MCPAuditEventSerializer(many=True))},+ )+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ self._require_project_admin()+ query = request.validated_query_data+ queryset = self.filter_queryset(self.get_queryset())++ quick_filter = query.get("quick_filter", "all")+ if quick_filter == "agents":+ queryset = queryset.filter(actor_service_account__isnull=False)+ elif quick_filter == "approvals":+ queryset = queryset.filter(decision__in=["approved", "pending"])+ elif quick_filter == "blocked":+ queryset = queryset.filter(decision="blocked")++ if account_id := query.get("actor_service_account_id"):+ queryset = queryset.filter(actor_service_account_id=account_id)++ page = self.paginate_queryset(queryset)+ serializer = self.get_serializer(page, many=True)+ return self.get_paginated_response(serializer.data)++ @extend_schema(responses={200: OpenApiResponse(response=AuditCountsSerializer)})+ @action(detail=False, methods=["get"], url_path="counts")+ def counts(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Totals backing the quick-filter chips."""+ self._require_project_admin()+ return Response(+ MCPAuditEvent.objects.for_team(self.team_id).aggregate(+ all=Count("id"),+ agents=Count("id", filter=Q(actor_service_account__isnull=False)),+ approvals=Count("id", filter=Q(decision__in=["approved", "pending"])),+ blocked=Count("id", filter=Q(decision="blocked")),+ )+ )+++class MCPGatewayConfigViewSet(GatewayAdminMixin, TeamAndOrgViewSetMixin, viewsets.ViewSet):+ """Team-wide gateway settings. `list` returns the single config object."""++ scope_object = "project"+ scope_object_read_actions = ["list"]+ scope_object_write_actions = ["update_settings", "apply_preset", "set_all_servers_enabled"]+ permission_classes = [IsAuthenticated, DenyMCPBuiltInAgentOAuth]+ pagination_class = None+ # Plain ViewSet: spectacular needs a fallback serializer for schema generation.+ serializer_class = TeamMCPGatewayConfigSerializer++ def _get_or_create_config(self) -> TeamMCPGatewayConfig:+ config, _ = TeamMCPGatewayConfig.objects.get_or_create(team_id=self.team_id)+ return config++ def _serialize_config(self, config: TeamMCPGatewayConfig) -> dict[str, Any]:+ return TeamMCPGatewayConfigSerializer(config, context={"is_admin": self._is_project_admin()}).data++ @extend_schema(responses={200: OpenApiResponse(response=TeamMCPGatewayConfigSerializer)})+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """The team's gateway settings, plus whether the caller can administer them."""+ return Response(self._serialize_config(self._get_or_create_config()))++ @validated_request(+ request_serializer=GatewayConfigUpdateSerializer,+ responses={200: OpenApiResponse(response=TeamMCPGatewayConfigSerializer)},+ )+ @action(detail=False, methods=["post"], url_path="update_settings")+ def update_settings(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Update team gateway settings (admin-only)."""+ self._require_project_admin()+ config = self._get_or_create_config()+ data = request.validated_data+ for field, value in data.items():+ setattr(config, field, value)+ config.save()+ if "allow_custom_servers" in data:+ report_user_action(+ request.user,+ "mcp_gateway custom servers toggled",+ properties={"allow_custom_servers": data["allow_custom_servers"]},+ team=self.team,+ )+ if "allow_member_agent_access" in data:+ report_user_action(+ request.user,+ "mcp_gateway member agent access toggled",+ properties={"allow_member_agent_access": data["allow_member_agent_access"]},+ team=self.team,+ )+ return Response(self._serialize_config(config))++ @validated_request(+ request_serializer=SetAllServersEnabledSerializer,+ responses={200: OpenApiResponse(response=TeamMCPGatewayConfigSerializer)},+ )+ @action(detail=False, methods=["post"], url_path="set_all_servers_enabled")+ def set_all_servers_enabled(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Enable or disable every MCP server for the team (admin-only): flips+ each registered server and the default for untouched catalog servers,+ so newly published templates follow the same posture."""+ self._require_project_admin()+ enabled = request.validated_data["enabled"]+ with transaction.atomic():+ config = self._get_or_create_config()+ config.default_servers_enabled = enabled+ config.save(update_fields=["default_servers_enabled", "updated_at"])+ MCPGatewayServer.objects.for_team(self.team_id).update(is_team_enabled=enabled, updated_at=timezone.now())+ report_user_action(+ request.user,+ "mcp_gateway all servers toggled",+ properties={"enabled": enabled},+ team=self.team,+ )+ return Response(self._serialize_config(config))++ @validated_request(+ request_serializer=ApplyPresetSerializer,+ responses={200: OpenApiResponse(response=TeamMCPGatewayConfigSerializer)},+ )+ @action(detail=False, methods=["post"], url_path="apply_preset")+ def apply_preset(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Set the policy baseline for members or agents (admin-only)."""+ self._require_project_admin()+ data = request.validated_data+ audience = data["audience"]+ preset = data["preset"]+ config = self._get_or_create_config()+ if audience == "members":+ config.member_default_preset = preset+ else:+ config.agent_default_preset = preset+ config.save(update_fields=["member_default_preset", "agent_default_preset", "updated_at"])+ report_user_action(+ request.user,+ "mcp_gateway preset applied",+ properties={"audience": audience, "preset": preset},+ team=self.team,+ )+ return Response(self._serialize_config(config))+++class MCPGatewayMemberViewSet(GatewayAdminMixin, TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """Admin overview of each member's gateway posture, plus the per-member+ server kill switch."""++ scope_object = "project"+ scope_object_read_actions = ["list", "retrieve"]+ scope_object_write_actions = ["set_access"]+ permission_classes = [IsAuthenticated, DenyMCPBuiltInAgentOAuth]+ serializer_class = GatewayMemberSummarySerializer++ def _memberships(self) -> QuerySet[OrganizationMembership]:+ return (+ OrganizationMembership.objects.filter(organization_id=self.team.organization_id)+ .select_related("user")+ .order_by("user__first_name", "user__email")+ )++ def _member_rows(self, memberships: Sequence[OrganizationMembership]) -> list[dict[str, Any]]:+ user_ids = [membership.user_id for membership in memberships]+ connected: dict[int, list[str]] = {}+ for user_id, server_id in MCPServerInstallation.objects.filter(+ team_id=self.team_id,+ user_id__in=user_ids,+ scope="personal",+ gateway_server__isnull=False,+ ).values_list("user_id", "gateway_server_id"):+ connected.setdefault(user_id, []).append(str(server_id))++ revoked: dict[int, list[str]] = {}+ for user_id, server_id in (+ MCPMemberServerRevocation.objects.for_team(self.team_id)+ .filter(user_id__in=user_ids)+ .values_list("user_id", "gateway_server_id")+ ):+ revoked.setdefault(user_id, []).append(str(server_id))++ rows: list[dict[str, Any]] = []+ for membership in memberships:+ rows.append(+ {+ "user": UserBasicSerializer(membership.user).data,+ "is_org_admin": membership.level >= OrganizationMembership.Level.ADMIN,+ "connected_server_ids": connected.get(membership.user_id, []),+ "revoked_server_ids": revoked.get(membership.user_id, []),+ }+ )+ return rows++ @extend_schema(responses={200: GatewayMemberSummarySerializer(many=True)})+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ self._require_project_admin()+ memberships = self.paginate_queryset(self._memberships())+ if memberships is None:+ return Response(self._member_rows(list(self._memberships())))+ return self.get_paginated_response(self._member_rows(memberships))++ @extend_schema(responses={200: GatewayMemberSummarySerializer})+ def retrieve(self, request: Request, pk: str | None = None, *args: Any, **kwargs: Any) -> Response:+ self._require_project_admin()+ try:+ user_id = int(pk or "")+ membership = self._memberships().get(user_id=user_id)+ except (OrganizationMembership.DoesNotExist, ValueError):+ raise NotFound("Member not found.")+ return Response(self._member_rows([membership])[0])++ @validated_request(+ request_serializer=MemberAccessUpdateSerializer,+ responses={204: None},+ )+ @action(detail=True, methods=["post"], url_path="set_access")+ def set_access(self, request: Request, pk: str | None = None, *args: Any, **kwargs: Any) -> Response:+ """Turn one gateway server off (or back on) for one member."""+ self._require_project_admin()+ try:+ user_id = int(pk or "")+ except ValueError:+ raise NotFound("Member not found.")+ if not OrganizationMembership.objects.filter(+ organization_id=self.team.organization_id, user_id=user_id+ ).exists():+ raise NotFound("Member not found.")++ data = request.validated_data+ try:+ server = MCPGatewayServer.objects.for_team(self.team_id).get(id=data["gateway_server_id"])+ except MCPGatewayServer.DoesNotExist:+ raise NotFound("Gateway server not found.")++ if data["enabled"]:+ MCPMemberServerRevocation.objects.filter(gateway_server=server, user_id=user_id).delete()+ else:+ MCPMemberServerRevocation.objects.for_team(self.team_id).get_or_create(+ gateway_server=server,+ user_id=user_id,+ defaults={"team_id": self.team_id, "revoked_by": cast(User, request.user)},+ )++ report_user_action(+ cast(User, request.user),+ "mcp_gateway member access changed",+ properties={"server_name": server.name, "enabled": data["enabled"]},+ team=self.team,+ )+ return Response(status=status.HTTP_204_NO_CONTENT)diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.pyindex 3b317c47626a..a5537fae9029 100644--- a/products/mcp_store/backend/presentation/views.py+++ b/products/mcp_store/backend/presentation/views.py@@ -16,7 +16,7 @@ from django.http.response import HttpResponseBasefrom django.utils import timezoneimport structlog-from drf_spectacular.utils import OpenApiResponse, extend_schema+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_fieldfrom rest_framework import mixins, renderers, serializers, status, viewsetsfrom rest_framework.authentication import SessionAuthenticationfrom rest_framework.decorators import action@@ -31,6 +31,8 @@ from posthog.cdp.services.icons import CDPIconsServicefrom posthog.cloud_utils import is_dev_modefrom posthog.event_usage import report_user_actionfrom posthog.models import User+from posthog.models.scoping.manager import resolve_effective_team_id+from posthog.permissions import DenyMCPBuiltInAgentOAuthfrom posthog.rate_limit import (MCPOAuthBurstThrottle,MCPOAuthRedirectBurstThrottle,@@ -41,7 +43,21 @@ from posthog.rate_limit import ()from posthog.security.url_validation import is_url_allowed-from ..models import MCPOAuthState, MCPServerInstallation, MCPServerInstallationTool, MCPServerTemplate, SensitiveConfig+from ..agents import sync_built_in_agents+from ..gateway import link_installation_to_gateway, members_can_manage_agent_access, server_disabled_reason+from ..models import (+ APPROVAL_STATES,+ MCPMemberServerRevocation,+ MCPOAuthState,+ MCPServerInstallation,+ MCPServerInstallationTool,+ MCPServerTemplate,+ MCPServiceAccount,+ MCPServiceAccountServerAccess,+ MCPToolPolicy,+ SensitiveConfig,+ TeamMCPGatewayConfig,+)from ..oauth import (DcrClientRegistration,OAuthAuthorizeURLError,@@ -54,6 +70,7 @@ from ..oauth import (requested_oauth_scopes,select_token_endpoint_auth_method,)+from ..policy import GatewayCaller, PolicyContext, ResolvedPolicy, is_policy_state_allowedfrom ..proxy import proxy_mcp_request, validate_installation_authfrom ..tasks import sync_installation_tools_taskfrom ..tools import ToolsFetchError, sync_installation_tools@@ -99,6 +116,7 @@ def _create_oauth_state(posthog_code_callback_url: str = "",pkce_verifier: str = "",template: MCPServerTemplate | None = None,+ web_return_path: str = "",) -> MCPOAuthState:# Ties the state to the initiating user. Only that user can consume it; prevents OAuth CSRF/session fixation.return MCPOAuthState.objects.create(@@ -108,12 +126,18 @@ def _create_oauth_state(template=template,install_source=install_source,posthog_code_callback_url=posthog_code_callback_url,+ web_return_path=web_return_path,pkce_verifier=pkce_verifier,expires_at=timezone.now() + timedelta(seconds=OAUTH_STATE_MAX_AGE_SECONDS),created_by=cast(User, request.user),)+def _is_valid_web_return_path(path: str) -> bool:+ """Same-app relative path only — rejects protocol-relative and absolute URLs (open-redirect guard)."""+ return path.startswith("/") and not path.startswith("//") and ":" not in path.split("?")[0]++def _is_https(url: str) -> bool:"""Check that a URL uses HTTPS. Returns True in dev mode to allow http://localhost."""if is_dev_mode():@@ -197,7 +221,7 @@ class MCPServerViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, viewsets.Gscope_object = "project"serializer_class = MCPServerTemplateSerializer- permission_classes = [IsAuthenticated]+ permission_classes = [IsAuthenticated, DenyMCPBuiltInAgentOAuth]@validated_request(responses={200: OpenApiResponse(response=MCPServerTemplateSerializer(many=True))},@@ -340,7 +364,29 @@ class InstallCustomSerializer(serializers.Serializer):choices=["personal", "shared"],required=False,default="personal",- help_text="'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).",+ help_text="'personal' is per-user; 'shared' makes the credential available to project members. Agent access is granted separately.",+ )+ # Team-wide install options remain admin-only. Agent grants follow the+ # team's allow_member_agent_access setting.+ team_enabled = serializers.BooleanField(+ required=False,+ default=True,+ help_text="Whether the server starts enabled for the whole team. Non-default values are admin-only.",+ )+ agent_ids = serializers.ListField(+ child=serializers.UUIDField(),+ required=False,+ default=list,+ help_text=(+ "Service accounts to share the server with at install time. "+ "Available to members when team settings allow member-managed agent access."+ ),+ )+ return_path = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ help_text="In-app path to land back on after the OAuth round-trip. Must be a same-app relative path.",)def validate_url(self, value: str) -> str:@@ -364,7 +410,29 @@ class InstallTemplateSerializer(serializers.Serializer):choices=["personal", "shared"],required=False,default="personal",- help_text="'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).",+ help_text="'personal' is per-user; 'shared' makes the credential available to project members. Agent access is granted separately.",+ )+ # Team-wide install options remain admin-only. Agent grants follow the+ # team's allow_member_agent_access setting.+ team_enabled = serializers.BooleanField(+ required=False,+ default=True,+ help_text="Whether the server starts enabled for the whole team. Non-default values are admin-only.",+ )+ agent_ids = serializers.ListField(+ child=serializers.UUIDField(),+ required=False,+ default=list,+ help_text=(+ "Service accounts to share the server with at install time. "+ "Available to members when team settings allow member-managed agent access."+ ),+ )+ return_path = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ help_text="In-app path to land back on after the OAuth round-trip. Must be a same-app relative path.",)def validate_posthog_code_callback_url(self, value: str) -> str:@@ -379,6 +447,12 @@ class AuthorizeQuerySerializer(serializers.Serializer):installation_id = serializers.UUIDField(required=False)install_source = serializers.ChoiceField(choices=["posthog", "posthog-code"], required=False, default="posthog")posthog_code_callback_url = serializers.CharField(required=False, allow_blank=True, default="")+ return_path = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ help_text="In-app path to land back on after the OAuth round-trip. Must be a same-app relative path.",+ )def validate(self, attrs: dict) -> dict:if bool(attrs.get("template_id")) == bool(attrs.get("installation_id")):@@ -397,6 +471,15 @@ class OAuthRedirectResponseSerializer(serializers.Serializer):class MCPServerInstallationToolSerializer(serializers.ModelSerializer):+ approval_state = serializers.SerializerMethodField(help_text="Effective state after applying the team ceiling.")+ team_state = serializers.SerializerMethodField(+ help_text="Team-admin ceiling for this tool. Null when the team imposes no ceiling."+ )+ locked = serializers.SerializerMethodField(+ help_text="True when a rule or Blocked team ceiling leaves no editable state."+ )+ decided_by = serializers.SerializerMethodField(help_text="Policy layer that decided the effective state.")+class Meta:model = MCPServerInstallationToolfields = [@@ -406,6 +489,9 @@ class MCPServerInstallationToolSerializer(serializers.ModelSerializer):"description","input_schema","approval_state",+ "team_state",+ "locked",+ "decided_by","last_seen_at","removed_at","created_at",@@ -423,6 +509,34 @@ class MCPServerInstallationToolSerializer(serializers.ModelSerializer):"updated_at",]+ def _resolved_policy(self, obj: MCPServerInstallationTool) -> ResolvedPolicy | None:+ context = cast(PolicyContext | None, self.context.get("policy_context"))+ if context is None:+ return None+ return context.resolve(obj.tool_name, obj.annotations)++ @extend_schema_field(serializers.ChoiceField(choices=APPROVAL_STATES))+ def get_approval_state(self, obj: MCPServerInstallationTool) -> str:+ resolved = self._resolved_policy(obj)+ return resolved.state if resolved is not None else obj.approval_state++ @extend_schema_field(serializers.ChoiceField(choices=APPROVAL_STATES, allow_null=True))+ def get_team_state(self, obj: MCPServerInstallationTool) -> str | None:+ resolved = self._resolved_policy(obj)+ return resolved.team_state if resolved is not None else None++ @extend_schema_field(serializers.BooleanField())+ def get_locked(self, obj: MCPServerInstallationTool) -> bool:+ resolved = self._resolved_policy(obj)+ if resolved is None:+ return False+ return resolved.locked or resolved.team_state == "do_not_use"++ @extend_schema_field(serializers.CharField())+ def get_decided_by(self, obj: MCPServerInstallationTool) -> str:+ resolved = self._resolved_policy(obj)+ return resolved.decided_by if resolved is not None else "legacy"+class ToolApprovalUpdateSerializer(serializers.Serializer):approval_state = serializers.ChoiceField(choices=["approved", "needs_approval", "do_not_use"])@@ -447,7 +561,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetqueryset = MCPServerInstallation.objects.all()serializer_class = MCPServerInstallationSerializerlookup_field = "id"- permission_classes = [IsAuthenticated]+ permission_classes = [IsAuthenticated, DenyMCPBuiltInAgentOAuth]# Installations are user-scoped or shared (safely_get_queryset returns both),# so write actions don't need project admin access.@@ -480,11 +594,25 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetteam_id=self.team_id,).filter(Q(scope="shared") | Q(user=self.request.user))- .select_related("template")+ .select_related("template", "gateway_server").annotate(tool_count_annotated=Count("tools", filter=Q(tools__removed_at__isnull=True))).order_by("-created_at"))+ def _tool_serializer_context(self, installation: MCPServerInstallation) -> dict[str, Any]:+ if not installation.gateway_server_id:+ return {}+ gateway_server = installation.gateway_server+ if gateway_server is None:+ return {}+ policy_context = PolicyContext(+ team_id=self.team_id,+ caller=GatewayCaller(kind="member", user_id=cast(User, self.request.user).id),+ gateway_server=gateway_server,+ installation=installation,+ )+ return {"policy_context": policy_context}+def check_object_permissions(self, request: Request, obj: Any) -> None:# Enforce owner-only mutation of shared rows centrally so every action in# _OWNER_ONLY_ACTIONS is guarded via get_object() — a new owner-only action@@ -516,6 +644,25 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetif installation.scope == "shared" and installation.user_id != self.request.user.id:raise PermissionDenied("Only the credential owner can modify a shared server.")+ def _reset_recycled_installation(self, installation: MCPServerInstallation, *, auth_type: str = "") -> None:+ """Freshen a row that get_or_create matched instead of creating.++ Installs are keyed on (team, url, scope), so removing a server and+ adding it back reuses the original row. Removing a gateway server+ disables its installations rather than deleting them, so without this+ the re-added server comes back switched off. An explicit install means+ the user wants it on.+ """+ update_fields = []+ if auth_type and installation.auth_type != auth_type:+ installation.auth_type = auth_type+ update_fields.append("auth_type")+ if not installation.is_enabled:+ installation.is_enabled = True+ update_fields.append("is_enabled")+ if update_fields:+ installation.save(update_fields=[*update_fields, "updated_at"])+def _is_project_admin(self) -> bool:"""True for organization admins/owners, or users explicitly grantedadmin on this project via access controls.@@ -532,17 +679,104 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetdef _require_admin_for_shared_scope(self, scope: str) -> None:"""Creating a team-wide shared MCP server is admin-only.- A shared install exposes the installer's credential to every project- member and all autonomous agents, and any action taken through it is- attributed to the credential owner (e.g. a member could write to Linear- as the owner). Gating creation to admins keeps a regular member from- standing up a shared server that others act through.+ A shared install exposes the installer's credential to project members,+ and admins may separately grant it to built-in agents. Any action taken+ through it is attributed to the credential owner (e.g. a member could+ write to Linear as the owner). Gating creation to admins keeps a regular+ member from standing up a shared server that others act through."""if scope != "shared":returnif not self._is_project_admin():raise PermissionDenied("Only project admins can create shared MCP servers.")+ def _require_server_enabled_for_team(self, url: str, allow_admin_posture_override: bool = False) -> None:+ """Connect-time gate: refuse installs and OAuth starts against a server+ the team disabled (explicitly, or via the catalog default posture). The+ proxy enforces the same rule at call time; this keeps members from even+ connecting or handing tokens to a disabled server.++ Custom-server installs pass allow_admin_posture_override: an admin+ adding a custom server under a disabled default posture is itself the+ allowlisting act (the install materializes an explicitly enabled row),+ and there is no per-URL pre-enable action they could use instead. An+ explicit row disable stays authoritative for everyone."""+ reason = server_disabled_reason(self.team_id, url)+ if reason is None:+ return+ if allow_admin_posture_override and reason == "default_disabled" and self._is_project_admin():+ return+ report_user_action(+ cast(User, self.request.user),+ "mcp_store install blocked",+ properties={"server_url": url, "reason": reason},+ team=self.team,+ )+ raise PermissionDenied("This server is disabled for your team.")++ def _require_custom_servers_allowed(self) -> None:+ """Admins can always add custom servers; members only while the team+ gateway setting allows it."""+ if self._is_project_admin():+ return+ config = TeamMCPGatewayConfig.objects.filter(team_id=self.team_id).first()+ if config is not None and not config.allow_custom_servers:+ raise PermissionDenied("Custom MCP servers are limited to project admins in this project.")++ @staticmethod+ def _wants_team_gateway_options(data: dict) -> bool:+ return not data.get("team_enabled", True)++ def _validate_gateway_options(self, data: dict) -> None:+ """Validate team-level options and agent grants before creating rows."""+ if self._wants_team_gateway_options(data) and not self._is_project_admin():+ raise PermissionDenied("Only project admins can set team availability.")++ agent_ids = set(data.get("agent_ids") or [])+ if not agent_ids:+ return+ if not self._is_project_admin() and not members_can_manage_agent_access(self.team_id):+ raise PermissionDenied("Only project admins can share servers with agents in this project.")++ built_in_agent_ids = {account.id for account in sync_built_in_agents(self.team)}+ if not agent_ids.issubset(built_in_agent_ids):+ raise serializers.ValidationError({"agent_ids": "Select only the PostHog agents listed for this project."})++ def _apply_gateway_options(self, installation: MCPServerInstallation, data: dict) -> None:+ """Register the installation with the gateway and apply install-time+ team options (enablement, personal connections, agent shares).++ Called only once the install is persisted for good; `_validate_gateway_options`+ has already gated team options and agent grants.+ """+ agent_ids = set(data.get("agent_ids") or [])+ accounts_by_id = {+ account.id: account for account in MCPServiceAccount.objects.for_team(self.team_id).filter(id__in=agent_ids)+ }+ if agent_ids != set(accounts_by_id):+ raise serializers.ValidationError(+ {"agent_ids": "One or more selected PostHog agents are no longer available. Refresh and try again."}+ )++ server = link_installation_to_gateway(installation, created_by=cast(User, self.request.user))++ if self._wants_team_gateway_options(data):+ team_enabled = data.get("team_enabled", True)+ if server.is_team_enabled != team_enabled:+ server.is_team_enabled = team_enabled+ server.save(update_fields=["is_team_enabled", "updated_at"])++ for account in accounts_by_id.values():+ MCPServiceAccountServerAccess.objects.for_team(self.team_id).update_or_create(+ service_account=account,+ gateway_server=server,+ defaults={+ "team_id": self.team_id,+ "installation": installation,+ "granted_by": cast(User, self.request.user),+ },+ )+def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)@@ -653,8 +887,8 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet"""Escalate a personal installation to a team-wide shared one.Owner-only AND admin-only: sharing exposes the owner's credential to- every project member and all autonomous agents, so it carries the same- gate as creating a shared install outright.+ project members, so it carries the same gate as creating a shared+ install outright. Agents require separate explicit grants."""installation = self.get_object()if installation.scope != "personal":@@ -684,6 +918,8 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetstatus=status.HTTP_409_CONFLICT,)+ link_installation_to_gateway(installation, created_by=cast(User, request.user))+report_user_action(request.user,"mcp_store server shared",@@ -766,11 +1002,35 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetuser_id=request.user.id,)+ gateway_server = installation.gateway_server+ if gateway_server is not None:+ if not gateway_server.is_team_enabled:+ return HttpResponse(+ '{"error": "Server is disabled for this team"}',+ content_type="application/json",+ status=403,+ )+ if MCPMemberServerRevocation.objects.filter(+ gateway_server=gateway_server, user=cast(User, request.user)+ ).exists():+ return HttpResponse(+ '{"error": "Your access to this server has been turned off by an admin"}',+ content_type="application/json",+ status=403,+ )+ok, error_response = validate_installation_auth(installation)if not ok and error_response is not None:return error_response- return proxy_mcp_request(request, installation)+ caller = GatewayCaller(kind="member", user_id=request.user.id)+ return proxy_mcp_request(+ request,+ installation,+ caller=caller,+ gateway_server=gateway_server,+ actor_label=cast(User, request.user).email or "",+ )@validated_request(InstallTemplateSerializer,@@ -792,11 +1052,13 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetposthog_code_callback_url = data.get("posthog_code_callback_url", "")scope = data.get("scope", "personal")self._require_admin_for_shared_scope(scope)+ self._validate_gateway_options(data)try:template = MCPServerTemplate.objects.get(id=template_id, is_active=True)except MCPServerTemplate.DoesNotExist:return Response({"detail": "Template not found"}, status=status.HTTP_404_NOT_FOUND)+ self._require_server_enabled_for_team(template.url)lookup = {"team_id": self.team_id, "url": template.url, "scope": scope}if scope == "personal":@@ -814,6 +1076,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet# A pre-existing shared row may belong to another member; block hijacking its creds.if not created:self._assert_shared_mutation_allowed(installation)+ self._reset_recycled_installation(installation)# Re-link in case a previous install pointed elsewhere (e.g. post-migration reconnect).if installation.template_id != template.id:installation.template = template@@ -830,6 +1093,8 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetinstallation.sensitive_configuration = {"api_key": api_key}installation.save(update_fields=["sensitive_configuration", "updated_at"])+ self._apply_gateway_options(installation, data)+# Tool sync runs in the background so a slow upstream can't block the install request.transaction.on_commit(lambda: sync_installation_tools_task.delay(str(installation.id)))@@ -933,6 +1198,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetposthog_code_callback_url,pkce_verifier=pkce.code_verifier,template=template,+ web_return_path=data.get("return_path", ""),)try:@@ -953,6 +1219,8 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetinstallation.delete()return Response({"detail": "Could not build OAuth authorize URL"}, status=status.HTTP_400_BAD_REQUEST)+ self._apply_gateway_options(installation, data)+report_user_action(request.user,"mcp_store oauth started",@@ -990,6 +1258,8 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetuser_client_secret = (data.get("client_secret") or "").strip()scope = data.get("scope", "personal")self._require_admin_for_shared_scope(scope)+ self._require_custom_servers_allowed()+ self._validate_gateway_options(data)install_source = data.get("install_source", "posthog")posthog_code_callback_url = data.get("posthog_code_callback_url", "")@@ -1005,8 +1275,10 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetinstall_source=install_source,posthog_code_callback_url=posthog_code_callback_url,scope=scope,+ gateway_options=data,)if auth_type == "api_key":+ self._require_server_enabled_for_team(url, allow_admin_posture_override=True)sensitive_config: SensitiveConfig = {}if api_key:sensitive_config["api_key"] = api_key@@ -1028,6 +1300,8 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetif not created:return Response({"detail": "This server URL is already installed."}, status=status.HTTP_400_BAD_REQUEST)+ self._apply_gateway_options(installation, data)+transaction.on_commit(lambda: sync_installation_tools_task.delay(str(installation.id)))logger.info(@@ -1067,6 +1341,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetinstall_source: str = "posthog",posthog_code_callback_url: str = "",scope: str = "personal",+ gateway_options: dict | None = None,) -> HttpResponse:"""Kick off an OAuth flow for a user-added MCP server.@@ -1077,6 +1352,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet"""if blocked_response := self._validate_mcp_url_or_error_response(mcp_url):return blocked_response+ self._require_server_enabled_for_team(mcp_url, allow_admin_posture_override=True)redirect_uri = _get_oauth_redirect_uri()@@ -1096,9 +1372,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet# from swapping its DCR client / clearing its tokens via reinstall.if not created:self._assert_shared_mutation_allowed(installation)- if not created and installation.auth_type != "oauth":- installation.auth_type = "oauth"- installation.save(update_fields=["auth_type", "updated_at"])+ self._reset_recycled_installation(installation, auth_type="oauth")try:metadata = discover_oauth_metadata(mcp_url)@@ -1195,6 +1469,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetposthog_code_callback_url,pkce_verifier=pkce.code_verifier,template=None,+ web_return_path=(gateway_options or {}).get("return_path", ""),)try:@@ -1210,6 +1485,8 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetinstallation.delete()return Response({"detail": "Authorization endpoint must use HTTPS"}, status=status.HTTP_400_BAD_REQUEST)+ self._apply_gateway_options(installation, gateway_options or {})+return Response({"redirect_url": authorize_url}, status=status.HTTP_200_OK)@validated_request(query_serializer=AuthorizeQuerySerializer)@@ -1229,6 +1506,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetquery = request.validated_query_datainstall_source = query.get("install_source", "posthog")posthog_code_callback_url = query.get("posthog_code_callback_url", "")+ web_return_path = query.get("return_path", "")if posthog_code_callback_url and not _is_valid_posthog_code_callback_url(posthog_code_callback_url):return Response({"detail": "Invalid callback URL"}, status=status.HTTP_400_BAD_REQUEST)@@ -1239,6 +1517,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSettemplate_id=template_id,install_source=install_source,posthog_code_callback_url=posthog_code_callback_url,+ web_return_path=web_return_path,)installation_id = query.get("installation_id")@@ -1247,6 +1526,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetinstallation_id=installation_id,install_source=install_source,posthog_code_callback_url=posthog_code_callback_url,+ web_return_path=web_return_path,)def _authorize_for_template(@@ -1257,11 +1537,13 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetinstall_source: str,posthog_code_callback_url: str,installation: MCPServerInstallation | None = None,+ web_return_path: str = "",) -> HttpResponse:try:template = MCPServerTemplate.objects.get(id=template_id, is_active=True)except MCPServerTemplate.DoesNotExist:return Response({"detail": "Template not found"}, status=status.HTTP_404_NOT_FOUND)+ self._require_server_enabled_for_team(template.url)if installation is None:# Direct marketplace (re)connect keyed on template — always the@@ -1329,6 +1611,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetposthog_code_callback_url,pkce_verifier=pkce.code_verifier,template=template,+ web_return_path=web_return_path,)try:authorize_url = self._build_authorize_url_from_metadata(@@ -1346,6 +1629,8 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet)return Response({"detail": "Could not build OAuth authorize URL"}, status=status.HTTP_400_BAD_REQUEST)+ link_installation_to_gateway(installation, created_by=cast(User, request.user))+report_user_action(request.user,"mcp_store oauth started",@@ -1366,6 +1651,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetinstallation_id: Any,install_source: str,posthog_code_callback_url: str,+ web_return_path: str = "",) -> HttpResponse:"""Reconnect an existing installation — typically for a custom (non-template) OAuth install.@@ -1387,10 +1673,12 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetinstall_source=install_source,posthog_code_callback_url=posthog_code_callback_url,installation=installation,+ web_return_path=web_return_path,)if blocked_response := self._validate_mcp_url_or_error_response(installation.url):return blocked_response+ self._require_server_enabled_for_team(installation.url)metadata = installation.oauth_metadata or {}sensitive = installation.sensitive_configuration or {}@@ -1412,6 +1700,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetposthog_code_callback_url,pkce_verifier=pkce.code_verifier,template=None,+ web_return_path=web_return_path,)try:authorize_url = self._build_authorize_url_from_metadata(@@ -1424,6 +1713,8 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetexcept OAuthAuthorizeURLError:return Response({"detail": "Authorization endpoint must use HTTPS"}, status=status.HTTP_400_BAD_REQUEST)+ link_installation_to_gateway(installation, created_by=cast(User, request.user))+return _oauth_authorize_response(authorize_url, install_source)@extend_schema(responses={200: OpenApiResponse(response=MCPServerInstallationToolSerializer(many=True))})@@ -1434,7 +1725,11 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetqueryset = installation.tools.order_by("tool_name")if not include_removed:queryset = queryset.filter(removed_at__isnull=True)- serializer = MCPServerInstallationToolSerializer(queryset, many=True)+ serializer = MCPServerInstallationToolSerializer(+ queryset,+ many=True,+ context=self._tool_serializer_context(installation),+ )return Response({"results": serializer.data})@validated_request(@@ -1454,9 +1749,27 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetreturn Response({"detail": "Tool not found"}, status=status.HTTP_404_NOT_FOUND)new_state = request.validated_data["approval_state"]+ if installation.gateway_server_id:+ policy_context = PolicyContext(+ team_id=self.team_id,+ caller=GatewayCaller(kind="member", user_id=cast(User, request.user).id),+ gateway_server=installation.gateway_server,+ installation=installation,+ )+ team_state = policy_context.team_state(tool.tool_name, tool.annotations)+ if not is_policy_state_allowed(new_state, team_state):+ raise serializers.ValidationError(+ {+ "approval_state": (+ "A team admin set a stricter ceiling for this tool. "+ "Choose the ceiling or a more restrictive state."+ )+ }+ )if tool.approval_state != new_state:tool.approval_state = new_statetool.save(update_fields=["approval_state", "updated_at"])+ self._mirror_tool_approval_to_gateway(installation, tool.tool_name, new_state)report_user_action(request.user,"mcp_store tool approval changed",@@ -1469,7 +1782,30 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetteam=self.team,)- return Response(MCPServerInstallationToolSerializer(tool).data)+ return Response(+ MCPServerInstallationToolSerializer(+ tool,+ context=self._tool_serializer_context(installation),+ ).data+ )++ def _mirror_tool_approval_to_gateway(+ self, installation: MCPServerInstallation, tool_name: str, new_state: str+ ) -> None:+ """Keep the gateway policy row in sync with the legacy per-installation+ approval toggle: an installation's states are the owner's member scope."""+ if not installation.gateway_server_id:+ return+ policy_team_id = resolve_effective_team_id(installation.team_id)+ MCPToolPolicy.objects.for_team(policy_team_id, canonical=True).update_or_create(+ team_id=policy_team_id,+ gateway_server_id=installation.gateway_server_id,+ tool_name=tool_name,+ scope_type="member",+ scope_user=installation.user,+ scope_service_account=None,+ defaults={"state": new_state},+ )@extend_schema(responses={200: OpenApiResponse(response=MCPServerInstallationToolSerializer(many=True))})@action(@@ -1496,7 +1832,11 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet)queryset = installation.tools.filter(removed_at__isnull=True).order_by("tool_name")- serializer = MCPServerInstallationToolSerializer(queryset, many=True)+ serializer = MCPServerInstallationToolSerializer(+ queryset,+ many=True,+ context=self._tool_serializer_context(installation),+ )return Response({"results": serializer.data})@@ -1533,6 +1873,7 @@ class MCPOAuthRedirectViewSet(viewsets.ViewSet):installation = oauth_state.installationinstall_source = oauth_state.install_sourceposthog_code_callback_url = oauth_state.posthog_code_callback_url+ web_return_path = oauth_state.web_return_pathtemplate = oauth_state.templateserver_name = template.name if template else _installation_name(installation)server_identifier = str(template.id) if template else str(installation.id)@@ -1554,7 +1895,11 @@ class MCPOAuthRedirectViewSet(viewsets.ViewSet):team=installation.team,)return self._build_oauth_redirect(- install_source, installation, error=error_msg, posthog_code_callback_url=posthog_code_callback_url+ install_source,+ installation,+ error=error_msg,+ posthog_code_callback_url=posthog_code_callback_url,+ web_return_path=web_return_path,)code = request.query_params.get("code")@@ -1569,6 +1914,7 @@ class MCPOAuthRedirectViewSet(viewsets.ViewSet):installation,error="Missing authorization code",posthog_code_callback_url=posthog_code_callback_url,+ web_return_path=web_return_path,)try:@@ -1596,6 +1942,7 @@ class MCPOAuthRedirectViewSet(viewsets.ViewSet):installation,error="token_exchange_failed",posthog_code_callback_url=posthog_code_callback_url,+ web_return_path=web_return_path,)# Tool sync runs in the background so a slow upstream can't block the OAuth redirect.@@ -1624,17 +1971,33 @@ class MCPOAuthRedirectViewSet(viewsets.ViewSet):)return self._build_oauth_redirect(- install_source, installation, posthog_code_callback_url=posthog_code_callback_url+ install_source,+ installation,+ posthog_code_callback_url=posthog_code_callback_url,+ web_return_path=web_return_path,)def _consume_oauth_state(self, request: Request, state_token: str) -> MCPOAuthState | None:# Only allow the user who created the state to redeem it. Prevents CSRF or session fixation.- if not request.user or not request.user.is_authenticated:+ dev_mode = is_dev_mode()+ is_authenticated = bool(request.user and request.user.is_authenticated)+ if not is_authenticated and not dev_mode:logger.warning("OAuth redirect: unauthenticated callback")return Nonetoken_hash = _hash_oauth_state_token(state_token)now = timezone.now()+ state_filters: dict[str, Any] = {+ "token_hash": token_hash,+ "consumed_at__isnull": True,+ }+ if dev_mode:+ ownership_filter = Q(install_source="posthog-code", created_by__isnull=False)+ if is_authenticated:+ ownership_filter |= Q(created_by=request.user)+ else:+ ownership_filter = Q(created_by=request.user)+with transaction.atomic():# Lock only the oauth_state row. `template` is nullable, so the# select_related join is a LEFT OUTER JOIN — Postgres rejects@@ -1642,13 +2005,23 @@ class MCPOAuthRedirectViewSet(viewsets.ViewSet):oauth_state = (MCPOAuthState.objects.select_for_update(of=("self",)).select_related("installation", "template")- .filter(token_hash=token_hash, consumed_at__isnull=True, created_by=request.user)+ .filter(ownership_filter, **state_filters).first())if not oauth_state or oauth_state.expires_at <= now:logger.warning("OAuth redirect: state missing, expired, or owned by a different user")return None+ request_user_id = getattr(request.user, "id", None)+ if (+ dev_mode+ and oauth_state.install_source == "posthog-code"+ and oauth_state.created_by_id != request_user_id+ ):+ # Code's dev callback crosses into the system browser, which+ # does not share the API client's local PostHog session.+ logger.info("OAuth redirect: allowing PostHog Code callback without user binding in dev mode")+oauth_state.consumed_at = nowoauth_state.save(update_fields=["consumed_at", "updated_at"])return oauth_state@@ -1694,18 +2067,20 @@ class MCPOAuthRedirectViewSet(viewsets.ViewSet):team_id: int | None = None,error: str | None = None,posthog_code_callback_url: str = "",+ web_return_path: str = "",) -> HttpResponse:if install_source == "posthog-code" and posthog_code_callback_url:params = {"status": "error", "error": error} if error else {"status": "success"}separator = "&" if "?" in posthog_code_callback_url else "?"redirect_url = f"{posthog_code_callback_url}{separator}{urlencode(params)}"- elif error:- fallback_team_id = installation.team_id if installation else team_id- redirect_url = f"{settings.SITE_URL}/project/{fallback_team_id}/settings/mcp-servers?oauth_error=true"else:- redirect_url = (- f"{settings.SITE_URL}/project/{installation.team_id}/settings/mcp-servers?oauth_complete=true"- )+ result_param = "oauth_error=true" if error else "oauth_complete=true"+ if web_return_path and _is_valid_web_return_path(web_return_path):+ separator = "&" if "?" in web_return_path else "?"+ redirect_url = f"{settings.SITE_URL}{web_return_path}{separator}{result_param}"+ else:+ fallback_team_id = installation.team_id if installation else team_id+ redirect_url = f"{settings.SITE_URL}/project/{fallback_team_id}/settings/mcp-servers?{result_param}"response = HttpResponse(status=302)response["Location"] = redirect_urldiff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.pyindex 31a1c676c1f4..1d37e1411912 100644--- a/products/mcp_store/backend/proxy.py+++ b/products/mcp_store/backend/proxy.py@@ -5,6 +5,7 @@ from urllib.parse import urljoin, urlparsefrom django.http import HttpResponse, StreamingHttpResponsefrom django.http.response import HttpResponseBase+from django.utils import timezoneimport httpximport structlog@@ -15,8 +16,9 @@ from posthog.settings import SERVER_GATEWAY_INTERFACEfrom ee.hogai.utils.asgi import SyncIterableToAsync-from .models import MCPServerInstallation, MCPServerInstallationTool+from .models import MCPAuditEvent, MCPGatewayServer, MCPServerInstallation, MCPServerInstallationToolfrom .oauth import TokenRefreshError, is_token_expiring, refresh_installation_token+from .policy import GatewayCaller, PolicyContextlogger = structlog.get_logger(__name__)@@ -207,13 +209,36 @@ def _is_tools_call(item: Any) -> bool:return isinstance(item, dict) and item.get("method") == "tools/call"+def _gateway_decision(policy_context: PolicyContext, tool: MCPServerInstallationTool) -> tuple[str, bool]:+ """Map a resolved policy onto an audit decision and whether to block.++ approved via the caller's own scope (or a legacy per-installation approval)+ reads as a human having approved it; approved via team baseline/rule is+ auto. needs_approval blocks at the proxy — approval happens in PostHog, not+ inline — and is recorded as pending."""+ resolved = policy_context.resolve(tool.tool_name, tool.annotations)+ if resolved.state == "do_not_use":+ return "blocked", True+ if resolved.state == "needs_approval":+ return "pending", True+ if resolved.decided_by in ("scope", "legacy"):+ return "approved", False+ return "auto", False++def _evaluate_tool_call(- tools_by_name: dict[str, MCPServerInstallationTool], item: dict[str, Any]+ tools_by_name: dict[str, MCPServerInstallationTool],+ item: dict[str, Any],+ policy_context: PolicyContext | None = None,+ audit_entries: list[tuple[str, str]] | None = None,) -> dict[str, Any] | None:"""Check a single JSON-RPC item against the installation's tool approval state.Returns a JSON-RPC error object to send back (short-circuiting the upstream- call), or ``None`` to let the call pass through.+ call), or ``None`` to let the call pass through. With a ``policy_context``,+ the effective state comes from the gateway policy engine instead of the raw+ per-installation approval flag, and each decision is appended to+ ``audit_entries`` as ``(tool_name, decision)``."""if not _is_tools_call(item):return None@@ -240,6 +265,24 @@ def _evaluate_tool_call(f"Tool '{tool_name}' is no longer available on the upstream server",)+ if policy_context is not None:+ decision, blocked = _gateway_decision(policy_context, tool)+ if audit_entries is not None:+ audit_entries.append((tool_name, decision))+ if not blocked:+ return None+ if decision == "pending":+ return _jsonrpc_error(+ request_id,+ TOOL_NEEDS_APPROVAL_CODE,+ f"Tool '{tool_name}' requires approval before it can be called",+ )+ return _jsonrpc_error(+ request_id,+ TOOL_DISABLED_CODE,+ f"Tool '{tool_name}' is blocked by team policy",+ )+if tool.approval_state == "approved":return Noneif tool.approval_state == "needs_approval":@@ -260,6 +303,8 @@ def _evaluate_tool_call(def enforce_tool_approval(installation: MCPServerInstallation,data: dict[str, Any] | list[Any],+ policy_context: PolicyContext | None = None,+ audit_entries: list[tuple[str, str]] | None = None,) -> HttpResponse | None:"""Inspect a JSON-RPC body and short-circuit tools/call that isn't approved.@@ -277,7 +322,7 @@ def enforce_tool_approval(any_blocked = Falseany_passthrough = Falsefor item in data:- blocked = _evaluate_tool_call(tools_by_name, item)+ blocked = _evaluate_tool_call(tools_by_name, item, policy_context, audit_entries)if blocked is not None:responses.append(blocked)any_blocked = True@@ -290,6 +335,8 @@ def enforce_tool_approval(# items like tools/list have no per-item approval concept, so signaling# "approval needed" on them would mislead client retry logic.if any_blocked and any_passthrough:+ if audit_entries is not None:+ audit_entries[:] = [entry for entry in audit_entries if entry[1] in ("blocked", "pending")]return HttpResponse(json.dumps([@@ -312,13 +359,51 @@ def enforce_tool_approval(if not _is_tools_call(data):return Nonetools_by_name = {t.tool_name: t for t in installation.tools.all()}- blocked = _evaluate_tool_call(tools_by_name, data)+ blocked = _evaluate_tool_call(tools_by_name, data, policy_context, audit_entries)if blocked is None:return Nonereturn HttpResponse(json.dumps(blocked), content_type="application/json", status=200)-def proxy_mcp_request(request: Any, installation: MCPServerInstallation) -> HttpResponseBase:+def _write_audit_events(+ installation: MCPServerInstallation,+ gateway_server: MCPGatewayServer,+ caller: GatewayCaller,+ actor_label: str,+ entries: list[tuple[str, str]],+) -> None:+ """Best-effort audit trail — a failed insert must never break the proxy."""+ try:+ MCPAuditEvent.objects.for_team(gateway_server.team_id, canonical=True).bulk_create(+ [+ MCPAuditEvent(+ team_id=gateway_server.team_id,+ gateway_server=gateway_server,+ installation=installation,+ actor_user_id=caller.user_id,+ actor_service_account_id=caller.service_account_id,+ actor_label=actor_label,+ server_name=gateway_server.name,+ tool_name=tool_name,+ decision=decision,+ )+ for tool_name, decision in entries+ ]+ )+ if any(decision in ("auto", "approved") for _, decision in entries):+ MCPServerInstallation.objects.filter(pk=installation.pk).update(last_used_at=timezone.now())+ except Exception:+ logger.exception("Failed to write MCP gateway audit events", installation_id=str(installation.id))+++def proxy_mcp_request(+ request: Any,+ installation: MCPServerInstallation,+ *,+ caller: GatewayCaller | None = None,+ gateway_server: MCPGatewayServer | None = None,+ actor_label: str = "",+) -> HttpResponseBase:allowed, error = is_url_allowed(installation.url)if not allowed:logger.warning("SSRF: blocked proxy request", url=installation.url, reason=error)@@ -337,7 +422,20 @@ def proxy_mcp_request(request: Any, installation: MCPServerInstallation) -> Httpstatus=400,)- if enforcement_response := enforce_tool_approval(installation, data):+ policy_context: PolicyContext | None = None+ audit_entries: list[tuple[str, str]] = []+ if gateway_server is not None and caller is not None:+ policy_context = PolicyContext(+ team_id=installation.team_id,+ caller=caller,+ gateway_server=gateway_server,+ installation=installation,+ )++ enforcement_response = enforce_tool_approval(installation, data, policy_context, audit_entries)+ if gateway_server is not None and caller is not None and audit_entries:+ _write_audit_events(installation, gateway_server, caller, actor_label, audit_entries)+ if enforcement_response:return enforcement_responsebody = json.dumps(data).encode()diff --git a/products/mcp_store/backend/routes.py b/products/mcp_store/backend/routes.pyindex 93b1e707cef8..5eb51d895a45 100644--- a/products/mcp_store/backend/routes.py+++ b/products/mcp_store/backend/routes.py@@ -1,10 +1,15 @@from posthog.api.routing import RouterRegistryimport products.mcp_store.backend.presentation.views as mcp_store+import products.mcp_store.backend.presentation.agent_views as mcp_agent+import products.mcp_store.backend.presentation.gateway_views as mcp_gatewaydef register_routes(routers: RouterRegistry) -> None:routers.root.register(r"mcp_store/oauth_redirect", mcp_store.MCPOAuthRedirectViewSet, "mcp_oauth_redirect")+ # Agent-facing surface: built-in agents authenticate with a short-lived+ # signed token, so this is root-level (the token resolves the team).+ routers.root.register(r"mcp_store/gateway/servers", mcp_agent.MCPGatewayAgentViewSet, "mcp_gateway_agent_servers")routers.projects.register(r"mcp_servers", mcp_store.MCPServerViewSet, "project_mcp_servers", ["team_id"])routers.projects.register(r"mcp_server_installations",@@ -12,3 +17,24 @@ def register_routes(routers: RouterRegistry) -> None:"project_mcp_server_installations",["team_id"],)+ routers.projects.register(+ r"mcp_gateway/servers", mcp_gateway.MCPGatewayServerViewSet, "project_mcp_gateway_servers", ["team_id"]+ )+ routers.projects.register(+ r"mcp_gateway/service_accounts",+ mcp_gateway.MCPServiceAccountViewSet,+ "project_mcp_gateway_service_accounts",+ ["team_id"],+ )+ routers.projects.register(+ r"mcp_gateway/rules", mcp_gateway.MCPOrgRuleViewSet, "project_mcp_gateway_rules", ["team_id"]+ )+ routers.projects.register(+ r"mcp_gateway/audit", mcp_gateway.MCPAuditEventViewSet, "project_mcp_gateway_audit", ["team_id"]+ )+ routers.projects.register(+ r"mcp_gateway/config", mcp_gateway.MCPGatewayConfigViewSet, "project_mcp_gateway_config", ["team_id"]+ )+ routers.projects.register(+ r"mcp_gateway/members", mcp_gateway.MCPGatewayMemberViewSet, "project_mcp_gateway_members", ["team_id"]+ )diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.pyindex a7d29727b934..881b435cf4b8 100644--- a/products/mcp_store/backend/test/test_api.py+++ b/products/mcp_store/backend/test/test_api.py@@ -5,22 +5,57 @@ from urllib.parse import parse_qs, urlparsefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTestfrom unittest.mock import patch+from django.core.cache import cache+from django.core.signing import SignatureExpired+from django.db import connectionfrom django.http import HttpResponse-from django.test import TestCase+from django.test import SimpleTestCase, TestCase+from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom parameterized import parameterized-from rest_framework import status+from rest_framework import serializers, statusfrom rest_framework.test import APIClient+from posthog.models import Organization, Team, Userfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication--from products.mcp_store.backend.models import MCPOAuthState, MCPServerInstallation, MCPServerTemplate+from posthog.models.organization import OrganizationMembership++from products.mcp_store.backend.agents import create_gateway_agent_token, sync_built_in_agents+from products.mcp_store.backend.models import (+ MCPGatewayServer,+ MCPMemberServerRevocation,+ MCPOAuthState,+ MCPServerInstallation,+ MCPServerInstallationTool,+ MCPServerTemplate,+ MCPServiceAccount,+ MCPServiceAccountServerAccess,+ MCPToolPolicy,+ TeamMCPGatewayConfig,+)from products.mcp_store.backend.oauth import DcrClientRegistration+from products.mcp_store.backend.presentation.gateway_views import (+ MAX_TOOL_POLICIES_PER_REQUEST,+ GatewayPoliciesUpsertSerializer,+ ServiceAccountAccessUpdateSerializer,+)from products.mcp_store.backend.presentation.views import _is_valid_posthog_code_callback_urlALLOW_URL = patch("products.mcp_store.backend.presentation.views.is_url_allowed", return_value=(True, None))+POLICY_REQUEST_SERIALIZER_CASES = [+ ("policy_upsert", GatewayPoliciesUpsertSerializer, {}),+ (+ "service_account_access",+ ServiceAccountAccessUpdateSerializer,+ {+ "gateway_server_id": "00000000-0000-0000-0000-000000000001",+ "enabled": True,+ },+ ),+]+class TestIsValidPosthogCodeCallbackUrl(TestCase):@parameterized.expand(@@ -85,6 +120,45 @@ class TestMCPServerTemplateIconKeyNormalization(TestCase):assert template.icon_domain == expected+class TestMCPGatewayRequestSerializerValidation(SimpleTestCase):+ @parameterized.expand(POLICY_REQUEST_SERIALIZER_CASES)+ def test_rejects_tool_names_longer_than_database_field(+ self,+ _name: str,+ serializer_class: type[serializers.Serializer],+ base_data: dict[str, object],+ ) -> None:+ serializer = serializer_class(+ data={+ **base_data,+ "policies": [{"tool_name": "x" * 201, "policy_state": "approved"}],+ }+ )++ assert not serializer.is_valid()+ assert serializer.errors["policies"][0]["tool_name"][0].code == "max_length"++ @parameterized.expand(POLICY_REQUEST_SERIALIZER_CASES)+ def test_rejects_oversized_policy_batches(+ self,+ _name: str,+ serializer_class: type[serializers.Serializer],+ base_data: dict[str, object],+ ) -> None:+ serializer = serializer_class(+ data={+ **base_data,+ "policies": [+ {"tool_name": f"tool_{index}", "policy_state": "approved"}+ for index in range(MAX_TOOL_POLICIES_PER_REQUEST + 1)+ ],+ }+ )++ assert not serializer.is_valid()+ assert serializer.errors["policies"][0].code == "max_length"++class TestMCPServerAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def _create_active_template(self, **overrides) -> MCPServerTemplate:import uuid as _uuid@@ -142,77 +216,1774 @@ class TestMCPServerAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):f"/api/environments/{self.team.id}/mcp_servers/",data={"name": "My Server", "url": "https://mcp.example.com"},)- assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED-- @parameterized.expand(- [- ("path_traversal", "linear.app/../evil"),- ("full_url", "https://evil.example"),- ("query_injection", "linear.app?token=steal"),- ("empty", ""),- ("single_label", "localhost"),- ("overlong_hostname", "a." * 127 + "com"),+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED++ @parameterized.expand(+ [+ ("path_traversal", "linear.app/../evil"),+ ("full_url", "https://evil.example"),+ ("query_injection", "linear.app?token=steal"),+ ("empty", ""),+ ("single_label", "localhost"),+ ("overlong_hostname", "a." * 127 + "com"),+ ]+ )+ def test_icon_rejects_non_hostname_domains(self, _name, bad_domain):+ # The domain param becomes a path segment of img.logo.dev/{domain} — anything but a bare+ # hostname must be rejected or the endpoint can be steered off the logo host.+ response = self.client.get(f"/api/environments/{self.team.id}/mcp_servers/icon/", data={"domain": bad_domain})+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ @parameterized.expand(+ [+ ("no_theme", {"domain": "linear.app"}, None),+ ("dark_theme", {"domain": "linear.app", "theme": "dark"}, "dark"),+ ("unknown_theme_dropped", {"domain": "linear.app", "theme": "neon"}, None),+ ("case_and_fqdn_dot_canonicalized", {"domain": "LINEAR.APP."}, None),+ ]+ )+ def test_icon_proxies_valid_domain(self, _name, params, expected_theme):+ # Both halves of the icon cache key must stay canonical: unknown themes are dropped+ # rather than forwarded, and the domain is lowercased with any FQDN trailing dot+ # stripped so case variants can't mint separate cache entries.+ with patch("products.mcp_store.backend.presentation.views.CDPIconsService") as service:+ service.return_value.get_icon_http_response.return_value = HttpResponse(b"png", content_type="image/png")+ response = self.client.get(f"/api/environments/{self.team.id}/mcp_servers/icon/", data=params)+ assert response.status_code == status.HTTP_200_OK+ service.return_value.get_icon_http_response.assert_called_once_with(+ "linear.app", theme=expected_theme, fallback="404", team_id=self.team.id+ )++ def test_icon_allows_oauth_project_read_scope(self):+ oauth_application = OAuthApplication.objects.create(+ name="MCP icon test",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ organization=self.organization,+ user=self.user,+ )+ access_token = OAuthAccessToken.objects.create(+ user=self.user,+ application=oauth_application,+ token="pha_test_mcp_icon",+ expires=timezone.now() + timedelta(hours=1),+ scope="project:read",+ )+ client = APIClient()++ with patch("products.mcp_store.backend.presentation.views.CDPIconsService") as service:+ service.return_value.get_icon_http_response.return_value = HttpResponse(b"png", content_type="image/png")+ response = client.get(+ f"/api/environments/{self.team.id}/mcp_servers/icon/",+ data={"domain": "linear.app"},+ headers={"authorization": f"Bearer {access_token.token}"},+ )++ assert response.status_code == status.HTTP_200_OK++ def test_unauthenticated_access(self):+ client = APIClient()+ response = client.get(f"/api/environments/{self.team.id}/mcp_servers/")+ assert response.status_code == status.HTTP_401_UNAUTHORIZED+++class TestMCPGatewayServerAPI(APIBaseTest):+ def _api_url(self, suffix: str = "") -> str:+ base = f"/api/projects/{self.team.id}/mcp_gateway/servers/"+ return f"{base}{suffix}" if suffix else base++ def _make_admin(self) -> None:+ membership = self.user.organization_memberships.get(organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()++ def _make_member(self) -> None:+ membership = self.user.organization_memberships.get(organization=self.organization)+ membership.level = OrganizationMembership.Level.MEMBER+ membership.save()++ def _template(self, name: str, *, active: bool = True, auth_type: str = "oauth") -> MCPServerTemplate:+ return MCPServerTemplate.objects.create(+ name=name,+ url=f"https://mcp.{name.lower()}.gateway-test.example.com/mcp",+ description=f"{name} integration",+ auth_type=auth_type,+ category="dev",+ is_active=active,+ )++ def _server_with_personal_tool(+ self, *, approval_state: str = "approved"+ ) -> tuple[MCPGatewayServer, MCPServerInstallation, MCPServerInstallationTool]:+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Ceiling test",+ url="https://mcp.ceiling-test.example.com/mcp",+ created_by=self.user,+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "secret"},+ scope="personal",+ gateway_server=server,+ )+ tool = MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name="create_issue",+ description="Create an issue",+ approval_state=approval_state,+ last_seen_at=timezone.now(),+ )+ return server, installation, tool++ def test_list_returns_only_registered_servers_without_materializing_catalog_templates(self) -> None:+ self._make_admin()+ untouched = self._template("Untouched")+ registered = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Registered",+ url="https://mcp.registered.gateway-test.example.com/mcp",+ created_by=self.user,+ )++ response = self.client.get(self._api_url())++ assert response.status_code == status.HTTP_200_OK+ assert [result["id"] for result in response.json()["results"]] == [str(registered.id)]+ assert not MCPGatewayServer.objects.for_team(self.team.id).filter(url=untouched.url).exists()++ def test_list_exposes_template_auth_type_and_leaves_custom_auth_choice_open(self) -> None:+ self._make_admin()+ template = self._template("API key", auth_type="api_key")+ template_server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name=template.name,+ url=template.url,+ template=template,+ created_by=self.user,+ )+ custom = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Custom",+ url="https://mcp.custom-auth.gateway-test.example.com/mcp",+ created_by=self.user,+ )++ response = self.client.get(self._api_url())++ assert response.status_code == status.HTTP_200_OK+ by_id = {result["id"]: result for result in response.json()["results"]}+ assert by_id[str(template_server.id)]["template_auth_type"] == "api_key"+ assert by_id[str(custom.id)]["template_auth_type"] is None++ def test_disabled_catalog_server_is_hidden_from_members_but_visible_to_admins(self) -> None:+ self._make_admin()+ template = self._template("Visibility")+ disable_response = self.client.post(+ self._api_url("set_template_enabled/"),+ data={"template_id": str(template.id), "enabled": False},+ format="json",+ )+ assert disable_response.status_code == status.HTTP_200_OK+ server_id = disable_response.json()["id"]++ admin_response = self.client.get(self._api_url())+ admin_result = next(result for result in admin_response.json()["results"] if result["id"] == server_id)+ assert admin_result["is_team_enabled"] is False++ self._make_member()+ member_response = self.client.get(self._api_url())+ assert member_response.status_code == status.HTTP_200_OK+ assert server_id not in {result["id"] for result in member_response.json()["results"]}++ def test_set_template_enabled_materializes_a_row_and_is_idempotent(self) -> None:+ self._make_admin()+ template = self._template("Materialize")++ first_response = self.client.post(+ self._api_url("set_template_enabled/"),+ data={"template_id": str(template.id), "enabled": False},+ format="json",+ )+ repeat_response = self.client.post(+ self._api_url("set_template_enabled/"),+ data={"template_id": str(template.id), "enabled": False},+ format="json",+ )++ assert first_response.status_code == status.HTTP_200_OK+ assert repeat_response.status_code == status.HTTP_200_OK+ assert first_response.json()["is_team_enabled"] is False+ assert first_response.json()["template_id"] == str(template.id)+ server = MCPGatewayServer.objects.for_team(self.team.id).get(url=template.url)+ assert server.is_team_enabled is False+ assert server.template_id == template.id+ assert server.created_by_id == self.user.id++ reenable_response = self.client.post(+ self._api_url("set_template_enabled/"),+ data={"template_id": str(template.id), "enabled": True},+ format="json",+ )++ assert reenable_response.status_code == status.HTTP_200_OK+ reenabled = MCPGatewayServer.objects.for_team(self.team.id).get(url=template.url)+ assert reenabled.id == server.id+ assert reenabled.is_team_enabled is True++ def test_set_template_enabled_adopts_existing_templateless_row_with_same_url(self) -> None:+ self._make_admin()+ template = self._template("Adopt")+ existing = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Existing custom name",+ url=template.url,+ created_by=self.user,+ )++ response = self.client.post(+ self._api_url("set_template_enabled/"),+ data={"template_id": str(template.id), "enabled": False},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["id"] == str(existing.id)+ existing.refresh_from_db()+ assert existing.template_id == template.id+ assert existing.is_team_enabled is False+ assert existing.name == "Existing custom name"+ assert MCPGatewayServer.objects.for_team(self.team.id).filter(url=template.url).count() == 1++ def test_set_template_enabled_is_admin_only(self) -> None:+ self._make_member()+ template = self._template("Member blocked")++ response = self.client.post(+ self._api_url("set_template_enabled/"),+ data={"template_id": str(template.id), "enabled": False},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert not MCPGatewayServer.objects.for_team(self.team.id).filter(url=template.url).exists()++ @parameterized.expand([("inactive",), ("unknown",)])+ def test_set_template_enabled_returns_404_for_unavailable_templates(self, scenario: str) -> None:+ import uuid as _uuid++ self._make_admin()+ template_id = self._template("Inactive", active=False).id if scenario == "inactive" else _uuid.uuid4()++ response = self.client.post(+ self._api_url("set_template_enabled/"),+ data={"template_id": str(template_id), "enabled": False},+ format="json",+ )++ assert response.status_code == status.HTTP_404_NOT_FOUND+ assert not MCPGatewayServer.objects.for_team(self.team.id).exists()++ def test_delete_disables_linked_installations_only(self) -> None:+ self._make_admin()+ server, own_installation, _tool = self._server_with_personal_tool()+ other_user = self._create_user("[email protected]")+ other_installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=other_user,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "other-secret"},+ scope="personal",+ gateway_server=server,+ )+ unrelated_server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Unrelated server",+ url="https://mcp.unrelated-delete-test.example.com/mcp",+ created_by=self.user,+ )+ unrelated_installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name=unrelated_server.name,+ url=unrelated_server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "unrelated-secret"},+ scope="personal",+ gateway_server=unrelated_server,+ )++ response = self.client.delete(self._api_url(f"{server.id}/"))++ assert response.status_code == status.HTTP_204_NO_CONTENT+ assert not MCPGatewayServer.objects.for_team(self.team.id).filter(id=server.id).exists()+ for installation in (own_installation, other_installation):+ installation.refresh_from_db()+ assert installation.is_enabled is False+ assert installation.gateway_server_id is None+ unrelated_installation.refresh_from_db()+ assert unrelated_installation.is_enabled is True+ assert unrelated_installation.gateway_server_id == unrelated_server.id++ @parameterized.expand([("list", False), ("retrieve", True)])+ def test_member_metadata_is_visible_only_to_admins(self, _name: str, retrieve: bool) -> None:+ self._make_admin()+ server, own_installation, _tool = self._server_with_personal_tool()+ other_user = self._create_user("[email protected]")+ other_installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=other_user,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "other-secret"},+ scope="personal",+ gateway_server=server,+ )+ MCPMemberServerRevocation.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ user=other_user,+ revoked_by=self.user,+ )+ url = self._api_url(f"{server.id}/") if retrieve else self._api_url()++ admin_response = self.client.get(url)++ assert admin_response.status_code == status.HTTP_200_OK+ admin_payload = (+ admin_response.json()+ if retrieve+ else next(result for result in admin_response.json()["results"] if result["id"] == str(server.id))+ )+ assert {connection["installation_id"] for connection in admin_payload["connections"]} == {+ str(own_installation.id),+ str(other_installation.id),+ }+ assert admin_payload["revoked_user_ids"] == [other_user.id]++ self._make_member()+ member_response = self.client.get(url)++ assert member_response.status_code == status.HTTP_200_OK+ member_payload = (+ member_response.json()+ if retrieve+ else next(result for result in member_response.json()["results"] if result["id"] == str(server.id))+ )+ assert member_payload["connections"] == []+ assert member_payload["revoked_user_ids"] == []+ assert member_payload["your_connection"]["installation_id"] == str(own_installation.id)+ assert member_payload["is_revoked_for_you"] is False++ def test_team_policy_is_a_ceiling_for_member_and_legacy_tool_views(self) -> None:+ self._make_admin()+ server, installation, _tool = self._server_with_personal_tool(approval_state="approved")+ MCPToolPolicy.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ tool_name="create_issue",+ scope_type="member",+ scope_user=self.user,+ state="approved",+ )++ team_response = self.client.post(+ self._api_url(f"{server.id}/policies/"),+ data={+ "scope_type": "team",+ "policies": [{"tool_name": "create_issue", "policy_state": "needs_approval"}],+ },+ format="json",+ )++ assert team_response.status_code == status.HTTP_200_OK+ assert team_response.json()["results"][0]["policy_state"] == "needs_approval"++ self._make_member()+ member_response = self.client.get(+ self._api_url(f"{server.id}/tools/"),+ {"scope_type": "member"},+ )+ assert member_response.status_code == status.HTTP_200_OK+ member_tool = member_response.json()["results"][0]+ assert member_tool["policy_state"] == "needs_approval"+ assert member_tool["team_state"] == "needs_approval"+ assert member_tool["decided_by"] == "team"+ assert member_tool["locked"] is False++ legacy_response = self.client.get(+ f"/api/environments/{self.team.id}/mcp_server_installations/{installation.id}/tools/"+ )+ assert legacy_response.status_code == status.HTTP_200_OK+ legacy_tool = legacy_response.json()["results"][0]+ assert legacy_tool["approval_state"] == "needs_approval"+ assert legacy_tool["team_state"] == "needs_approval"+ assert legacy_tool["decided_by"] == "team"+ assert legacy_tool["locked"] is False++ def test_policy_upsert_rejects_oversized_tool_names_without_writes(self) -> None:+ self._make_admin()+ server, _installation, _tool = self._server_with_personal_tool()++ response = self.client.post(+ self._api_url(f"{server.id}/policies/"),+ data={+ "scope_type": "team",+ "policies": [{"tool_name": "x" * 201, "policy_state": "approved"}],+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not MCPToolPolicy.objects.for_team(self.team.id).filter(gateway_server=server).exists()++ def test_member_can_choose_below_team_ceiling_but_not_above_it(self) -> None:+ self._make_admin()+ server, installation, _tool = self._server_with_personal_tool(approval_state="needs_approval")+ team_response = self.client.post(+ self._api_url(f"{server.id}/policies/"),+ data={+ "scope_type": "team",+ "policies": [{"tool_name": "create_issue", "policy_state": "needs_approval"}],+ },+ format="json",+ )+ assert team_response.status_code == status.HTTP_200_OK++ self._make_member()+ stricter_response = self.client.post(+ self._api_url(f"{server.id}/policies/"),+ data={+ "scope_type": "member",+ "policies": [{"tool_name": "create_issue", "policy_state": "do_not_use"}],+ },+ format="json",+ )+ assert stricter_response.status_code == status.HTTP_200_OK+ assert stricter_response.json()["results"][0]["policy_state"] == "do_not_use"+ assert stricter_response.json()["results"][0]["decided_by"] == "scope"++ above_ceiling_response = self.client.post(+ self._api_url(f"{server.id}/policies/"),+ data={+ "scope_type": "member",+ "policies": [{"tool_name": "create_issue", "policy_state": "approved"}],+ },+ format="json",+ )+ assert above_ceiling_response.status_code == status.HTTP_400_BAD_REQUEST++ legacy_above_ceiling_response = self.client.patch(+ f"/api/environments/{self.team.id}/mcp_server_installations/{installation.id}/tools/create_issue/",+ data={"approval_state": "approved"},+ format="json",+ )+ assert legacy_above_ceiling_response.status_code == status.HTTP_400_BAD_REQUEST++ def test_member_policy_ceiling_uses_latest_known_annotations_across_installations(self) -> None:+ self._make_admin()+ server, _installation, latest_tool = self._server_with_personal_tool()+ now = timezone.now()+ latest_tool.tool_name = "manage_issue"+ latest_tool.annotations = {"destructiveHint": True}+ latest_tool.last_seen_at = now+ latest_tool.save(update_fields=["tool_name", "annotations", "last_seen_at", "updated_at"])+ older_installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "shared-secret"},+ scope="shared",+ gateway_server=server,+ )+ MCPServerInstallationTool.objects.create(+ installation=older_installation,+ tool_name=latest_tool.tool_name,+ description="Inspect issue details",+ approval_state="approved",+ last_seen_at=now - timedelta(hours=1),+ )+ TeamMCPGatewayConfig.objects.for_team(self.team.id).create(+ team=self.team,+ member_default_preset="block",+ )+ request_data = {+ "scope_type": "member",+ "policies": [{"tool_name": latest_tool.tool_name, "policy_state": "approved"}],+ }++ tools_response = self.client.get(+ self._api_url(f"{server.id}/tools/"),+ {"scope_type": "member"},+ )+ active_response = self.client.post(+ self._api_url(f"{server.id}/policies/"),+ data=request_data,+ format="json",+ )++ assert tools_response.status_code == status.HTTP_200_OK+ assert tools_response.json()["results"][0]["team_state"] == "do_not_use"+ assert active_response.status_code == status.HTTP_400_BAD_REQUEST++ MCPServerInstallationTool.objects.filter(+ installation__gateway_server=server,+ tool_name=latest_tool.tool_name,+ ).update(removed_at=now)++ removed_response = self.client.post(+ self._api_url(f"{server.id}/policies/"),+ data=request_data,+ format="json",+ )++ assert removed_response.status_code == status.HTTP_400_BAD_REQUEST+ assert (+ not MCPToolPolicy.objects.for_team(self.team.id)+ .filter(+ gateway_server=server,+ scope_type="member",+ scope_user=self.user,+ tool_name=latest_tool.tool_name,+ )+ .exists()+ )++ def test_legacy_tool_approval_updates_reuse_policy_for_child_environment(self) -> None:+ child = Team.objects.create(organization=self.organization, parent_team=self.team, name="Child environment")+ server = MCPGatewayServer.objects.for_team(child.id).create(+ team=child,+ name="Child environment server",+ url="https://mcp.child-environment.example.com/mcp",+ created_by=self.user,+ )+ installation = MCPServerInstallation.objects.create(+ team=child,+ user=self.user,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "secret"},+ scope="personal",+ gateway_server=server,+ )+ tool = MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name="child_tool",+ approval_state="approved",+ last_seen_at=timezone.now(),+ )+ url = f"/api/environments/{child.id}/mcp_server_installations/{installation.id}/tools/{tool.tool_name}/"++ first_response = self.client.patch(url, data={"approval_state": "do_not_use"}, format="json")+ second_response = self.client.patch(url, data={"approval_state": "needs_approval"}, format="json")++ assert first_response.status_code == status.HTTP_200_OK+ assert second_response.status_code == status.HTTP_200_OK+ policy = MCPToolPolicy.objects.for_team(self.team.id).get(+ gateway_server=server,+ scope_type="member",+ scope_user=self.user,+ tool_name=tool.tool_name,+ )+ assert policy.team_id == self.team.id+ assert policy.state == "needs_approval"++ def test_team_scope_displays_an_always_allow_ceiling(self) -> None:+ self._make_admin()+ server, _installation, _tool = self._server_with_personal_tool(approval_state="needs_approval")++ default_response = self.client.get(+ self._api_url(f"{server.id}/tools/"),+ {"scope_type": "team"},+ )++ assert default_response.status_code == status.HTTP_200_OK+ default_policy = default_response.json()["results"][0]+ assert default_policy["policy_state"] == "approved"+ assert default_policy["team_state"] is None+ assert default_policy["decided_by"] == "default"++ response = self.client.post(+ self._api_url(f"{server.id}/policies/"),+ data={+ "scope_type": "team",+ "policies": [{"tool_name": "create_issue", "policy_state": "approved"}],+ },+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ policy = response.json()["results"][0]+ assert policy["policy_state"] == "approved"+ assert policy["team_state"] == "approved"+ assert policy["decided_by"] == "team"++ def test_agent_access_policy_cannot_exceed_team_ceiling(self) -> None:+ self._make_admin()+ server, _installation, _tool = self._server_with_personal_tool(approval_state="needs_approval")+ account = sync_built_in_agents(self.team)[0]+ team_response = self.client.post(+ self._api_url(f"{server.id}/policies/"),+ data={+ "scope_type": "team",+ "policies": [{"tool_name": "create_issue", "policy_state": "needs_approval"}],+ },+ format="json",+ )+ assert team_response.status_code == status.HTTP_200_OK++ response = self.client.post(+ f"/api/projects/{self.team.id}/mcp_gateway/service_accounts/{account.id}/access/",+ data={+ "gateway_server_id": str(server.id),+ "enabled": True,+ "policies": [{"tool_name": "create_issue", "policy_state": "approved"}],+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert (+ not MCPToolPolicy.objects.for_team(self.team.id)+ .filter(+ gateway_server=server,+ scope_type="agent",+ scope_service_account=account,+ )+ .exists()+ )+++class TestMCPGatewayConfigAPI(APIBaseTest):+ def _api_url(self, suffix: str = "") -> str:+ base = f"/api/projects/{self.team.id}/mcp_gateway/config/"+ return f"{base}{suffix}" if suffix else base++ def _make_admin(self) -> None:+ membership = self.user.organization_memberships.get(organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()++ def _make_member(self) -> None:+ membership = self.user.organization_memberships.get(organization=self.organization)+ membership.level = OrganizationMembership.Level.MEMBER+ membership.save()++ def _server(self, name: str, *, is_team_enabled: bool = True) -> MCPGatewayServer:+ return MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name=name,+ url=f"https://mcp.{name.lower()}.config-test.example.com/mcp",+ is_team_enabled=is_team_enabled,+ )++ def test_default_servers_enabled_round_trips_through_config_api(self) -> None:+ self._make_admin()+ initial_response = self.client.get(self._api_url())+ assert initial_response.status_code == status.HTTP_200_OK+ assert initial_response.json()["default_servers_enabled"] is True++ update_response = self.client.post(+ self._api_url("update_settings/"),+ data={"default_servers_enabled": False},+ format="json",+ )++ assert update_response.status_code == status.HTTP_200_OK+ assert update_response.json()["default_servers_enabled"] is False+ assert TeamMCPGatewayConfig.objects.for_team(self.team.id).get().default_servers_enabled is False++ def test_set_all_servers_enabled_flips_default_and_every_registered_server(self) -> None:+ self._make_admin()+ enabled_server = self._server("Enabled")+ disabled_server = self._server("Disabled", is_team_enabled=False)++ disable_response = self.client.post(+ self._api_url("set_all_servers_enabled/"),+ data={"enabled": False},+ format="json",+ )++ assert disable_response.status_code == status.HTTP_200_OK+ assert disable_response.json()["default_servers_enabled"] is False+ for server in (enabled_server, disabled_server):+ server.refresh_from_db()+ assert server.is_team_enabled is False++ enable_response = self.client.post(+ self._api_url("set_all_servers_enabled/"),+ data={"enabled": True},+ format="json",+ )++ assert enable_response.status_code == status.HTTP_200_OK+ assert enable_response.json()["default_servers_enabled"] is True+ for server in (enabled_server, disabled_server):+ server.refresh_from_db()+ assert server.is_team_enabled is True++ def test_set_all_servers_enabled_is_admin_only(self) -> None:+ self._make_member()+ server = self._server("Protected")++ response = self.client.post(+ self._api_url("set_all_servers_enabled/"),+ data={"enabled": False},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ server.refresh_from_db()+ assert server.is_team_enabled is True+ config = TeamMCPGatewayConfig.objects.for_team(self.team.id).first()+ assert config is None or config.default_servers_enabled is True+++class TestMCPGatewayMemberAPI(APIBaseTest):+ def _api_url(self, suffix: str = "") -> str:+ base = f"/api/projects/{self.team.id}/mcp_gateway/members/"+ return f"{base}{suffix}" if suffix else base++ def _make_admin(self) -> None:+ membership = self.user.organization_memberships.get(organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()++ def test_list_paginates_organization_members(self) -> None:+ self._make_admin()+ self._create_user("[email protected]", first_name="Alice")+ self._create_user("[email protected]", first_name="Zoe")++ first_response = self.client.get(self._api_url(), {"limit": 1})++ assert first_response.status_code == status.HTTP_200_OK+ first_page = first_response.json()+ assert first_page["count"] == 3+ assert len(first_page["results"]) == 1+ assert first_page["next"] is not None++ second_response = self.client.get(first_page["next"])++ assert second_response.status_code == status.HTTP_200_OK+ second_page = second_response.json()+ assert len(second_page["results"]) == 1+ assert second_page["results"][0]["user"]["id"] != first_page["results"][0]["user"]["id"]++ def test_retrieve_returns_one_members_connections_and_revocations(self) -> None:+ self._make_admin()+ member = self._create_user("[email protected]")+ connected_server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Connected",+ url="https://mcp.connected-member.example.com/mcp",+ )+ revoked_server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Revoked",+ url="https://mcp.revoked-member.example.com/mcp",+ )+ MCPServerInstallation.objects.create(+ team=self.team,+ user=member,+ display_name=connected_server.name,+ url=connected_server.url,+ auth_type="api_key",+ scope="personal",+ gateway_server=connected_server,+ )+ MCPMemberServerRevocation.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=revoked_server,+ user=member,+ revoked_by=self.user,+ )++ response = self.client.get(self._api_url(f"{member.id}/"))++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["user"]["id"] == member.id+ assert response.json()["connected_server_ids"] == [str(connected_server.id)]+ assert response.json()["revoked_server_ids"] == [str(revoked_server.id)]++ def test_retrieve_does_not_expose_members_from_another_organization(self) -> None:+ self._make_admin()+ other_organization = Organization.objects.create(name="Other organization")+ other_member = User.objects.create_and_join(+ other_organization,+ "[email protected]",+ "password",+ )++ response = self.client.get(self._api_url(f"{other_member.id}/"))++ assert response.status_code == status.HTTP_404_NOT_FOUND+++class TestMCPGatewayWriteScopeAPI(APIBaseTest):+ def _make_admin(self) -> None:+ membership = self.user.organization_memberships.get(organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()++ def _read_only_oauth_client(self) -> APIClient:+ application = OAuthApplication.objects.create(+ name="Read-only MCP gateway",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ organization=self.organization,+ user=self.user,+ )+ access_token = OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token="pha_read_only_mcp_gateway",+ expires=timezone.now() + timedelta(hours=1),+ scope="project:read",+ scoped_teams=[self.team.id],+ )+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")+ return client++ @parameterized.expand([("policies",), ("agent_access",)])+ def test_read_only_oauth_token_cannot_mutate_gateway(self, action_name: str) -> None:+ self._make_admin()+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Scope protected",+ url="https://mcp.scope-protected.example.com/mcp",+ )+ MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ scope="personal",+ gateway_server=server,+ )+ account = sync_built_in_agents(self.team)[0]+ data: dict[str, object]+ if action_name == "policies":+ url = f"/api/projects/{self.team.id}/mcp_gateway/servers/{server.id}/policies/"+ data = {+ "scope_type": "team",+ "policies": [{"tool_name": "search", "policy_state": "approved"}],+ }+ else:+ url = f"/api/projects/{self.team.id}/mcp_gateway/service_accounts/{account.id}/access/"+ data = {"gateway_server_id": str(server.id), "enabled": True}++ response = self._read_only_oauth_client().post(url, data=data, format="json")++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert not MCPToolPolicy.objects.for_team(self.team.id).filter(gateway_server=server).exists()+ assert not MCPServiceAccountServerAccess.objects.for_team(self.team.id).filter(gateway_server=server).exists()+++class TestMCPServiceAccountAPI(APIBaseTest):+ def _api_url(self, suffix: str = "") -> str:+ base = f"/api/projects/{self.team.id}/mcp_gateway/service_accounts/"+ return f"{base}{suffix}" if suffix else base++ def _make_admin(self) -> None:+ membership = self.user.organization_memberships.get(organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()++ def _make_member(self) -> None:+ membership = self.user.organization_memberships.get(organization=self.organization)+ membership.level = OrganizationMembership.Level.MEMBER+ membership.save()++ def _active_scout_account(self) -> MCPServiceAccount:+ return next(agent for agent in sync_built_in_agents(self.team) if agent.handle == "posthog-scout")++ @staticmethod+ def _agent_client(account: MCPServiceAccount, token: str | None = None) -> APIClient:+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {token or create_gateway_agent_token(account)}")+ return client++ def _oauth_client(self, *, built_in_agent: bool) -> APIClient:+ application = OAuthApplication.objects.create(+ name="Sandbox agent",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ organization=self.organization,+ user=self.user,+ )+ scopes = ["project:read", "project:write"]+ if built_in_agent:+ scopes.append("mcp_builtin_agent:read")+ access_token = OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token=f"pha_mcp_agent_{'built_in' if built_in_agent else 'generic'}",+ expires=timezone.now() + timedelta(hours=1),+ scope=" ".join(scopes),+ scoped_teams=[self.team.id],+ )+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")+ return client++ def test_list_materializes_only_the_fixed_posthog_agent_catalog(self) -> None:+ self._make_admin()++ response = self.client.get(self._api_url())++ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert [agent["agent_key"] for agent in results] == ["support", "scout"]+ assert [agent["handle"] for agent in results] == ["posthog-support", "posthog-scout"]+ assert all(agent["status"] == "active" for agent in results)+ assert MCPServiceAccount.objects.for_team(self.team.id).count() == 2++ def test_list_reconciles_legacy_built_in_agent_handles(self) -> None:+ self._make_admin()+ support_account = sync_built_in_agents(self.team)[0]+ MCPServiceAccount.objects.for_team(self.team.id).filter(id=support_account.id).update(+ handle="svc-posthog-support"+ )++ response = self.client.get(self._api_url())++ assert response.status_code == status.HTTP_200_OK+ support_account.refresh_from_db()+ assert support_account.handle == "posthog-support"+ assert response.json()["results"][0]["id"] == str(support_account.id)+ # Reconciliation renames the legacy row in place (keyed on token_hash),+ # so the catalog stays at exactly one row per built-in agent.+ assert MCPServiceAccount.objects.for_team(self.team.id).count() == 2++ def test_agents_cannot_be_created_or_deleted(self) -> None:+ self._make_admin()++ create_response = self.client.post(self._api_url(), data={"name": "Custom agent"}, format="json")+ account_id = self.client.get(self._api_url()).json()["results"][0]["id"]+ delete_response = self.client.delete(self._api_url(f"{account_id}/"))++ assert create_response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED+ assert delete_response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED++ @ALLOW_URL+ def test_member_can_delegate_a_personal_credential_during_install(self, _mock_is_url_allowed) -> None:+ self._make_member()+ accounts = sync_built_in_agents(self.team)+ install_url = "https://mcp.personal-agent-grant.example.com/mcp"++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",+ data={+ "name": "Personal grant",+ "url": install_url,+ "auth_type": "api_key",+ "api_key": "secret",+ "scope": "personal",+ "agent_ids": [str(account.id) for account in accounts],+ },+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED+ installation = MCPServerInstallation.objects.get(team=self.team, url=install_url)+ accesses = MCPServiceAccountServerAccess.objects.for_team(self.team.id).filter(+ service_account__in=accounts,+ gateway_server=installation.gateway_server,+ )+ access_rows = set(accesses.values_list("service_account_id", "installation_id"))+ assert installation.scope == "personal"+ assert access_rows == {(account.id, installation.id) for account in accounts}++ @ALLOW_URL+ def test_install_rejects_member_agent_grant_when_team_setting_is_off(self, _mock_is_url_allowed) -> None:+ self._make_member()+ TeamMCPGatewayConfig.objects.for_team(self.team.id).create(team=self.team, allow_member_agent_access=False)+ account = sync_built_in_agents(self.team)[0]+ install_url = "https://mcp.restricted-agent-grant.example.com/mcp"++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",+ data={+ "name": "Restricted grant",+ "url": install_url,+ "auth_type": "api_key",+ "api_key": "secret",+ "scope": "personal",+ "agent_ids": [str(account.id)],+ },+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert not MCPServerInstallation.objects.filter(team=self.team, url=install_url).exists()++ @ALLOW_URL+ def test_install_rejects_hidden_legacy_service_account(self, _mock_is_url_allowed) -> None:+ self._make_admin()+ legacy_account = MCPServiceAccount.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ name="Legacy custom agent",+ handle="svc-legacy-custom-agent",+ token_hash="legacy-custom-agent-token-hash",+ )+ install_url = "https://mcp.legacy-agent-grant.example.com/mcp"++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",+ data={+ "name": "Legacy grant",+ "url": install_url,+ "auth_type": "api_key",+ "api_key": "secret",+ "scope": "shared",+ "agent_ids": [str(legacy_account.id)],+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not MCPServerInstallation.objects.filter(team=self.team, url=install_url).exists()++ def test_member_can_delegate_their_credential_and_control_agent_tools_by_default(self) -> None:+ self._make_member()+ account = sync_built_in_agents(self.team)[1]+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Personal Notion",+ url="https://mcp.personal-notion.example.com/mcp",+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name="Personal Notion",+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "secret"},+ scope="personal",+ gateway_server=server,+ )+ MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name="create_issue",+ description="Create an issue",+ last_seen_at=timezone.now(),+ )++ response = self.client.post(+ self._api_url(f"{account.id}/access/"),+ data={+ "gateway_server_id": str(server.id),+ "enabled": True,+ "policies": [{"tool_name": "create_issue", "policy_state": "do_not_use"}],+ },+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ access = MCPServiceAccountServerAccess.objects.for_team(self.team.id).get(+ service_account=account,+ gateway_server=server,+ )+ assert access.installation == installation+ assert access.installation.scope == "personal"+ assert (+ MCPToolPolicy.objects.for_team(self.team.id)+ .get(+ gateway_server=server,+ scope_type="agent",+ scope_service_account=account,+ tool_name="create_issue",+ )+ .state+ == "do_not_use"+ )++ policy_response = self.client.post(+ f"/api/projects/{self.team.id}/mcp_gateway/servers/{server.id}/policies/",+ data={+ "scope_type": "agent",+ "scope_service_account_id": str(account.id),+ "policies": [{"tool_name": "create_issue", "policy_state": "needs_approval"}],+ },+ format="json",+ )+ assert policy_response.status_code == status.HTTP_200_OK+ assert policy_response.json()["results"][0]["policy_state"] == "needs_approval"++ member_response = self.client.get(self._api_url())+ scout = next(row for row in member_response.json()["results"] if row["agent_key"] == "scout")+ assert scout["servers"] == [+ {+ "id": str(server.id),+ "name": "Personal Notion",+ "description": "",+ "icon_key": "",+ "icon_domain": "",+ "connection_state": "ready",+ }+ ]++ def test_restricted_member_cannot_change_existing_agent_access_but_admin_can(self) -> None:+ self._make_member()+ account = sync_built_in_agents(self.team)[0]+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Restricted access",+ url="https://mcp.restricted-access.example.com/mcp",+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "secret"},+ scope="personal",+ gateway_server=server,+ )+ MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name="create_issue",+ last_seen_at=timezone.now(),+ )+ access = MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ service_account=account,+ gateway_server=server,+ installation=installation,+ granted_by=self.user,+ )+ TeamMCPGatewayConfig.objects.for_team(self.team.id).create(team=self.team, allow_member_agent_access=False)++ policy_response = self.client.post(+ f"/api/projects/{self.team.id}/mcp_gateway/servers/{server.id}/policies/",+ data={+ "scope_type": "agent",+ "scope_service_account_id": str(account.id),+ "policies": [{"tool_name": "create_issue", "policy_state": "do_not_use"}],+ },+ format="json",+ )+ revoke_response = self.client.post(+ self._api_url(f"{account.id}/access/"),+ data={"gateway_server_id": str(server.id), "enabled": False},+ format="json",+ )++ assert policy_response.status_code == status.HTTP_403_FORBIDDEN+ assert revoke_response.status_code == status.HTTP_403_FORBIDDEN+ assert MCPServiceAccountServerAccess.objects.for_team(self.team.id).filter(id=access.id).exists()++ self._make_admin()+ admin_revoke_response = self.client.post(+ self._api_url(f"{account.id}/access/"),+ data={"gateway_server_id": str(server.id), "enabled": False},+ format="json",+ )+ assert admin_revoke_response.status_code == status.HTTP_200_OK+ assert not MCPServiceAccountServerAccess.objects.for_team(self.team.id).filter(id=access.id).exists()++ def test_only_admin_can_update_member_agent_access_setting(self) -> None:+ self._make_member()+ config_url = f"/api/projects/{self.team.id}/mcp_gateway/config/"+ response = self.client.get(config_url)+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["allow_member_agent_access"] is True++ member_response = self.client.post(+ f"{config_url}update_settings/",+ data={"allow_member_agent_access": False},+ format="json",+ )+ assert member_response.status_code == status.HTTP_403_FORBIDDEN++ self._make_admin()+ admin_response = self.client.post(+ f"{config_url}update_settings/",+ data={"allow_member_agent_access": False},+ format="json",+ )+ assert admin_response.status_code == status.HTTP_200_OK+ assert admin_response.json()["allow_member_agent_access"] is False++ def test_member_can_see_legacy_agent_grant_that_needs_a_credential(self) -> None:+ account = sync_built_in_agents(self.team)[1]+ template = MCPServerTemplate.objects.create(+ name="Notion",+ url="https://mcp.notion-agent-summary.example.com/mcp",+ description="Notion workspace",+ auth_type="oauth",+ icon_key="notion",+ icon_domain="notion.so",+ is_active=True,+ )+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ template=template,+ name=template.name,+ url=template.url,+ description=template.description,+ )+ MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ template=template,+ display_name=template.name,+ url=server.url,+ auth_type="oauth",+ scope="personal",+ gateway_server=server,+ sensitive_configuration={"access_token": "personal-token"},+ )+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ service_account=account,+ gateway_server=server,+ granted_by=self.user,+ )+ self._make_member()++ response = self.client.get(self._api_url())++ assert response.status_code == status.HTTP_200_OK+ scout = next(row for row in response.json()["results"] if row["agent_key"] == "scout")+ assert scout["servers"] == [+ {+ "id": str(server.id),+ "name": "Notion",+ "description": "Notion workspace",+ "icon_key": "notion",+ "icon_domain": "notion.so",+ "connection_state": "missing_credential",+ }+ ]++ def test_deleting_delegated_credential_preserves_grant_without_switching_credentials(self) -> None:+ account = sync_built_in_agents(self.team)[1]+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Delegated Notion",+ url="https://mcp.deleted-agent-credential.example.com/mcp",+ )+ MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name="Shared Notion",+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "shared-secret"},+ scope="shared",+ gateway_server=server,+ )+ personal_installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name="Personal Notion",+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "personal-secret"},+ scope="personal",+ gateway_server=server,+ )+ access = MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ service_account=account,+ gateway_server=server,+ installation=personal_installation,+ granted_by=self.user,+ )++ personal_installation.delete()+ access.refresh_from_db()+ response = self.client.get(self._api_url())++ assert access.installation_id is None+ assert response.status_code == status.HTTP_200_OK+ scout = next(row for row in response.json()["results"] if row["agent_key"] == "scout")+ assert scout["servers"][0]["connection_state"] == "missing_credential"++ def test_agent_endpoint_rejects_tampered_signed_token(self) -> None:+ account = self._active_scout_account()+ token = create_gateway_agent_token(account)+ tampered_token = f"{token[:-1]}{'a' if token[-1] != 'a' else 'b'}"++ response = self._agent_client(account, tampered_token).get("/api/mcp_store/gateway/servers/")++ assert response.status_code == status.HTTP_401_UNAUTHORIZED++ def test_agent_endpoint_rejects_expired_signed_token(self) -> None:+ account = self._active_scout_account()+ client = self._agent_client(account)++ with patch(+ "products.mcp_store.backend.agents.signing.loads",+ side_effect=SignatureExpired("Gateway token expired"),+ ):+ response = client.get("/api/mcp_store/gateway/servers/")++ assert response.status_code == status.HTTP_401_UNAUTHORIZED++ def test_agent_endpoint_throttles_last_active_updates(self) -> None:+ account = self._active_scout_account()+ client = self._agent_client(account)+ recent_active_at = timezone.now()+ MCPServiceAccount.objects.for_team(self.team.id).filter(pk=account.pk).update(last_active_at=recent_active_at)++ recent_response = client.get("/api/mcp_store/gateway/servers/")+ account.refresh_from_db()++ assert recent_response.status_code == status.HTTP_200_OK+ assert account.last_active_at == recent_active_at++ stale_active_at = timezone.now() - timedelta(minutes=61)+ MCPServiceAccount.objects.for_team(self.team.id).filter(pk=account.pk).update(last_active_at=stale_active_at)+ before_stale_request = timezone.now()+ stale_response = client.get("/api/mcp_store/gateway/servers/")+ after_stale_request = timezone.now()+ account.refresh_from_db()++ assert stale_response.status_code == status.HTTP_200_OK+ assert account.last_active_at is not None+ assert before_stale_request <= account.last_active_at <= after_stale_request++ def test_agent_endpoint_rechecks_pause_after_mint(self) -> None:+ account = self._active_scout_account()+ token = create_gateway_agent_token(account)+ client = self._agent_client(account, token)++ account.status = "paused"+ account.save(update_fields=["status", "updated_at"])+ assert client.get("/api/mcp_store/gateway/servers/").status_code == status.HTTP_401_UNAUTHORIZED++ def test_agent_endpoint_does_not_gate_on_product_state(self) -> None:+ account = self._active_scout_account()+ client = self._agent_client(account)++ self.organization.is_ai_data_processing_approved = False+ self.organization.save(update_fields=["is_ai_data_processing_approved"])+ assert client.get("/api/mcp_store/gateway/servers/").status_code == status.HTTP_200_OK++ @parameterized.expand(+ [+ ("catalog", "GET", "/api/mcp_store/gateway/servers/", status.HTTP_200_OK),+ (+ "proxy",+ "POST",+ "/api/mcp_store/gateway/servers/00000000-0000-0000-0000-000000000001/proxy/",+ status.HTTP_404_NOT_FOUND,+ ),+ ]+ )+ def test_agent_gateway_rate_limits_are_scoped_per_service_account(+ self, _name: str, method: str, url: str, allowed_status: int+ ) -> None:+ accounts = sync_built_in_agents(self.team)+ primary_account = next(account for account in accounts if account.handle == "posthog-scout")+ secondary_account = next(account for account in accounts if account.handle == "posthog-support")+ primary_client = self._agent_client(primary_account)+ secondary_client = self._agent_client(secondary_account)+ cache.clear()+ self.addCleanup(cache.clear)++ with (+ patch(+ "products.mcp_store.backend.presentation.agent_views.MCPGatewayAgentBurstThrottle.rate",+ "1/minute",+ ),+ patch(+ "products.mcp_store.backend.presentation.agent_views.MCPGatewayAgentSustainedThrottle.rate",+ "1/minute",+ ),+ ):+ first_response = primary_client.generic(method, url, REMOTE_ADDR="192.0.2.1")+ throttled_response = primary_client.generic(method, url, REMOTE_ADDR="192.0.2.2")+ secondary_response = secondary_client.generic(method, url, REMOTE_ADDR="192.0.2.1")++ assert first_response.status_code == allowed_status+ assert throttled_response.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ assert secondary_response.status_code == allowed_status++ @parameterized.expand(+ [+ ("ungranted",),+ ("revoked",),+ ("cross_team",),+ ]+ )+ @patch("products.mcp_store.backend.presentation.agent_views.proxy_mcp_request")+ def test_agent_proxy_hides_servers_outside_its_grant_set(self, scenario: str, mock_proxy) -> None:+ account = self._active_scout_account()+ server_team = self.team+ if scenario == "cross_team":+ server_team = self.organization.teams.create(name="Other gateway team")+ server = MCPGatewayServer.objects.for_team(server_team.id).create(+ team=server_team,+ name=f"Hidden {scenario}",+ url=f"https://mcp.{scenario}.example.com/mcp",+ )+ if scenario == "revoked":+ access = MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ service_account=account,+ gateway_server=server,+ granted_by=self.user,+ )+ access.delete()++ response = self._agent_client(account).post(+ f"/api/mcp_store/gateway/servers/{server.id}/proxy/",+ data={"jsonrpc": "2.0", "method": "tools/list", "id": 1},+ format="json",+ )++ assert response.status_code == status.HTTP_404_NOT_FOUND+ mock_proxy.assert_not_called()++ @patch("products.mcp_store.backend.presentation.agent_views.proxy_mcp_request")+ def test_agent_proxy_rejects_server_disabled_for_team(self, mock_proxy) -> None:+ account = self._active_scout_account()+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Killed",+ url="https://mcp.killed.example.com/mcp",+ is_team_enabled=False,+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name="Shared agent credential",+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "secret"},+ scope="shared",+ gateway_server=server,+ )+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ service_account=account,+ gateway_server=server,+ installation=installation,+ granted_by=self.user,+ )++ response = self._agent_client(account).post(+ f"/api/mcp_store/gateway/servers/{server.id}/proxy/",+ data={"jsonrpc": "2.0", "method": "tools/list", "id": 1},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ mock_proxy.assert_not_called()++ @patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.proxy.httpx.Client")+ def test_agent_grant_enforces_agent_scope_policy(self, mock_http_client, _mock_is_url_allowed) -> None:+ account = self._active_scout_account()+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Agent policy",+ url="https://mcp.agent-policy.example.com/mcp",+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name="Shared agent credential",+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "secret"},+ scope="shared",+ gateway_server=server,+ )+ MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name="delete_everything",+ last_seen_at=timezone.now(),+ )+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ service_account=account,+ gateway_server=server,+ installation=installation,+ granted_by=self.user,+ )+ MCPToolPolicy.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ tool_name="delete_everything",+ scope_type="agent",+ scope_service_account=account,+ state="do_not_use",+ )++ response = self._agent_client(account).post(+ f"/api/mcp_store/gateway/servers/{server.id}/proxy/",+ data={+ "jsonrpc": "2.0",+ "method": "tools/call",+ "id": 1,+ "params": {"name": "delete_everything", "arguments": {}},+ },+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["error"]["code"] == -32002+ mock_http_client.assert_not_called()++ def test_agent_grant_on_disabled_server_stays_dormant_until_team_enabled(self) -> None:+ self._make_admin()+ catalog_response = self.client.get(self._api_url())+ scout = next(agent for agent in catalog_response.json()["results"] if agent["agent_key"] == "scout")+ granted_server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Agent only",+ url="https://mcp.agent-only.example.com/mcp",+ is_team_enabled=False,+ )+ shared_installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name="Shared",+ url=granted_server.url,+ auth_type="api_key",+ scope="shared",+ gateway_server=granted_server,+ )+ personal_installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name="Personal",+ url=granted_server.url,+ auth_type="api_key",+ scope="personal",+ gateway_server=granted_server,+ )+ MCPServerInstallationTool.objects.create(+ installation=shared_installation,+ tool_name="shared_tool",+ last_seen_at=timezone.now(),+ )+ MCPServerInstallationTool.objects.create(+ installation=personal_installation,+ tool_name="personal_tool",+ last_seen_at=timezone.now(),+ )+ MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Not granted",+ url="https://mcp.not-granted.example.com/mcp",+ )++ grant_response = self.client.post(+ self._api_url(f"{scout['id']}/access/"),+ data={"gateway_server_id": str(granted_server.id), "enabled": True},+ format="json",+ )+ assert grant_response.status_code == status.HTTP_200_OK+ access = MCPServiceAccountServerAccess.objects.for_team(self.team.id).get(+ service_account_id=scout["id"],+ gateway_server=granted_server,+ )+ assert access.installation == personal_installation+ assert grant_response.json()["servers"] == [+ {+ "id": str(granted_server.id),+ "name": "Agent only",+ "description": "",+ "icon_key": "",+ "icon_domain": "",+ "connection_state": "ready",+ }]- )- def test_icon_rejects_non_hostname_domains(self, _name, bad_domain):- # The domain param becomes a path segment of img.logo.dev/{domain} — anything but a bare- # hostname must be rejected or the endpoint can be steered off the logo host.- response = self.client.get(f"/api/environments/{self.team.id}/mcp_servers/icon/", data={"domain": bad_domain})- assert response.status_code == status.HTTP_400_BAD_REQUEST- @parameterized.expand(- [- ("no_theme", {"domain": "linear.app"}, None),- ("dark_theme", {"domain": "linear.app", "theme": "dark"}, "dark"),- ("unknown_theme_dropped", {"domain": "linear.app", "theme": "neon"}, None),- ("case_and_fqdn_dot_canonicalized", {"domain": "LINEAR.APP."}, None),- ]- )- def test_icon_proxies_valid_domain(self, _name, params, expected_theme):- # Both halves of the icon cache key must stay canonical: unknown themes are dropped- # rather than forwarded, and the domain is lowercased with any FQDN trailing dot- # stripped so case variants can't mint separate cache entries.- with patch("products.mcp_store.backend.presentation.views.CDPIconsService") as service:- service.return_value.get_icon_http_response.return_value = HttpResponse(b"png", content_type="image/png")- response = self.client.get(f"/api/environments/{self.team.id}/mcp_servers/icon/", data=params)+ account = MCPServiceAccount.objects.for_team(self.team.id).get(id=scout["id"])+ agent_client = APIClient()+ agent_client.credentials(HTTP_AUTHORIZATION=f"Bearer {create_gateway_agent_token(account)}")+ dormant_response = agent_client.get("/api/mcp_store/gateway/servers/")++ assert dormant_response.status_code == status.HTTP_200_OK+ assert dormant_response.json()["results"] == []++ granted_server.is_team_enabled = True+ granted_server.save(update_fields=["is_team_enabled"])+ response = agent_client.get("/api/mcp_store/gateway/servers/")+assert response.status_code == status.HTTP_200_OK- service.return_value.get_icon_http_response.assert_called_once_with(- "linear.app", theme=expected_theme, fallback="404", team_id=self.team.id- )+ assert [server["id"] for server in response.json()["results"]] == [str(granted_server.id)]+ assert [tool["name"] for tool in response.json()["results"][0]["tools"]] == ["personal_tool"]- def test_icon_allows_oauth_project_read_scope(self):- oauth_application = OAuthApplication.objects.create(- name="MCP icon test",- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,- redirect_uris="https://example.com/callback",- algorithm="RS256",- organization=self.organization,+ revoke_response = self.client.post(+ self._api_url(f"{scout['id']}/access/"),+ data={"gateway_server_id": str(granted_server.id), "enabled": False},+ format="json",+ )+ revoked_catalog_response = agent_client.get("/api/mcp_store/gateway/servers/")++ assert revoke_response.status_code == status.HTTP_200_OK+ assert str(granted_server.id) not in revoke_response.json()["server_ids"]+ assert revoked_catalog_response.status_code == status.HTTP_200_OK+ assert revoked_catalog_response.json()["results"] == []++ def test_agent_catalog_query_count_does_not_grow_with_accessible_servers(self) -> None:+ account = self._active_scout_account()+ client = self._agent_client(account)++ def grant_server(index: int) -> MCPGatewayServer:+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name=f"Catalog server {index}",+ url=f"https://mcp.catalog-{index}.example.com/mcp",+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ scope="shared",+ gateway_server=server,+ )+ MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name=f"catalog_tool_{index}",+ description=f"Catalog tool {index}",+ input_schema={"type": "object", "properties": {"index": {"type": "integer"}}},+ last_seen_at=timezone.now(),+ )+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ service_account=account,+ gateway_server=server,+ installation=installation,+ granted_by=self.user,+ )+ MCPToolPolicy.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ tool_name=f"catalog_tool_{index}",+ scope_type="agent",+ scope_service_account=account,+ state="do_not_use",+ )+ return server++ servers = [grant_server(0)]+ assert client.get("/api/mcp_store/gateway/servers/").status_code == status.HTTP_200_OK+ with CaptureQueriesContext(connection) as one_server_queries:+ one_server_response = client.get("/api/mcp_store/gateway/servers/")++ servers.extend(grant_server(index) for index in range(1, 5))+ with CaptureQueriesContext(connection) as five_server_queries:+ five_server_response = client.get("/api/mcp_store/gateway/servers/")++ assert one_server_response.status_code == status.HTTP_200_OK+ assert five_server_response.status_code == status.HTTP_200_OK+ results_by_id = {row["id"]: row for row in five_server_response.json()["results"]}+ for index, server in enumerate(servers):+ assert results_by_id[str(server.id)]["tools"] == [+ {+ "name": f"catalog_tool_{index}",+ "description": f"Catalog tool {index}",+ "input_schema": {+ "type": "object",+ "properties": {"index": {"type": "integer"}},+ },+ "state": "do_not_use",+ }+ ]+ assert len(five_server_queries.captured_queries) == len(one_server_queries.captured_queries)++ def test_built_in_agent_oauth_cannot_use_member_mcp_or_control_plane(self) -> None:+ self._make_admin()+ catalog = self.client.get(self._api_url()).json()["results"]+ account = next(agent for agent in catalog if agent["agent_key"] == "scout")+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Restricted",+ url="https://mcp.restricted.example.com/mcp",+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,user=self.user,+ display_name="Personal",+ url=server.url,+ auth_type="api_key",+ gateway_server=server,)- access_token = OAuthAccessToken.objects.create(+ client = self._oauth_client(built_in_agent=True)++ assert client.get(f"/api/environments/{self.team.id}/mcp_server_installations/").status_code == 403+ assert (+ client.get(f"/api/environments/{self.team.id}/mcp_server_installations/{installation.id}/").status_code+ == 403+ )+ assert (+ client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/{installation.id}/proxy/"+ ).status_code+ == 403+ )+ assert (+ client.patch(+ f"/api/projects/{self.team.id}/mcp_gateway/servers/{server.id}/",+ data={"is_team_enabled": False},+ format="json",+ ).status_code+ == 403+ )+ assert (+ client.post(+ self._api_url(f"{account['id']}/access/"),+ data={"gateway_server_id": str(server.id), "enabled": True},+ format="json",+ ).status_code+ == 403+ )+ assert (+ client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/{installation.id}/share/"+ ).status_code+ == 403+ )++ server.refresh_from_db()+ installation.refresh_from_db()+ assert server.is_team_enabled is True+ assert installation.scope == "personal"+ assert not MCPServiceAccountServerAccess.objects.for_team(self.team.id).exists()++ def test_generic_sandbox_oauth_keeps_member_mcp_access(self) -> None:+ installation = MCPServerInstallation.objects.create(+ team=self.team,user=self.user,- application=oauth_application,- token="pha_test_mcp_icon",- expires=timezone.now() + timedelta(hours=1),- scope="project:read",+ display_name="Personal",+ url="https://mcp.generic-sandbox.example.com/mcp",+ auth_type="api_key",)- client = APIClient()+ client = self._oauth_client(built_in_agent=False)- with patch("products.mcp_store.backend.presentation.views.CDPIconsService") as service:- service.return_value.get_icon_http_response.return_value = HttpResponse(b"png", content_type="image/png")- response = client.get(- f"/api/environments/{self.team.id}/mcp_servers/icon/",- data={"domain": "linear.app"},- headers={"authorization": f"Bearer {access_token.token}"},- )+ response = client.get(f"/api/environments/{self.team.id}/mcp_server_installations/")assert response.status_code == status.HTTP_200_OK-- def test_unauthenticated_access(self):- client = APIClient()- response = client.get(f"/api/environments/{self.team.id}/mcp_servers/")- assert response.status_code == status.HTTP_401_UNAUTHORIZED+ assert [row["id"] for row in response.json()["results"]] == [str(installation.id)]class TestMCPServerInstallationAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):@@ -522,6 +2293,100 @@ class TestInstallCustomAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):)assert response.status_code == status.HTTP_201_CREATED+ @parameterized.expand(+ [+ ("row_disabled_api_key", "row_disabled", "api_key"),+ ("row_disabled_oauth", "row_disabled", "oauth"),+ ("default_disabled_api_key", "default_disabled", "api_key"),+ ]+ )+ @ALLOW_URL+ def test_install_custom_refused_when_server_disabled_for_team(+ self, _name: str, scenario: str, auth_type: str, _mock+ ) -> None:+ url = "https://mcp.disabled-custom.example.com/mcp"+ if scenario == "row_disabled":+ MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Disabled",+ url=url,+ is_team_enabled=False,+ )+ else:+ TeamMCPGatewayConfig.objects.for_team(self.team.id).create(team=self.team, default_servers_enabled=False)++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",+ data={"name": "Disabled", "url": url, "auth_type": auth_type, "api_key": "sk-x"},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert response.json()["detail"] == "This server is disabled for your team."+ assert not MCPServerInstallation.objects.filter(team=self.team, url=url).exists()++ def _make_admin(self) -> None:+ membership = self.user.organization_memberships.get(organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()++ @parameterized.expand([("api_key",), ("oauth",)])+ @ALLOW_URL+ @patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")+ @patch(+ "products.mcp_store.backend.presentation.views.register_dcr_client",+ return_value=DcrClientRegistration(+ client_id="dcr-client-id", client_secret=None, token_endpoint_auth_method="none"+ ),+ )+ def test_admin_can_install_custom_despite_disabled_default_posture(+ self, auth_type: str, _mock_dcr, mock_discover, _allow+ ) -> None:+ """Adding a custom server under a disabled posture is the admin's+ allowlisting act: it materializes an explicitly enabled row without+ flipping the posture for everything else."""+ mock_discover.return_value = {+ "issuer": "https://auth.example.com",+ "authorization_endpoint": "https://auth.example.com/authorize",+ "token_endpoint": "https://auth.example.com/token",+ "registration_endpoint": "https://auth.example.com/register",+ }+ TeamMCPGatewayConfig.objects.for_team(self.team.id).create(team=self.team, default_servers_enabled=False)+ self._make_admin()+ url = "https://mcp.admin-override.example.com/mcp"++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",+ data={"name": "Override", "url": url, "auth_type": auth_type, "api_key": "sk-x"},+ format="json",+ )++ assert response.status_code == (status.HTTP_201_CREATED if auth_type == "api_key" else status.HTTP_200_OK)+ server = MCPGatewayServer.objects.for_team(self.team.id).get(url=url)+ assert server.is_team_enabled is True+ config = TeamMCPGatewayConfig.objects.for_team(self.team.id).get()+ assert config.default_servers_enabled is False++ @ALLOW_URL+ def test_admin_still_blocked_when_custom_row_explicitly_disabled(self, _mock) -> None:+ self._make_admin()+ url = "https://mcp.row-off.example.com/mcp"+ MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Row off",+ url=url,+ is_team_enabled=False,+ )++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",+ data={"name": "Row off", "url": url, "auth_type": "api_key", "api_key": "sk-x"},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert not MCPServerInstallation.objects.filter(team=self.team, url=url).exists()+class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def _create_template(self, **kwargs) -> MCPServerTemplate:@@ -668,7 +2533,8 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert "status=error" in locationassert "error=cancelled" in location- def test_callback_rejects_state_for_anonymous_consumer(self):+ @patch("products.mcp_store.backend.presentation.views.is_dev_mode", return_value=False)+ def test_callback_rejects_state_for_anonymous_consumer(self, _is_dev):"""State in an unauthenticated browser must return 400.If an OAuth state is handled by a browser where no user is logged in,@@ -690,7 +2556,62 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):attacker_install.refresh_from_db()assert not (attacker_install.sensitive_configuration or {}).get("access_token")- def test_callback_rejects_state_for_different_authenticated_user(self):+ @patch("products.mcp_store.backend.presentation.views.is_dev_mode", return_value=True)+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_callback_rejects_anonymous_posthog_consumer_in_dev(self, mock_post, _allow, _is_dev):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"access_token": "tok", "token_type": "bearer"}++ installation = self._create_installation()+ state_token = "anonymous-posthog-dev-callback"+ self._create_oauth_state(installation, state_token, pkce_verifier="v", install_source="posthog")++ browser_client = APIClient()+ response = browser_client.get(+ "/api/mcp_store/oauth_redirect/",+ {"state": state_token, "code": "code"},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ mock_post.assert_not_called()+ row = MCPOAuthState.objects.get(token_hash=hashlib.sha256(state_token.encode("utf-8")).hexdigest())+ assert row.consumed_at is None+ installation.refresh_from_db()+ assert not (installation.sensitive_configuration or {}).get("access_token")++ @patch("products.mcp_store.backend.presentation.views.is_dev_mode", return_value=True)+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))+ @patch("products.mcp_store.backend.oauth.requests.post")+ def test_callback_accepts_anonymous_consumer_in_dev(self, mock_post, _allow, _is_dev):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"access_token": "tok", "token_type": "bearer"}++ installation = self._create_installation()+ state_token = "anonymous-dev-callback"+ callback_url = "http://localhost:8238/mcp-oauth-complete"+ self._create_oauth_state(+ installation,+ state_token,+ pkce_verifier="v",+ install_source="posthog-code",+ posthog_code_callback_url=callback_url,+ )++ browser_client = APIClient()+ response = browser_client.get(+ "/api/mcp_store/oauth_redirect/",+ {"state": state_token, "code": "code"},+ )++ assert response.status_code == 302+ assert response["Location"].startswith(f"{callback_url}?")+ assert "status=success" in response["Location"]+ installation.refresh_from_db()+ assert installation.sensitive_configuration["access_token"] == "tok"++ @patch("products.mcp_store.backend.presentation.views.is_dev_mode", return_value=True)+ def test_callback_rejects_state_for_different_authenticated_user(self, _is_dev):"""State created by user A cannot be consumed by user B in the same browser.Covers the scenario where the victim IS logged into PostHog but as a@@ -707,7 +2628,7 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):victim_client.force_login(victim_user)response = victim_client.get("/api/mcp_store/oauth_redirect/",- {"state": state_token, "code": "victim-auth-code"},+ {"state": state_token, "error": "access_denied"},)assert response.status_code == status.HTTP_400_BAD_REQUEST@@ -869,6 +2790,43 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):row = MCPOAuthState.objects.get(token_hash=hashlib.sha256(state_token.encode("utf-8")).hexdigest())assert row.created_by_id == self.user.id+ @ALLOW_URL+ @patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")+ @patch(+ "products.mcp_store.backend.presentation.views.register_dcr_client",+ return_value=DcrClientRegistration(+ client_id="dcr-client-id", client_secret=None, token_endpoint_auth_method="none"+ ),+ )+ def test_install_custom_reenables_recycled_installation(self, _mock_dcr, mock_discover, _allow):+ """Removing a gateway server disables its rows; reinstalling must switch them back on."""+ mock_discover.return_value = {+ "issuer": "https://auth.example.com",+ "authorization_endpoint": "https://auth.example.com/authorize",+ "token_endpoint": "https://auth.example.com/token",+ "registration_endpoint": "https://auth.example.com/register",+ }+ url = "https://mcp.recycled.com/mcp"+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ url=url,+ display_name="srv",+ auth_type="oauth",+ scope="personal",+ is_enabled=False,+ )++ resp = self.client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",+ data={"name": "srv", "url": url, "auth_type": "oauth"},+ format="json",+ )+ assert resp.status_code == status.HTTP_200_OK, resp.content++ installation.refresh_from_db()+ assert installation.is_enabled is True+class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def _create_template(self, **overrides) -> MCPServerTemplate:@@ -1478,6 +3436,94 @@ class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest# A half-created installation should not linger after DCR failure.assert not MCPServerInstallation.objects.filter(url=template.url, user=self.user).exists()+ @parameterized.expand([("row_disabled",), ("default_disabled",)])+ def test_install_template_refused_when_server_disabled_for_team(self, scenario: str) -> None:+ template = self._template()+ if scenario == "row_disabled":+ MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name=template.name,+ url=template.url,+ template=template,+ is_team_enabled=False,+ )+ else:+ TeamMCPGatewayConfig.objects.for_team(self.team.id).create(team=self.team, default_servers_enabled=False)++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/install_template/",+ data={"template_id": str(template.id)},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert response.json()["detail"] == "This server is disabled for your team."+ assert not MCPServerInstallation.objects.filter(team=self.team, url=template.url).exists()+ assert not MCPOAuthState.objects.filter(team=self.team).exists()++ def test_install_template_allowed_when_row_is_enabled_despite_disabled_default(self) -> None:+ template = self._template()+ TeamMCPGatewayConfig.objects.for_team(self.team.id).create(team=self.team, default_servers_enabled=False)+ MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name=template.name,+ url=template.url,+ template=template,+ is_team_enabled=True,+ )++ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_server_installations/install_template/",+ data={"template_id": str(template.id)},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.content+ assert MCPServerInstallation.objects.filter(team=self.team, url=template.url, user=self.user).exists()++ @parameterized.expand([("template",), ("installation",)])+ @ALLOW_URL+ def test_authorize_refuses_oauth_start_for_disabled_server(self, scenario: str, _mock) -> None:+ template = self._template()+ params: dict[str, str]+ if scenario == "template":+ MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name=template.name,+ url=template.url,+ template=template,+ is_team_enabled=False,+ )+ params = {"template_id": str(template.id)}+ else:+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name="Custom",+ url="https://mcp.disabled-reconnect.example.com/mcp",+ auth_type="oauth",+ oauth_metadata={+ "authorization_endpoint": "https://auth.test.example.com/authorize",+ "token_endpoint": "https://auth.test.example.com/token",+ },+ sensitive_configuration={"dcr_client_id": "dcr-client-id"},+ )+ MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Custom",+ url=installation.url,+ is_team_enabled=False,+ )+ params = {"installation_id": str(installation.id)}++ response = self.client.get(+ f"/api/environments/{self.team.id}/mcp_server_installations/authorize/",+ params,+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert not MCPOAuthState.objects.filter(team=self.team).exists()+class TestInstallationToolsAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):def _installation(self, **kwargs) -> MCPServerInstallation:diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.pyindex 0e53c5f81f45..93c25b4d339d 100644--- a/products/mcp_store/backend/test/test_facade.py+++ b/products/mcp_store/backend/test/test_facade.py@@ -1,12 +1,20 @@from posthog.test.base import BaseTest+from unittest.mock import patchfrom parameterized import parameterizedfrom posthog.models import User+from products.mcp_store.backend.agents import get_built_in_agentfrom products.mcp_store.backend.facade.api import get_active_installations, get_installations_for_sandboxfrom products.mcp_store.backend.facade.contracts import ActiveInstallationInfo-from products.mcp_store.backend.models import MCPServerInstallation, MCPServerTemplate+from products.mcp_store.backend.models import (+ MCPGatewayServer,+ MCPServerInstallation,+ MCPServerTemplate,+ MCPServiceAccount,+ MCPServiceAccountServerAccess,+)class TestGetActiveInstallations(BaseTest):@@ -147,6 +155,12 @@ class TestGetActiveInstallations(BaseTest):class TestGetInstallationsForSandbox(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ patcher = patch("products.mcp_store.backend.facade.api.is_builtin_agent_enforcement_enabled", return_value=True)+ self.enforcement_enabled_mock = patcher.start()+ self.addCleanup(patcher.stop)+def _create_installation(self, **kwargs) -> MCPServerInstallation:defaults: dict = {"team": self.team,@@ -160,6 +174,19 @@ class TestGetInstallationsForSandbox(BaseTest):defaults.update(kwargs)return MCPServerInstallation.objects.create(**defaults)+ def _create_gateway_server(self, *, name: str, url: str, is_team_enabled: bool = True) -> MCPGatewayServer:+ return MCPGatewayServer.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ name=name,+ url=url,+ is_team_enabled=is_team_enabled,+ )++ def _support_agent(self) -> MCPServiceAccount:+ account = get_built_in_agent(self.team.id, "support")+ assert account is not None+ return account+def test_shared_always_returned(self) -> None:shared = self._create_installation(scope="shared", display_name="Shared Server")@@ -203,6 +230,177 @@ class TestGetInstallationsForSandbox(BaseTest):assert len(results) == 1+ @parameterized.expand([("unstamped", None), ("stamped", "support")])+ def test_agent_origin_resolves_legacy_until_gateway_flag_rollout(+ self, _name: str, task_agent_key: str | None+ ) -> None:+ self.enforcement_enabled_mock.return_value = False+ shared = self._create_installation(scope="shared", display_name="Shared")+ personal = self._create_installation(+ scope="personal", url="https://personal.example.com/mcp", display_name="Personal"+ )++ results = get_installations_for_sandbox(+ self.team.id,+ user_id=self.user.id,+ include_personal=True,+ task_origin="support_reply",+ task_agent_key=task_agent_key,+ )++ assert {result.id for result in results} == {str(shared.id), str(personal.id)}+ assert all(result.proxy_token is None for result in results)++ def test_built_in_agent_only_gets_its_explicitly_delegated_credential(self) -> None:+ account = self._support_agent()+ granted_server = self._create_gateway_server(+ name="Granted",+ url="https://granted.example.com/mcp",+ )+ ungranted_server = self._create_gateway_server(+ name="Ungranted",+ url="https://ungranted.example.com/mcp",+ )+ self._create_installation(+ scope="shared",+ gateway_server=granted_server,+ url=granted_server.url,+ display_name="Granted",+ )+ personal = self._create_installation(+ scope="personal",+ gateway_server=granted_server,+ url=granted_server.url,+ display_name="Personal",+ )+ self._create_installation(+ scope="shared",+ gateway_server=ungranted_server,+ url=ungranted_server.url,+ display_name="Ungranted",+ )+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ service_account=account,+ gateway_server=granted_server,+ installation=personal,+ granted_by=self.user,+ )++ results = get_installations_for_sandbox(+ self.team.id,+ user_id=self.user.id,+ include_personal=True,+ task_origin="support_reply",+ task_agent_key="support",+ )++ assert [result.id for result in results] == [str(personal.id)]+ assert results[0].proxy_path == f"/api/mcp_store/gateway/servers/{granted_server.id}/proxy/"+ assert results[0].proxy_token is not None+ assert results[0].proxy_token.startswith("mcp_gw_")++ account.status = "paused"+ account.save(update_fields=["status"])+ assert (+ get_installations_for_sandbox(+ self.team.id,+ task_origin="support_reply",+ task_agent_key="support",+ )+ == []+ )++ account.status = "active"+ account.save(update_fields=["status"])++ unstamped_results = get_installations_for_sandbox(+ self.team.id,+ user_id=self.user.id,+ include_personal=True,+ task_origin="support_reply",+ )+ assert unstamped_results == []++ mismatched_results = get_installations_for_sandbox(+ self.team.id,+ user_id=self.user.id,+ include_personal=True,+ task_origin="support_reply",+ task_agent_key="scout",+ )+ assert mismatched_results == []++ def test_built_in_agent_does_not_fall_back_after_delegated_credential_is_deleted(self) -> None:+ account = self._support_agent()+ server = self._create_gateway_server(+ name="Delegated",+ url="https://delegated.example.com/mcp",+ )+ self._create_installation(+ scope="shared",+ gateway_server=server,+ url=server.url,+ display_name="Shared",+ )+ delegated = self._create_installation(+ scope="personal",+ gateway_server=server,+ url=server.url,+ display_name="Delegated",+ )+ access = MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ service_account=account,+ gateway_server=server,+ installation=delegated,+ granted_by=self.user,+ )++ delegated.delete()++ access.refresh_from_db()+ assert access.installation_id is None+ assert (+ get_installations_for_sandbox(+ self.team.id,+ task_origin="support_reply",+ task_agent_key="support",+ )+ == []+ )++ def test_built_in_agent_blocked_when_admin_disables_server_for_team(self) -> None:+ account = self._support_agent()+ server = self._create_gateway_server(name="Granted", url="https://granted.example.com/mcp")+ delegated = self._create_installation(scope="personal", gateway_server=server, url=server.url)+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ service_account=account,+ gateway_server=server,+ installation=delegated,+ granted_by=self.user,+ )++ results = get_installations_for_sandbox(+ self.team.id,+ task_origin="support_reply",+ task_agent_key="support",+ )+ assert [result.id for result in results] == [str(delegated.id)]++ server.is_team_enabled = False+ server.save(update_fields=["is_team_enabled"])++ assert (+ get_installations_for_sandbox(+ self.team.id,+ task_origin="support_reply",+ task_agent_key="support",+ )+ == []+ )+def test_other_users_personal_not_returned(self) -> None:other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")self._create_installation(scope="personal", user=other_user)diff --git a/products/mcp_store/backend/test/test_gateway_tools.py b/products/mcp_store/backend/test/test_gateway_tools.pynew file mode 100644index 000000000000..7f61a0bb65f7--- /dev/null+++ b/products/mcp_store/backend/test/test_gateway_tools.py@@ -0,0 +1,152 @@+from posthog.test.base import APIBaseTest++from django.utils import timezone++from rest_framework import status++from products.mcp_store.backend.models import (+ MCPGatewayServer,+ MCPServerInstallation,+ MCPServerInstallationTool,+ MCPToolPolicy,+)+from products.mcp_store.backend.policy import SYNC_DEFAULT_APPROVAL_STATE+++class TestMCPGatewayToolPoliciesAPI(APIBaseTest):+ def test_tools_include_the_upstream_input_schema(self) -> None:+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Schema server",+ url="https://mcp.schema-test.example.com/mcp",+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ gateway_server=server,+ display_name="Schema server",+ url=server.url,+ )+ input_schema = {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ }+ MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name="search_items",+ description="Search for matching items.",+ input_schema=input_schema,+ last_seen_at=timezone.now(),+ )++ response = self.client.get(+ f"/api/projects/{self.team.id}/mcp_gateway/servers/{server.id}/tools/",+ {"scope_type": "team"},+ )++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["results"][0]["input_schema"] == input_schema++ def _server_with_tool(self, slug: str, *, legacy_state: str) -> tuple[MCPGatewayServer, MCPServerInstallation]:+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name=f"{slug} server",+ url=f"https://mcp.{slug}-test.example.com/mcp",+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ gateway_server=server,+ display_name=f"{slug} server",+ url=server.url,+ )+ MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name="search_items",+ description="Search for matching items.",+ last_seen_at=timezone.now(),+ approval_state=legacy_state,+ )+ return server, installation++ def _member_row(self, server: MCPGatewayServer) -> dict:+ response = self.client.get(+ f"/api/projects/{self.team.id}/mcp_gateway/servers/{server.id}/tools/",+ {"scope_type": "member", "scope_user_id": str(self.user.id)},+ )+ assert response.status_code == status.HTTP_200_OK+ return response.json()["results"][0]++ def test_synced_default_does_not_become_a_member_preference(self) -> None:+ """A tool nobody has touched must resolve the same for "You" as for the team.++ Tool sync stamps needs_approval on every new row. Treating that as the+ member's own choice made it beat the team baseline, so a fresh install+ showed Always Allow under Team Default and every agent, but Needs+ Approval for the signed-in member.+ """+ server, _ = self._server_with_tool("synced", legacy_state=SYNC_DEFAULT_APPROVAL_STATE)+ MCPToolPolicy.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ tool_name="search_items",+ scope_type="team",+ state="approved",+ )++ team_response = self.client.get(+ f"/api/projects/{self.team.id}/mcp_gateway/servers/{server.id}/tools/",+ {"scope_type": "team"},+ )+ assert team_response.status_code == status.HTTP_200_OK++ row = self._member_row(server)+ assert row["policy_state"] == "approved"+ assert row["decided_by"] == "team"+ assert row["policy_state"] == team_response.json()["results"][0]["policy_state"]++ def test_explicit_legacy_state_is_still_a_member_preference(self) -> None:+ """Only the synced default is ignored — a real choice still applies.++ A state the sync never writes can only have come from the member, so it+ keeps beating a laxer team ceiling, and this view has to report it or+ the UI would promise access the proxy then refuses.+ """+ server, _ = self._server_with_tool("explicit", legacy_state="do_not_use")+ MCPToolPolicy.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ tool_name="search_items",+ scope_type="team",+ state="approved",+ )++ row = self._member_row(server)+ assert row["policy_state"] == "do_not_use"+ assert row["decided_by"] == "legacy"+ # The team ceiling is still reported, so the UI can show what's available.+ assert row["team_state"] == "approved"++ def test_member_scope_row_overrides_the_legacy_state(self) -> None:+ """Choosing "Always Allow" writes a member scope row, which wins."""+ server, _ = self._server_with_tool("override", legacy_state="do_not_use")+ MCPToolPolicy.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ tool_name="search_items",+ scope_type="team",+ state="approved",+ )+ MCPToolPolicy.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ tool_name="search_items",+ scope_type="member",+ scope_user=self.user,+ state="approved",+ )++ row = self._member_row(server)+ assert row["policy_state"] == "approved"+ assert row["decided_by"] == "scope"diff --git a/products/mcp_store/backend/test/test_policy.py b/products/mcp_store/backend/test/test_policy.pynew file mode 100644index 000000000000..f083ec93aa82--- /dev/null+++ b/products/mcp_store/backend/test/test_policy.py@@ -0,0 +1,41 @@+from typing import Any++from django.test import SimpleTestCase++from parameterized import parameterized++from products.mcp_store.backend.policy import is_destructive_tool, member_preset_team_state+++class TestDestructiveToolDetection(SimpleTestCase):+ @parameterized.expand(+ [+ ("camel_case", "deleteUser", None, True),+ ("snake_case", "bulk_delete_users", None, True),+ ("kebab_case", "archive-project", None, True),+ ("substring_dropdown", "list_dropdown_options", None, False),+ ("substring_preset", "get_preset", None, False),+ ("substring_swipe", "swipe_card", None, False),+ ("hint_escalates_neutral_name", "manage_issue", {"destructiveHint": True}, True),+ ("hint_never_clears_name_match", "delete_user", {"destructiveHint": False}, True),+ ("hint_absent", "manage_issue", {}, False),+ ("hint_non_bool_ignored", "manage_issue", {"destructiveHint": "true"}, False),+ ("hint_truthy_int_ignored", "manage_issue", {"destructiveHint": 1}, False),+ ]+ )+ def test_detects_destructive_names_and_hints(+ self, _name: str, tool_name: str, annotations: dict[str, Any] | None, expected: bool+ ) -> None:+ assert is_destructive_tool(tool_name, annotations) is expected++ @parameterized.expand(+ [+ ("ask_gates_on_hint", "ask", {"destructiveHint": True}, "needs_approval"),+ ("block_gates_on_hint", "block", {"destructiveHint": True}, "do_not_use"),+ ("block_allows_without_signal", "block", None, "approved"),+ ]+ )+ def test_presets_thread_annotations_through(+ self, _name: str, preset: str, annotations: dict[str, Any] | None, expected: str+ ) -> None:+ assert member_preset_team_state(preset, "manage_issue", annotations) == expecteddiff --git a/products/mcp_store/backend/test/test_proxy.py b/products/mcp_store/backend/test/test_proxy.pyindex e568962be657..9dcbbc9ad3ba 100644--- a/products/mcp_store/backend/test/test_proxy.py+++ b/products/mcp_store/backend/test/test_proxy.py@@ -4,7 +4,9 @@ import uuidfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTestfrom unittest.mock import MagicMock, patch+from django.db import connectionfrom django.test import override_settings+from django.test.utils import CaptureQueriesContextfrom django.utils import timezoneimport httpx@@ -13,7 +15,13 @@ from rest_framework import statusfrom posthog.models import Organization, Team, User-from products.mcp_store.backend.models import MCPServerInstallation, MCPServerInstallationTool+from products.mcp_store.backend.models import (+ MCPAuditEvent,+ MCPGatewayServer,+ MCPServerInstallation,+ MCPServerInstallationTool,+ MCPToolPolicy,+)from products.mcp_store.backend.proxy import _build_sse_response@@ -712,18 +720,89 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTeassert [entry["error"]["code"] for entry in body] == [-32001, -32002]mock_client_cls.assert_not_called()+ def test_gateway_audit_query_count_does_not_grow_with_batch_size(self) -> None:+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Audited tools",+ url="https://mcp.audited-tools.example.com/mcp",+ )+ installation = self._installation()+ installation.gateway_server = server+ installation.save(update_fields=["gateway_server", "updated_at"])+ for index in range(5):+ self._tool(installation, f"pending-{index}", "needs_approval")++ single_call = {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": {"name": "pending-0"},+ }+ assert self.client.post(self._proxy_url(installation.id), data=single_call, format="json").status_code == 200+ MCPAuditEvent.objects.for_team(self.team.id).all().delete()++ with CaptureQueriesContext(connection) as single_call_queries:+ single_response = self.client.post(+ self._proxy_url(installation.id),+ data=single_call,+ format="json",+ )+ with CaptureQueriesContext(connection) as batch_call_queries:+ batch_response = self.client.post(+ self._proxy_url(installation.id),+ data=[+ {+ "jsonrpc": "2.0",+ "id": index,+ "method": "tools/call",+ "params": {"name": f"pending-{index}"},+ }+ for index in range(5)+ ],+ format="json",+ )++ assert single_response.status_code == 200+ assert batch_response.status_code == 200+ assert len(batch_call_queries.captured_queries) == len(single_call_queries.captured_queries)+ assert MCPAuditEvent.objects.for_team(self.team.id).count() == 6+@patch("products.mcp_store.backend.proxy.httpx.Client")def test_mixed_batch_rejects_whole_request_with_batch_code(self, mock_client_cls):- """Mixed batches are rejected atomically with a batch-level code, not a per-item code."""+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Audited batch",+ url="https://mcp.audited-batch.example.com/mcp",+ )installation = self._installation()+ installation.gateway_server = server+ installation.save(update_fields=["gateway_server", "updated_at"])self._tool(installation, "approved-tool", "approved")+ self._tool(installation, "auto-tool", "approved")self._tool(installation, "unapproved-tool", "needs_approval")+ MCPToolPolicy.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ tool_name="approved-tool",+ scope_type="member",+ scope_user=self.user,+ state="approved",+ )+ MCPToolPolicy.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ tool_name="unapproved-tool",+ scope_type="member",+ scope_user=self.user,+ state="needs_approval",+ )response = self.client.post(self._proxy_url(installation.id),data=[{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approved-tool"}},- {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "unapproved-tool"}},+ {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "auto-tool"}},+ {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "unapproved-tool"}},],format="json",)@@ -735,6 +814,13 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTefor entry in body:assert entry["error"]["code"] == -32000mock_client_cls.assert_not_called()+ assert list(+ MCPAuditEvent.objects.for_team(self.team.id)+ .filter(gateway_server=server)+ .values_list("tool_name", "decision")+ ) == [("unapproved-tool", "pending")]+ installation.refresh_from_db()+ assert installation.last_used_at is None@patch("products.mcp_store.backend.proxy.httpx.Client")def test_mixed_batch_with_tools_list_sibling_uses_batch_code(self, mock_client_cls):diff --git a/products/mcp_store/backend/test/test_tools.py b/products/mcp_store/backend/test/test_tools.pyindex 8dba487026b7..23d662b2d5b0 100644--- a/products/mcp_store/backend/test/test_tools.py+++ b/products/mcp_store/backend/test/test_tools.py@@ -250,6 +250,17 @@ class TestSyncInstallationTools(ClickhouseTestMixin, APIBaseTest):assert tool.description == "Search something"assert tool.removed_at is None+ @patch("products.mcp_store.backend.tools.fetch_upstream_tools")+ def test_sync_persists_upstream_annotations(self, mock_fetch):+ installation = self._installation()+ mock_fetch.return_value = [{"name": "search", "annotations": {"destructiveHint": True}}]+ sync_installation_tools(installation)+ assert installation.tools.get(tool_name="search").annotations == {"destructiveHint": True}++ mock_fetch.return_value = [{"name": "search", "annotations": {"destructiveHint": False}}]+ sync_installation_tools(installation)+ assert installation.tools.get(tool_name="search").annotations == {"destructiveHint": False}+@patch("products.mcp_store.backend.tools.fetch_upstream_tools")def test_disappeared_tool_marked_removed_state_preserved(self, mock_fetch):installation = self._installation()diff --git a/products/mcp_store/backend/tools.py b/products/mcp_store/backend/tools.pyindex 2ac47c529e47..65da2f5b7d6d 100644--- a/products/mcp_store/backend/tools.py+++ b/products/mcp_store/backend/tools.py@@ -17,6 +17,7 @@ from posthog.security.url_validation import is_url_allowedfrom .models import MCPServerInstallation, MCPServerInstallationToolfrom .oauth import TokenRefreshError, is_token_expiring, refresh_installation_token+from .policy import SYNC_DEFAULT_APPROVAL_STATEfrom .proxy import build_upstream_auth_headers, validated_same_origin_redirect_urllogger = structlog.get_logger(__name__)@@ -246,7 +247,7 @@ def sync_installation_tools(installation: MCPServerInstallation) -> list[MCPServ"""Upsert tool rows for an installation against the latest upstream ``tools/list``.- New tools are inserted with ``approval_state="needs_approval"`` (explicit opt-in).- - Existing tools keep their approval state; name/description/schema/last_seen_at are updated.+ - Existing tools keep their approval state; name/description/schema/annotations/last_seen_at are updated.- Tools that disappear upstream get ``removed_at`` set (approval state preserved for later).- Tools that reappear get ``removed_at`` cleared."""@@ -262,6 +263,7 @@ def sync_installation_tools(installation: MCPServerInstallation) -> list[MCPServdisplay_name = tool.get("title") or tool.get("displayName") or ""description = tool.get("description") or ""input_schema = tool.get("inputSchema") or {}+ annotations = tool.get("annotations") or {}row = existing_by_name.get(tool_name)if row is None:@@ -271,8 +273,11 @@ def sync_installation_tools(installation: MCPServerInstallation) -> list[MCPServdisplay_name=display_name,description=description,input_schema=input_schema,+ annotations=annotations,# New tools default to needs_approval so adoption stays explicit.- approval_state="needs_approval",+ # The policy engine keys off this exact value to tell a synced+ # default apart from a member's real choice — keep them in step.+ approval_state=SYNC_DEFAULT_APPROVAL_STATE,last_seen_at=now,removed_at=None,)@@ -280,6 +285,7 @@ def sync_installation_tools(installation: MCPServerInstallation) -> list[MCPServrow.display_name = display_namerow.description = descriptionrow.input_schema = input_schema+ row.annotations = annotationsrow.last_seen_at = now# A previously-removed tool reappeared; preserve approval_state but clear the flag.row.removed_at = None@@ -288,6 +294,7 @@ def sync_installation_tools(installation: MCPServerInstallation) -> list[MCPServ"display_name","description","input_schema",+ "annotations","last_seen_at","removed_at","updated_at",diff --git a/products/mcp_store/frontend/gateway/GatewayAgentScene.tsx b/products/mcp_store/frontend/gateway/GatewayAgentScene.tsxnew file mode 100644index 000000000000..d01ad90ce92c--- /dev/null+++ b/products/mcp_store/frontend/gateway/GatewayAgentScene.tsx@@ -0,0 +1,156 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'++import { IconSparkles } from '@posthog/icons'+import { LemonButton, LemonDivider, LemonSwitch, LemonTable, LemonTag, Spinner } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'++import { ServerIcon } from '../scene/icons'+import { gatewayAgentLogic } from './gatewayAgentLogic'+import { DecisionTag } from './gatewayUtils'+import { agentServerAccessKey } from './mcpGatewayLogic'++export const scene: SceneExport<(typeof gatewayAgentLogic)['props']> = {+ component: GatewayAgentScene,+ logic: gatewayAgentLogic,+ paramsToProps: ({ params: { id } }) => ({ id }),+}++export function GatewayAgentScene(): JSX.Element {+ const {+ account,+ accountLoading,+ accountStatusLoadingIds,+ agentServerAccessLoadingKeys,+ allServers,+ allServersLoading,+ sharedServerIds,+ recentCalls,+ recentCallsLoading,+ } = useValues(gatewayAgentLogic)+ const { setAgentServerAccess, toggleAccountStatus } = useActions(gatewayAgentLogic)++ if (!account && accountLoading) {+ return <SceneContent>Loading…</SceneContent>+ }+ if (!account) {+ return <SceneContent>Agent not found.</SceneContent>+ }++ const paused = account.status === 'paused'++ return (+ <SceneContent>+ <LemonButton size="small" onClick={() => router.actions.push(urls.mcpGatewayTab('team'))}>+ ‹ Back to team & agents+ </LemonButton>++ <div className="flex items-center gap-3">+ <div className="flex items-center justify-center bg-surface-secondary rounded w-[52px] h-[52px]">+ <IconSparkles className="text-2xl" />+ </div>+ <div className="flex-1">+ <div className="flex items-center gap-2">+ <h1 className="mb-0">{account.name}</h1>+ <LemonTag type={paused ? 'warning' : 'success'}>+ {paused ? 'MCP paused' : 'MCP enabled'}+ </LemonTag>+ </div>+ <div className="text-secondary">{account.description}</div>+ </div>+ <LemonButton+ type="secondary"+ loading={accountStatusLoadingIds.has(account.id)}+ onClick={() => toggleAccountStatus(account.id, !paused)}+ >+ {paused ? 'Resume agent' : 'Pause agent'}+ </LemonButton>+ </div>++ <LemonDivider />++ <div className="flex flex-col gap-2">+ <h3 className="mb-0">+ Shared servers{!allServersLoading && ` · ${sharedServerIds.size} of ${allServers.length}`}+ </h3>+ <div className="border rounded divide-y">+ {allServersLoading && allServers.length === 0 ? (+ <div className="flex items-center gap-2 p-3 text-sm text-secondary">+ <Spinner /> Loading shared servers…+ </div>+ ) : (+ allServers.map((server) => {+ const shared = sharedServerIds.has(server.id)+ const needsConnection = !shared && server.your_connection === null+ return (+ <div key={server.id} className="flex items-center gap-3 p-2">+ <ServerIcon iconDomain={server.icon_domain} serverUrl={server.url} size={28} />+ <div className="flex-1 min-w-0">+ <div className="font-semibold">{server.name}</div>+ <div className="text-xs text-secondary">+ {shared ? `${server.tool_count} tools` : 'Not shared'}+ </div>+ </div>+ {shared && (+ <LemonButton+ size="xsmall"+ type="secondary"+ to={urls.mcpGatewayServer(server.id, `agent:${account.id}`)}+ >+ Tool policies+ </LemonButton>+ )}+ <LemonSwitch+ checked={shared}+ loading={agentServerAccessLoadingKeys.has(+ agentServerAccessKey(account.id, server.id)+ )}+ disabledReason={+ needsConnection+ ? 'Connect this server before sharing it with an agent.'+ : undefined+ }+ aria-label={`${shared ? 'Revoke' : 'Grant'} ${account.name} access to ${server.name}`}+ onChange={(checked) => setAgentServerAccess(account.id, server.id, checked)}+ />+ </div>+ )+ })+ )}+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Recent tool calls</h3>+ <LemonTable+ dataSource={recentCalls}+ loading={recentCallsLoading}+ emptyState="No tool calls from this agent yet."+ columns={[+ {+ title: 'Time',+ dataIndex: 'created_at',+ render: (_, row) => <TZLabel time={row.created_at} />,+ },+ { title: 'MCP server', dataIndex: 'server_name' },+ {+ title: 'Tool',+ dataIndex: 'tool_name',+ render: (_, row) => <span className="font-mono text-xs">{row.tool_name}()</span>,+ },+ {+ title: 'Decision',+ dataIndex: 'decision',+ render: (_, row) => <DecisionTag decision={row.decision} />,+ },+ ]}+ />+ </div>+ </SceneContent>+ )+}diff --git a/products/mcp_store/frontend/gateway/GatewayAuditLog.tsx b/products/mcp_store/frontend/gateway/GatewayAuditLog.tsxnew file mode 100644index 000000000000..123e474e8d39--- /dev/null+++ b/products/mcp_store/frontend/gateway/GatewayAuditLog.tsx@@ -0,0 +1,96 @@+import { useActions, useValues } from 'kea'++import { IconSparkles } from '@posthog/icons'+import { LemonButton, LemonSnack, LemonTable, ProfilePicture } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'++import { AuditCountsApi } from '../generated/api.schemas'+import { AUDIT_PAGE_SIZE, AuditQuickFilter, gatewayAuditLogic } from './gatewayAuditLogic'+import { DecisionTag, toProfileUser } from './gatewayUtils'++const FILTERS: { key: AuditQuickFilter; label: string; countKey: keyof AuditCountsApi }[] = [+ { key: 'all', label: 'All activity', countKey: 'all' },+ { key: 'agents', label: 'Agents only', countKey: 'agents' },+ { key: 'approvals', label: 'Approvals', countKey: 'approvals' },+ { key: 'blocked', label: 'Blocked', countKey: 'blocked' },+]++export function GatewayAuditLog(): JSX.Element {+ const { auditResponse, auditResponseLoading, counts, quickFilter, page } = useValues(gatewayAuditLogic)+ const { setQuickFilter, setPage } = useActions(gatewayAuditLogic)++ return (+ <div className="flex flex-col gap-4">+ <div className="text-sm text-secondary">+ Every tool call routed through the gateway — each row is one call to a tool on one of your team's MCP+ servers, and how the gateway decided it.+ </div>++ <div className="flex items-center gap-2 flex-wrap">+ {FILTERS.map((filter) => (+ <LemonButton+ key={filter.key}+ size="small"+ type={quickFilter === filter.key ? 'primary' : 'tertiary'}+ onClick={() => setQuickFilter(filter.key)}+ >+ {filter.label}+ {counts && <LemonSnack className="ml-1">{counts[filter.countKey] ?? 0}</LemonSnack>}+ </LemonButton>+ ))}+ </div>++ <LemonTable+ loading={auditResponseLoading}+ dataSource={auditResponse.results}+ emptyState="No tool calls match these filters."+ pagination={{+ controlled: true,+ pageSize: AUDIT_PAGE_SIZE,+ currentPage: page,+ entryCount: auditResponse.count,+ onForward: () => setPage(page + 1),+ onBackward: () => setPage(page - 1),+ }}+ columns={[+ {+ title: 'Time',+ dataIndex: 'created_at',+ render: (_, row) => <TZLabel time={row.created_at} />,+ },+ {+ title: 'Caller',+ key: 'caller',+ render: (_, row) =>+ row.actor_service_account ? (+ <span className="flex items-center gap-1">+ <IconSparkles />+ {row.actor_service_account.name}+ </span>+ ) : row.actor_user ? (+ <ProfilePicture user={toProfileUser(row.actor_user)} size="sm" showName />+ ) : (+ <span className="text-secondary">{row.actor_label || 'Unknown'}</span>+ ),+ },+ {+ title: 'MCP server · tool',+ key: 'server',+ render: (_, row) => (+ <div>+ <div className="font-semibold text-xs">{row.server_name}</div>+ <div className="font-mono text-xs text-secondary">{row.tool_name}()</div>+ </div>+ ),+ },+ {+ title: 'Decision',+ dataIndex: 'decision',+ render: (_, row) => <DecisionTag decision={row.decision} />,+ },+ ]}+ />+ </div>+ )+}diff --git a/products/mcp_store/frontend/gateway/GatewayMemberScene.tsx b/products/mcp_store/frontend/gateway/GatewayMemberScene.tsxnew file mode 100644index 000000000000..54d2a1cc9f2a--- /dev/null+++ b/products/mcp_store/frontend/gateway/GatewayMemberScene.tsx@@ -0,0 +1,107 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'++import { LemonButton, LemonDivider, LemonSwitch, LemonTag, ProfilePicture, Spinner } from '@posthog/lemon-ui'++import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'++import { ServerIcon } from '../scene/icons'+import { gatewayMemberLogic } from './gatewayMemberLogic'+import { toProfileUser } from './gatewayUtils'+import { memberServerAccessKey } from './mcpGatewayLogic'++export const scene: SceneExport<(typeof gatewayMemberLogic)['props']> = {+ component: GatewayMemberScene,+ logic: gatewayMemberLogic,+ paramsToProps: ({ params: { id } }) => ({ id }),+}++export function GatewayMemberScene(): JSX.Element {+ const {+ allServers,+ allServersInitialized,+ member,+ memberInitialized,+ memberLoading,+ memberServerAccessLoadingKeys,+ } = useValues(gatewayMemberLogic)+ const { setMemberServerAccess } = useActions(gatewayMemberLogic)++ if (!allServersInitialized || (!member && (!memberInitialized || memberLoading))) {+ return (+ <SceneContent>+ <div className="flex items-center gap-2 text-secondary">+ <Spinner /> Loading member…+ </div>+ </SceneContent>+ )+ }+ if (!member) {+ return <SceneContent>Member not found.</SceneContent>+ }++ const connected = new Set(member.connected_server_ids)+ const revoked = new Set(member.revoked_server_ids)++ return (+ <SceneContent>+ <LemonButton size="small" onClick={() => router.actions.push(urls.mcpGatewayTab('team'))}>+ ‹ Back to team & agents+ </LemonButton>++ <div className="flex items-center gap-3">+ <ProfilePicture user={toProfileUser(member.user)} size="xl" />+ <div>+ <div className="flex items-center gap-2">+ <h1 className="mb-0">+ {member.user.first_name} {member.user.last_name}+ </h1>+ {member.is_org_admin && <LemonTag type="highlight">admin</LemonTag>}+ </div>+ <div className="text-secondary">{member.user.email}</div>+ </div>+ </div>++ <LemonDivider />++ <h3 className="mb-0">Server access</h3>+ <div className="border rounded divide-y">+ {allServers.map((server) => {+ const isRevoked = revoked.has(server.id)+ const isConnected = connected.has(server.id)+ return (+ <div key={server.id} className="flex items-center gap-3 p-2">+ <ServerIcon iconDomain={server.icon_domain} serverUrl={server.url} size={28} />+ <div className="flex-1 min-w-0">+ <div className="font-semibold">{server.name}</div>+ <div className="text-xs text-secondary">+ {isRevoked+ ? `Access turned off for ${member.user.first_name}`+ : isConnected+ ? 'Connected'+ : 'Not connected yet'}+ </div>+ </div>+ {isConnected && (+ <LemonButton size="xsmall" type="secondary" to={urls.mcpGatewayServer(server.id)}>+ Tool policies+ </LemonButton>+ )}+ <LemonSwitch+ checked={!isRevoked}+ loading={memberServerAccessLoadingKeys.has(+ memberServerAccessKey(member.user.id, server.id)+ )}+ aria-label={`${isRevoked ? 'Restore' : 'Turn off'} ${member.user.first_name || member.user.email}'s access to ${server.name}`}+ onChange={(checked) => setMemberServerAccess(member.user.id, server.id, checked)}+ />+ </div>+ )+ })}+ </div>+ </SceneContent>+ )+}diff --git a/products/mcp_store/frontend/gateway/GatewayServerAccess.tsx b/products/mcp_store/frontend/gateway/GatewayServerAccess.tsxnew file mode 100644index 000000000000..75ea10bbf1b3--- /dev/null+++ b/products/mcp_store/frontend/gateway/GatewayServerAccess.tsx@@ -0,0 +1,134 @@+import { useActions, useValues } from 'kea'++import { LemonSwitch, LemonTag, ProfilePicture, Spinner } from '@posthog/lemon-ui'++import { gatewayServerLogic } from './gatewayServerLogic'+import { toProfileUser } from './gatewayUtils'+import { agentServerAccessKey, mcpGatewayLogic } from './mcpGatewayLogic'++/** Access section on the server detail. Team and connection controls are+ * admin-only; agent grants follow the team's member-agent-access setting. */+export function GatewayAccessSection(): JSX.Element | null {+ const { server } = useValues(gatewayServerLogic)+ const {+ agentServerAccessLoadingKeys,+ allServersEnabledLoading,+ canManageAgentAccess,+ isAdmin,+ serverEnabledLoadingIds,+ serviceAccounts,+ serviceAccountsLoading,+ } = useValues(mcpGatewayLogic)+ const { toggleServerEnabled, setAgentServerAccess } = useActions(mcpGatewayLogic)++ if (!server || !canManageAgentAccess) {+ return null+ }++ const connections = server.connections ?? []++ return (+ <div className="flex flex-col gap-3">+ <h3 className="mb-0">Access</h3>++ {isAdmin && (+ <>+ <div className="border rounded p-3 flex items-center justify-between gap-3">+ <div>+ <div className="font-semibold">Available to the team</div>+ <div className="text-sm text-secondary">+ {server.is_team_enabled+ ? `Members can connect their own ${server.name} account.`+ : `Turned off. Members and agents can't see or call ${server.name}.`}+ </div>+ </div>+ <LemonSwitch+ checked={server.is_team_enabled}+ loading={allServersEnabledLoading || serverEnabledLoadingIds.has(server.id)}+ aria-label={`${server.is_team_enabled ? 'Turn off' : 'Turn on'} ${server.name} for the team`}+ onChange={(checked) => toggleServerEnabled(server.id, checked)}+ />+ </div>++ <div>+ <div className="text-xs uppercase text-secondary font-semibold mb-1">+ People connected · {connections.length}+ </div>+ {connections.length === 0 ? (+ <div className="border border-dashed rounded p-3 text-sm text-secondary">+ No one has connected yet.+ </div>+ ) : (+ <div className="border rounded divide-y">+ {connections.map((connection) => (+ <div key={connection.installation_id} className="flex items-center gap-2 p-2">+ <ProfilePicture user={toProfileUser(connection.user)} size="sm" showName />+ <div className="flex-1" />+ {connection.pending_oauth ? (+ <LemonTag type="warning">Pending</LemonTag>+ ) : connection.needs_reauth ? (+ <LemonTag type="danger">Needs reauth</LemonTag>+ ) : (+ <LemonTag type="success">Connected</LemonTag>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ </>+ )}++ <div>+ <div className="text-xs uppercase text-secondary font-semibold mb-1">+ Agents · {serviceAccounts.length}+ </div>+ <div className="text-sm text-secondary mb-2">+ {isAdmin+ ? 'Agent access is separate from team member availability.'+ : 'Share a connection available to you, then choose which tools the agent may call below.'}+ </div>+ {serviceAccountsLoading ? (+ <div className="border border-dashed rounded p-3 text-sm text-secondary flex items-center gap-2">+ <Spinner /> Loading agents…+ </div>+ ) : serviceAccounts.length === 0 ? (+ <div className="border border-dashed rounded p-3 text-sm text-secondary">+ No PostHog agents are available for this project.+ </div>+ ) : (+ <div className="border rounded divide-y">+ {serviceAccounts.map((account) => {+ const shared = account.server_ids.includes(server.id)+ const needsConnection = !shared && server.your_connection === null+ return (+ <div key={account.id} className="flex items-center gap-2 p-2">+ <div className="flex-1 min-w-0">+ <div className="font-semibold">{account.name}</div>+ <div className="text-xs text-secondary truncate">{account.description}</div>+ </div>+ <LemonTag type={account.status === 'paused' ? 'warning' : 'success'} size="small">+ {account.status === 'paused' ? 'MCP paused' : 'MCP enabled'}+ </LemonTag>+ <LemonSwitch+ checked={shared}+ loading={agentServerAccessLoadingKeys.has(+ agentServerAccessKey(account.id, server.id)+ )}+ disabledReason={+ needsConnection+ ? 'Connect this server before sharing it with an agent.'+ : undefined+ }+ aria-label={`${shared ? 'Revoke' : 'Grant'} ${account.name} access to ${server.name}`}+ onChange={(checked) => setAgentServerAccess(account.id, server.id, checked)}+ />+ </div>+ )+ })}+ </div>+ )}+ </div>+ </div>+ )+}diff --git a/products/mcp_store/frontend/gateway/GatewayServerScene.tsx b/products/mcp_store/frontend/gateway/GatewayServerScene.tsxnew file mode 100644index 000000000000..a40e8881c778--- /dev/null+++ b/products/mcp_store/frontend/gateway/GatewayServerScene.tsx@@ -0,0 +1,264 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'++import { IconLock } from '@posthog/icons'+import {+ LemonButton,+ LemonCollapse,+ LemonDivider,+ LemonSegmentedButton,+ LemonTag,+ Spinner,+ Tooltip,+} from '@posthog/lemon-ui'++import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'++import { ResolvedToolPolicyApi } from '../generated/api.schemas'+import { ServerIcon } from '../scene/icons'+import { isPolicyStateAllowedByCeiling } from './gatewayPolicyUtils'+import { GatewayAccessSection } from './GatewayServerAccess'+import { gatewayServerLogic } from './gatewayServerLogic'+import { POLICY_OPTIONS, PolicySummary } from './gatewayUtils'++export const scene: SceneExport<(typeof gatewayServerLogic)['props']> = {+ component: GatewayServerScene,+ logic: gatewayServerLogic,+ paramsToProps: ({ params: { id } }) => ({ id }),+}++export function GatewayServerScene(): JSX.Element {+ const { server, serverLoading, isAdmin, canManageAgentAccess } = useValues(gatewayServerLogic)++ if (!server && serverLoading) {+ return <SceneContent>Loading…</SceneContent>+ }+ if (!server) {+ return <SceneContent>Server not found.</SceneContent>+ }++ return (+ <SceneContent>+ <LemonButton size="small" onClick={() => router.actions.push(urls.mcpGateway())}>+ ‹ Back to servers+ </LemonButton>++ <div className="flex items-center gap-3">+ <ServerIcon iconDomain={server.icon_domain} serverUrl={server.url} size={52} />+ <div className="flex-1">+ <div className="flex items-center gap-2">+ <h1 className="mb-0">{server.name}</h1>+ {isAdmin && !server.is_team_enabled && <LemonTag type="muted">Off</LemonTag>}+ </div>+ <div className="text-secondary">{server.description || server.url}</div>+ </div>+ </div>++ <LemonDivider />++ {canManageAgentAccess && <GatewayAccessSection />}++ <ToolPoliciesSection />+ </SceneContent>+ )+}++function ToolPoliciesSection(): JSX.Element {+ const {+ toolPolicies,+ toolPoliciesLoading,+ policyCounts,+ scope,+ scopeIsResolving,+ availableScopes,+ isAdmin,+ canManageAgentAccess,+ } = useValues(gatewayServerLogic)+ const { setScope, setAllTools } = useActions(gatewayServerLogic)+ const canEditScope =+ isAdmin || scope.scopeType === 'member' || (scope.scopeType === 'agent' && canManageAgentAccess)++ if (scopeIsResolving) {+ return (+ <div className="border border-dashed rounded p-4 text-sm text-secondary flex items-center gap-2">+ <Spinner /> Loading agent tool policies…+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-3">+ <div className="flex items-center justify-between flex-wrap gap-2">+ <div className="flex items-center gap-2">+ <h3 className="mb-0">Tool policies</h3>+ <PolicySummary counts={policyCounts} />+ </div>+ {canEditScope && (+ <div className="flex items-center gap-1">+ <span className="text-xs text-secondary mr-1">Set all</span>+ {POLICY_OPTIONS.map((option) => (+ <LemonButton+ key={option.value}+ size="xsmall"+ icon={option.icon}+ tooltip={option.label}+ loading={toolPoliciesLoading}+ onClick={() => setAllTools({ state: option.value })}+ />+ ))}+ </div>+ )}+ </div>++ {canManageAgentAccess && availableScopes.length > 1 && (+ <div className="flex items-center gap-2 flex-wrap">+ <span className="text-xs text-secondary">Policy for</span>+ <LemonSegmentedButton+ size="small"+ value={scope.scopeServiceAccountId ?? scope.scopeType}+ options={availableScopes.map((candidate) => ({+ value: candidate.scopeServiceAccountId ?? candidate.scopeType,+ label: candidate.label,+ }))}+ disabledReason={toolPoliciesLoading ? 'Updating tool policies…' : undefined}+ onChange={(value) => {+ const next = availableScopes.find(+ (candidate) => (candidate.scopeServiceAccountId ?? candidate.scopeType) === value+ )+ if (next) {+ setScope(next)+ }+ }}+ />+ </div>+ )}++ {toolPolicies.length === 0 && !toolPoliciesLoading ? (+ <div className="border border-dashed rounded p-6 text-center text-secondary text-sm">+ No tools discovered yet. Connect the server and refresh its tools.+ </div>+ ) : (+ <div className="border rounded divide-y">+ {toolPolicies.map((policy) => (+ <ToolPolicyRow key={policy.tool_name} policy={policy} />+ ))}+ </div>+ )}+ </div>+ )+}++function ToolPolicyRow({ policy }: { policy: ResolvedToolPolicyApi }): JSX.Element {+ const { server, scope, isAdmin, canManageAgentAccess, toolPoliciesLoading } = useValues(gatewayServerLogic)+ const { setToolPolicy } = useActions(gatewayServerLogic)++ const fqName = `${server?.name ?? ''}.${policy.tool_name}`+ const ruleLocked = policy.decided_by === 'rule'+ const setByTeamAdmin =+ scope.scopeType !== 'team' && (policy.decided_by === 'team' || policy.decided_by === 'preset')+ const canEditScope =+ isAdmin || scope.scopeType === 'member' || (scope.scopeType === 'agent' && canManageAgentAccess)+ const options = POLICY_OPTIONS.map((option) => ({+ ...option,+ disabledReason:+ scope.scopeType === 'team' || isPolicyStateAllowedByCeiling(option.value, policy.team_state)+ ? undefined+ : 'Unavailable because of the team admin ceiling',+ }))++ return (+ <LemonCollapse+ embedded+ panels={[+ {+ key: policy.tool_name,+ header: (+ <div className="flex items-center justify-between gap-3 w-full pr-2">+ <div className="min-w-0">+ <div+ className={`font-mono text-sm ${+ policy.policy_state === 'do_not_use' ? 'line-through text-secondary' : ''+ }`}+ >+ {fqName}+ </div>+ <div className="text-xs text-secondary truncate italic">+ {policy.description || 'No description provided'}+ </div>+ </div>+ <div+ className="shrink-0"+ onClick={(e) => e.stopPropagation()}+ onKeyDown={(e) => e.stopPropagation()}+ role="presentation"+ >+ {ruleLocked || !canEditScope ? (+ <Tooltip+ title={+ ruleLocked+ ? `${policy.rule_name} — team rule, overrides every scope.`+ : 'This policy is read-only.'+ }+ >+ <LemonTag icon={<IconLock />} type="muted">+ {ruleLocked+ ? policy.policy_state === 'do_not_use'+ ? 'Blocked by team policy'+ : 'Needs Approval by team policy'+ : POLICY_OPTIONS.find((option) => option.value === policy.policy_state)+ ?.label}+ </LemonTag>+ </Tooltip>+ ) : (+ <div className="flex items-center gap-2">+ {setByTeamAdmin && (+ <Tooltip title="This effective state is capped by the team admin ceiling.">+ <LemonTag icon={<IconLock />} type="muted">+ Set by team admin+ </LemonTag>+ </Tooltip>+ )}+ <LemonSegmentedButton+ size="xsmall"+ value={policy.policy_state}+ options={options}+ disabledReason={+ toolPoliciesLoading+ ? 'Updating tool policies…'+ : policy.locked+ ? 'The team admin ceiling is Blocked.'+ : undefined+ }+ onChange={(value) =>+ setToolPolicy({ toolName: policy.tool_name, state: value })+ }+ />+ </div>+ )}+ </div>+ </div>+ ),+ content: (+ <div className="text-sm flex flex-col gap-2">+ <div>+ <div className="text-xs uppercase text-secondary font-semibold">Description</div>+ <div className="italic">{policy.description || 'No description provided'}</div>+ </div>+ {ruleLocked && (+ <div>+ <div className="text-xs uppercase text-secondary font-semibold">Applied rule</div>+ <div>+ {policy.rule_name} — {policy.rule_description}+ </div>+ </div>+ )}+ </div>+ ),+ },+ ]}+ />+ )+}diff --git a/products/mcp_store/frontend/gateway/GatewayServersHome.tsx b/products/mcp_store/frontend/gateway/GatewayServersHome.tsxnew file mode 100644index 000000000000..c32d28ce3d84--- /dev/null+++ b/products/mcp_store/frontend/gateway/GatewayServersHome.tsx@@ -0,0 +1,336 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'++import { IconGear } from '@posthog/icons'+import {+ LemonButton,+ LemonCollapse,+ LemonInput,+ LemonModal,+ LemonSelect,+ LemonSnack,+ LemonTag,+ ProfilePicture,+ Spinner,+ Tooltip,+} from '@posthog/lemon-ui'++import { LemonField } from 'lib/lemon-ui/LemonField'+import { urls } from 'scenes/urls'++import { InstallCustomAuthTypeEnumApi } from '../generated/api.schemas'+import { ServerIcon } from '../scene/icons'+import { toProfileUser } from './gatewayUtils'+import { GATEWAY_CATEGORY_LABELS, GatewayServerEntry, isTemplateOnlyServer, mcpGatewayLogic } from './mcpGatewayLogic'++const AUTH_TYPE_OPTIONS = [+ { value: 'oauth' as const, label: 'OAuth' },+ { value: 'api_key' as const, label: 'API key' },+]++export function GatewayServersHome(): JSX.Element {+ const { filteredServers, serversLoading, searchQuery, categoryFilter, categoryCounts, isAdmin, mergedServers } =+ useValues(mcpGatewayLogic)+ const { setSearchQuery, setCategoryFilter } = useActions(mcpGatewayLogic)++ const categories = Object.keys(GATEWAY_CATEGORY_LABELS).filter((category) => categoryCounts[category])++ return (+ <div className="flex flex-col gap-4">+ <GatewayConnectionModal />++ <div className="flex items-center gap-2 flex-wrap">+ <LemonInput+ type="search"+ placeholder="Search team servers…"+ value={searchQuery}+ onChange={setSearchQuery}+ className="max-w-md"+ />+ </div>++ <div className="flex items-center gap-2 flex-wrap">+ <LemonButton+ size="small"+ type={categoryFilter === null ? 'primary' : 'tertiary'}+ onClick={() => setCategoryFilter(null)}+ >+ All <LemonSnack className="ml-1">{mergedServers.length}</LemonSnack>+ </LemonButton>+ {categories.map((category) => (+ <LemonButton+ key={category}+ size="small"+ type={categoryFilter === category ? 'primary' : 'tertiary'}+ onClick={() => setCategoryFilter(category)}+ >+ {GATEWAY_CATEGORY_LABELS[category]}{' '}+ <LemonSnack className="ml-1">{categoryCounts[category]}</LemonSnack>+ </LemonButton>+ ))}+ </div>++ {filteredServers.length === 0 && !serversLoading ? (+ <div className="border border-dashed rounded p-8 text-center text-secondary">+ <p className="font-semibold mb-1">No servers match.</p>+ <p className="text-sm">+ {isAdmin+ ? 'Connect a server, or clear the search.'+ : 'Try a different search, or ask an admin to add a server.'}+ </p>+ </div>+ ) : (+ <div className="flex flex-col gap-2">+ {filteredServers.map((server) => (+ <GatewayServerCard key={server.id} server={server} />+ ))}+ </div>+ )}+ </div>+ )+}++function GatewayServerCard({ server }: { server: GatewayServerEntry }): JSX.Element {+ const { isAdmin, connectingServerId, canAddServers } = useValues(mcpGatewayLogic)+ const { connectServer } = useActions(mcpGatewayLogic)++ // Catalog templates without a registry row: connect-only, no detail scene.+ const recommended = isTemplateOnlyServer(server)+ const connected = Boolean(server.your_connection)+ const connecting = connectingServerId === server.id+ const disabled = !server.is_team_enabled+ const canConnectIndividual = !connected+ const connectionDisabledReason =+ recommended && disabled+ ? 'Catalog servers are turned off for this team. An admin can enable them in Team settings.'+ : !recommended && !server.template_id && !canAddServers+ ? 'Only project admins can connect custom servers for this team.'+ : undefined++ return (+ <div+ className="border rounded p-3 flex items-center gap-3 hover:border-accent transition-colors"+ // Admins see disabled servers dimmed with an "Off" pill.+ style={disabled ? { opacity: 0.6 } : undefined}+ >+ <div className="shrink-0">+ <ServerIcon iconDomain={server.icon_domain} serverUrl={server.url} size={42} />+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ {recommended ? (+ <span className="font-semibold">{server.name}</span>+ ) : (+ <button+ className="font-semibold text-left hover:text-accent"+ onClick={() => router.actions.push(urls.mcpGatewayServer(server.id))}+ >+ {server.name}+ </button>+ )}+ {recommended && <LemonTag type="highlight">Recommended</LemonTag>}+ {connected && <LemonTag type="success">Connected</LemonTag>}+ {disabled && (+ <Tooltip+ title={+ recommended+ ? 'Catalog servers are turned off for this team. An admin can enable them in Team settings.'+ : undefined+ }+ >+ <LemonTag type="muted">Off</LemonTag>+ </Tooltip>+ )}+ </div>+ <div className="text-sm text-secondary truncate">{server.description || server.url}</div>+ {isAdmin && !recommended && <PeopleRow server={server} />}+ </div>+ <div className="shrink-0">+ {canConnectIndividual ? (+ connecting ? (+ <LemonButton size="small" disabledReason="Authorizing…" icon={<Spinner />}>+ Authorizing…+ </LemonButton>+ ) : (+ <LemonButton+ size="small"+ type="secondary"+ onClick={() => connectServer(server.id)}+ disabledReason={connectionDisabledReason}+ >+ Connect+ </LemonButton>+ )+ ) : (+ <LemonButton+ size="small"+ icon={<IconGear />}+ onClick={() => router.actions.push(urls.mcpGatewayServer(server.id))}+ />+ )}+ </div>+ </div>+ )+}++function GatewayConnectionModal(): JSX.Element | null {+ const {+ connectionModalServer,+ connectionAuthType,+ connectionApiKey,+ connectionClientId,+ connectionClientSecret,+ connectingServerId,+ connectionSubmitDisabledReason,+ } = useValues(mcpGatewayLogic)+ const {+ closeConnectionModal,+ setConnectionAuthType,+ setConnectionApiKey,+ setConnectionClientId,+ setConnectionClientSecret,+ submitConnection,+ } = useActions(mcpGatewayLogic)++ if (!connectionModalServer) {+ return null+ }++ const isCustomServer = !connectionModalServer.template_id+ const connecting = connectingServerId === connectionModalServer.id+ const closeModal = (): void => {+ if (!connecting) {+ closeConnectionModal()+ }+ }++ return (+ <LemonModal+ isOpen+ onClose={closeModal}+ title={`Connect ${connectionModalServer.name}`}+ description={+ isCustomServer+ ? 'Choose how this server authenticates, then enter your personal credentials.'+ : 'Enter the credentials for your personal connection.'+ }+ footer={+ <div className="flex items-center justify-end gap-2">+ <LemonButton+ type="secondary"+ onClick={closeModal}+ disabledReason={connecting ? 'Connection in progress' : undefined}+ >+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ htmlType="submit"+ form="mcp-gateway-connect-server-form"+ loading={connecting}+ disabledReason={connectionSubmitDisabledReason ?? undefined}+ >+ Connect+ </LemonButton>+ </div>+ }+ width={560}+ >+ <form+ id="mcp-gateway-connect-server-form"+ className="flex flex-col gap-3"+ onSubmit={(event) => {+ event.preventDefault()+ if (!connecting && !connectionSubmitDisabledReason) {+ submitConnection()+ }+ }}+ >+ {isCustomServer && (+ <LemonField.Pure label="Authentication">+ <LemonSelect<InstallCustomAuthTypeEnumApi>+ value={connectionAuthType}+ onChange={setConnectionAuthType}+ options={AUTH_TYPE_OPTIONS}+ fullWidth+ />+ </LemonField.Pure>+ )}++ {connectionAuthType === 'api_key' ? (+ <LemonField.Pure label="API key">+ <LemonInput+ type="password"+ value={connectionApiKey}+ onChange={setConnectionApiKey}+ placeholder="Enter API key"+ autoFocus+ fullWidth+ />+ </LemonField.Pure>+ ) : (+ isCustomServer && (+ <LemonCollapse+ panels={[+ {+ key: 'oauth-settings',+ header: 'Advanced OAuth settings',+ content: (+ <div className="flex flex-col gap-3">+ <LemonField.Pure+ label="OAuth client ID"+ help="Leave blank to let PostHog register a client for you."+ >+ <LemonInput+ value={connectionClientId}+ onChange={setConnectionClientId}+ placeholder="Optional"+ fullWidth+ />+ </LemonField.Pure>+ <LemonField.Pure+ label="OAuth client secret"+ help="Only needed for confidential clients."+ >+ <LemonInput+ type="password"+ value={connectionClientSecret}+ onChange={setConnectionClientSecret}+ placeholder="Optional"+ fullWidth+ />+ </LemonField.Pure>+ </div>+ ),+ },+ ]}+ />+ )+ )}+ </form>+ </LemonModal>+ )+}++function PeopleRow({ server }: { server: GatewayServerEntry }): JSX.Element {+ if (!server.is_team_enabled) {+ return <div className="text-xs text-secondary mt-1">Disabled — enable it in Team settings</div>+ }+ const connections = server.connections ?? []+ const agentCount = (server.agents ?? []).length+ return (+ <div className="flex items-center gap-2 text-xs text-secondary mt-1">+ <div className="flex -space-x-1">+ {connections.slice(0, 4).map((connection) => (+ <ProfilePicture key={connection.installation_id} user={toProfileUser(connection.user)} size="xs" />+ ))}+ </div>+ <span>+ {connections.length === 0+ ? 'No one connected yet'+ : `${connections.length} teammate${connections.length === 1 ? '' : 's'} connected`}+ {agentCount > 0 && ` · ${agentCount} agent${agentCount === 1 ? '' : 's'}`}+ </span>+ </div>+ )+}diff --git a/products/mcp_store/frontend/gateway/GatewayTeamAndAgents.tsx b/products/mcp_store/frontend/gateway/GatewayTeamAndAgents.tsxnew file mode 100644index 000000000000..4d0180745620--- /dev/null+++ b/products/mcp_store/frontend/gateway/GatewayTeamAndAgents.tsx@@ -0,0 +1,114 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'++import { IconSparkles } from '@posthog/icons'+import { LemonSwitch, LemonTable, LemonTag, ProfilePicture, Spinner } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { toProfileUser } from './gatewayUtils'+import { GATEWAY_MEMBERS_PAGE_SIZE, mcpGatewayLogic } from './mcpGatewayLogic'++export function GatewayTeamAndAgents(): JSX.Element {+ const {+ serviceAccounts,+ members,+ memberCount,+ membersOffset,+ serviceAccountsLoading,+ membersLoading,+ accountStatusLoadingIds,+ } = useValues(mcpGatewayLogic)+ const { setMembersOffset, toggleAccountStatus } = useActions(mcpGatewayLogic)+ const membersPage = Math.floor(membersOffset / GATEWAY_MEMBERS_PAGE_SIZE) + 1++ return (+ <div className="flex flex-col gap-6">+ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Agents · {serviceAccounts.length}</h3>++ <div className="border rounded divide-y">+ {serviceAccountsLoading ? (+ <div className="p-4 text-sm text-secondary flex items-center gap-2">+ <Spinner /> Loading agents…+ </div>+ ) : serviceAccounts.length === 0 ? (+ <div className="p-4 text-sm text-secondary">+ No PostHog agents are available for this project.+ </div>+ ) : (+ serviceAccounts.map((account) => (+ <div key={account.id} className="flex items-center gap-3 p-3">+ <div className="flex items-center justify-center bg-surface-secondary rounded w-9 h-9">+ <IconSparkles />+ </div>+ <button+ className="flex-1 text-left"+ onClick={() => router.actions.push(urls.mcpGatewayAgent(account.id))}+ >+ <div className="font-semibold hover:text-accent">{account.name}</div>+ <div className="text-xs text-secondary">+ {account.server_ids.length} server{account.server_ids.length === 1 ? '' : 's'}+ </div>+ </button>+ <div className="flex items-center justify-end gap-1 flex-wrap">+ <LemonTag type={account.status === 'paused' ? 'warning' : 'success'} size="small">+ {account.status === 'paused' ? 'MCP paused' : 'MCP enabled'}+ </LemonTag>+ </div>+ <LemonSwitch+ checked={account.status === 'active'}+ loading={accountStatusLoadingIds.has(account.id)}+ aria-label={`${account.status === 'active' ? 'Pause' : 'Resume'} ${account.name}`}+ onChange={(checked) => toggleAccountStatus(account.id, !checked)}+ />+ </div>+ ))+ )}+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Members · {memberCount}</h3>+ <LemonTable+ loading={membersLoading}+ dataSource={members}+ emptyState="No members found."+ pagination={{+ controlled: true,+ currentPage: membersPage,+ entryCount: memberCount,+ pageSize: GATEWAY_MEMBERS_PAGE_SIZE,+ onForward: () => setMembersOffset(membersOffset + GATEWAY_MEMBERS_PAGE_SIZE),+ onBackward: () => setMembersOffset(membersOffset - GATEWAY_MEMBERS_PAGE_SIZE),+ useUrl: false,+ }}+ onRow={(member) => ({+ onClick: () => router.actions.push(urls.mcpGatewayMember(member.user.id)),+ className: 'cursor-pointer',+ })}+ columns={[+ {+ title: 'Member',+ key: 'member',+ render: (_, member) => (+ <ProfilePicture user={toProfileUser(member.user)} size="md" showName />+ ),+ },+ {+ title: 'Role',+ key: 'role',+ render: (_, member) =>+ member.is_org_admin ? <LemonTag type="highlight">admin</LemonTag> : 'member',+ },+ {+ title: 'Personal connections',+ key: 'servers',+ render: (_, member) => member.connected_server_ids.length,+ },+ ]}+ />+ </div>+ </div>+ )+}diff --git a/products/mcp_store/frontend/gateway/GatewayTeamSettings.tsx b/products/mcp_store/frontend/gateway/GatewayTeamSettings.tsxnew file mode 100644index 000000000000..1c75edc713f8--- /dev/null+++ b/products/mcp_store/frontend/gateway/GatewayTeamSettings.tsx@@ -0,0 +1,240 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { LemonButton, LemonDivider, LemonInput, LemonSwitch } from '@posthog/lemon-ui'++import { MCPPolicyPresetEnumApi } from '../generated/api.schemas'+import { AudienceEnumApi } from '../generated/api.schemas'+import { ServerIcon } from '../scene/icons'+import { GatewayServerEntry, isTemplateOnlyServer, mcpGatewayLogic } from './mcpGatewayLogic'++const PRESETS: { value: MCPPolicyPresetEnumApi; label: string; description: string }[] = [+ { value: 'allow', label: 'Allow all', description: 'Every tool is set to Always Allow.' },+ { value: 'user', label: 'Member decides', description: 'Every call asks first.' },+ { value: 'ask', label: 'Ask for destructive', description: 'Destructive tools need approval, rest Always Allow.' },+ { value: 'block', label: 'Block destructive', description: 'Destructive tools are Blocked, rest Always Allow.' },+]++export function GatewayTeamSettings(): JSX.Element {+ const {+ allServersEnabledLoading,+ allowCustomServers,+ allowCustomServersLoading,+ allowMemberAgentAccess,+ allowMemberAgentAccessLoading,+ applyingPresetByAudience,+ config,+ defaultServersEnabled,+ enabledServerCount,+ mergedServers,+ serverEnabledLoadingIds,+ templateEnabledLoadingIds,+ } = useValues(mcpGatewayLogic)+ const { setAllowCustomServers, setAllowMemberAgentAccess, applyPreset, setAllServersEnabled } =+ useActions(mcpGatewayLogic)+ const [serverSearch, setServerSearch] = useState('')++ const filteredServers = mergedServers.filter((server) =>+ server.name.toLowerCase().includes(serverSearch.trim().toLowerCase())+ )+ const presetUpdateInProgress = Object.keys(applyingPresetByAudience).length > 0++ return (+ <div className="flex flex-col gap-6">+ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Custom servers</h3>+ <div className="border rounded p-3 flex items-center justify-between gap-3">+ <div>+ <div className="font-semibold">Allow custom servers</div>+ <div className="text-sm text-secondary">+ Members can add their own MCP servers, the same way admins do. Team rules and baselines+ still apply.+ </div>+ </div>+ <LemonSwitch+ checked={allowCustomServers}+ loading={allowCustomServersLoading}+ aria-label={`${allowCustomServers ? 'Disable' : 'Enable'} custom MCP servers`}+ onChange={setAllowCustomServers}+ />+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Agent access</h3>+ <div className="border rounded p-3 flex items-center justify-between gap-3">+ <div>+ <div className="font-semibold">Allow members to manage agent access</div>+ <div className="text-sm text-secondary">+ Members can share connections with PostHog agents and choose which tools those agents may+ call. Turn this off to make those controls admin-only.+ </div>+ </div>+ <LemonSwitch+ checked={allowMemberAgentAccess}+ loading={allowMemberAgentAccessLoading}+ aria-label={`${allowMemberAgentAccess ? 'Disable' : 'Enable'} member-managed agent access`}+ onChange={setAllowMemberAgentAccess}+ />+ </div>+ </div>++ <div className="flex flex-col gap-3">+ <h3 className="mb-0">Policy baselines</h3>+ {(['members', 'agents'] as AudienceEnumApi[]).map((audience) => {+ const current =+ audience === 'members' ? config?.member_default_preset : config?.agent_default_preset+ const applyingPreset = applyingPresetByAudience[audience]+ return (+ <div key={audience} className="border rounded p-3 flex flex-col gap-2">+ <div className="font-semibold capitalize">{audience}</div>+ <div className="flex gap-2 flex-wrap">+ {PRESETS.map((preset) => (+ <LemonButton+ key={preset.value}+ size="small"+ type={current === preset.value ? 'primary' : 'secondary'}+ tooltip={preset.description}+ loading={applyingPreset === preset.value}+ disabledReason={+ presetUpdateInProgress+ ? 'Wait for the baseline update to finish'+ : undefined+ }+ onClick={() => applyPreset(audience, preset.value)}+ >+ {preset.label}+ </LemonButton>+ ))}+ </div>+ </div>+ )+ })}+ </div>++ <LemonDivider />++ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <h3 className="mb-0">+ Server access · {enabledServerCount} of {mergedServers.length} enabled+ </h3>+ <LemonInput+ type="search"+ placeholder="Search servers…"+ value={serverSearch}+ onChange={setServerSearch}+ size="small"+ />+ </div>+ <div className="border rounded p-3 flex items-center justify-between gap-3">+ <div>+ <div className="font-semibold">All servers</div>+ <div className="text-sm text-secondary">+ Turning this off disables every server, including catalog servers PostHog adds later.+ Turning it on enables them all. You can still switch individual servers below.+ </div>+ </div>+ <LemonSwitch+ checked={defaultServersEnabled}+ loading={allServersEnabledLoading}+ disabledReason={+ serverEnabledLoadingIds.size > 0 || templateEnabledLoadingIds.size > 0+ ? 'Wait for the server update to finish'+ : undefined+ }+ aria-label={`${defaultServersEnabled ? 'Disable' : 'Enable'} all MCP servers for the team`}+ onChange={setAllServersEnabled}+ />+ </div>+ <div className="text-sm text-secondary">+ Switching a server off blocks members and agents alike. Servers no one has touched follow the "All+ servers" default above.+ </div>+ <div className="border rounded divide-y">+ {filteredServers.map((server) => (+ <GatewayServerAccessRow key={server.id} server={server} />+ ))}+ {filteredServers.length === 0 && (+ <div className="p-3 text-sm text-secondary">+ {mergedServers.length === 0+ ? 'No servers configured for this team yet.'+ : `No servers match “${serverSearch.trim()}”.`}+ </div>+ )}+ </div>+ </div>++ <GatewayRulesSection />+ </div>+ )+}++function GatewayServerAccessRow({ server }: { server: GatewayServerEntry }): JSX.Element {+ const { allServersEnabledLoading, serverEnabledLoadingIds, templateEnabledLoadingIds } = useValues(mcpGatewayLogic)+ const { toggleServerEnabled, setTemplateEnabled } = useActions(mcpGatewayLogic)++ // Untouched catalog templates have no registry row yet: toggling one+ // materializes it through set_template_enabled instead of a PATCH.+ const templateOnly = isTemplateOnlyServer(server)+ const loading =+ allServersEnabledLoading ||+ (templateOnly && server.template_id+ ? templateEnabledLoadingIds.has(server.template_id)+ : serverEnabledLoadingIds.has(server.id))++ return (+ <div className="flex items-center gap-3 p-2">+ <ServerIcon iconDomain={server.icon_domain} serverUrl={server.url} size={28} />+ <div className="flex-1 min-w-0">+ <div className="font-semibold">{server.name}</div>+ <div className="text-xs text-secondary truncate">{server.url}</div>+ </div>+ <LemonSwitch+ checked={server.is_team_enabled}+ loading={loading}+ aria-label={`${server.is_team_enabled ? 'Turn off' : 'Turn on'} ${server.name} for the team`}+ onChange={(checked) =>+ templateOnly && server.template_id+ ? setTemplateEnabled(server.template_id, checked)+ : toggleServerEnabled(server.id, checked)+ }+ />+ </div>+ )+}++function GatewayRulesSection(): JSX.Element {+ const { ruleEnabledLoadingIds, rules, rulesLoading } = useValues(mcpGatewayLogic)+ const { toggleRuleEnabled } = useActions(mcpGatewayLogic)++ return (+ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Org rules</h3>+ <div className="text-sm text-secondary">+ Guardrails evaluated before any scope policy. A matching enabled rule locks the tool for its audience —+ no scope can loosen it.+ </div>+ <div className="border rounded divide-y">+ {rules.length === 0 && !rulesLoading ? (+ <div className="p-3 text-sm text-secondary">No org rules yet.</div>+ ) : (+ rules.map((rule) => (+ <div key={rule.id} className="flex items-center gap-3 p-3">+ <div className="flex-1">+ <div className="font-semibold">{rule.name}</div>+ <div className="text-xs text-secondary">{rule.description}</div>+ </div>+ <LemonSwitch+ checked={rule.enabled ?? true}+ loading={ruleEnabledLoadingIds.has(rule.id)}+ aria-label={`${(rule.enabled ?? true) ? 'Disable' : 'Enable'} ${rule.name}`}+ onChange={(checked) => toggleRuleEnabled(rule.id, checked)}+ />+ </div>+ ))+ )}+ </div>+ </div>+ )+}diff --git a/products/mcp_store/frontend/gateway/McpGatewayScene.tsx b/products/mcp_store/frontend/gateway/McpGatewayScene.tsxnew file mode 100644index 000000000000..99807ab01755--- /dev/null+++ b/products/mcp_store/frontend/gateway/McpGatewayScene.tsx@@ -0,0 +1,76 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonTabs } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { sceneConfigurations } from 'scenes/scenes'+import { Scene, SceneExport } from 'scenes/sceneTypes'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'++import { GatewayAuditLog } from './GatewayAuditLog'+import { GatewayServersHome } from './GatewayServersHome'+import { GatewayTeamAndAgents } from './GatewayTeamAndAgents'+import { GatewayTeamSettings } from './GatewayTeamSettings'+import { mcpGatewayLogic } from './mcpGatewayLogic'+import { GatewayTab, mcpGatewaySceneLogic } from './mcpGatewaySceneLogic'++export const scene: SceneExport = {+ component: McpGatewayScene,+ logic: mcpGatewaySceneLogic,+}++const TAB_LABELS: Record<GatewayTab, string> = {+ servers: 'Servers',+ team: 'Team & agents',+ settings: 'Team settings',+ audit: 'Audit log',+}++export function McpGatewayScene(): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)+ const { activeTab, availableTabs } = useValues(mcpGatewaySceneLogic)+ const { setTab } = useActions(mcpGatewaySceneLogic)+ const { isAdmin } = useValues(mcpGatewayLogic)++ if (!featureFlags[FEATURE_FLAGS.MCP_GATEWAY]) {+ return (+ <SceneContent>+ <LemonBanner type="warning">The MCP gateway is not enabled for this project.</LemonBanner>+ </SceneContent>+ )+ }++ const tabContent: Record<GatewayTab, JSX.Element> = {+ servers: <GatewayServersHome />,+ team: <GatewayTeamAndAgents />,+ settings: <GatewayTeamSettings />,+ audit: <GatewayAuditLog />,+ }++ return (+ <SceneContent>+ <SceneTitleSection+ name={sceneConfigurations[Scene.McpGateway].name}+ description="Every MCP server your team runs through the gateway. Route people and agents through one control plane."+ resourceType={{ type: sceneConfigurations[Scene.McpGateway].iconType || 'default_icon_type' }}+ />+ {isAdmin ? (+ <LemonTabs+ activeKey={activeTab}+ onChange={(key) => setTab(key)}+ sceneInset+ tabs={availableTabs.map((tab) => ({+ key: tab,+ label: TAB_LABELS[tab],+ content: tabContent[tab],+ }))}+ />+ ) : (+ <GatewayServersHome />+ )}+ </SceneContent>+ )+}diff --git a/products/mcp_store/frontend/gateway/gatewayAgentLogic.ts b/products/mcp_store/frontend/gateway/gatewayAgentLogic.tsnew file mode 100644index 000000000000..b7fcb8c80c04--- /dev/null+++ b/products/mcp_store/frontend/gateway/gatewayAgentLogic.ts@@ -0,0 +1,145 @@+import { MakeLogicType, afterMount, connect, kea, key, path, props, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { Breadcrumb } from '~/types'++import { mcpGatewayAuditList } from '../generated/api'+import { MCPAuditEventApi, MCPGatewayServerApi, MCPServiceAccountApi } from '../generated/api.schemas'+import { mcpGatewayLogic } from './mcpGatewayLogic'++export interface GatewayAgentLogicProps {+ id: string+}++function currentProjectId(): string {+ return String(teamLogic.values.currentTeamId)+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayAgentLogicValues {+ accountLoading: boolean // mcpGatewayLogic+ accountStatusLoadingIds: Set<string> // mcpGatewayLogic+ agentServerAccessLoadingKeys: Set<string> // mcpGatewayLogic+ allServers: MCPGatewayServerApi[] // mcpGatewayLogic+ allServersLoading: boolean // mcpGatewayLogic+ serviceAccounts: MCPServiceAccountApi[] // mcpGatewayLogic+ account: MCPServiceAccountApi | null+ breadcrumbs: Breadcrumb[]+ recentCalls: MCPAuditEventApi[]+ recentCallsLoading: boolean+ sharedServerIds: Set<string>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayAgentLogicActions {+ setAgentServerAccess: (+ accountId: string,+ serverId: string,+ enabled: boolean+ ) => {+ accountId: string+ enabled: boolean+ serverId: string+ } // mcpGatewayLogic+ toggleAccountStatus: (+ accountId: string,+ paused: boolean+ ) => {+ accountId: string+ paused: boolean+ } // mcpGatewayLogic+ loadRecentCalls: () => any+ loadRecentCallsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRecentCallsSuccess: (+ recentCalls: MCPAuditEventApi[],+ payload?: any+ ) => {+ recentCalls: MCPAuditEventApi[]+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayAgentLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ account: (serviceAccounts: MCPServiceAccountApi[], arg: any) => MCPServiceAccountApi | null+ breadcrumbs: (account: MCPServiceAccountApi | null) => Breadcrumb[]+ sharedServerIds: (account: MCPServiceAccountApi | null) => Set<string>+ }+}++export type gatewayAgentLogicType = MakeLogicType<+ gatewayAgentLogicValues,+ gatewayAgentLogicActions,+ GatewayAgentLogicProps,+ gatewayAgentLogicMeta+>++export const gatewayAgentLogic = kea<gatewayAgentLogicType>([+ path((key) => ['products', 'mcp_store', 'frontend', 'gateway', 'gatewayAgentLogic', key]),+ props({} as GatewayAgentLogicProps),+ key((props) => props.id),++ connect(() => ({+ values: [+ mcpGatewayLogic,+ [+ 'accountStatusLoadingIds',+ 'agentServerAccessLoadingKeys',+ 'servers as allServers',+ 'serversLoading as allServersLoading',+ 'serviceAccounts',+ 'serviceAccountsLoading as accountLoading',+ ],+ ],+ actions: [mcpGatewayLogic, ['setAgentServerAccess', 'toggleAccountStatus']],+ })),++ loaders(({ props }) => ({+ recentCalls: [+ [] as MCPAuditEventApi[],+ {+ loadRecentCalls: async () => {+ const response = await mcpGatewayAuditList(currentProjectId(), {+ actor_service_account_id: props.id,+ limit: 10,+ })+ return response.results+ },+ },+ ],+ })),++ selectors({+ account: [+ (s) => [s.serviceAccounts, (_, props) => props.id],+ (serviceAccounts: MCPServiceAccountApi[], id: string): MCPServiceAccountApi | null =>+ serviceAccounts.find((account) => account.id === id) ?? null,+ ],+ breadcrumbs: [+ (s) => [s.account],+ (account: MCPServiceAccountApi | null): Breadcrumb[] => [+ { key: 'mcp-gateway', name: 'MCP servers', path: urls.mcpGatewayTab('team') },+ { key: 'mcp-gateway-agent', name: account?.name ?? 'Agent' },+ ],+ ],+ sharedServerIds: [+ (s) => [s.account],+ (account: MCPServiceAccountApi | null): Set<string> => new Set(account?.server_ids ?? []),+ ],+ }),++ afterMount(({ actions }) => {+ actions.loadRecentCalls()+ }),+])diff --git a/products/mcp_store/frontend/gateway/gatewayAuditLogic.test.ts b/products/mcp_store/frontend/gateway/gatewayAuditLogic.test.tsnew file mode 100644index 000000000000..6ef4162e2d64--- /dev/null+++ b/products/mcp_store/frontend/gateway/gatewayAuditLogic.test.ts@@ -0,0 +1,113 @@+import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import { mcpGatewayAuditCountsRetrieve, mcpGatewayAuditList } from '../generated/api'+import type { MCPAuditEventApi } from '../generated/api.schemas'+import { gatewayAuditLogic } from './gatewayAuditLogic'++jest.mock('../generated/api', () => ({+ mcpGatewayAuditCountsRetrieve: jest.fn(),+ mcpGatewayAuditList: jest.fn(),+}))++const mockAuditCountsRetrieve = jest.mocked(mcpGatewayAuditCountsRetrieve)+const mockAuditList = jest.mocked(mcpGatewayAuditList)++function auditEvent(id: string): MCPAuditEventApi {+ return {+ id,+ created_at: '2026-07-24T00:00:00Z',+ server_name: 'Example server',+ tool_name: id,+ decision: 'auto',+ actor_user: null,+ actor_service_account: null,+ actor_label: '[email protected]',+ }+}++describe('gatewayAuditLogic', () => {+ let logic: ReturnType<typeof gatewayAuditLogic.build>++ beforeEach(async () => {+ initKeaTests()+ mockAuditList.mockResolvedValue({ count: 0, results: [] })+ mockAuditCountsRetrieve.mockResolvedValue({ all: 0, agents: 0, approvals: 0, blocked: 0 })+ logic = gatewayAuditLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ })++ afterEach(() => {+ logic.unmount()+ jest.clearAllMocks()+ })++ it('discards an earlier filter response that resolves after the latest one', async () => {+ const staleEvent = auditEvent('stale-agent-tool')+ const freshEvent = auditEvent('fresh-blocked-tool')+ let resolveStale: (value: Awaited<ReturnType<typeof mcpGatewayAuditList>>) => void = () => {}++ mockAuditList.mockReset()+ mockAuditList+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveStale = resolve+ })+ )+ .mockResolvedValueOnce({ count: 1, results: [freshEvent] })++ await expectLogic(logic, () => {+ logic.actions.setQuickFilter('agents')+ logic.actions.setQuickFilter('blocked')+ }).toDispatchActions(['loadAuditSuccess'])++ expect(logic.values.quickFilter).toBe('blocked')+ expect(logic.values.auditResponse).toEqual({ count: 1, results: [freshEvent] })++ resolveStale({ count: 1, results: [staleEvent] })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.auditResponse).toEqual({ count: 1, results: [freshEvent] })+ })++ it('refreshes count badges after a filter change', async () => {+ const refreshedCounts = { all: 4, agents: 3, approvals: 2, blocked: 1 }+ mockAuditCountsRetrieve.mockResolvedValue(refreshedCounts)++ await expectLogic(logic, () => {+ logic.actions.setQuickFilter('blocked')+ })+ .toFinishAllListeners()+ .toMatchValues({ counts: refreshedCounts })+ })++ it('discards an earlier count response that resolves after the latest one', async () => {+ const staleCounts = { all: 1, agents: 1, approvals: 0, blocked: 0 }+ const freshCounts = { all: 2, agents: 1, approvals: 0, blocked: 1 }+ let resolveStale: (value: Awaited<ReturnType<typeof mcpGatewayAuditCountsRetrieve>>) => void = () => {}++ mockAuditCountsRetrieve.mockReset()+ mockAuditCountsRetrieve+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveStale = resolve+ })+ )+ .mockResolvedValueOnce(freshCounts)++ await expectLogic(logic, () => {+ logic.actions.setQuickFilter('agents')+ logic.actions.setQuickFilter('blocked')+ }).toDispatchActions(['loadCountsSuccess'])++ expect(logic.values.counts).toEqual(freshCounts)++ resolveStale(staleCounts)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.counts).toEqual(freshCounts)+ })+})diff --git a/products/mcp_store/frontend/gateway/gatewayAuditLogic.ts b/products/mcp_store/frontend/gateway/gatewayAuditLogic.tsnew file mode 100644index 000000000000..808201429c60--- /dev/null+++ b/products/mcp_store/frontend/gateway/gatewayAuditLogic.ts@@ -0,0 +1,132 @@+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { mcpGatewayAuditCountsRetrieve, mcpGatewayAuditList } from '../generated/api'+import { AuditCountsApi, MCPAuditEventApi } from '../generated/api.schemas'++export type AuditQuickFilter = 'all' | 'agents' | 'approvals' | 'blocked'++const PAGE_SIZE = 10++function currentProjectId(): string {+ return String(teamLogic.values.currentTeamId)+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayAuditLogicValues {+ auditResponse: {+ count: number+ results: MCPAuditEventApi[]+ }+ auditResponseLoading: boolean+ counts: AuditCountsApi | null+ countsLoading: boolean+ page: number+ quickFilter: AuditQuickFilter+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayAuditLogicActions {+ loadAudit: (_: void) => void+ loadAuditFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAuditSuccess: (+ auditResponse: {+ count: number+ results: MCPAuditEventApi[]+ },+ payload?: void+ ) => {+ auditResponse: {+ count: number+ results: MCPAuditEventApi[]+ }+ payload?: void+ }+ loadCounts: (_: void) => void+ loadCountsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadCountsSuccess: (+ counts: AuditCountsApi,+ payload?: void+ ) => {+ counts: AuditCountsApi+ payload?: void+ }+ setPage: (page: number) => {+ page: number+ }+ setQuickFilter: (quickFilter: AuditQuickFilter) => {+ quickFilter: AuditQuickFilter+ }+}++export type gatewayAuditLogicType = MakeLogicType<gatewayAuditLogicValues, gatewayAuditLogicActions>++export const gatewayAuditLogic = kea<gatewayAuditLogicType>([+ path(['products', 'mcp_store', 'frontend', 'gateway', 'gatewayAuditLogic']),++ actions({+ setQuickFilter: (quickFilter: AuditQuickFilter) => ({ quickFilter }),+ setPage: (page: number) => ({ page }),+ }),++ reducers({+ quickFilter: ['all' as AuditQuickFilter, { setQuickFilter: (_, { quickFilter }) => quickFilter }],+ page: [1, { setPage: (_, { page }) => page, setQuickFilter: () => 1 }],+ }),++ loaders(({ values }) => ({+ auditResponse: [+ { count: 0, results: [] as MCPAuditEventApi[] } as { count: number; results: MCPAuditEventApi[] },+ {+ loadAudit: async (_: void, breakpoint) => {+ const response = await mcpGatewayAuditList(currentProjectId(), {+ quick_filter: values.quickFilter,+ limit: PAGE_SIZE,+ offset: (values.page - 1) * PAGE_SIZE,+ })+ breakpoint()+ return { count: response.count, results: response.results }+ },+ },+ ],+ counts: [+ null as AuditCountsApi | null,+ {+ loadCounts: async (_: void, breakpoint) => {+ const counts = await mcpGatewayAuditCountsRetrieve(currentProjectId())+ breakpoint()+ return counts+ },+ },+ ],+ })),++ listeners(({ actions }) => ({+ setQuickFilter: () => {+ actions.loadAudit()+ actions.loadCounts()+ },+ setPage: () => actions.loadAudit(),+ })),++ afterMount(({ actions }) => {+ actions.loadAudit()+ actions.loadCounts()+ }),+])++export { PAGE_SIZE as AUDIT_PAGE_SIZE }diff --git a/products/mcp_store/frontend/gateway/gatewayMemberLogic.test.ts b/products/mcp_store/frontend/gateway/gatewayMemberLogic.test.tsnew file mode 100644index 000000000000..8cb3f297ac8f--- /dev/null+++ b/products/mcp_store/frontend/gateway/gatewayMemberLogic.test.ts@@ -0,0 +1,110 @@+import { MOCK_DEFAULT_BASIC_USER } from '~/lib/api.mock'++import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import {+ mcpGatewayConfigList,+ mcpGatewayMembersList,+ mcpGatewayMembersRetrieve,+ mcpGatewayRulesList,+ mcpGatewayServersList,+ mcpGatewayServiceAccountsList,+ mcpServersList,+} from '../generated/api'+import type { GatewayMemberSummaryApi } from '../generated/api.schemas'+import { gatewayMemberLogic } from './gatewayMemberLogic'+import { mcpGatewayLogic } from './mcpGatewayLogic'++jest.mock('../generated/api', () => ({+ ...jest.requireActual('../generated/api'),+ mcpGatewayConfigList: jest.fn(),+ mcpGatewayMembersList: jest.fn(),+ mcpGatewayMembersRetrieve: jest.fn(),+ mcpGatewayRulesList: jest.fn(),+ mcpGatewayServersList: jest.fn(),+ mcpGatewayServiceAccountsList: jest.fn(),+ mcpServersList: jest.fn(),+}))++const mockConfigList = jest.mocked(mcpGatewayConfigList)+const mockMembersList = jest.mocked(mcpGatewayMembersList)+const mockMemberRetrieve = jest.mocked(mcpGatewayMembersRetrieve)+const mockRulesList = jest.mocked(mcpGatewayRulesList)+const mockServersList = jest.mocked(mcpGatewayServersList)+const mockServiceAccountsList = jest.mocked(mcpGatewayServiceAccountsList)+const mockTemplatesList = jest.mocked(mcpServersList)++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 }+}++function gatewayMember(): GatewayMemberSummaryApi {+ return {+ user: {+ id: MOCK_DEFAULT_BASIC_USER.id,+ uuid: MOCK_DEFAULT_BASIC_USER.uuid,+ distinct_id: MOCK_DEFAULT_BASIC_USER.distinct_id,+ first_name: MOCK_DEFAULT_BASIC_USER.first_name,+ email: MOCK_DEFAULT_BASIC_USER.email,+ hedgehog_config: null,+ },+ is_org_admin: false,+ connected_server_ids: [],+ revoked_server_ids: [],+ }+}++describe('gatewayMemberLogic', () => {+ let parentLogic: ReturnType<typeof mcpGatewayLogic.build>+ let logic: ReturnType<typeof gatewayMemberLogic.build>++ beforeEach(async () => {+ initKeaTests()+ jest.resetAllMocks()+ mockConfigList.mockResolvedValue({+ is_admin: true,+ allow_custom_servers: true,+ allow_member_agent_access: true,+ })+ mockMembersList.mockResolvedValue({ count: 0, results: [] })+ mockRulesList.mockResolvedValue({ count: 0, results: [] })+ mockServersList.mockResolvedValue({ count: 0, results: [] })+ mockServiceAccountsList.mockResolvedValue({ count: 0, results: [] })+ mockTemplatesList.mockResolvedValue({ count: 0, results: [] })++ parentLogic = mcpGatewayLogic()+ parentLogic.mount()+ await expectLogic(parentLogic).toFinishAllListeners()+ })++ afterEach(() => {+ logic?.unmount()+ parentLogic.unmount()+ })++ it('loads the member directly while reusing the gateway server registry', async () => {+ const member = gatewayMember()+ const pendingMember = deferred<GatewayMemberSummaryApi>()+ mockMemberRetrieve.mockReturnValue(pendingMember.promise)++ logic = gatewayMemberLogic({ id: String(member.user.id) })+ logic.mount()++ expect(logic.values.member).toBeNull()+ expect(logic.values.memberInitialized).toBe(false)+ expect(logic.values.memberLoading).toBe(true)++ pendingMember.resolve(member)+ await expectLogic(logic).toFinishAllListeners()++ expect(mockMemberRetrieve).toHaveBeenCalledWith(expect.any(String), String(member.user.id))+ expect(mockServersList).toHaveBeenCalledTimes(1)+ expect(logic.values.member).toEqual(member)+ expect(logic.values.memberInitialized).toBe(true)+ })+})diff --git a/products/mcp_store/frontend/gateway/gatewayMemberLogic.ts b/products/mcp_store/frontend/gateway/gatewayMemberLogic.tsnew file mode 100644index 000000000000..24eb382369ee--- /dev/null+++ b/products/mcp_store/frontend/gateway/gatewayMemberLogic.ts@@ -0,0 +1,148 @@+import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { Breadcrumb } from '~/types'++import { mcpGatewayMembersRetrieve } from '../generated/api'+import { GatewayMemberSummaryApi, MCPGatewayServerApi } from '../generated/api.schemas'+import { mcpGatewayLogic } from './mcpGatewayLogic'++export interface GatewayMemberLogicProps {+ id: string+}++function currentProjectId(): string {+ return String(teamLogic.values.currentTeamId)+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayMemberLogicValues {+ allServers: MCPGatewayServerApi[] // mcpGatewayLogic+ allServersInitialized: boolean // mcpGatewayLogic+ memberServerAccessLoadingKeys: Set<string> // mcpGatewayLogic+ breadcrumbs: Breadcrumb[]+ member: GatewayMemberSummaryApi | null+ memberInitialized: boolean+ memberLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayMemberLogicActions {+ setMemberServerAccess: (+ userId: number,+ serverId: string,+ enabled: boolean+ ) => {+ enabled: boolean+ serverId: string+ userId: number+ } // mcpGatewayLogic+ setMemberServerAccessComplete: (+ userId: number,+ serverId: string+ ) => {+ serverId: string+ userId: number+ } // mcpGatewayLogic+ loadMember: () => any+ loadMemberFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadMemberSuccess: (+ member: GatewayMemberSummaryApi,+ payload?: any+ ) => {+ member: GatewayMemberSummaryApi+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayMemberLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ breadcrumbs: (member: GatewayMemberSummaryApi | null) => Breadcrumb[]+ }+}++export type gatewayMemberLogicType = MakeLogicType<+ gatewayMemberLogicValues,+ gatewayMemberLogicActions,+ GatewayMemberLogicProps,+ gatewayMemberLogicMeta+>++export const gatewayMemberLogic = kea<gatewayMemberLogicType>([+ path((key) => ['products', 'mcp_store', 'frontend', 'gateway', 'gatewayMemberLogic', key]),+ props({} as GatewayMemberLogicProps),+ key((props) => props.id),++ connect(() => ({+ values: [+ mcpGatewayLogic,+ ['memberServerAccessLoadingKeys', 'servers as allServers', 'serversInitialized as allServersInitialized'],+ ],+ actions: [mcpGatewayLogic, ['setMemberServerAccess', 'setMemberServerAccessComplete']],+ })),++ loaders(({ props }) => ({+ member: [+ null as GatewayMemberSummaryApi | null,+ {+ loadMember: async () => await mcpGatewayMembersRetrieve(currentProjectId(), props.id),+ },+ ],+ })),++ reducers({+ memberInitialized: [+ false,+ {+ loadMember: () => false,+ loadMemberSuccess: () => true,+ loadMemberFailure: () => true,+ },+ ],+ }),++ selectors({+ breadcrumbs: [+ (s) => [s.member],+ (member: GatewayMemberSummaryApi | null): Breadcrumb[] => [+ { key: 'mcp-gateway', name: 'MCP servers', path: urls.mcpGatewayTab('team') },+ {+ key: 'mcp-gateway-member',+ name: member ? `${member.user.first_name} ${member.user.last_name}` : 'Member',+ },+ ],+ ],+ }),++ listeners(({ actions, props, values }) => ({+ setMemberServerAccess: ({ userId, serverId, enabled }) => {+ if (String(userId) !== props.id || !values.member) {+ return+ }+ const revokedServerIds = enabled+ ? values.member.revoked_server_ids.filter((revokedServerId) => revokedServerId !== serverId)+ : Array.from(new Set([...values.member.revoked_server_ids, serverId]))+ actions.loadMemberSuccess({ ...values.member, revoked_server_ids: revokedServerIds })+ },+ setMemberServerAccessComplete: ({ userId }) => {+ if (String(userId) === props.id) {+ actions.loadMember()+ }+ },+ })),++ afterMount(({ actions }) => {+ actions.loadMember()+ }),+])diff --git a/products/mcp_store/frontend/gateway/gatewayPolicyUtils.test.ts b/products/mcp_store/frontend/gateway/gatewayPolicyUtils.test.tsnew file mode 100644index 000000000000..973d70bc4aa1--- /dev/null+++ b/products/mcp_store/frontend/gateway/gatewayPolicyUtils.test.ts@@ -0,0 +1,16 @@+import { isPolicyStateAllowedByCeiling } from './gatewayPolicyUtils'++describe('isPolicyStateAllowedByCeiling', () => {+ it.each([+ ['approved', 'needs_approval', false],+ ['needs_approval', 'needs_approval', true],+ ['do_not_use', 'needs_approval', true],+ ['approved', 'do_not_use', false],+ ['needs_approval', 'do_not_use', false],+ ['do_not_use', 'do_not_use', true],+ ['approved', 'approved', true],+ ['approved', null, true],+ ] as const)('%s under a %s ceiling is %s', (state, ceiling, expected) => {+ expect(isPolicyStateAllowedByCeiling(state, ceiling)).toBe(expected)+ })+})diff --git a/products/mcp_store/frontend/gateway/gatewayPolicyUtils.ts b/products/mcp_store/frontend/gateway/gatewayPolicyUtils.tsnew file mode 100644index 000000000000..40e9c8f06b74--- /dev/null+++ b/products/mcp_store/frontend/gateway/gatewayPolicyUtils.ts@@ -0,0 +1,15 @@+import { MCPToolApprovalStateEnumApi } from '../generated/api.schemas'++const POLICY_STRICTNESS: Record<MCPToolApprovalStateEnumApi, number> = {+ approved: 0,+ needs_approval: 1,+ do_not_use: 2,+}++/** A member or agent may match the team ceiling or choose a stricter state. */+export function isPolicyStateAllowedByCeiling(+ state: MCPToolApprovalStateEnumApi,+ ceiling: MCPToolApprovalStateEnumApi | null+): boolean {+ return ceiling === null || POLICY_STRICTNESS[state] >= POLICY_STRICTNESS[ceiling]+}diff --git a/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts b/products/mcp_store/frontend/gateway/gatewayServerLogic.test.tsnew file mode 100644index 000000000000..8df8b4d91a10--- /dev/null+++ b/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts@@ -0,0 +1,194 @@+import { MOCK_DEFAULT_BASIC_USER } from '~/lib/api.mock'++import { lemonToast } from '@posthog/lemon-ui'++import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import {+ mcpGatewayConfigList,+ mcpGatewayMembersList,+ mcpGatewayRulesList,+ mcpGatewayServersPoliciesCreate,+ mcpGatewayServersList,+ mcpGatewayServersToolsRetrieve,+ mcpGatewayServiceAccountsList,+ mcpServersList,+} from '../generated/api'+import type { MCPGatewayServerApi, ResolvedToolPolicyApi } from '../generated/api.schemas'+import { gatewayServerLogic } from './gatewayServerLogic'+import { mcpGatewayLogic } from './mcpGatewayLogic'++jest.mock('../generated/api', () => ({+ ...jest.requireActual('../generated/api'),+ mcpGatewayConfigList: jest.fn(),+ mcpGatewayMembersList: jest.fn(),+ mcpGatewayRulesList: jest.fn(),+ mcpGatewayServersPoliciesCreate: jest.fn(),+ mcpGatewayServersList: jest.fn(),+ mcpGatewayServersToolsRetrieve: jest.fn(),+ mcpGatewayServiceAccountsList: jest.fn(),+ mcpServersList: jest.fn(),+}))++const mockConfigList = jest.mocked(mcpGatewayConfigList)+const mockMembersList = jest.mocked(mcpGatewayMembersList)+const mockPoliciesCreate = jest.mocked(mcpGatewayServersPoliciesCreate)+const mockRulesList = jest.mocked(mcpGatewayRulesList)+const mockServersList = jest.mocked(mcpGatewayServersList)+const mockToolsRetrieve = jest.mocked(mcpGatewayServersToolsRetrieve)+const mockServiceAccountsList = jest.mocked(mcpGatewayServiceAccountsList)+const mockTemplatesList = jest.mocked(mcpServersList)++function gatewayServer(): MCPGatewayServerApi {+ return {+ id: 'server-id',+ name: 'Test server',+ url: 'https://mcp.example.com/mcp',+ description: '',+ category: 'dev',+ template_auth_type: null,+ is_team_enabled: true,+ icon_key: '',+ icon_domain: '',+ docs_url: '',+ template_id: null,+ tool_count: 2,+ connections: [],+ your_connection: null,+ agents: [],+ revoked_user_ids: [],+ is_revoked_for_you: false,+ created_by: {+ id: MOCK_DEFAULT_BASIC_USER.id,+ uuid: MOCK_DEFAULT_BASIC_USER.uuid,+ distinct_id: MOCK_DEFAULT_BASIC_USER.distinct_id,+ first_name: MOCK_DEFAULT_BASIC_USER.first_name,+ email: MOCK_DEFAULT_BASIC_USER.email,+ hedgehog_config: null,+ },+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ }+}++function toolPolicy(toolName: string, overrides: Partial<ResolvedToolPolicyApi> = {}): ResolvedToolPolicyApi {+ return {+ tool_name: toolName,+ description: '',+ input_schema: {},+ policy_state: 'approved',+ team_state: null,+ locked: false,+ decided_by: 'default',+ rule_name: '',+ rule_description: '',+ ...overrides,+ }+}++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 }+}++describe('gatewayServerLogic', () => {+ let parentLogic: ReturnType<typeof mcpGatewayLogic.build>+ let logic: ReturnType<typeof gatewayServerLogic.build>++ beforeEach(async () => {+ initKeaTests()+ jest.resetAllMocks()+ mockConfigList.mockResolvedValue({+ is_admin: true,+ allow_custom_servers: true,+ allow_member_agent_access: true,+ })+ mockMembersList.mockResolvedValue({ count: 0, results: [] })+ mockRulesList.mockResolvedValue({ count: 0, results: [] })+ mockServersList.mockResolvedValue({ count: 1, results: [gatewayServer()] })+ mockServiceAccountsList.mockResolvedValue({ count: 0, results: [] })+ mockTemplatesList.mockResolvedValue({ count: 0, results: [] })+ mockToolsRetrieve.mockResolvedValue({ count: 0, results: [] })++ parentLogic = mcpGatewayLogic()+ parentLogic.mount()+ await expectLogic(parentLogic).toFinishAllListeners()++ logic = gatewayServerLogic({ id: 'server-id' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ })++ afterEach(() => {+ logic.unmount()+ parentLogic.unmount()+ jest.restoreAllMocks()+ })++ it('uses the policy mutation response while keeping the loader in flight', async () => {+ const pendingResponse = deferred<Awaited<ReturnType<typeof mcpGatewayServersPoliciesCreate>>>()+ const updatedPolicy = toolPolicy('create_issue', { policy_state: 'needs_approval' })+ mockPoliciesCreate.mockReturnValue(pendingResponse.promise)++ logic.actions.setToolPolicy({ toolName: updatedPolicy.tool_name, state: updatedPolicy.policy_state })++ expect(logic.values.toolPoliciesLoading).toBe(true)+ expect(mockPoliciesCreate).toHaveBeenCalledTimes(1)++ pendingResponse.resolve({ count: 1, results: [updatedPolicy] })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.toolPoliciesLoading).toBe(false)+ expect(logic.values.toolPolicies).toEqual([updatedPolicy])+ expect(mockToolsRetrieve).toHaveBeenCalledTimes(1)+ })++ it('discards a stale policy response after the scope changes', async () => {+ const staleResponse = deferred<Awaited<ReturnType<typeof mcpGatewayServersToolsRetrieve>>>()+ const latestResponse = deferred<Awaited<ReturnType<typeof mcpGatewayServersToolsRetrieve>>>()+ const stalePolicy = toolPolicy('create_issue', { policy_state: 'approved' })+ const latestPolicy = toolPolicy('create_issue', { policy_state: 'needs_approval' })+ mockToolsRetrieve.mockReset()+ mockToolsRetrieve.mockReturnValueOnce(staleResponse.promise).mockReturnValueOnce(latestResponse.promise)++ logic.actions.setScope({ scopeType: 'team', label: 'Team default' })+ logic.actions.setScope({ scopeType: 'member', label: 'You' })++ expect(mockToolsRetrieve).toHaveBeenCalledTimes(2)++ latestResponse.resolve({ count: 1, results: [latestPolicy] })+ staleResponse.resolve({ count: 1, results: [stalePolicy] })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.scope.scopeType).toBe('member')+ expect(logic.values.toolPolicies).toEqual([latestPolicy])+ })++ it('reports the number of tools changed by a bulk update', async () => {+ const editablePolicy = toolPolicy('create_issue')+ const lockedPolicy = toolPolicy('delete_issue', { locked: true, policy_state: 'do_not_use' })+ logic.actions.loadToolPoliciesSuccess([editablePolicy, lockedPolicy])+ mockPoliciesCreate.mockResolvedValue({+ count: 2,+ results: [{ ...editablePolicy, policy_state: 'needs_approval' }, lockedPolicy],+ })+ const toast = jest.spyOn(lemonToast, 'success')++ await expectLogic(logic, () => {+ logic.actions.setAllTools({ state: 'needs_approval' })+ }).toFinishAllListeners()++ expect(mockPoliciesCreate).toHaveBeenCalledWith(+ expect.any(String),+ 'server-id',+ expect.objectContaining({+ policies: [{ tool_name: editablePolicy.tool_name, policy_state: 'needs_approval' }],+ })+ )+ expect(toast).toHaveBeenCalledWith('Updated 1 tool')+ })+})diff --git a/products/mcp_store/frontend/gateway/gatewayServerLogic.ts b/products/mcp_store/frontend/gateway/gatewayServerLogic.tsnew file mode 100644index 000000000000..15edc5d82a92--- /dev/null+++ b/products/mcp_store/frontend/gateway/gatewayServerLogic.ts@@ -0,0 +1,405 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { actionToUrl, urlToAction } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { Breadcrumb } from '~/types'++import { mcpGatewayServersPoliciesCreate, mcpGatewayServersToolsRetrieve } from '../generated/api'+import {+ MCPGatewayServerApi,+ MCPToolApprovalStateEnumApi,+ ResolvedToolPolicyApi,+ ScopeTypeEnumApi,+} from '../generated/api.schemas'+import type { MCPServiceAccountApi } from '../generated/api.schemas'+import { isPolicyStateAllowedByCeiling } from './gatewayPolicyUtils'+import { mcpGatewayLogic } from './mcpGatewayLogic'++export interface GatewayServerLogicProps {+ id: string+}++export interface PolicyScope {+ scopeType: ScopeTypeEnumApi+ scopeUserId?: number+ scopeServiceAccountId?: string+ label: string+}++function currentProjectId(): string {+ return String(teamLogic.values.currentTeamId)+}++function defaultPolicyScope(isAdmin: boolean): PolicyScope {+ return isAdmin ? { scopeType: 'team', label: 'Team default' } : { scopeType: 'member', label: 'You' }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayServerLogicValues {+ canManageAgentAccess: boolean // mcpGatewayLogic+ isAdmin: boolean // mcpGatewayLogic+ serverLoading: boolean // mcpGatewayLogic+ servers: MCPGatewayServerApi[] // mcpGatewayLogic+ serversInitialized: boolean // mcpGatewayLogic+ serviceAccounts: MCPServiceAccountApi[] // mcpGatewayLogic+ serviceAccountsInitialized: boolean // mcpGatewayLogic+ serviceAccountsLoading: boolean // mcpGatewayLogic+ availableScopes: PolicyScope[]+ breadcrumbs: Breadcrumb[]+ policyCounts: Record<MCPToolApprovalStateEnumApi, number>+ requestedAgentScopeId: string | null+ scope: PolicyScope+ scopeIsResolving: boolean+ server: MCPGatewayServerApi | null+ toolPolicies: ResolvedToolPolicyApi[]+ toolPoliciesLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayServerLogicActions {+ loadServersSuccess: (+ servers: MCPGatewayServerApi[],+ payload?: any+ ) => {+ payload?: any+ servers: MCPGatewayServerApi[]+ } // mcpGatewayLogic+ loadServiceAccountsSuccess: (+ serviceAccounts: MCPServiceAccountApi[],+ payload?: any+ ) => {+ payload?: any+ serviceAccounts: MCPServiceAccountApi[]+ } // mcpGatewayLogic+ loadToolPolicies: (_: void) => void+ loadToolPoliciesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadToolPoliciesSuccess: (+ toolPolicies: ResolvedToolPolicyApi[],+ payload?: void+ ) => {+ toolPolicies: ResolvedToolPolicyApi[]+ payload?: void+ }+ setAllTools: ({ state }: { state: MCPToolApprovalStateEnumApi }) => {+ state: MCPToolApprovalStateEnumApi+ }+ setAllToolsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ setAllToolsSuccess: (+ toolPolicies: ResolvedToolPolicyApi[],+ payload?: {+ state: MCPToolApprovalStateEnumApi+ }+ ) => {+ toolPolicies: ResolvedToolPolicyApi[]+ payload?: {+ state: MCPToolApprovalStateEnumApi+ }+ }+ setRequestedAgentScopeId: (accountId: string | null) => {+ accountId: string | null+ }+ setScope: (scope: PolicyScope) => {+ scope: PolicyScope+ }+ setToolPolicy: ({ toolName, state }: { state: MCPToolApprovalStateEnumApi; toolName: string }) => {+ toolName: string+ state: MCPToolApprovalStateEnumApi+ }+ setToolPolicyFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ setToolPolicySuccess: (+ toolPolicies: ResolvedToolPolicyApi[],+ payload?: {+ toolName: string+ state: MCPToolApprovalStateEnumApi+ }+ ) => {+ toolPolicies: ResolvedToolPolicyApi[]+ payload?: {+ toolName: string+ state: MCPToolApprovalStateEnumApi+ }+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface gatewayServerLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ server: (servers: MCPGatewayServerApi[], arg: any) => MCPGatewayServerApi | null+ breadcrumbs: (server: MCPGatewayServerApi | null) => Breadcrumb[]+ policyCounts: (toolPolicies: ResolvedToolPolicyApi[]) => Record<MCPToolApprovalStateEnumApi, number>+ availableScopes: (+ server: MCPGatewayServerApi | null,+ serviceAccounts: MCPServiceAccountApi[],+ isAdmin: boolean,+ canManageAgentAccess: boolean+ ) => PolicyScope[]+ scopeIsResolving: (requestedAgentScopeId: string | null, scope: PolicyScope) => boolean+ }+}++export type gatewayServerLogicType = MakeLogicType<+ gatewayServerLogicValues,+ gatewayServerLogicActions,+ GatewayServerLogicProps,+ gatewayServerLogicMeta+>++export const gatewayServerLogic = kea<gatewayServerLogicType>([+ path((key) => ['products', 'mcp_store', 'frontend', 'gateway', 'gatewayServerLogic', key]),+ props({} as GatewayServerLogicProps),+ key((props) => props.id),++ connect(() => ({+ values: [+ mcpGatewayLogic,+ [+ 'canManageAgentAccess',+ 'isAdmin',+ 'servers',+ 'serversInitialized',+ 'serversLoading as serverLoading',+ 'serviceAccounts',+ 'serviceAccountsInitialized',+ 'serviceAccountsLoading',+ ],+ ],+ actions: [mcpGatewayLogic, ['loadServersSuccess', 'loadServiceAccountsSuccess']],+ })),++ actions({+ setScope: (scope: PolicyScope) => ({ scope }),+ setRequestedAgentScopeId: (accountId: string | null) => ({ accountId }),+ }),++ loaders(({ props, values }) => ({+ toolPolicies: [+ [] as ResolvedToolPolicyApi[],+ {+ loadToolPolicies: async (_: void, breakpoint) => {+ const scope = values.scope+ const response = await mcpGatewayServersToolsRetrieve(currentProjectId(), props.id, {+ scope_type: scope.scopeType,+ scope_user_id: scope.scopeUserId,+ scope_service_account_id: scope.scopeServiceAccountId,+ })+ breakpoint()+ return response.results+ },+ setToolPolicy: async ({+ toolName,+ state,+ }: {+ toolName: string+ state: MCPToolApprovalStateEnumApi+ }) => {+ const scope = values.scope+ const response = await mcpGatewayServersPoliciesCreate(currentProjectId(), props.id, {+ scope_type: scope.scopeType,+ scope_user_id: scope.scopeUserId,+ scope_service_account_id: scope.scopeServiceAccountId,+ policies: [{ tool_name: toolName, policy_state: state }],+ })+ return response.results+ },+ setAllTools: async ({ state }: { state: MCPToolApprovalStateEnumApi }) => {+ const editable = values.toolPolicies.filter(+ (policy) =>+ !policy.locked &&+ (values.scope.scopeType === 'team' ||+ isPolicyStateAllowedByCeiling(state, policy.team_state))+ )+ if (!editable.length) {+ return values.toolPolicies+ }+ const scope = values.scope+ const response = await mcpGatewayServersPoliciesCreate(currentProjectId(), props.id, {+ scope_type: scope.scopeType,+ scope_user_id: scope.scopeUserId,+ scope_service_account_id: scope.scopeServiceAccountId,+ policies: editable.map((policy) => ({+ tool_name: policy.tool_name,+ policy_state: state,+ })),+ })+ lemonToast.success(`Updated ${editable.length} ${editable.length === 1 ? 'tool' : 'tools'}`)+ return response.results+ },+ },+ ],+ })),++ reducers({+ requestedAgentScopeId: [+ null as string | null,+ {+ setRequestedAgentScopeId: (_, { accountId }) => accountId,+ },+ ],+ scope: [+ { scopeType: 'team', label: 'Team default' } as PolicyScope,+ {+ setScope: (_, { scope }) => scope,+ },+ ],+ }),++ selectors({+ server: [+ (s) => [s.servers, (_, props) => props.id],+ (servers: MCPGatewayServerApi[], id: string): MCPGatewayServerApi | null =>+ servers.find((server) => server.id === id) ?? null,+ ],+ breadcrumbs: [+ (s) => [s.server],+ (server: MCPGatewayServerApi | null): Breadcrumb[] => [+ { key: 'mcp-gateway', name: 'MCP servers', path: urls.mcpGateway() },+ { key: 'mcp-gateway-server', name: server?.name ?? 'Server' },+ ],+ ],+ policyCounts: [+ (s) => [s.toolPolicies],+ (toolPolicies: ResolvedToolPolicyApi[]): Record<MCPToolApprovalStateEnumApi, number> => {+ const counts: Record<MCPToolApprovalStateEnumApi, number> = {+ approved: 0,+ needs_approval: 0,+ do_not_use: 0,+ }+ for (const policy of toolPolicies) {+ counts[policy.policy_state] += 1+ }+ return counts+ },+ ],+ // Members always manage their own policy. Admins can also manage the+ // team baseline, and agent scopes follow the team setting.+ availableScopes: [+ (s) => [s.server, s.serviceAccounts, s.isAdmin, s.canManageAgentAccess],+ (+ server: MCPGatewayServerApi | null,+ serviceAccounts: MCPServiceAccountApi[],+ isAdmin: boolean,+ canManageAgentAccess: boolean+ ): PolicyScope[] => {+ const scopes: PolicyScope[] = [{ scopeType: 'member', label: 'You' }]+ if (isAdmin) {+ scopes.unshift({ scopeType: 'team', label: 'Team default' })+ }+ if (!canManageAgentAccess) {+ return scopes+ }+ for (const account of serviceAccounts) {+ if (server && account.server_ids.includes(server.id)) {+ scopes.push({+ scopeType: 'agent',+ scopeServiceAccountId: account.id,+ label: account.name,+ })+ }+ }+ return scopes+ },+ ],+ scopeIsResolving: [+ (s) => [s.requestedAgentScopeId, s.scope],+ (requestedAgentScopeId: string | null, scope: PolicyScope): boolean =>+ requestedAgentScopeId !== null && scope.scopeServiceAccountId !== requestedAgentScopeId,+ ],+ }),++ listeners(({ actions, values }) => ({+ setRequestedAgentScopeId: () => {+ const accountId = values.requestedAgentScopeId+ if (!accountId) {+ const defaultScope = defaultPolicyScope(values.isAdmin)+ if (values.scope.scopeType !== defaultScope.scopeType) {+ actions.setScope(defaultScope)+ }+ return+ }+ const match = values.availableScopes.find((scope) => scope.scopeServiceAccountId === accountId)+ if (match) {+ if (values.scope.scopeServiceAccountId !== accountId) {+ actions.setScope(match)+ }+ return+ }+ if (+ values.serversInitialized &&+ values.serviceAccountsInitialized &&+ !values.serverLoading &&+ !values.serviceAccountsLoading+ ) {+ actions.setRequestedAgentScopeId(null)+ actions.setScope(defaultPolicyScope(values.isAdmin))+ lemonToast.error('This agent does not have access to this MCP server.')+ }+ },+ loadServersSuccess: () => {+ if (values.requestedAgentScopeId) {+ actions.setRequestedAgentScopeId(values.requestedAgentScopeId)+ }+ },+ loadServiceAccountsSuccess: () => {+ if (values.requestedAgentScopeId) {+ actions.setRequestedAgentScopeId(values.requestedAgentScopeId)+ }+ },+ setScope: () => {+ actions.loadToolPolicies()+ },+ })),++ actionToUrl(({ values, props }) => ({+ setScope: () => {+ const scope = values.scope+ if (scope.scopeType === 'agent' && scope.scopeServiceAccountId) {+ return urls.mcpGatewayServer(props.id, `agent:${scope.scopeServiceAccountId}`)+ }+ return urls.mcpGatewayServer(props.id)+ },+ })),++ urlToAction(({ actions }) => ({+ [urls.mcpGatewayServer(':id')]: (_, searchParams) => {+ const scopeParam = searchParams.scope as string | undefined+ if (scopeParam?.startsWith('agent:')) {+ actions.setRequestedAgentScopeId(scopeParam.slice('agent:'.length))+ return+ }+ actions.setRequestedAgentScopeId(null)+ },+ })),++ afterMount(({ actions, values }) => {+ const defaultScope = defaultPolicyScope(values.isAdmin)+ if (values.scope.scopeType !== defaultScope.scopeType) {+ actions.setScope(defaultScope)+ } else {+ actions.loadToolPolicies()+ }+ }),+])diff --git a/products/mcp_store/frontend/gateway/gatewayUtils.tsx b/products/mcp_store/frontend/gateway/gatewayUtils.tsxnew file mode 100644index 000000000000..4d96d23550a1--- /dev/null+++ b/products/mcp_store/frontend/gateway/gatewayUtils.tsx@@ -0,0 +1,63 @@+import { IconCheck, IconShieldLock, IconX } from '@posthog/icons'+import { LemonBadge, LemonTag } from '@posthog/lemon-ui'++import { MCPToolApprovalStateEnumApi, UserBasicApi } from '../generated/api.schemas'++/** ProfilePicture wants a UserBasicType-ish shape; the generated UserBasicApi's+ * `hedgehog_config` type isn't assignable, so pass the fields it actually reads. */+export function toProfileUser(user: UserBasicApi): { first_name?: string; last_name?: string; email: string } {+ return { first_name: user.first_name, last_name: user.last_name, email: user.email }+}++export const POLICY_LABELS: Record<MCPToolApprovalStateEnumApi, string> = {+ approved: 'Always Allow',+ needs_approval: 'Needs Approval',+ do_not_use: 'Blocked',+}++export const POLICY_HINTS: Record<MCPToolApprovalStateEnumApi, string> = {+ approved: 'Runs without asking',+ needs_approval: 'Waits for a human to approve',+ do_not_use: 'Never allowed',+}++export const POLICY_OPTIONS: { value: MCPToolApprovalStateEnumApi; label: string; icon: JSX.Element }[] = [+ { value: 'approved', label: 'Always Allow', icon: <IconCheck /> },+ { value: 'needs_approval', label: 'Needs Approval', icon: <IconShieldLock /> },+ { value: 'do_not_use', label: 'Blocked', icon: <IconX /> },+]++/** Small colored summary of how many tools sit in each policy state. */+export function PolicySummary({ counts }: { counts: Record<MCPToolApprovalStateEnumApi, number> }): JSX.Element {+ return (+ <div className="flex items-center gap-2 text-xs">+ <span className="flex items-center gap-1">+ <LemonBadge.Number count={counts.approved} status="success" showZero />+ <span className="text-secondary">Always Allow</span>+ </span>+ <span className="flex items-center gap-1">+ <LemonBadge.Number count={counts.needs_approval} status="warning" showZero />+ <span className="text-secondary">Needs Approval</span>+ </span>+ <span className="flex items-center gap-1">+ <LemonBadge.Number count={counts.do_not_use} status="danger" showZero />+ <span className="text-secondary">blocked</span>+ </span>+ </div>+ )+}++export function DecisionTag({ decision }: { decision: string }): JSX.Element {+ switch (decision) {+ case 'auto':+ return <LemonTag type="success">Auto-approved</LemonTag>+ case 'approved':+ return <LemonTag type="completion">Approved</LemonTag>+ case 'pending':+ return <LemonTag type="warning">Awaiting approval</LemonTag>+ case 'blocked':+ return <LemonTag type="danger">Blocked</LemonTag>+ default:+ return <LemonTag>{decision}</LemonTag>+ }+}diff --git a/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.ts b/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.tsnew file mode 100644index 000000000000..8165a48d2f49--- /dev/null+++ b/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.ts@@ -0,0 +1,400 @@+import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_TEAM } from '~/lib/api.mock'++import { lemonToast } from '@posthog/lemon-ui'++import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import {+ mcpGatewayConfigApplyPresetCreate,+ mcpGatewayConfigList,+ mcpGatewayConfigSetAllServersEnabledCreate,+ mcpGatewayMembersList,+ mcpGatewayRulesList,+ mcpGatewayServersList,+ mcpGatewayServersPartialUpdate,+ mcpGatewayServersSetTemplateEnabledCreate,+ mcpGatewayServiceAccountsList,+ mcpServerInstallationsInstallCustomCreate,+ mcpServerInstallationsInstallTemplateCreate,+ mcpServersList,+} from '../generated/api'+import type { GatewayMemberSummaryApi, MCPGatewayServerApi, MCPServerTemplateApi } from '../generated/api.schemas'+import { GATEWAY_MEMBERS_PAGE_SIZE, mcpGatewayLogic } from './mcpGatewayLogic'++jest.mock('../generated/api', () => ({+ mcpGatewayConfigApplyPresetCreate: jest.fn(),+ mcpGatewayConfigList: jest.fn(),+ mcpGatewayConfigSetAllServersEnabledCreate: jest.fn(),+ mcpGatewayMembersList: jest.fn(),+ mcpGatewayRulesList: jest.fn(),+ mcpGatewayServersList: jest.fn(),+ mcpGatewayServersPartialUpdate: jest.fn(),+ mcpGatewayServersSetTemplateEnabledCreate: jest.fn(),+ mcpGatewayServiceAccountsList: jest.fn(),+ mcpServerInstallationsInstallCustomCreate: jest.fn(),+ mcpServerInstallationsInstallTemplateCreate: jest.fn(),+ mcpServersList: jest.fn(),+}))++const mockApplyPreset = mcpGatewayConfigApplyPresetCreate as jest.MockedFunction<+ typeof mcpGatewayConfigApplyPresetCreate+>+const mockConfigList = mcpGatewayConfigList as jest.MockedFunction<typeof mcpGatewayConfigList>+const mockSetAllServersEnabled = mcpGatewayConfigSetAllServersEnabledCreate as jest.MockedFunction<+ typeof mcpGatewayConfigSetAllServersEnabledCreate+>+const mockMembersList = mcpGatewayMembersList as jest.MockedFunction<typeof mcpGatewayMembersList>+const mockRulesList = mcpGatewayRulesList as jest.MockedFunction<typeof mcpGatewayRulesList>+const mockServersList = mcpGatewayServersList as jest.MockedFunction<typeof mcpGatewayServersList>+const mockServersPartialUpdate = mcpGatewayServersPartialUpdate as jest.MockedFunction<+ typeof mcpGatewayServersPartialUpdate+>+const mockSetTemplateEnabled = mcpGatewayServersSetTemplateEnabledCreate as jest.MockedFunction<+ typeof mcpGatewayServersSetTemplateEnabledCreate+>+const mockServiceAccountsList = mcpGatewayServiceAccountsList as jest.MockedFunction<+ typeof mcpGatewayServiceAccountsList+>+const mockInstallCustom = mcpServerInstallationsInstallCustomCreate as jest.MockedFunction<+ typeof mcpServerInstallationsInstallCustomCreate+>+const mockInstallTemplate = mcpServerInstallationsInstallTemplateCreate as jest.MockedFunction<+ typeof mcpServerInstallationsInstallTemplateCreate+>+const mockTemplatesList = mcpServersList as jest.MockedFunction<typeof mcpServersList>++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 }+}++function apiError(detail: string): Error & { detail: string } {+ return Object.assign(new Error(detail), { detail })+}++function gatewayServer(overrides: Partial<MCPGatewayServerApi>): MCPGatewayServerApi {+ return {+ id: 'server-id',+ name: 'Test server',+ url: 'https://mcp.example.com/mcp',+ description: '',+ category: 'dev',+ template_auth_type: null,+ is_team_enabled: true,+ icon_key: '',+ icon_domain: '',+ docs_url: '',+ template_id: null,+ tool_count: 0,+ connections: [],+ your_connection: null,+ agents: [],+ revoked_user_ids: [],+ is_revoked_for_you: false,+ created_by: {+ id: MOCK_DEFAULT_BASIC_USER.id,+ uuid: MOCK_DEFAULT_BASIC_USER.uuid,+ distinct_id: MOCK_DEFAULT_BASIC_USER.distinct_id,+ first_name: MOCK_DEFAULT_BASIC_USER.first_name,+ email: MOCK_DEFAULT_BASIC_USER.email,+ hedgehog_config: null,+ },+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ ...overrides,+ }+}++function serverTemplate(overrides: Partial<MCPServerTemplateApi>): MCPServerTemplateApi {+ return {+ id: 'template-id',+ name: 'Catalog template',+ url: 'https://mcp.template.example.com/mcp',+ docs_url: '',+ description: '',+ auth_type: 'oauth',+ icon_key: '',+ icon_domain: '',+ category: 'dev',+ ...overrides,+ }+}++function gatewayMember(userId: number): GatewayMemberSummaryApi {+ return {+ user: {+ id: userId,+ uuid: `user-${userId}`,+ first_name: 'Test',+ last_name: 'Member',+ email: `member-${userId}@example.com`,+ hedgehog_config: null,+ },+ is_org_admin: false,+ connected_server_ids: [],+ revoked_server_ids: [],+ }+}++describe('mcpGatewayLogic', () => {+ let logic: ReturnType<typeof mcpGatewayLogic.build>++ beforeEach(async () => {+ initKeaTests()+ jest.resetAllMocks()+ mockConfigList.mockResolvedValue({ is_admin: true, allow_custom_servers: true })+ mockMembersList.mockResolvedValue({ count: 0, results: [] })+ mockRulesList.mockResolvedValue({ count: 0, results: [] })+ mockServersList.mockResolvedValue({ count: 0, results: [] })+ mockServiceAccountsList.mockResolvedValue({ count: 0, results: [] })+ mockTemplatesList.mockResolvedValue({ count: 0, results: [] })+ mockInstallCustom.mockResolvedValue({ redirect_url: '' })+ mockInstallTemplate.mockResolvedValue({ redirect_url: '' })++ logic = mcpGatewayLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ })++ it('connects a custom API-key server with the selected auth type and credential', async () => {+ const server = gatewayServer({ id: 'custom-server' })+ logic.actions.loadServersSuccess([server])+ logic.actions.connectServer(server.id)+ logic.actions.setConnectionAuthType('api_key')+ logic.actions.setConnectionApiKey('sk-custom')++ await expectLogic(logic, () => {+ logic.actions.submitConnection()+ }).toFinishAllListeners()++ expect(mockInstallCustom).toHaveBeenCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.objectContaining({+ name: server.name,+ url: server.url,+ auth_type: 'api_key',+ api_key: 'sk-custom',+ scope: 'personal',+ })+ )+ })++ it('passes the entered API key when connecting a catalog template', async () => {+ const server = gatewayServer({+ id: 'template-server',+ template_id: 'template-id',+ template_auth_type: 'api_key',+ })+ logic.actions.loadServersSuccess([server])+ logic.actions.connectServer(server.id)+ logic.actions.setConnectionApiKey('sk-template')++ await expectLogic(logic, () => {+ logic.actions.submitConnection()+ }).toFinishAllListeners()++ expect(mockInstallTemplate).toHaveBeenCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.objectContaining({+ template_id: server.template_id,+ api_key: 'sk-template',+ scope: 'personal',+ })+ )+ })++ it('does not connect an API-key server without a key', () => {+ const server = gatewayServer({ id: 'custom-server' })+ logic.actions.loadServersSuccess([server])+ logic.actions.connectServer(server.id)+ logic.actions.setConnectionAuthType('api_key')++ logic.actions.submitConnection()++ expect(logic.values.connectionSubmitDisabledReason).toBe('Enter an API key to connect this server.')+ expect(mockInstallCustom).not.toHaveBeenCalled()+ })++ it('does not start a second OAuth connection while the first is in flight', async () => {+ const pendingInstall = deferred<Awaited<ReturnType<typeof mcpServerInstallationsInstallTemplateCreate>>>()+ mockInstallTemplate.mockReturnValue(pendingInstall.promise)+ const server = gatewayServer({+ id: 'oauth-template-server',+ template_id: 'template-id',+ template_auth_type: 'oauth',+ })+ logic.actions.loadServersSuccess([server])++ logic.actions.connectServer(server.id)+ logic.actions.connectServer(server.id)++ expect(mockInstallTemplate).toHaveBeenCalledTimes(1)++ pendingInstall.resolve({ redirect_url: '' })+ await expectLogic(logic).toFinishAllListeners()+ })++ it('surfaces access update failures and clears the loading state', async () => {+ const server = gatewayServer({ is_team_enabled: true })+ const toast = jest.spyOn(lemonToast, 'error')+ mockServersPartialUpdate.mockRejectedValue(apiError('You cannot update this server.'))+ logic.actions.loadServersSuccess([server])++ await expectLogic(logic, () => {+ logic.actions.toggleServerEnabled(server.id, false)+ }).toFinishAllListeners()++ expect(toast).toHaveBeenCalledWith('You cannot update this server.')+ expect(logic.values.serverEnabledLoadingIds).toEqual(new Set())+ expect(logic.values.servers[0].is_team_enabled).toBe(true)+ })++ it('bulk-disables through the config endpoint instead of per-server PATCHes', async () => {+ const server = gatewayServer({ id: 'row-server', is_team_enabled: true })+ const pendingBulk = deferred<Awaited<ReturnType<typeof mcpGatewayConfigSetAllServersEnabledCreate>>>()+ mockSetAllServersEnabled.mockReturnValue(pendingBulk.promise)+ mockServersList.mockClear()+ mockServersList.mockResolvedValue({ count: 1, results: [{ ...server, is_team_enabled: false }] })+ logic.actions.loadServersSuccess([server])++ logic.actions.setAllServersEnabled(false)+ await Promise.resolve()++ expect(logic.values.allServersEnabledLoading).toBe(true)+ pendingBulk.resolve({ ...logic.values.config!, default_servers_enabled: false })+ await expectLogic(logic).toFinishAllListeners()++ expect(mockSetAllServersEnabled).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), { enabled: false })+ expect(mockServersPartialUpdate).not.toHaveBeenCalled()+ expect(logic.values.defaultServersEnabled).toBe(false)+ expect(logic.values.servers).toEqual([{ ...server, is_team_enabled: false }])+ expect(logic.values.allServersEnabledLoading).toBe(false)+ })++ it.each([+ ['materializes a new row', 'materialized-server'],+ ['replaces the existing row', 'server-id'],+ ])('setTemplateEnabled %s without duplicating servers', async (_name, returnedServerId) => {+ const existing = gatewayServer({ id: 'server-id', is_team_enabled: true })+ const returned = gatewayServer({+ id: returnedServerId,+ template_id: 'catalog-template',+ is_team_enabled: false,+ })+ mockSetTemplateEnabled.mockResolvedValue(returned)+ logic.actions.loadServersSuccess([existing])++ await expectLogic(logic, () => {+ logic.actions.setTemplateEnabled('catalog-template', false)+ }).toFinishAllListeners()++ expect(mockSetTemplateEnabled).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), {+ template_id: 'catalog-template',+ enabled: false,+ })+ expect(logic.values.servers).toEqual(returnedServerId === existing.id ? [returned] : [existing, returned])+ expect(logic.values.templateEnabledLoadingIds).toEqual(new Set())+ })++ it('recommends only catalog templates without a registry row, ignoring trailing slashes', () => {+ const linkedTemplate = serverTemplate({ id: 'linked-template', url: 'https://linked.example.com/mcp' })+ const sameUrlTemplate = serverTemplate({ id: 'same-url-template', url: 'https://custom.example.com/mcp/' })+ const freshTemplate = serverTemplate({ id: 'fresh-template', url: 'https://fresh.example.com/mcp' })+ logic.actions.loadTemplatesSuccess([linkedTemplate, sameUrlTemplate, freshTemplate])+ logic.actions.loadServersSuccess([+ gatewayServer({ id: 'linked-row', template_id: 'linked-template', url: 'https://linked.example.com/mcp' }),+ gatewayServer({ id: 'custom-row', template_id: null, url: 'https://custom.example.com/mcp' }),+ ])++ expect(logic.values.recommendedTemplates).toEqual([freshTemplate])+ expect(logic.values.mergedServers.map((server) => server.id)).toEqual([+ 'linked-row',+ 'custom-row',+ 'template:fresh-template',+ ])+ })++ it.each([+ [true, false, true],+ [false, false, false],+ [false, true, true],+ ])(+ 'shows recommended templates (isAdmin=%s, defaultEnabled=%s) -> visible=%s',+ (isAdmin, defaultEnabled, visible) => {+ logic.actions.loadConfigSuccess({+ is_admin: isAdmin,+ allow_custom_servers: true,+ default_servers_enabled: defaultEnabled,+ })+ logic.actions.loadTemplatesSuccess([serverTemplate({ id: 'fresh-template' })])++ if (!visible) {+ expect(logic.values.templateOnlyServers).toEqual([])+ } else {+ expect(logic.values.templateOnlyServers).toHaveLength(1)+ expect(logic.values.templateOnlyServers[0].is_team_enabled).toBe(defaultEnabled)+ }+ }+ )++ it('connects a recommended template through the template install flow', async () => {+ logic.actions.loadTemplatesSuccess([serverTemplate({ id: 'fresh-template', auth_type: 'oauth' })])++ await expectLogic(logic, () => {+ logic.actions.connectServer('template:fresh-template')+ }).toFinishAllListeners()++ expect(mockInstallTemplate).toHaveBeenCalledWith(+ String(MOCK_DEFAULT_TEAM.id),+ expect.objectContaining({ template_id: 'fresh-template', scope: 'personal' })+ )+ })++ it('tracks preset updates by audience and uses the mutation response', async () => {+ const pendingPreset = deferred<Awaited<ReturnType<typeof mcpGatewayConfigApplyPresetCreate>>>()+ const updatedConfig = {+ ...logic.values.config!,+ member_default_preset: 'block' as const,+ }+ mockApplyPreset.mockReturnValue(pendingPreset.promise)+ const configLoadCalls = mockConfigList.mock.calls.length++ logic.actions.applyPreset('members', 'block')+ logic.actions.applyPreset('agents', 'allow')++ expect(logic.values.applyingPresetByAudience).toEqual({ members: 'block' })+ expect(mockApplyPreset).toHaveBeenCalledTimes(1)++ pendingPreset.resolve(updatedConfig)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.applyingPresetByAudience).toEqual({})+ expect(logic.values.config).toEqual(updatedConfig)+ expect(mockConfigList).toHaveBeenCalledTimes(configLoadCalls)+ })++ it('loads members one server-controlled page at a time', async () => {+ const secondPageMember = gatewayMember(101)+ mockMembersList.mockResolvedValue({ count: 101, results: [secondPageMember] })++ await expectLogic(logic, () => {+ logic.actions.setMembersOffset(GATEWAY_MEMBERS_PAGE_SIZE)+ }).toFinishAllListeners()++ expect(mockMembersList).toHaveBeenLastCalledWith(String(MOCK_DEFAULT_TEAM.id), {+ limit: GATEWAY_MEMBERS_PAGE_SIZE,+ offset: GATEWAY_MEMBERS_PAGE_SIZE,+ })+ expect(logic.values.memberCount).toBe(101)+ expect(logic.values.members).toEqual([secondPageMember])+ })+})diff --git a/products/mcp_store/frontend/gateway/mcpGatewayLogic.ts b/products/mcp_store/frontend/gateway/mcpGatewayLogic.tsnew file mode 100644index 000000000000..17129e8c888b--- /dev/null+++ b/products/mcp_store/frontend/gateway/mcpGatewayLogic.ts@@ -0,0 +1,1216 @@+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import { teamLogic } from 'scenes/teamLogic'++import {+ mcpGatewayConfigApplyPresetCreate,+ mcpGatewayConfigList,+ mcpGatewayConfigSetAllServersEnabledCreate,+ mcpGatewayConfigUpdateSettingsCreate,+ mcpGatewayMembersList,+ mcpGatewayMembersSetAccessCreate,+ mcpGatewayRulesList,+ mcpGatewayRulesPartialUpdate,+ mcpGatewayServersDestroy,+ mcpGatewayServersList,+ mcpGatewayServersPartialUpdate,+ mcpGatewayServersSetTemplateEnabledCreate,+ mcpGatewayServiceAccountsAccessCreate,+ mcpGatewayServiceAccountsList,+ mcpGatewayServiceAccountsPartialUpdate,+ mcpServerInstallationsDestroy,+ mcpServerInstallationsInstallCustomCreate,+ mcpServerInstallationsInstallTemplateCreate,+ mcpServerInstallationsPartialUpdate,+ mcpServersList,+} from '../generated/api'+import {+ AudienceEnumApi,+ GatewayMemberSummaryApi,+ InstallCustomAuthTypeEnumApi,+ MCPGatewayServerApi,+ MCPOrgRuleApi,+ MCPPolicyPresetEnumApi,+ MCPServerTemplateApi,+ MCPServiceAccountApi,+ TeamMCPGatewayConfigApi,+} from '../generated/api.schemas'++export const GATEWAY_CATEGORY_LABELS: Record<string, string> = {+ business: 'Business Operations',+ data: 'Data & Analytics',+ design: 'Design & Content',+ dev: 'Developer Tools & APIs',+ infra: 'Infrastructure',+ productivity: 'Productivity & Collaboration',+}++function currentProjectId(): string {+ return String(teamLogic.values.currentTeamId)+}++/** The registry is sparse: catalog templates without a row are rendered from+ * client-side entries whose ids carry this prefix. */+export const TEMPLATE_SERVER_ID_PREFIX = 'template:'++/** A real registry row, or a catalog template synthesized client-side (no+ * `created_by` until an install or admin toggle materializes the row). */+export type GatewayServerEntry = MCPGatewayServerApi++export function isTemplateOnlyServer(server: Pick<GatewayServerEntry, 'id'>): boolean {+ return server.id.startsWith(TEMPLATE_SERVER_ID_PREFIX)+}++function normalizeServerUrl(url: string): string {+ return url.replace(/\/+$/, '')+}++function templateAsGatewayServer(template: MCPServerTemplateApi, enabled: boolean): GatewayServerEntry {+ return {+ id: `${TEMPLATE_SERVER_ID_PREFIX}${template.id}`,+ name: template.name,+ url: template.url,+ description: template.description ?? '',+ category: template.category ?? 'dev',+ template_auth_type: template.auth_type ?? 'oauth',+ is_team_enabled: enabled,+ icon_key: template.icon_key,+ icon_domain: template.icon_domain,+ docs_url: template.docs_url ?? '',+ template_id: template.id,+ tool_count: 0,+ connections: [],+ your_connection: null,+ agents: [],+ revoked_user_ids: [],+ is_revoked_for_you: false,+ created_by: null,+ created_at: '',+ updated_at: '',+ }+}++async function fetchGatewayServers(): Promise<MCPGatewayServerApi[]> {+ const response = await mcpGatewayServersList(currentProjectId(), { limit: 500 })+ return response.results+}++function errorDetail(error: unknown): string | null {+ if (typeof error !== 'object' || error === null || !('detail' in error)) {+ return null+ }+ return typeof error.detail === 'string' ? error.detail : null+}++export function agentServerAccessKey(accountId: string, serverId: string): string {+ return `${accountId}:${serverId}`+}++export function memberServerAccessKey(userId: number, serverId: string): string {+ return `${userId}:${serverId}`+}++export const GATEWAY_MEMBERS_PAGE_SIZE = 100++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpGatewayLogicValues {+ accountStatusLoadingIds: Set<string>+ activeAgentCount: number+ agentServerAccessLoadingKeys: Set<string>+ allServersEnabledLoading: boolean+ allowCustomServers: boolean+ allowCustomServersLoading: boolean+ allowMemberAgentAccess: boolean+ allowMemberAgentAccessLoading: boolean+ applyingPresetByAudience: Partial<Record<AudienceEnumApi, MCPPolicyPresetEnumApi>>+ canAddServers: boolean+ canManageAgentAccess: boolean+ categoryCounts: Record<string, number>+ categoryFilter: string | null+ config: TeamMCPGatewayConfigApi | null+ configLoading: boolean+ connectingServerId: string | null+ connectionApiKey: string+ connectionAuthType: InstallCustomAuthTypeEnumApi+ connectionClientId: string+ connectionClientSecret: string+ connectionModalServer: GatewayServerEntry | null+ connectionModalServerId: string | null+ connectionSubmitDisabledReason: string | null+ defaultServersEnabled: boolean+ enabledServerCount: number+ filteredServers: GatewayServerEntry[]+ isAdmin: boolean+ memberCount: number+ memberServerAccessLoadingKeys: Set<string>+ members: GatewayMemberSummaryApi[]+ membersLoading: boolean+ membersOffset: number+ mergedServers: GatewayServerEntry[]+ recommendedTemplates: MCPServerTemplateApi[]+ ruleEnabledLoadingIds: Set<string>+ rules: MCPOrgRuleApi[]+ rulesLoading: boolean+ searchQuery: string+ serverEnabledLoadingIds: Set<string>+ servers: MCPGatewayServerApi[]+ serversInitialized: boolean+ serversLoading: boolean+ serviceAccounts: MCPServiceAccountApi[]+ serviceAccountsInitialized: boolean+ serviceAccountsLoading: boolean+ templateEnabledLoadingIds: Set<string>+ templateOnlyServers: GatewayServerEntry[]+ templates: MCPServerTemplateApi[]+ templatesLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpGatewayLogicActions {+ applyPreset: (+ audience: AudienceEnumApi,+ preset: MCPPolicyPresetEnumApi+ ) => {+ audience: AudienceEnumApi+ preset: MCPPolicyPresetEnumApi+ }+ applyPresetComplete: (audience: AudienceEnumApi) => {+ audience: AudienceEnumApi+ }+ applyPresetStarted: (+ audience: AudienceEnumApi,+ preset: MCPPolicyPresetEnumApi+ ) => {+ audience: AudienceEnumApi+ preset: MCPPolicyPresetEnumApi+ }+ closeConnectionModal: () => {+ value: true+ }+ connectServer: (serverId: string) => {+ serverId: string+ }+ disconnectServer: (+ serverId: string,+ installationId: string+ ) => {+ installationId: string+ serverId: string+ }+ loadConfig: () => any+ loadConfigFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadConfigSuccess: (+ config: TeamMCPGatewayConfigApi,+ payload?: any+ ) => {+ config: TeamMCPGatewayConfigApi+ payload?: any+ }+ loadMembers: (_: void) => void+ loadMembersFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadMembersSuccess: (+ members: GatewayMemberSummaryApi[],+ payload?: void+ ) => {+ members: GatewayMemberSummaryApi[]+ payload?: void+ }+ loadRules: () => any+ loadRulesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRulesSuccess: (+ rules: MCPOrgRuleApi[],+ payload?: any+ ) => {+ rules: MCPOrgRuleApi[]+ payload?: any+ }+ loadServers: () => any+ loadServersFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadServersSuccess: (+ servers: MCPGatewayServerApi[],+ payload?: any+ ) => {+ servers: MCPGatewayServerApi[]+ payload?: any+ }+ loadServiceAccounts: () => any+ loadServiceAccountsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadServiceAccountsSuccess: (+ serviceAccounts: MCPServiceAccountApi[],+ payload?: any+ ) => {+ serviceAccounts: MCPServiceAccountApi[]+ payload?: any+ }+ loadTemplates: () => any+ loadTemplatesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadTemplatesSuccess: (+ templates: MCPServerTemplateApi[],+ payload?: any+ ) => {+ templates: MCPServerTemplateApi[]+ payload?: any+ }+ openConnectionModal: (+ serverId: string,+ authType: InstallCustomAuthTypeEnumApi+ ) => {+ authType: InstallCustomAuthTypeEnumApi+ serverId: string+ }+ performConnection: (+ serverId: string,+ authType: InstallCustomAuthTypeEnumApi,+ apiKey: string,+ clientId: string,+ clientSecret: string+ ) => {+ apiKey: string+ authType: InstallCustomAuthTypeEnumApi+ clientId: string+ clientSecret: string+ serverId: string+ }+ performConnectionComplete: () => {+ value: true+ }+ removeServer: (serverId: string) => {+ serverId: string+ }+ setAgentServerAccess: (+ accountId: string,+ serverId: string,+ enabled: boolean+ ) => {+ accountId: string+ enabled: boolean+ serverId: string+ }+ setAgentServerAccessComplete: (+ accountId: string,+ serverId: string+ ) => {+ accountId: string+ serverId: string+ }+ setAllServersEnabled: (enabled: boolean) => {+ enabled: boolean+ }+ setAllServersEnabledComplete: () => {+ value: true+ }+ setAllowCustomServers: (allowed: boolean) => {+ allowed: boolean+ }+ setAllowCustomServersComplete: () => {+ value: true+ }+ setAllowMemberAgentAccess: (allowed: boolean) => {+ allowed: boolean+ }+ setAllowMemberAgentAccessComplete: () => {+ value: true+ }+ setCategoryFilter: (category: string | null) => {+ category: string | null+ }+ setConnectionApiKey: (apiKey: string) => {+ apiKey: string+ }+ setConnectionAuthType: (authType: InstallCustomAuthTypeEnumApi) => {+ authType: InstallCustomAuthTypeEnumApi+ }+ setConnectionClientId: (clientId: string) => {+ clientId: string+ }+ setConnectionClientSecret: (clientSecret: string) => {+ clientSecret: string+ }+ setMemberCount: (memberCount: number) => {+ memberCount: number+ }+ setMemberServerAccess: (+ userId: number,+ serverId: string,+ enabled: boolean+ ) => {+ enabled: boolean+ serverId: string+ userId: number+ }+ setMemberServerAccessComplete: (+ userId: number,+ serverId: string+ ) => {+ serverId: string+ userId: number+ }+ setMembersOffset: (membersOffset: number) => {+ membersOffset: number+ }+ setSearchQuery: (query: string) => {+ query: string+ }+ setTemplateEnabled: (+ templateId: string,+ enabled: boolean+ ) => {+ enabled: boolean+ templateId: string+ }+ setTemplateEnabledComplete: (templateId: string) => {+ templateId: string+ }+ submitConnection: () => {+ value: true+ }+ toggleAccountStatus: (+ accountId: string,+ paused: boolean+ ) => {+ accountId: string+ paused: boolean+ }+ toggleAccountStatusComplete: (accountId: string) => {+ accountId: string+ }+ toggleRuleEnabled: (+ ruleId: string,+ enabled: boolean+ ) => {+ enabled: boolean+ ruleId: string+ }+ toggleRuleEnabledComplete: (ruleId: string) => {+ ruleId: string+ }+ toggleServerEnabled: (+ serverId: string,+ enabled: boolean+ ) => {+ enabled: boolean+ serverId: string+ }+ toggleServerEnabledComplete: (serverId: string) => {+ serverId: string+ }+ toggleYourConnectionEnabled: (+ installationId: string,+ enabled: boolean+ ) => {+ enabled: boolean+ installationId: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpGatewayLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ isAdmin: (config: TeamMCPGatewayConfigApi | null) => boolean+ allowCustomServers: (config: TeamMCPGatewayConfigApi | null) => boolean+ allowMemberAgentAccess: (config: TeamMCPGatewayConfigApi | null) => boolean+ canAddServers: (isAdmin: boolean, allowCustomServers: boolean) => boolean+ canManageAgentAccess: (isAdmin: boolean, allowMemberAgentAccess: boolean) => boolean+ defaultServersEnabled: (config: TeamMCPGatewayConfigApi | null) => boolean+ recommendedTemplates: (+ templates: MCPServerTemplateApi[],+ servers: MCPGatewayServerApi[]+ ) => MCPServerTemplateApi[]+ templateOnlyServers: (+ recommendedTemplates: MCPServerTemplateApi[],+ defaultServersEnabled: boolean,+ isAdmin: boolean+ ) => GatewayServerEntry[]+ mergedServers: (+ servers: MCPGatewayServerApi[],+ templateOnlyServers: MCPGatewayServerApi[]+ ) => GatewayServerEntry[]+ connectionModalServer: (+ mergedServers: MCPGatewayServerApi[],+ connectionModalServerId: string | null+ ) => GatewayServerEntry | null+ connectionSubmitDisabledReason: (+ connectionAuthType: InstallCustomAuthTypeEnumApi,+ connectionApiKey: string+ ) => string | null+ categoryCounts: (mergedServers: MCPGatewayServerApi[]) => Record<string, number>+ filteredServers: (+ mergedServers: MCPGatewayServerApi[],+ searchQuery: string,+ categoryFilter: string | null+ ) => GatewayServerEntry[]+ activeAgentCount: (serviceAccounts: MCPServiceAccountApi[]) => number+ enabledServerCount: (mergedServers: MCPGatewayServerApi[]) => number+ }+}++export type mcpGatewayLogicType = MakeLogicType<+ mcpGatewayLogicValues,+ mcpGatewayLogicActions,+ Record<string, any>,+ mcpGatewayLogicMeta+>++export const mcpGatewayLogic = kea<mcpGatewayLogicType>([+ path(['products', 'mcp_store', 'frontend', 'gateway', 'mcpGatewayLogic']),++ actions({+ setSearchQuery: (query: string) => ({ query }),+ setCategoryFilter: (category: string | null) => ({ category }),+ toggleServerEnabled: (serverId: string, enabled: boolean) => ({ serverId, enabled }),+ toggleServerEnabledComplete: (serverId: string) => ({ serverId }),+ removeServer: (serverId: string) => ({ serverId }),+ connectServer: (serverId: string) => ({ serverId }),+ openConnectionModal: (serverId: string, authType: InstallCustomAuthTypeEnumApi) => ({+ serverId,+ authType,+ }),+ closeConnectionModal: true,+ setConnectionAuthType: (authType: InstallCustomAuthTypeEnumApi) => ({ authType }),+ setConnectionApiKey: (apiKey: string) => ({ apiKey }),+ setConnectionClientId: (clientId: string) => ({ clientId }),+ setConnectionClientSecret: (clientSecret: string) => ({ clientSecret }),+ submitConnection: true,+ performConnection: (+ serverId: string,+ authType: InstallCustomAuthTypeEnumApi,+ apiKey: string,+ clientId: string,+ clientSecret: string+ ) => ({ serverId, authType, apiKey, clientId, clientSecret }),+ performConnectionComplete: true,+ disconnectServer: (serverId: string, installationId: string) => ({ serverId, installationId }),+ toggleYourConnectionEnabled: (installationId: string, enabled: boolean) => ({ installationId, enabled }),+ toggleAccountStatus: (accountId: string, paused: boolean) => ({ accountId, paused }),+ toggleAccountStatusComplete: (accountId: string) => ({ accountId }),+ toggleRuleEnabled: (ruleId: string, enabled: boolean) => ({ ruleId, enabled }),+ toggleRuleEnabledComplete: (ruleId: string) => ({ ruleId }),+ setAllowCustomServers: (allowed: boolean) => ({ allowed }),+ setAllowCustomServersComplete: true,+ setAllowMemberAgentAccess: (allowed: boolean) => ({ allowed }),+ setAllowMemberAgentAccessComplete: true,+ applyPreset: (audience: AudienceEnumApi, preset: MCPPolicyPresetEnumApi) => ({ audience, preset }),+ applyPresetComplete: (audience: AudienceEnumApi) => ({ audience }),+ applyPresetStarted: (audience: AudienceEnumApi, preset: MCPPolicyPresetEnumApi) => ({ audience, preset }),+ setMemberServerAccess: (userId: number, serverId: string, enabled: boolean) => ({+ userId,+ serverId,+ enabled,+ }),+ setMemberServerAccessComplete: (userId: number, serverId: string) => ({ userId, serverId }),+ setMemberCount: (memberCount: number) => ({ memberCount }),+ setMembersOffset: (membersOffset: number) => ({ membersOffset: Math.max(0, membersOffset) }),+ setAgentServerAccess: (accountId: string, serverId: string, enabled: boolean) => ({+ accountId,+ serverId,+ enabled,+ }),+ setAgentServerAccessComplete: (accountId: string, serverId: string) => ({ accountId, serverId }),+ setAllServersEnabled: (enabled: boolean) => ({ enabled }),+ setAllServersEnabledComplete: true,+ setTemplateEnabled: (templateId: string, enabled: boolean) => ({ templateId, enabled }),+ setTemplateEnabledComplete: (templateId: string) => ({ templateId }),+ }),++ loaders(({ actions, values }) => ({+ config: [+ null as TeamMCPGatewayConfigApi | null,+ {+ loadConfig: async () => await mcpGatewayConfigList(currentProjectId()),+ },+ ],+ servers: [+ [] as MCPGatewayServerApi[],+ {+ loadServers: async () => fetchGatewayServers(),+ },+ ],+ templates: [+ [] as MCPServerTemplateApi[],+ {+ loadTemplates: async () => {+ const response = await mcpServersList(currentProjectId(), { limit: 500 })+ return response.results+ },+ },+ ],+ serviceAccounts: [+ [] as MCPServiceAccountApi[],+ {+ loadServiceAccounts: async () => {+ const response = await mcpGatewayServiceAccountsList(currentProjectId(), { limit: 500 })+ return response.results+ },+ },+ ],+ rules: [+ [] as MCPOrgRuleApi[],+ {+ loadRules: async () => {+ const response = await mcpGatewayRulesList(currentProjectId(), { limit: 500 })+ return response.results+ },+ },+ ],+ members: [+ [] as GatewayMemberSummaryApi[],+ {+ loadMembers: async (_: void, breakpoint) => {+ const response = await mcpGatewayMembersList(currentProjectId(), {+ limit: GATEWAY_MEMBERS_PAGE_SIZE,+ offset: values.membersOffset,+ })+ breakpoint()+ actions.setMemberCount(response.count)+ return response.results+ },+ },+ ],+ })),++ reducers({+ searchQuery: ['', { setSearchQuery: (_, { query }) => query }],+ categoryFilter: [null as string | null, { setCategoryFilter: (_, { category }) => category }],+ memberCount: [0, { setMemberCount: (_, { memberCount }) => memberCount }],+ membersOffset: [0, { setMembersOffset: (_, { membersOffset }) => membersOffset }],+ connectingServerId: [+ null as string | null,+ {+ performConnection: (_, { serverId }) => serverId,+ performConnectionComplete: () => null,+ },+ ],+ connectionModalServerId: [+ null as string | null,+ {+ openConnectionModal: (_, { serverId }) => serverId,+ closeConnectionModal: () => null,+ },+ ],+ connectionAuthType: [+ 'oauth' as InstallCustomAuthTypeEnumApi,+ {+ openConnectionModal: (_, { authType }) => authType,+ setConnectionAuthType: (_, { authType }) => authType,+ closeConnectionModal: () => 'oauth',+ },+ ],+ connectionApiKey: [+ '',+ {+ setConnectionApiKey: (_, { apiKey }) => apiKey,+ setConnectionAuthType: () => '',+ openConnectionModal: () => '',+ closeConnectionModal: () => '',+ },+ ],+ connectionClientId: [+ '',+ {+ setConnectionClientId: (_, { clientId }) => clientId,+ setConnectionAuthType: () => '',+ openConnectionModal: () => '',+ closeConnectionModal: () => '',+ },+ ],+ connectionClientSecret: [+ '',+ {+ setConnectionClientSecret: (_, { clientSecret }) => clientSecret,+ setConnectionAuthType: () => '',+ openConnectionModal: () => '',+ closeConnectionModal: () => '',+ },+ ],+ serversInitialized: [+ false,+ {+ loadServersSuccess: () => true,+ loadServersFailure: () => true,+ },+ ],+ serviceAccountsInitialized: [+ false,+ {+ loadServiceAccountsSuccess: () => true,+ loadServiceAccountsFailure: () => true,+ },+ ],+ accountStatusLoadingIds: [+ new Set<string>(),+ {+ toggleAccountStatus: (state, { accountId }) => new Set(state).add(accountId),+ toggleAccountStatusComplete: (state, { accountId }) => {+ const next = new Set(state)+ next.delete(accountId)+ return next+ },+ },+ ],+ agentServerAccessLoadingKeys: [+ new Set<string>(),+ {+ setAgentServerAccess: (state, { accountId, serverId }) =>+ new Set(state).add(agentServerAccessKey(accountId, serverId)),+ setAgentServerAccessComplete: (state, { accountId, serverId }) => {+ const next = new Set(state)+ next.delete(agentServerAccessKey(accountId, serverId))+ return next+ },+ },+ ],+ serverEnabledLoadingIds: [+ new Set<string>(),+ {+ toggleServerEnabled: (state, { serverId }) => new Set(state).add(serverId),+ toggleServerEnabledComplete: (state, { serverId }) => {+ const next = new Set(state)+ next.delete(serverId)+ return next+ },+ },+ ],+ templateEnabledLoadingIds: [+ new Set<string>(),+ {+ setTemplateEnabled: (state, { templateId }) => new Set(state).add(templateId),+ setTemplateEnabledComplete: (state, { templateId }) => {+ const next = new Set(state)+ next.delete(templateId)+ return next+ },+ },+ ],+ memberServerAccessLoadingKeys: [+ new Set<string>(),+ {+ setMemberServerAccess: (state, { userId, serverId }) =>+ new Set(state).add(memberServerAccessKey(userId, serverId)),+ setMemberServerAccessComplete: (state, { userId, serverId }) => {+ const next = new Set(state)+ next.delete(memberServerAccessKey(userId, serverId))+ return next+ },+ },+ ],+ ruleEnabledLoadingIds: [+ new Set<string>(),+ {+ toggleRuleEnabled: (state, { ruleId }) => new Set(state).add(ruleId),+ toggleRuleEnabledComplete: (state, { ruleId }) => {+ const next = new Set(state)+ next.delete(ruleId)+ return next+ },+ },+ ],+ applyingPresetByAudience: [+ {} as Partial<Record<AudienceEnumApi, MCPPolicyPresetEnumApi>>,+ {+ applyPresetStarted: (state, { audience, preset }) => ({ ...state, [audience]: preset }),+ applyPresetComplete: (state, { audience }) => {+ const next = { ...state }+ delete next[audience]+ return next+ },+ },+ ],+ allowCustomServersLoading: [+ false,+ {+ setAllowCustomServers: () => true,+ setAllowCustomServersComplete: () => false,+ },+ ],+ allowMemberAgentAccessLoading: [+ false,+ {+ setAllowMemberAgentAccess: () => true,+ setAllowMemberAgentAccessComplete: () => false,+ },+ ],+ allServersEnabledLoading: [+ false,+ {+ setAllServersEnabled: () => true,+ setAllServersEnabledComplete: () => false,+ },+ ],+ }),++ selectors({+ isAdmin: [(s) => [s.config], (config: TeamMCPGatewayConfigApi | null): boolean => Boolean(config?.is_admin)],+ allowCustomServers: [+ (s) => [s.config],+ (config: TeamMCPGatewayConfigApi | null): boolean => config?.allow_custom_servers ?? true,+ ],+ allowMemberAgentAccess: [+ (s) => [s.config],+ (config: TeamMCPGatewayConfigApi | null): boolean => config?.allow_member_agent_access ?? true,+ ],+ canAddServers: [+ (s) => [s.isAdmin, s.allowCustomServers],+ (isAdmin: boolean, allowCustomServers: boolean): boolean => isAdmin || allowCustomServers,+ ],+ canManageAgentAccess: [+ (s) => [s.isAdmin, s.allowMemberAgentAccess],+ (isAdmin: boolean, allowMemberAgentAccess: boolean): boolean => isAdmin || allowMemberAgentAccess,+ ],+ defaultServersEnabled: [+ (s) => [s.config],+ (config: TeamMCPGatewayConfigApi | null): boolean => config?.default_servers_enabled ?? true,+ ],+ recommendedTemplates: [+ (s) => [s.templates, s.servers],+ (templates: MCPServerTemplateApi[], servers: MCPGatewayServerApi[]): MCPServerTemplateApi[] => {+ const registeredTemplateIds = new Set(servers.map((server) => server.template_id).filter(Boolean))+ const registeredUrls = new Set(servers.map((server) => normalizeServerUrl(server.url)))+ return templates.filter(+ (template) =>+ !registeredTemplateIds.has(template.id) && !registeredUrls.has(normalizeServerUrl(template.url))+ )+ },+ ],+ templateOnlyServers: [+ (s) => [s.recommendedTemplates, s.defaultServersEnabled, s.isAdmin],+ (+ recommendedTemplates: MCPServerTemplateApi[],+ defaultServersEnabled: boolean,+ isAdmin: boolean+ ): GatewayServerEntry[] =>+ // Members only see catalog servers while the team default keeps them enabled.+ !isAdmin && !defaultServersEnabled+ ? []+ : recommendedTemplates.map((template) => templateAsGatewayServer(template, defaultServersEnabled)),+ ],+ mergedServers: [+ (s) => [s.servers, s.templateOnlyServers],+ (servers: MCPGatewayServerApi[], templateOnlyServers: GatewayServerEntry[]): GatewayServerEntry[] => [+ ...servers,+ ...templateOnlyServers,+ ],+ ],+ connectionModalServer: [+ (s) => [s.mergedServers, s.connectionModalServerId],+ (mergedServers: GatewayServerEntry[], serverId: string | null): GatewayServerEntry | null =>+ mergedServers.find((server) => server.id === serverId) ?? null,+ ],+ connectionSubmitDisabledReason: [+ (s) => [s.connectionAuthType, s.connectionApiKey],+ (authType: InstallCustomAuthTypeEnumApi, apiKey: string): string | null =>+ authType === 'api_key' && !apiKey.trim() ? 'Enter an API key to connect this server.' : null,+ ],+ categoryCounts: [+ (s) => [s.mergedServers],+ (mergedServers: GatewayServerEntry[]): Record<string, number> => {+ const counts: Record<string, number> = {}+ for (const server of mergedServers) {+ counts[server.category ?? 'dev'] = (counts[server.category ?? 'dev'] || 0) + 1+ }+ return counts+ },+ ],+ filteredServers: [+ (s) => [s.mergedServers, s.searchQuery, s.categoryFilter],+ (+ mergedServers: GatewayServerEntry[],+ searchQuery: string,+ categoryFilter: string | null+ ): GatewayServerEntry[] => {+ const query = searchQuery.trim().toLowerCase()+ return mergedServers.filter((server) => {+ if (categoryFilter && server.category !== categoryFilter) {+ return false+ }+ if (!query) {+ return true+ }+ return (+ server.name.toLowerCase().includes(query) ||+ (server.description || '').toLowerCase().includes(query) ||+ server.url.toLowerCase().includes(query)+ )+ })+ },+ ],+ activeAgentCount: [+ (s) => [s.serviceAccounts],+ (serviceAccounts: MCPServiceAccountApi[]): number =>+ serviceAccounts.filter((account) => account.status === 'active').length,+ ],+ enabledServerCount: [+ (s) => [s.mergedServers],+ (mergedServers: GatewayServerEntry[]): number =>+ mergedServers.filter((server) => server.is_team_enabled).length,+ ],+ }),++ listeners(({ actions, values }) => ({+ toggleServerEnabled: async ({ serverId, enabled }) => {+ const server = values.servers.find((candidate) => candidate.id === serverId)+ try {+ await mcpGatewayServersPartialUpdate(currentProjectId(), serverId, { is_team_enabled: enabled })+ actions.loadServersSuccess(+ values.servers.map((candidate) =>+ candidate.id === serverId ? { ...candidate, is_team_enabled: enabled } : candidate+ )+ )+ actions.loadServers()+ lemonToast[enabled ? 'success' : 'info'](+ `${server?.name ?? 'Server'} ${enabled ? 'enabled for the team' : 'disabled'}`+ )+ } catch (error: unknown) {+ lemonToast.error(+ errorDetail(error) ?? `Could not ${enabled ? 'enable' : 'disable'} ${server?.name ?? 'this server'}`+ )+ } finally {+ actions.toggleServerEnabledComplete(serverId)+ }+ },+ setAllServersEnabled: async ({ enabled }) => {+ try {+ const config = await mcpGatewayConfigSetAllServersEnabledCreate(currentProjectId(), { enabled })+ actions.loadConfigSuccess(config)+ actions.loadServersSuccess(await fetchGatewayServers())+ lemonToast[enabled ? 'success' : 'info'](+ enabled+ ? 'Every server is enabled for the team'+ : 'All servers disabled, including catalog servers added later. Enable them one by one.'+ )+ } catch (error: unknown) {+ lemonToast.error(errorDetail(error) ?? 'Could not update all servers')+ } finally {+ actions.setAllServersEnabledComplete()+ }+ },+ setTemplateEnabled: async ({ templateId, enabled }) => {+ const template = values.templates.find((candidate) => candidate.id === templateId)+ try {+ const server = await mcpGatewayServersSetTemplateEnabledCreate(currentProjectId(), {+ template_id: templateId,+ enabled,+ })+ const exists = values.servers.some((candidate) => candidate.id === server.id)+ actions.loadServersSuccess(+ exists+ ? values.servers.map((candidate) => (candidate.id === server.id ? server : candidate))+ : [...values.servers, server]+ )+ lemonToast[enabled ? 'success' : 'info'](+ `${server.name} ${enabled ? 'enabled for the team' : 'disabled'}`+ )+ } catch (error: unknown) {+ lemonToast.error(+ errorDetail(error) ??+ `Could not ${enabled ? 'enable' : 'disable'} ${template?.name ?? 'this server'}`+ )+ } finally {+ actions.setTemplateEnabledComplete(templateId)+ }+ },+ removeServer: async ({ serverId }) => {+ const server = values.servers.find((candidate) => candidate.id === serverId)+ try {+ await mcpGatewayServersDestroy(currentProjectId(), serverId)+ actions.loadServers()+ lemonToast.info(+ server?.template_id+ ? `${server.name} removed. Everyone is disconnected and the server follows the team default again.`+ : `${server?.name ?? 'Server'} removed from the gateway. Everyone is disconnected.`+ )+ } catch (error: unknown) {+ lemonToast.error(errorDetail(error) ?? `Could not remove ${server?.name ?? 'this server'}`)+ }+ },+ connectServer: ({ serverId }) => {+ if (values.connectingServerId) {+ return+ }++ const server = values.mergedServers.find((candidate) => candidate.id === serverId)+ if (!server) {+ return+ }++ if (server.template_id && server.template_auth_type === 'oauth') {+ actions.performConnection(serverId, 'oauth', '', '', '')+ return+ }++ actions.openConnectionModal(serverId, server.template_auth_type ?? 'oauth')+ },+ submitConnection: () => {+ if (!values.connectionModalServerId || values.connectingServerId || values.connectionSubmitDisabledReason) {+ return+ }+ actions.performConnection(+ values.connectionModalServerId,+ values.connectionAuthType,+ values.connectionApiKey,+ values.connectionClientId,+ values.connectionClientSecret+ )+ },+ performConnection: async ({ serverId, authType, apiKey, clientId, clientSecret }) => {+ const server = values.mergedServers.find((candidate) => candidate.id === serverId)+ if (!server) {+ actions.performConnectionComplete()+ return+ }++ const returnPath = router.values.location.pathname+ const projectId = currentProjectId()+ try {+ const response = server.template_id+ ? await mcpServerInstallationsInstallTemplateCreate(projectId, {+ template_id: server.template_id,+ api_key: authType === 'api_key' ? apiKey || undefined : undefined,+ scope: 'personal',+ return_path: returnPath,+ })+ : await mcpServerInstallationsInstallCustomCreate(projectId, {+ name: server.name,+ url: server.url,+ auth_type: authType,+ api_key: authType === 'api_key' ? apiKey || undefined : undefined,+ description: server.description || '',+ client_id: authType === 'oauth' ? clientId || undefined : undefined,+ client_secret: authType === 'oauth' ? clientSecret || undefined : undefined,+ scope: 'personal',+ return_path: returnPath,+ })+ if ('redirect_url' in response && response.redirect_url) {+ window.location.href = response.redirect_url+ return+ }+ actions.closeConnectionModal()+ actions.loadServers()+ lemonToast.success(`Connected to ${server.name}`)+ } catch (error: unknown) {+ actions.loadServers()+ lemonToast.error(errorDetail(error) ?? `Could not connect to ${server.name}`)+ } finally {+ actions.performConnectionComplete()+ }+ },+ disconnectServer: async ({ serverId, installationId }) => {+ const server = values.servers.find((candidate) => candidate.id === serverId)+ try {+ await mcpServerInstallationsDestroy(currentProjectId(), installationId)+ actions.loadServers()+ lemonToast.info(`Disconnected from ${server?.name ?? 'server'}`)+ } catch (error: unknown) {+ lemonToast.error(errorDetail(error) ?? `Could not disconnect from ${server?.name ?? 'this server'}`)+ }+ },+ toggleYourConnectionEnabled: async ({ installationId, enabled }) => {+ try {+ await mcpServerInstallationsPartialUpdate(currentProjectId(), installationId, { is_enabled: enabled })+ actions.loadServers()+ } catch (error: unknown) {+ lemonToast.error(errorDetail(error) ?? 'Could not update this connection')+ }+ },+ toggleAccountStatus: async ({ accountId, paused }) => {+ const account = values.serviceAccounts.find((candidate) => candidate.id === accountId)+ try {+ await mcpGatewayServiceAccountsPartialUpdate(currentProjectId(), accountId, {+ status: paused ? 'paused' : 'active',+ })+ const status: MCPServiceAccountApi['status'] = paused ? 'paused' : 'active'+ actions.loadServiceAccountsSuccess(+ values.serviceAccounts.map((candidate) =>+ candidate.id === accountId ? { ...candidate, status } : candidate+ )+ )+ lemonToast[paused ? 'info' : 'success'](+ paused+ ? `${account?.name ?? 'Agent'} paused. All MCP access is off.`+ : `${account?.name ?? 'Agent'} is active again`+ )+ } catch (error: unknown) {+ lemonToast.error(+ errorDetail(error) ?? `Could not ${paused ? 'pause' : 'resume'} ${account?.name ?? 'this agent'}`+ )+ } finally {+ actions.toggleAccountStatusComplete(accountId)+ }+ },+ setAgentServerAccess: async ({ accountId, serverId, enabled }) => {+ const account = values.serviceAccounts.find((candidate) => candidate.id === accountId)+ const server = values.servers.find((candidate) => candidate.id === serverId)+ try {+ await mcpGatewayServiceAccountsAccessCreate(currentProjectId(), accountId, {+ gateway_server_id: serverId,+ enabled,+ })+ actions.loadServiceAccountsSuccess(+ values.serviceAccounts.map((candidate) => {+ if (candidate.id !== accountId) {+ return candidate+ }+ const serverIds = enabled+ ? Array.from(new Set([...candidate.server_ids, serverId]))+ : candidate.server_ids.filter((candidateServerId) => candidateServerId !== serverId)+ return { ...candidate, server_ids: serverIds }+ })+ )+ actions.loadServers()+ lemonToast[enabled ? 'success' : 'info'](+ enabled+ ? `${server?.name ?? 'Server'} shared with ${account?.name ?? 'agent'}`+ : `${account?.name ?? 'Agent'} can no longer access ${server?.name ?? 'server'}`+ )+ } catch (error: unknown) {+ lemonToast.error(+ errorDetail(error) ?? `Could not update server access for ${account?.name ?? 'this agent'}`+ )+ } finally {+ actions.setAgentServerAccessComplete(accountId, serverId)+ }+ },+ toggleRuleEnabled: async ({ ruleId, enabled }) => {+ const rule = values.rules.find((candidate) => candidate.id === ruleId)+ try {+ const updatedRule = await mcpGatewayRulesPartialUpdate(currentProjectId(), ruleId, { enabled })+ actions.loadRulesSuccess(+ values.rules.map((candidate) => (candidate.id === ruleId ? updatedRule : candidate))+ )+ lemonToast[enabled ? 'success' : 'info'](`${rule?.name ?? 'Rule'} ${enabled ? 'enabled' : 'disabled'}`)+ } catch (error: unknown) {+ lemonToast.error(errorDetail(error) ?? `Could not update ${rule?.name ?? 'this rule'}`)+ } finally {+ actions.toggleRuleEnabledComplete(ruleId)+ }+ },+ setAllowCustomServers: async ({ allowed }) => {+ try {+ const config = await mcpGatewayConfigUpdateSettingsCreate(currentProjectId(), {+ allow_custom_servers: allowed,+ })+ actions.loadConfigSuccess(config)+ lemonToast[allowed ? 'success' : 'info'](+ allowed ? 'Members can add custom servers' : 'Custom servers are now admin-only'+ )+ } catch (error: unknown) {+ lemonToast.error(errorDetail(error) ?? 'Could not update custom server access')+ } finally {+ actions.setAllowCustomServersComplete()+ }+ },+ setAllowMemberAgentAccess: async ({ allowed }) => {+ try {+ const config = await mcpGatewayConfigUpdateSettingsCreate(currentProjectId(), {+ allow_member_agent_access: allowed,+ })+ actions.loadConfigSuccess(config)+ lemonToast[allowed ? 'success' : 'info'](+ allowed ? 'Members can now manage agent access' : 'Only admins can manage agent access now'+ )+ } catch (error: unknown) {+ lemonToast.error(errorDetail(error) ?? 'Could not update member-managed agent access')+ } finally {+ actions.setAllowMemberAgentAccessComplete()+ }+ },+ applyPreset: async ({ audience, preset }) => {+ if (Object.keys(values.applyingPresetByAudience).length > 0) {+ return+ }+ actions.applyPresetStarted(audience, preset)+ try {+ const config = await mcpGatewayConfigApplyPresetCreate(currentProjectId(), { audience, preset })+ actions.loadConfigSuccess(config)+ lemonToast.success(`Baseline applied to ${audience}`)+ } catch (error: unknown) {+ lemonToast.error(errorDetail(error) ?? `Could not apply the baseline to ${audience}`)+ } finally {+ actions.applyPresetComplete(audience)+ }+ },+ setMemberServerAccess: async ({ userId, serverId, enabled }) => {+ const server = values.servers.find((candidate) => candidate.id === serverId)+ try {+ await mcpGatewayMembersSetAccessCreate(currentProjectId(), String(userId), {+ gateway_server_id: serverId,+ enabled,+ })+ actions.loadMembersSuccess(+ values.members.map((member) => {+ if (member.user.id !== userId) {+ return member+ }+ const revokedServerIds = enabled+ ? member.revoked_server_ids.filter((revokedServerId) => revokedServerId !== serverId)+ : Array.from(new Set([...member.revoked_server_ids, serverId]))+ return { ...member, revoked_server_ids: revokedServerIds }+ })+ )+ actions.loadServers()+ lemonToast[enabled ? 'success' : 'info'](+ `${enabled ? 'Restored' : 'Turned off'} access to ${server?.name ?? 'server'}`+ )+ } catch (error: unknown) {+ lemonToast.error(errorDetail(error) ?? `Could not update access to ${server?.name ?? 'this server'}`)+ } finally {+ actions.setMemberServerAccessComplete(userId, serverId)+ }+ },+ setMembersOffset: () => {+ actions.loadMembers()+ },+ loadConfigSuccess: () => {+ if (values.isAdmin) {+ actions.loadMembers()+ }+ },+ })),++ afterMount(({ actions }) => {+ actions.loadConfig()+ actions.loadServers()+ actions.loadTemplates()+ actions.loadServiceAccounts()+ actions.loadRules()+ }),+])diff --git a/products/mcp_store/frontend/gateway/mcpGatewaySceneLogic.test.ts b/products/mcp_store/frontend/gateway/mcpGatewaySceneLogic.test.tsnew file mode 100644index 000000000000..5771edd23717--- /dev/null+++ b/products/mcp_store/frontend/gateway/mcpGatewaySceneLogic.test.ts@@ -0,0 +1,77 @@+import { router } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import {+ mcpGatewayConfigList,+ mcpGatewayRulesList,+ mcpGatewayServersList,+ mcpGatewayServiceAccountsList,+ mcpServersList,+} from '../generated/api'+import { mcpGatewayLogic } from './mcpGatewayLogic'+import { mcpGatewaySceneLogic } from './mcpGatewaySceneLogic'++jest.mock('../generated/api', () => ({+ ...jest.requireActual('../generated/api'),+ mcpGatewayConfigList: jest.fn(),+ mcpGatewayRulesList: jest.fn(),+ mcpGatewayServersList: jest.fn(),+ mcpGatewayServiceAccountsList: jest.fn(),+ mcpServersList: jest.fn(),+}))++const mockConfigList = jest.mocked(mcpGatewayConfigList)+const mockRulesList = jest.mocked(mcpGatewayRulesList)+const mockServersList = jest.mocked(mcpGatewayServersList)+const mockServiceAccountsList = jest.mocked(mcpGatewayServiceAccountsList)+const mockTemplatesList = jest.mocked(mcpServersList)++describe('mcpGatewaySceneLogic', () => {+ let gatewayLogic: ReturnType<typeof mcpGatewayLogic.build>+ let sceneLogic: ReturnType<typeof mcpGatewaySceneLogic.build>++ beforeEach(async () => {+ initKeaTests()+ jest.resetAllMocks()+ mockConfigList.mockResolvedValue({+ is_admin: false,+ allow_custom_servers: true,+ allow_member_agent_access: true,+ })+ mockRulesList.mockResolvedValue({ count: 0, results: [] })+ mockServersList.mockResolvedValue({ count: 0, results: [] })+ mockServiceAccountsList.mockResolvedValue({ count: 0, results: [] })+ mockTemplatesList.mockResolvedValue({ count: 0, results: [] })++ gatewayLogic = mcpGatewayLogic()+ gatewayLogic.mount()+ sceneLogic = mcpGatewaySceneLogic()+ sceneLogic.mount()+ await expectLogic(gatewayLogic).toFinishAllListeners()+ })++ afterEach(() => {+ sceneLogic.unmount()+ gatewayLogic.unmount()+ jest.restoreAllMocks()+ })++ it.each([+ ['oauth_complete', 'success', 'Server connected'],+ ['oauth_error', 'error', 'OAuth authorization failed'],+ ] as const)('handles the %s callback and clears it from the URL', (queryParameter, toastType, message) => {+ const toast = jest.spyOn(lemonToast, toastType)++ router.actions.push(urls.mcpGateway(), { [queryParameter]: 'true' })++ expect(toast).toHaveBeenCalledWith(message)+ expect(router.values.location.pathname).toBe('/project/997/mcp-servers')+ expect(router.values.searchParams).toEqual({})+ })+})diff --git a/products/mcp_store/frontend/gateway/mcpGatewaySceneLogic.ts b/products/mcp_store/frontend/gateway/mcpGatewaySceneLogic.tsnew file mode 100644index 000000000000..1603c3fef001--- /dev/null+++ b/products/mcp_store/frontend/gateway/mcpGatewaySceneLogic.ts@@ -0,0 +1,91 @@+import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'+import { actionToUrl, router, urlToAction } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { mcpGatewayLogic } from './mcpGatewayLogic'++export type GatewayTab = 'servers' | 'team' | 'settings' | 'audit'++export const ADMIN_TABS: GatewayTab[] = ['servers', 'team', 'settings', 'audit']+const MEMBER_TABS: GatewayTab[] = ['servers']++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpGatewaySceneLogicValues {+ isAdmin: boolean // mcpGatewayLogic+ activeTab: GatewayTab+ availableTabs: GatewayTab[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpGatewaySceneLogicActions {+ _setTab: (tab: GatewayTab) => {+ tab: GatewayTab+ }+ setTab: (tab: GatewayTab) => {+ tab: GatewayTab+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpGatewaySceneLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ availableTabs: (isAdmin: boolean) => GatewayTab[]+ }+}++export type mcpGatewaySceneLogicType = MakeLogicType<+ mcpGatewaySceneLogicValues,+ mcpGatewaySceneLogicActions,+ Record<string, any>,+ mcpGatewaySceneLogicMeta+>++/** URL-synced active tab (see data_warehouse SourceScene pattern: `setTab` writes+ * the URL, `_setTab` reacts to it without a feedback loop). */+export const mcpGatewaySceneLogic = kea<mcpGatewaySceneLogicType>([+ path(['products', 'mcp_store', 'frontend', 'gateway', 'mcpGatewaySceneLogic']),+ connect(() => ({ values: [mcpGatewayLogic, ['isAdmin']] })),+ actions({+ setTab: (tab: GatewayTab) => ({ tab }),+ _setTab: (tab: GatewayTab) => ({ tab }),+ }),+ reducers({+ activeTab: ['servers' as GatewayTab, { setTab: (_, { tab }) => tab, _setTab: (_, { tab }) => tab }],+ }),+ selectors({+ availableTabs: [(s) => [s.isAdmin], (isAdmin: boolean): GatewayTab[] => (isAdmin ? ADMIN_TABS : MEMBER_TABS)],+ }),+ actionToUrl(({ values }) => ({+ setTab: () => (values.activeTab === 'servers' ? urls.mcpGateway() : urls.mcpGatewayTab(values.activeTab)),+ })),+ urlToAction(({ actions, values }) => {+ const handleOAuthCallback = (searchParams: Record<string, unknown>): void => {+ if (searchParams.oauth_complete === 'true') {+ lemonToast.success('Server connected')+ router.actions.replace(router.values.location.pathname)+ } else if (searchParams.oauth_error) {+ lemonToast.error('OAuth authorization failed')+ router.actions.replace(router.values.location.pathname)+ }+ }++ return {+ [urls.mcpGateway()]: (_, searchParams) => {+ handleOAuthCallback(searchParams ?? {})+ if (values.activeTab !== 'servers') {+ actions._setTab('servers')+ }+ },+ [urls.mcpGatewayTab(':tab')]: ({ tab }, searchParams) => {+ handleOAuthCallback(searchParams ?? {})+ const next = (ADMIN_TABS.includes(tab as GatewayTab) ? tab : 'servers') as GatewayTab+ if (next !== values.activeTab) {+ actions._setTab(next)+ }+ },+ }+ }),+])diff --git a/products/mcp_store/frontend/generated/api.schemas.ts b/products/mcp_store/frontend/generated/api.schemas.tsindex 96240fdcd880..c407cf749c49 100644--- a/products/mcp_store/frontend/generated/api.schemas.ts+++ b/products/mcp_store/frontend/generated/api.schemas.ts@@ -7,6 +7,369 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+/**+ * * `auto` - Auto-approved+ * * `approved` - Approved+ * * `pending` - Awaiting approval+ * * `blocked` - Blocked+ */+export type MCPAuditDecisionEnumApi = (typeof MCPAuditDecisionEnumApi)[keyof typeof MCPAuditDecisionEnumApi]++export const MCPAuditDecisionEnumApi = {+ Auto: 'auto',+ Approved: 'approved',+ Pending: 'pending',+ Blocked: 'blocked',+} as const++/**+ * * `engineering` - Engineering+ * * `data` - Data+ * * `product` - Product Management+ * * `founder` - Founder+ * * `leadership` - Leadership+ * * `marketing` - Marketing+ * * `sales` - Sales / Success+ * * `other` - Other+ */+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]++export const RoleAtOrganizationEnumApi = {+ Engineering: 'engineering',+ Data: 'data',+ Product: 'product',+ Founder: 'founder',+ Leadership: 'leadership',+ Marketing: 'marketing',+ Sales: 'sales',+ Other: 'other',+} as const++export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]++export const BlankEnumApi = {+ '': '',+} as const++/**+ * @nullable+ */+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null++export interface UserBasicApi {+ readonly id: number+ readonly uuid: string+ /**+ * @maxLength 200+ * @nullable+ */+ distinct_id?: string | null+ /** @maxLength 150 */+ first_name?: string+ /** @maxLength 150 */+ last_name?: string+ /** @maxLength 254 */+ email: string+ /** @nullable */+ is_email_verified?: boolean | null+ /** @nullable */+ readonly hedgehog_config: UserBasicApiHedgehogConfig+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null+}++export interface AuditActorServiceAccountApi {+ /** Service account id. */+ id: string+ /** Agent display name. */+ name: string+ /** Agent identity handle. */+ handle: string+}++export interface MCPAuditEventApi {+ readonly id: string+ readonly created_at: string+ /** Gateway server name at call time (denormalized). */+ readonly server_name: string+ /** Tool that was called. */+ readonly tool_name: string+ /** How the gateway decided the call.+ *+ * * `auto` - Auto-approved+ * * `approved` - Approved+ * * `pending` - Awaiting approval+ * * `blocked` - Blocked */+ readonly decision: MCPAuditDecisionEnumApi+ /** Member who made the call, if any. */+ readonly actor_user: UserBasicApi | null+ /** Agent that made the call, if any. Null for member calls. */+ readonly actor_service_account: AuditActorServiceAccountApi | null+ /** Denormalized actor label (email or handle) that survives deletion. */+ readonly actor_label: string+}++export interface PaginatedMCPAuditEventListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: MCPAuditEventApi[]+}++export interface AuditCountsApi {+ /** Every audited tool call. */+ all: number+ /** Calls made by service accounts. */+ agents: number+ /** Calls that were approved or are awaiting approval. */+ approvals: number+ /** Calls the gateway blocked. */+ blocked: number+}++/**+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive+ */+export type MCPPolicyPresetEnumApi = (typeof MCPPolicyPresetEnumApi)[keyof typeof MCPPolicyPresetEnumApi]++export const MCPPolicyPresetEnumApi = {+ Allow: 'allow',+ User: 'user',+ Ask: 'ask',+ Block: 'block',+} as const++export const TeamMCPGatewayConfigApiMemberDefaultPreset = { ...MCPPolicyPresetEnumApi, ...BlankEnumApi } as const+export const TeamMCPGatewayConfigApiAgentDefaultPreset = { ...MCPPolicyPresetEnumApi, ...BlankEnumApi } as const+export interface TeamMCPGatewayConfigApi {+ /** Whether non-admin members may register custom MCP servers with the gateway. */+ allow_custom_servers?: boolean+ /** Whether non-admin members may share their available MCP connections with agents and manage agent tool policies. */+ allow_member_agent_access?: boolean+ /** Whether servers with no gateway registration — including catalog templates published later — are enabled for the team. A registered server's own toggle always wins. */+ default_servers_enabled?: boolean+ /** Baseline preset for members. Empty until an admin applies one from Team settings.+ *+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive */+ member_default_preset?: (typeof TeamMCPGatewayConfigApiMemberDefaultPreset)[keyof typeof TeamMCPGatewayConfigApiMemberDefaultPreset]+ /** Baseline preset deriving default policies for tools an agent has no explicit row for.+ *+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive */+ agent_default_preset?: (typeof TeamMCPGatewayConfigApiAgentDefaultPreset)[keyof typeof TeamMCPGatewayConfigApiAgentDefaultPreset]+ /** Whether the requesting user can administer the gateway (org admin or explicit project admin). */+ readonly is_admin: boolean+}++/**+ * * `members` - members+ * * `agents` - agents+ */+export type AudienceEnumApi = (typeof AudienceEnumApi)[keyof typeof AudienceEnumApi]++export const AudienceEnumApi = {+ Members: 'members',+ Agents: 'agents',+} as const++export interface ApplyPresetApi {+ /** Which audience's baseline to overwrite.+ *+ * * `members` - members+ * * `agents` - agents */+ audience: AudienceEnumApi+ /** Preset to apply.+ *+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive */+ preset: MCPPolicyPresetEnumApi+}++export interface SetAllServersEnabledApi {+ /** True enables every MCP server for the team; false disables them all. Applies to every registered server and becomes the default for untouched and future catalog servers. */+ enabled: boolean+}++export const GatewayConfigUpdateApiMemberDefaultPreset = { ...MCPPolicyPresetEnumApi, ...BlankEnumApi } as const+export const GatewayConfigUpdateApiAgentDefaultPreset = { ...MCPPolicyPresetEnumApi, ...BlankEnumApi } as const+export interface GatewayConfigUpdateApi {+ /** Whether non-admin members may register custom MCP servers. */+ allow_custom_servers?: boolean+ /** Whether non-admin members may share their available MCP connections with agents and manage agent tool policies. */+ allow_member_agent_access?: boolean+ /** Whether servers with no gateway registration — including catalog templates published later — are enabled for the team. A registered server's own toggle always wins. */+ default_servers_enabled?: boolean+ /** Baseline preset for members.+ *+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive */+ member_default_preset?: (typeof GatewayConfigUpdateApiMemberDefaultPreset)[keyof typeof GatewayConfigUpdateApiMemberDefaultPreset]+ /** Baseline preset for agents.+ *+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive */+ agent_default_preset?: (typeof GatewayConfigUpdateApiAgentDefaultPreset)[keyof typeof GatewayConfigUpdateApiAgentDefaultPreset]+}++/**+ * One team member's gateway posture (admin overview).+ */+export interface GatewayMemberSummaryApi {+ /** The member. */+ user: UserBasicApi+ /** Whether the member is an organization admin or owner. */+ is_org_admin: boolean+ /** Gateway servers the member has a personal connection to. */+ connected_server_ids: string[]+ /** Gateway servers an admin turned off for this member. */+ revoked_server_ids: string[]+}++export interface PaginatedGatewayMemberSummaryListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: GatewayMemberSummaryApi[]+}++export interface MemberAccessUpdateApi {+ /** Gateway server to toggle for the member. */+ gateway_server_id: string+ /** False turns the server off for the member; true restores it. */+ enabled: boolean+}++/**+ * * `everyone` - Everyone+ * * `members` - Members+ * * `agents` - Agents+ */+export type AppliesToEnumApi = (typeof AppliesToEnumApi)[keyof typeof AppliesToEnumApi]++export const AppliesToEnumApi = {+ Everyone: 'everyone',+ Members: 'members',+ Agents: 'agents',+} as const++/**+ * * `needs_approval` - Require approval+ * * `do_not_use` - Block+ */+export type EffectEnumApi = (typeof EffectEnumApi)[keyof typeof EffectEnumApi]++export const EffectEnumApi = {+ NeedsApproval: 'needs_approval',+ DoNotUse: 'do_not_use',+} as const++export interface MCPOrgRuleApi {+ readonly id: string+ /**+ * Short rule name shown wherever the rule locks a tool.+ * @maxLength 200+ */+ name: string+ /** Why this guardrail exists. */+ description?: string+ /** Audience the rule constrains.+ *+ * * `everyone` - Everyone+ * * `members` - Members+ * * `agents` - Agents */+ applies_to?: AppliesToEnumApi+ /** State the rule forces on matching tools.+ *+ * * `needs_approval` - Require approval+ * * `do_not_use` - Block */+ effect?: EffectEnumApi+ /**+ * fnmatch pattern against tool names. Blank matches destructive tools heuristically.+ * @maxLength 400+ */+ tool_pattern?: string+ /** Disabled rules are kept but not evaluated. */+ enabled?: boolean+ readonly created_at: string+ readonly updated_at: string+}++export interface PaginatedMCPOrgRuleListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: MCPOrgRuleApi[]+}++export interface PatchedMCPOrgRuleApi {+ readonly id?: string+ /**+ * Short rule name shown wherever the rule locks a tool.+ * @maxLength 200+ */+ name?: string+ /** Why this guardrail exists. */+ description?: string+ /** Audience the rule constrains.+ *+ * * `everyone` - Everyone+ * * `members` - Members+ * * `agents` - Agents */+ applies_to?: AppliesToEnumApi+ /** State the rule forces on matching tools.+ *+ * * `needs_approval` - Require approval+ * * `do_not_use` - Block */+ effect?: EffectEnumApi+ /**+ * fnmatch pattern against tool names. Blank matches destructive tools heuristically.+ * @maxLength 400+ */+ tool_pattern?: string+ /** Disabled rules are kept but not evaluated. */+ enabled?: boolean+ readonly created_at?: string+ readonly updated_at?: string+}++/**+ * * `business` - Business Operations+ * * `data` - Data & Analytics+ * * `design` - Design & Content+ * * `dev` - Developer Tools & APIs+ * * `infra` - Infrastructure+ * * `productivity` - Productivity & Collaboration+ */+export type MCPServerCategoryEnumApi = (typeof MCPServerCategoryEnumApi)[keyof typeof MCPServerCategoryEnumApi]++export const MCPServerCategoryEnumApi = {+ Business: 'business',+ Data: 'data',+ Design: 'design',+ Dev: 'dev',+ Infra: 'infra',+ Productivity: 'productivity',+} as const+/*** * `api_key` - API Key* * `oauth` - OAuth@@ -18,6 +381,418 @@ export const MCPAuthTypeEnumApi = {Oauth: 'oauth',} as const+/**+ * One member's personal connection to a gateway server.+ */+export interface GatewayConnectionApi {+ /** Installation row backing this connection. */+ installation_id: string+ /** The member who connected. */+ user: UserBasicApi+ /**+ * When this connection last proxied a tool call. Null if never used.+ * @nullable+ */+ last_used_at: string | null+ /** True when the OAuth round-trip has not completed yet. */+ pending_oauth: boolean+ /** True when the stored token was invalidated and needs reauth. */+ needs_reauth: boolean+}++/**+ * The requesting user's own connection to a gateway server.+ */+export interface GatewayYourConnectionApi {+ /** The caller's installation row for this server. */+ installation_id: string+ /** Per-connection switch — false when self-disabled. */+ is_enabled: boolean+ /** True when the OAuth round-trip has not completed yet. */+ pending_oauth: boolean+ /** True when the stored token was invalidated and needs reauth. */+ needs_reauth: boolean+ /**+ * When the caller last proxied a call through this connection.+ * @nullable+ */+ last_used_at: string | null+}++/**+ * * `active` - Active+ * * `paused` - Paused+ */+export type MCPServiceAccountStatusEnumApi =+ (typeof MCPServiceAccountStatusEnumApi)[keyof typeof MCPServiceAccountStatusEnumApi]++export const MCPServiceAccountStatusEnumApi = {+ Active: 'active',+ Paused: 'paused',+} as const++/**+ * One agent's access to a gateway server.+ */+export interface GatewayAgentAccessApi {+ /** Service account granted access. */+ service_account_id: string+ /** Agent display name. */+ name: string+ /** Agent identity handle, e.g. posthog-support. */+ handle: string+ /** active, or paused (all access off).+ *+ * * `active` - Active+ * * `paused` - Paused */+ status: MCPServiceAccountStatusEnumApi+ /**+ * When the agent last made a call.+ * @nullable+ */+ last_active_at: string | null+ /** Admin who shared this server with the agent. */+ granted_by: UserBasicApi | null+}++/**+ * A server registered in the team's gateway, with connection summary.+ */+export interface MCPGatewayServerApi {+ readonly id: string+ readonly name: string+ readonly url: string+ readonly description: string+ readonly category: MCPServerCategoryEnumApi+ /** Fixed authentication type for catalog templates. Null for custom servers, where members choose.+ *+ * * `api_key` - API Key+ * * `oauth` - OAuth */+ readonly template_auth_type: MCPAuthTypeEnumApi | null+ readonly is_team_enabled: boolean+ /** Deprecated brand icon key from the linked template. Empty for custom servers. */+ readonly icon_key: string+ /** Brand domain from the linked template. Empty for custom servers. */+ readonly icon_domain: string+ /** Documentation URL from the template. */+ readonly docs_url: string+ /**+ * Linked catalog template.+ * @nullable+ */+ readonly template_id: string | null+ /** Number of live tools known for this server. */+ readonly tool_count: number+ /** Members with a connection to this server. Only project admins receive this list. */+ readonly connections: readonly GatewayConnectionApi[]+ /** The requesting user's own connection, or null when not connected. */+ readonly your_connection: GatewayYourConnectionApi | null+ /** Agents this server is shared with. */+ readonly agents: readonly GatewayAgentAccessApi[]+ /** Ids of members whose access an admin has turned off. Only project admins receive this list. */+ readonly revoked_user_ids: readonly number[]+ /** True when an admin has turned this server off for the requesting user. */+ readonly is_revoked_for_you: boolean+ /** Who registered the server. Null when that user was deleted. */+ readonly created_by: UserBasicApi | null+ readonly created_at: string+ readonly updated_at: string+}++export interface PaginatedMCPGatewayServerListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: MCPGatewayServerApi[]+}++export interface MCPGatewayServerUpdateApi {+ /**+ * Display name shown across the gateway.+ * @maxLength 200+ */+ name?: string+ /** Short description shown on server cards. */+ description?: string+ /** Catalog category used for filter chips.+ *+ * * `business` - Business Operations+ * * `data` - Data & Analytics+ * * `design` - Design & Content+ * * `dev` - Developer Tools & APIs+ * * `infra` - Infrastructure+ * * `productivity` - Productivity & Collaboration */+ category?: MCPServerCategoryEnumApi+ /** Whether the team can see and call the server. Turning it off also blocks agent access. */+ is_team_enabled?: boolean+}++export interface PatchedMCPGatewayServerUpdateApi {+ /**+ * Display name shown across the gateway.+ * @maxLength 200+ */+ name?: string+ /** Short description shown on server cards. */+ description?: string+ /** Catalog category used for filter chips.+ *+ * * `business` - Business Operations+ * * `data` - Data & Analytics+ * * `design` - Design & Content+ * * `dev` - Developer Tools & APIs+ * * `infra` - Infrastructure+ * * `productivity` - Productivity & Collaboration */+ category?: MCPServerCategoryEnumApi+ /** Whether the team can see and call the server. Turning it off also blocks agent access. */+ is_team_enabled?: boolean+}++/**+ * * `team` - Team default+ * * `member` - Member+ * * `agent` - Agent+ */+export type ScopeTypeEnumApi = (typeof ScopeTypeEnumApi)[keyof typeof ScopeTypeEnumApi]++export const ScopeTypeEnumApi = {+ Team: 'team',+ Member: 'member',+ Agent: 'agent',+} as const++export type MCPToolApprovalStateEnumApi = (typeof MCPToolApprovalStateEnumApi)[keyof typeof MCPToolApprovalStateEnumApi]++export const MCPToolApprovalStateEnumApi = {+ Approved: 'approved',+ NeedsApproval: 'needs_approval',+ DoNotUse: 'do_not_use',+} as const++export interface ToolPolicyEntryApi {+ /**+ * Tool to set the policy for, up to 200 characters.+ * @maxLength 200+ */+ tool_name: string+ /** State to apply for this scope.+ *+ * * `approved` - Approved+ * * `needs_approval` - Needs approval+ * * `do_not_use` - Do not use */+ policy_state: MCPToolApprovalStateEnumApi+}++export interface GatewayPoliciesUpsertApi {+ /** Which scope to resolve: the team default, one member, or one agent.+ *+ * * `team` - Team default+ * * `member` - Member+ * * `agent` - Agent */+ scope_type?: ScopeTypeEnumApi+ /** Member scope target. Defaults to the requesting user. */+ scope_user_id?: number+ /** Agent scope target. Required when scope_type is agent. */+ scope_service_account_id?: string+ /**+ * Per-tool states to upsert for the scope. At most 1,000 entries per request.+ * @maxItems 1000+ */+ policies: ToolPolicyEntryApi[]+}++/**+ * * `rule` - rule+ * * `scope` - scope+ * * `team` - team+ * * `preset` - preset+ * * `legacy` - legacy+ * * `default` - default+ */+export type DecidedByEnumApi = (typeof DecidedByEnumApi)[keyof typeof DecidedByEnumApi]++export const DecidedByEnumApi = {+ Rule: 'rule',+ Scope: 'scope',+ Team: 'team',+ Preset: 'preset',+ Legacy: 'legacy',+ Default: 'default',+} as const++/**+ * JSON Schema describing the tool's input arguments.+ */+export type ResolvedToolPolicyApiInputSchema = { [key: string]: unknown }++/**+ * One tool with its effective policy for the requested scope.+ */+export interface ResolvedToolPolicyApi {+ /** Tool name as exposed by the upstream server. */+ tool_name: string+ /** Tool description from the upstream server. */+ description: string+ /** JSON Schema describing the tool's input arguments. */+ input_schema: ResolvedToolPolicyApiInputSchema+ /** Effective state for the scope.+ *+ * * `approved` - Approved+ * * `needs_approval` - Needs approval+ * * `do_not_use` - Do not use */+ policy_state: MCPToolApprovalStateEnumApi+ /** What the team-level chain (row or preset) yields, ignoring the scope. Null when the team imposes nothing.+ *+ * * `approved` - Approved+ * * `needs_approval` - Needs approval+ * * `do_not_use` - Do not use */+ team_state: MCPToolApprovalStateEnumApi | null+ /** True when no state is editable for this scope (a rule match or a Blocked team ceiling). */+ locked: boolean+ /** Which policy layer decided the state.+ *+ * * `rule` - rule+ * * `scope` - scope+ * * `team` - team+ * * `preset` - preset+ * * `legacy` - legacy+ * * `default` - default */+ decided_by: DecidedByEnumApi+ /** Matching org rule name, when decided_by is rule. */+ rule_name: string+ /** Matching org rule description, when decided_by is rule. */+ rule_description: string+}++export interface PaginatedResolvedToolPolicyListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: ResolvedToolPolicyApi[]+}++export interface SetTemplateEnabledApi {+ /** Active catalog template to enable or disable for the team. */+ template_id: string+ /** True lets the team see and call the server; false hides it from members and blocks connections. */+ enabled: boolean+}++export type AgentKeyEnumApi = (typeof AgentKeyEnumApi)[keyof typeof AgentKeyEnumApi]++export const AgentKeyEnumApi = {+ Support: 'support',+ Scout: 'scout',+} as const++/**+ * * `ready` - ready+ * * `pending_oauth` - pending_oauth+ * * `needs_reauth` - needs_reauth+ * * `disabled` - disabled+ * * `missing_credential` - missing_credential+ */+export type ConnectionStateEnumApi = (typeof ConnectionStateEnumApi)[keyof typeof ConnectionStateEnumApi]++export const ConnectionStateEnumApi = {+ Ready: 'ready',+ PendingOauth: 'pending_oauth',+ NeedsReauth: 'needs_reauth',+ Disabled: 'disabled',+ MissingCredential: 'missing_credential',+} as const++/**+ * A credential-safe summary of a server configured for an agent.+ */+export interface MCPServiceAccountServerApi {+ /** Gateway server granted to the agent. */+ id: string+ /** Server display name. */+ name: string+ /** Server description. */+ description: string+ /** Deprecated brand icon key. Empty for custom servers. */+ icon_key: string+ /** Brand domain. Empty for custom servers. */+ icon_domain: string+ /** Whether the credential delegated to the agent is ready to use.+ *+ * * `ready` - ready+ * * `pending_oauth` - pending_oauth+ * * `needs_reauth` - needs_reauth+ * * `disabled` - disabled+ * * `missing_credential` - missing_credential */+ connection_state: ConnectionStateEnumApi+}++export interface MCPServiceAccountApi {+ readonly id: string+ readonly name: string+ readonly description: string+ /** Stable internal identity handle for this PostHog agent. */+ readonly handle: string+ /** Stable PostHog agent identifier. */+ readonly agent_key: AgentKeyEnumApi+ /** active, or paused (all MCP access off).+ *+ * * `active` - Active+ * * `paused` - Paused */+ readonly status: MCPServiceAccountStatusEnumApi+ /** Gateway servers configured for this agent. */+ readonly server_ids: readonly string[]+ /** Credential-safe summaries of the gateway servers configured for this agent. */+ readonly servers: readonly MCPServiceAccountServerApi[]+ /**+ * When the agent last made a call through the gateway.+ * @nullable+ */+ readonly last_active_at: string | null+ readonly created_at: string+ readonly updated_at: string+}++export interface PaginatedMCPServiceAccountListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: MCPServiceAccountApi[]+}++export interface MCPServiceAccountUpdateApi {+ /** active, or paused (all MCP access off).+ *+ * * `active` - Active+ * * `paused` - Paused */+ status?: MCPServiceAccountStatusEnumApi+}++export interface PatchedMCPServiceAccountUpdateApi {+ /** active, or paused (all MCP access off).+ *+ * * `active` - Active+ * * `paused` - Paused */+ status?: MCPServiceAccountStatusEnumApi+}++export interface ServiceAccountAccessUpdateApi {+ /** Gateway server to grant or revoke. */+ gateway_server_id: string+ /** True grants access, false revokes it. */+ enabled: boolean+ /**+ * Optional agent-scope tool policies to set alongside the grant. At most 1,000 entries per request.+ * @maxItems 1000+ */+ policies?: ToolPolicyEntryApi[]+}+/*** * `personal` - Personal* * `shared` - Shared@@ -74,27 +849,20 @@ export interface PatchedMCPServerInstallationUpdateApi {is_enabled?: boolean}-/**- * * `approved` - Approved- * * `needs_approval` - Needs approval- * * `do_not_use` - Do not use- */-export type MCPServerInstallationToolApprovalStateEnumApi =- (typeof MCPServerInstallationToolApprovalStateEnumApi)[keyof typeof MCPServerInstallationToolApprovalStateEnumApi]--export const MCPServerInstallationToolApprovalStateEnumApi = {- Approved: 'approved',- NeedsApproval: 'needs_approval',- DoNotUse: 'do_not_use',-} as const-export interface MCPServerInstallationToolApi {readonly id: stringreadonly tool_name: stringreadonly display_name: stringreadonly description: stringreadonly input_schema: unknown- approval_state?: MCPServerInstallationToolApprovalStateEnumApi+ /** Effective state after applying the team ceiling. */+ readonly approval_state: MCPToolApprovalStateEnumApi+ /** Team-admin ceiling for this tool. Null when the team imposes no ceiling. */+ readonly team_state: MCPToolApprovalStateEnumApi | null+ /** True when a rule or Blocked team ceiling leaves no editable state. */+ readonly locked: boolean+ /** Policy layer that decided the effective state. */+ readonly decided_by: stringreadonly last_seen_at: string/** @nullable */readonly removed_at: string | null@@ -176,11 +944,17 @@ export interface InstallCustomApi {client_secret?: stringinstall_source?: InstallSourceEnumApiposthog_code_callback_url?: string- /** 'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).+ /** 'personal' is per-user; 'shared' makes the credential available to project members. Agent access is granted separately.** * `personal` - personal* * `shared` - shared */scope?: MCPInstallationScopeEnumApi+ /** Whether the server starts enabled for the whole team. Non-default values are admin-only. */+ team_enabled?: boolean+ /** Service accounts to share the server with at install time. Available to members when team settings allow member-managed agent access. */+ agent_ids?: string[]+ /** In-app path to land back on after the OAuth round-trip. Must be a same-app relative path. */+ return_path?: string}export interface OAuthRedirectResponseApi {@@ -192,33 +966,19 @@ export interface InstallTemplateApi {api_key?: stringinstall_source?: InstallSourceEnumApiposthog_code_callback_url?: string- /** 'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).+ /** 'personal' is per-user; 'shared' makes the credential available to project members. Agent access is granted separately.** * `personal` - personal* * `shared` - shared */scope?: MCPInstallationScopeEnumApi+ /** Whether the server starts enabled for the whole team. Non-default values are admin-only. */+ team_enabled?: boolean+ /** Service accounts to share the server with at install time. Available to members when team settings allow member-managed agent access. */+ agent_ids?: string[]+ /** In-app path to land back on after the OAuth round-trip. Must be a same-app relative path. */+ return_path?: string}-/**- * * `business` - Business Operations- * * `data` - Data & Analytics- * * `design` - Design & Content- * * `dev` - Developer Tools & APIs- * * `infra` - Infrastructure- * * `productivity` - Productivity & Collaboration- */-export type MCPServerTemplateCategoryEnumApi =- (typeof MCPServerTemplateCategoryEnumApi)[keyof typeof MCPServerTemplateCategoryEnumApi]--export const MCPServerTemplateCategoryEnumApi = {- Business: 'business',- Data: 'data',- Design: 'design',- Dev: 'dev',- Infra: 'infra',- Productivity: 'productivity',-} as const-export interface MCPServerTemplateApi {readonly id: string/** @maxLength 200 */@@ -233,7 +993,7 @@ export interface MCPServerTemplateApi {readonly icon_key: string/** The vendor's brand domain (e.g. 'linear.app'), resolved to an icon at render time via the logo.dev proxy endpoint. Empty when no brand icon is known. */readonly icon_domain: string- category?: MCPServerTemplateCategoryEnumApi+ category?: MCPServerCategoryEnumApi}export interface PaginatedMCPServerTemplateListApi {@@ -245,6 +1005,114 @@ export interface PaginatedMCPServerTemplateListApi {results: MCPServerTemplateApi[]}+export type McpGatewayAuditListParams = {+ /**+ * Only calls made by this service account.+ */+ actor_service_account_id?: string+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * all, agents (agent calls only), approvals (approved or pending), or blocked.+ *+ * * `all` - all+ * * `agents` - agents+ * * `approvals` - approvals+ * * `blocked` - blocked+ * @minLength 1+ */+ quick_filter?: McpGatewayAuditListQuickFilter+}++export type McpGatewayAuditListQuickFilter =+ (typeof McpGatewayAuditListQuickFilter)[keyof typeof McpGatewayAuditListQuickFilter]++export const McpGatewayAuditListQuickFilter = {+ All: 'all',+ Agents: 'agents',+ Approvals: 'approvals',+ Blocked: 'blocked',+} as const++export type McpGatewayMembersListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}++export type McpGatewayRulesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}++export type McpGatewayServersListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}++export type McpGatewayServersToolsRetrieveParams = {+ /**+ * Agent scope target. Required when scope_type is agent.+ */+ scope_service_account_id?: string+ /**+ * Which scope to resolve: the team default, one member, or one agent.+ *+ * * `team` - Team default+ * * `member` - Member+ * * `agent` - Agent+ * @minLength 1+ */+ scope_type?: McpGatewayServersToolsRetrieveScopeType+ /**+ * Member scope target. Defaults to the requesting user.+ */+ scope_user_id?: number+}++export type McpGatewayServersToolsRetrieveScopeType =+ (typeof McpGatewayServersToolsRetrieveScopeType)[keyof typeof McpGatewayServersToolsRetrieveScopeType]++export const McpGatewayServersToolsRetrieveScopeType = {+ Team: 'team',+ Member: 'member',+ Agent: 'agent',+} as const++export type McpGatewayServiceAccountsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type McpServerInstallationsListParams = {/*** Number of results to return per page.@@ -265,6 +1133,10 @@ export type McpServerInstallationsAuthorizeRetrieveParams = {install_source?: McpServerInstallationsAuthorizeRetrieveInstallSourceinstallation_id?: stringposthog_code_callback_url?: string+ /**+ * In-app path to land back on after the OAuth round-trip. Must be a same-app relative path.+ */+ return_path?: stringtemplate_id?: string}diff --git a/products/mcp_store/frontend/generated/api.ts b/products/mcp_store/frontend/generated/api.tsindex b1be91e993c8..78f73163d0c5 100644--- a/products/mcp_store/frontend/generated/api.ts+++ b/products/mcp_store/frontend/generated/api.ts@@ -9,19 +9,50 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ ApplyPresetApi,+ AuditCountsApi,+ GatewayConfigUpdateApi,+ GatewayMemberSummaryApi,+ GatewayPoliciesUpsertApi,InstallCustomApi,InstallTemplateApi,+ MCPAuditEventApi,+ MCPGatewayServerApi,+ MCPGatewayServerUpdateApi,+ MCPOrgRuleApi,MCPServerInstallationApi,MCPServerInstallationToolApi,+ MCPServiceAccountApi,+ MCPServiceAccountUpdateApi,+ McpGatewayAuditListParams,+ McpGatewayMembersListParams,+ McpGatewayRulesListParams,+ McpGatewayServersListParams,+ McpGatewayServersToolsRetrieveParams,+ McpGatewayServiceAccountsListParams,McpServerInstallationsAuthorizeRetrieveParams,McpServerInstallationsListParams,McpServersListParams,+ MemberAccessUpdateApi,OAuthRedirectResponseApi,+ PaginatedGatewayMemberSummaryListApi,+ PaginatedMCPAuditEventListApi,+ PaginatedMCPGatewayServerListApi,+ PaginatedMCPOrgRuleListApi,PaginatedMCPServerInstallationListApi,PaginatedMCPServerInstallationToolListApi,PaginatedMCPServerTemplateListApi,+ PaginatedMCPServiceAccountListApi,+ PaginatedResolvedToolPolicyListApi,+ PatchedMCPGatewayServerUpdateApi,+ PatchedMCPOrgRuleApi,PatchedMCPServerInstallationUpdateApi,+ PatchedMCPServiceAccountUpdateApi,PatchedToolApprovalUpdateApi,+ ServiceAccountAccessUpdateApi,+ SetAllServersEnabledApi,+ SetTemplateEnabledApi,+ TeamMCPGatewayConfigApi,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -41,6 +72,669 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getMcpGatewayAuditListUrl = (projectId: string, params?: McpGatewayAuditListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/mcp_gateway/audit/?${stringifiedParams}`+ : `/api/projects/${projectId}/mcp_gateway/audit/`+}++/**+ * Read-only trail of proxied tool calls. Admin-only — it exposes what+ * every member and agent has been doing.+ */+export const mcpGatewayAuditList = async (+ projectId: string,+ params?: McpGatewayAuditListParams,+ options?: RequestInit+): Promise<PaginatedMCPAuditEventListApi> => {+ return apiMutator<PaginatedMCPAuditEventListApi>(getMcpGatewayAuditListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayAuditRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/audit/${id}/`+}++/**+ * Read-only trail of proxied tool calls. Admin-only — it exposes what+ * every member and agent has been doing.+ */+export const mcpGatewayAuditRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<MCPAuditEventApi> => {+ return apiMutator<MCPAuditEventApi>(getMcpGatewayAuditRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayAuditCountsRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/mcp_gateway/audit/counts/`+}++/**+ * Totals backing the quick-filter chips.+ */+export const mcpGatewayAuditCountsRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<AuditCountsApi> => {+ return apiMutator<AuditCountsApi>(getMcpGatewayAuditCountsRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayConfigListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/mcp_gateway/config/`+}++/**+ * The team's gateway settings, plus whether the caller can administer them.+ */+export const mcpGatewayConfigList = async (+ projectId: string,+ options?: RequestInit+): Promise<TeamMCPGatewayConfigApi> => {+ return apiMutator<TeamMCPGatewayConfigApi>(getMcpGatewayConfigListUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayConfigApplyPresetCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/mcp_gateway/config/apply_preset/`+}++/**+ * Set the policy baseline for members or agents (admin-only).+ */+export const mcpGatewayConfigApplyPresetCreate = async (+ projectId: string,+ applyPresetApi: ApplyPresetApi,+ options?: RequestInit+): Promise<TeamMCPGatewayConfigApi> => {+ return apiMutator<TeamMCPGatewayConfigApi>(getMcpGatewayConfigApplyPresetCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(applyPresetApi),+ })+}++export const getMcpGatewayConfigSetAllServersEnabledCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/mcp_gateway/config/set_all_servers_enabled/`+}++/**+ * Enable or disable every MCP server for the team (admin-only): flips+ * each registered server and the default for untouched catalog servers,+ * so newly published templates follow the same posture.+ */+export const mcpGatewayConfigSetAllServersEnabledCreate = async (+ projectId: string,+ setAllServersEnabledApi: SetAllServersEnabledApi,+ options?: RequestInit+): Promise<TeamMCPGatewayConfigApi> => {+ return apiMutator<TeamMCPGatewayConfigApi>(getMcpGatewayConfigSetAllServersEnabledCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(setAllServersEnabledApi),+ })+}++export const getMcpGatewayConfigUpdateSettingsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/mcp_gateway/config/update_settings/`+}++/**+ * Update team gateway settings (admin-only).+ */+export const mcpGatewayConfigUpdateSettingsCreate = async (+ projectId: string,+ gatewayConfigUpdateApi?: GatewayConfigUpdateApi,+ options?: RequestInit+): Promise<TeamMCPGatewayConfigApi> => {+ return apiMutator<TeamMCPGatewayConfigApi>(getMcpGatewayConfigUpdateSettingsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(gatewayConfigUpdateApi),+ })+}++export const getMcpGatewayMembersListUrl = (projectId: string, params?: McpGatewayMembersListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/mcp_gateway/members/?${stringifiedParams}`+ : `/api/projects/${projectId}/mcp_gateway/members/`+}++/**+ * Admin overview of each member's gateway posture, plus the per-member+ * server kill switch.+ */+export const mcpGatewayMembersList = async (+ projectId: string,+ params?: McpGatewayMembersListParams,+ options?: RequestInit+): Promise<PaginatedGatewayMemberSummaryListApi> => {+ return apiMutator<PaginatedGatewayMemberSummaryListApi>(getMcpGatewayMembersListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayMembersRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/members/${id}/`+}++/**+ * Admin overview of each member's gateway posture, plus the per-member+ * server kill switch.+ */+export const mcpGatewayMembersRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<GatewayMemberSummaryApi> => {+ return apiMutator<GatewayMemberSummaryApi>(getMcpGatewayMembersRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayMembersSetAccessCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/members/${id}/set_access/`+}++/**+ * Turn one gateway server off (or back on) for one member.+ */+export const mcpGatewayMembersSetAccessCreate = async (+ projectId: string,+ id: string,+ memberAccessUpdateApi: MemberAccessUpdateApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getMcpGatewayMembersSetAccessCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(memberAccessUpdateApi),+ })+}++export const getMcpGatewayRulesListUrl = (projectId: string, params?: McpGatewayRulesListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/mcp_gateway/rules/?${stringifiedParams}`+ : `/api/projects/${projectId}/mcp_gateway/rules/`+}++/**+ * Team guardrails evaluated before any scope policy.+ */+export const mcpGatewayRulesList = async (+ projectId: string,+ params?: McpGatewayRulesListParams,+ options?: RequestInit+): Promise<PaginatedMCPOrgRuleListApi> => {+ return apiMutator<PaginatedMCPOrgRuleListApi>(getMcpGatewayRulesListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayRulesCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/mcp_gateway/rules/`+}++/**+ * Team guardrails evaluated before any scope policy.+ */+export const mcpGatewayRulesCreate = async (+ projectId: string,+ mCPOrgRuleApi: NonReadonly<MCPOrgRuleApi>,+ options?: RequestInit+): Promise<MCPOrgRuleApi> => {+ return apiMutator<MCPOrgRuleApi>(getMcpGatewayRulesCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(mCPOrgRuleApi),+ })+}++export const getMcpGatewayRulesRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/rules/${id}/`+}++/**+ * Team guardrails evaluated before any scope policy.+ */+export const mcpGatewayRulesRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<MCPOrgRuleApi> => {+ return apiMutator<MCPOrgRuleApi>(getMcpGatewayRulesRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayRulesUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/rules/${id}/`+}++/**+ * Team guardrails evaluated before any scope policy.+ */+export const mcpGatewayRulesUpdate = async (+ projectId: string,+ id: string,+ mCPOrgRuleApi: NonReadonly<MCPOrgRuleApi>,+ options?: RequestInit+): Promise<MCPOrgRuleApi> => {+ return apiMutator<MCPOrgRuleApi>(getMcpGatewayRulesUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(mCPOrgRuleApi),+ })+}++export const getMcpGatewayRulesPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/rules/${id}/`+}++/**+ * Team guardrails evaluated before any scope policy.+ */+export const mcpGatewayRulesPartialUpdate = async (+ projectId: string,+ id: string,+ patchedMCPOrgRuleApi?: NonReadonly<PatchedMCPOrgRuleApi>,+ options?: RequestInit+): Promise<MCPOrgRuleApi> => {+ return apiMutator<MCPOrgRuleApi>(getMcpGatewayRulesPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedMCPOrgRuleApi),+ })+}++export const getMcpGatewayRulesDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/rules/${id}/`+}++/**+ * Team guardrails evaluated before any scope policy.+ */+export const mcpGatewayRulesDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getMcpGatewayRulesDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getMcpGatewayServersListUrl = (projectId: string, params?: McpGatewayServersListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/mcp_gateway/servers/?${stringifiedParams}`+ : `/api/projects/${projectId}/mcp_gateway/servers/`+}++/**+ * The team's gateway server registry. The registry is sparse: rows appear+ * through the install/share/OAuth-start flows in views.py, or when an admin+ * toggles an untouched catalog template here (`set_template_enabled`).+ * Servers with no row follow the team config's `default_servers_enabled`.+ */+export const mcpGatewayServersList = async (+ projectId: string,+ params?: McpGatewayServersListParams,+ options?: RequestInit+): Promise<PaginatedMCPGatewayServerListApi> => {+ return apiMutator<PaginatedMCPGatewayServerListApi>(getMcpGatewayServersListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayServersRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/servers/${id}/`+}++/**+ * The team's gateway server registry. The registry is sparse: rows appear+ * through the install/share/OAuth-start flows in views.py, or when an admin+ * toggles an untouched catalog template here (`set_template_enabled`).+ * Servers with no row follow the team config's `default_servers_enabled`.+ */+export const mcpGatewayServersRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<MCPGatewayServerApi> => {+ return apiMutator<MCPGatewayServerApi>(getMcpGatewayServersRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayServersUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/servers/${id}/`+}++/**+ * The team's gateway server registry. The registry is sparse: rows appear+ * through the install/share/OAuth-start flows in views.py, or when an admin+ * toggles an untouched catalog template here (`set_template_enabled`).+ * Servers with no row follow the team config's `default_servers_enabled`.+ */+export const mcpGatewayServersUpdate = async (+ projectId: string,+ id: string,+ mCPGatewayServerUpdateApi?: MCPGatewayServerUpdateApi,+ options?: RequestInit+): Promise<MCPGatewayServerUpdateApi> => {+ return apiMutator<MCPGatewayServerUpdateApi>(getMcpGatewayServersUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(mCPGatewayServerUpdateApi),+ })+}++export const getMcpGatewayServersPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/servers/${id}/`+}++/**+ * The team's gateway server registry. The registry is sparse: rows appear+ * through the install/share/OAuth-start flows in views.py, or when an admin+ * toggles an untouched catalog template here (`set_template_enabled`).+ * Servers with no row follow the team config's `default_servers_enabled`.+ */+export const mcpGatewayServersPartialUpdate = async (+ projectId: string,+ id: string,+ patchedMCPGatewayServerUpdateApi?: PatchedMCPGatewayServerUpdateApi,+ options?: RequestInit+): Promise<MCPGatewayServerUpdateApi> => {+ return apiMutator<MCPGatewayServerUpdateApi>(getMcpGatewayServersPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedMCPGatewayServerUpdateApi),+ })+}++export const getMcpGatewayServersDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/servers/${id}/`+}++/**+ * The team's gateway server registry. The registry is sparse: rows appear+ * through the install/share/OAuth-start flows in views.py, or when an admin+ * toggles an untouched catalog template here (`set_template_enabled`).+ * Servers with no row follow the team config's `default_servers_enabled`.+ */+export const mcpGatewayServersDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getMcpGatewayServersDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getMcpGatewayServersPoliciesCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/servers/${id}/policies/`+}++/**+ * Upsert per-tool states for a scope, returning the re-resolved catalog.+ */+export const mcpGatewayServersPoliciesCreate = async (+ projectId: string,+ id: string,+ gatewayPoliciesUpsertApi: GatewayPoliciesUpsertApi,+ options?: RequestInit+): Promise<PaginatedResolvedToolPolicyListApi> => {+ return apiMutator<PaginatedResolvedToolPolicyListApi>(getMcpGatewayServersPoliciesCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(gatewayPoliciesUpsertApi),+ })+}++export const getMcpGatewayServersToolsRetrieveUrl = (+ projectId: string,+ id: string,+ params?: McpGatewayServersToolsRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/mcp_gateway/servers/${id}/tools/?${stringifiedParams}`+ : `/api/projects/${projectId}/mcp_gateway/servers/${id}/tools/`+}++/**+ * Tool catalog with the resolved policy for a scope.+ */+export const mcpGatewayServersToolsRetrieve = async (+ projectId: string,+ id: string,+ params?: McpGatewayServersToolsRetrieveParams,+ options?: RequestInit+): Promise<PaginatedResolvedToolPolicyListApi> => {+ return apiMutator<PaginatedResolvedToolPolicyListApi>(getMcpGatewayServersToolsRetrieveUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayServersSetTemplateEnabledCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/mcp_gateway/servers/set_template_enabled/`+}++/**+ * Enable or disable a catalog template for the team (admin-only),+ * materializing its gateway registration on the first toggle.+ */+export const mcpGatewayServersSetTemplateEnabledCreate = async (+ projectId: string,+ setTemplateEnabledApi: SetTemplateEnabledApi,+ options?: RequestInit+): Promise<MCPGatewayServerApi> => {+ return apiMutator<MCPGatewayServerApi>(getMcpGatewayServersSetTemplateEnabledCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(setTemplateEnabledApi),+ })+}++export const getMcpGatewayServiceAccountsListUrl = (+ projectId: string,+ params?: McpGatewayServiceAccountsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/mcp_gateway/service_accounts/?${stringifiedParams}`+ : `/api/projects/${projectId}/mcp_gateway/service_accounts/`+}++/**+ * PostHog's built-in agents and their MCP access grants.+ *+ * The catalog is fixed. Projects can pause an agent's MCP access and grant or+ * revoke servers, but cannot create, rename, rotate, or delete agents.+ */+export const mcpGatewayServiceAccountsList = async (+ projectId: string,+ params?: McpGatewayServiceAccountsListParams,+ options?: RequestInit+): Promise<PaginatedMCPServiceAccountListApi> => {+ return apiMutator<PaginatedMCPServiceAccountListApi>(getMcpGatewayServiceAccountsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayServiceAccountsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/service_accounts/${id}/`+}++/**+ * PostHog's built-in agents and their MCP access grants.+ *+ * The catalog is fixed. Projects can pause an agent's MCP access and grant or+ * revoke servers, but cannot create, rename, rotate, or delete agents.+ */+export const mcpGatewayServiceAccountsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<MCPServiceAccountApi> => {+ return apiMutator<MCPServiceAccountApi>(getMcpGatewayServiceAccountsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getMcpGatewayServiceAccountsUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/service_accounts/${id}/`+}++/**+ * PostHog's built-in agents and their MCP access grants.+ *+ * The catalog is fixed. Projects can pause an agent's MCP access and grant or+ * revoke servers, but cannot create, rename, rotate, or delete agents.+ */+export const mcpGatewayServiceAccountsUpdate = async (+ projectId: string,+ id: string,+ mCPServiceAccountUpdateApi?: MCPServiceAccountUpdateApi,+ options?: RequestInit+): Promise<MCPServiceAccountUpdateApi> => {+ return apiMutator<MCPServiceAccountUpdateApi>(getMcpGatewayServiceAccountsUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(mCPServiceAccountUpdateApi),+ })+}++export const getMcpGatewayServiceAccountsPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/service_accounts/${id}/`+}++/**+ * PostHog's built-in agents and their MCP access grants.+ *+ * The catalog is fixed. Projects can pause an agent's MCP access and grant or+ * revoke servers, but cannot create, rename, rotate, or delete agents.+ */+export const mcpGatewayServiceAccountsPartialUpdate = async (+ projectId: string,+ id: string,+ patchedMCPServiceAccountUpdateApi?: PatchedMCPServiceAccountUpdateApi,+ options?: RequestInit+): Promise<MCPServiceAccountUpdateApi> => {+ return apiMutator<MCPServiceAccountUpdateApi>(getMcpGatewayServiceAccountsPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedMCPServiceAccountUpdateApi),+ })+}++export const getMcpGatewayServiceAccountsAccessCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/mcp_gateway/service_accounts/${id}/access/`+}++/**+ * Grant or revoke this agent's access to one gateway server.+ */+export const mcpGatewayServiceAccountsAccessCreate = async (+ projectId: string,+ id: string,+ serviceAccountAccessUpdateApi: ServiceAccountAccessUpdateApi,+ options?: RequestInit+): Promise<MCPServiceAccountApi> => {+ return apiMutator<MCPServiceAccountApi>(getMcpGatewayServiceAccountsAccessCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(serviceAccountAccessUpdateApi),+ })+}+export const getMcpServerInstallationsListUrl = (projectId: string, params?: McpServerInstallationsListParams) => {const normalizedParams = new URLSearchParams()@@ -177,8 +871,8 @@ export const getMcpServerInstallationsShareCreateUrl = (projectId: string, id: s* Escalate a personal installation to a team-wide shared one.** Owner-only AND admin-only: sharing exposes the owner's credential to- * every project member and all autonomous agents, so it carries the same- * gate as creating a shared install outright.+ * project members, so it carries the same gate as creating a shared+ * install outright. Agents require separate explicit grants.*/export const mcpServerInstallationsShareCreate = async (projectId: string,diff --git a/products/mcp_store/frontend/generated/api.zod.ts b/products/mcp_store/frontend/generated/api.zod.tsindex e7875ddb9fad..452e3637fc06 100644--- a/products/mcp_store/frontend/generated/api.zod.ts+++ b/products/mcp_store/frontend/generated/api.zod.ts@@ -9,6 +9,363 @@*/import * as zod from 'zod'+/**+ * Set the policy baseline for members or agents (admin-only).+ */+export const McpGatewayConfigApplyPresetCreateBody = /* @__PURE__ */ zod.object({+ audience: zod+ .enum(['members', 'agents'])+ .describe('\* `members` - members\n\* `agents` - agents')+ .describe("Which audience's baseline to overwrite.\n\n\* `members` - members\n\* `agents` - agents"),+ preset: zod+ .enum(['allow', 'user', 'ask', 'block'])+ .describe(+ '\* `allow` - Allow all\n\* `user` - Member decides\n\* `ask` - Ask for destructive\n\* `block` - Block destructive'+ )+ .describe(+ 'Preset to apply.\n\n\* `allow` - Allow all\n\* `user` - Member decides\n\* `ask` - Ask for destructive\n\* `block` - Block destructive'+ ),+})++/**+ * Enable or disable every MCP server for the team (admin-only): flips+ * each registered server and the default for untouched catalog servers,+ * so newly published templates follow the same posture.+ */+export const McpGatewayConfigSetAllServersEnabledCreateBody = /* @__PURE__ */ zod.object({+ enabled: zod+ .boolean()+ .describe(+ 'True enables every MCP server for the team; false disables them all. Applies to every registered server and becomes the default for untouched and future catalog servers.'+ ),+})++/**+ * Update team gateway settings (admin-only).+ */+export const McpGatewayConfigUpdateSettingsCreateBody = /* @__PURE__ */ zod.object({+ allow_custom_servers: zod+ .boolean()+ .optional()+ .describe('Whether non-admin members may register custom MCP servers.'),+ allow_member_agent_access: zod+ .boolean()+ .optional()+ .describe(+ 'Whether non-admin members may share their available MCP connections with agents and manage agent tool policies.'+ ),+ default_servers_enabled: zod+ .boolean()+ .optional()+ .describe(+ "Whether servers with no gateway registration — including catalog templates published later — are enabled for the team. A registered server's own toggle always wins."+ ),+ member_default_preset: zod+ .union([+ zod+ .enum(['allow', 'user', 'ask', 'block'])+ .describe(+ '\* `allow` - Allow all\n\* `user` - Member decides\n\* `ask` - Ask for destructive\n\* `block` - Block destructive'+ ),+ zod.enum(['']),+ ])+ .optional()+ .describe(+ 'Baseline preset for members.\n\n\* `allow` - Allow all\n\* `user` - Member decides\n\* `ask` - Ask for destructive\n\* `block` - Block destructive'+ ),+ agent_default_preset: zod+ .union([+ zod+ .enum(['allow', 'user', 'ask', 'block'])+ .describe(+ '\* `allow` - Allow all\n\* `user` - Member decides\n\* `ask` - Ask for destructive\n\* `block` - Block destructive'+ ),+ zod.enum(['']),+ ])+ .optional()+ .describe(+ 'Baseline preset for agents.\n\n\* `allow` - Allow all\n\* `user` - Member decides\n\* `ask` - Ask for destructive\n\* `block` - Block destructive'+ ),+})++/**+ * Turn one gateway server off (or back on) for one member.+ */+export const McpGatewayMembersSetAccessCreateBody = /* @__PURE__ */ zod.object({+ gateway_server_id: zod.uuid().describe('Gateway server to toggle for the member.'),+ enabled: zod.boolean().describe('False turns the server off for the member; true restores it.'),+})++/**+ * Team guardrails evaluated before any scope policy.+ */+export const mcpGatewayRulesCreateBodyNameMax = 200++export const mcpGatewayRulesCreateBodyToolPatternMax = 400++export const McpGatewayRulesCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(mcpGatewayRulesCreateBodyNameMax)+ .describe('Short rule name shown wherever the rule locks a tool.'),+ description: zod.string().optional().describe('Why this guardrail exists.'),+ applies_to: zod+ .enum(['everyone', 'members', 'agents'])+ .describe('\* `everyone` - Everyone\n\* `members` - Members\n\* `agents` - Agents')+ .optional()+ .describe(+ 'Audience the rule constrains.\n\n\* `everyone` - Everyone\n\* `members` - Members\n\* `agents` - Agents'+ ),+ effect: zod+ .enum(['needs_approval', 'do_not_use'])+ .describe('\* `needs_approval` - Require approval\n\* `do_not_use` - Block')+ .optional()+ .describe(+ 'State the rule forces on matching tools.\n\n\* `needs_approval` - Require approval\n\* `do_not_use` - Block'+ ),+ tool_pattern: zod+ .string()+ .max(mcpGatewayRulesCreateBodyToolPatternMax)+ .optional()+ .describe('fnmatch pattern against tool names. Blank matches destructive tools heuristically.'),+ enabled: zod.boolean().optional().describe('Disabled rules are kept but not evaluated.'),+})++/**+ * Team guardrails evaluated before any scope policy.+ */+export const mcpGatewayRulesUpdateBodyNameMax = 200++export const mcpGatewayRulesUpdateBodyToolPatternMax = 400++export const McpGatewayRulesUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(mcpGatewayRulesUpdateBodyNameMax)+ .describe('Short rule name shown wherever the rule locks a tool.'),+ description: zod.string().optional().describe('Why this guardrail exists.'),+ applies_to: zod+ .enum(['everyone', 'members', 'agents'])+ .describe('\* `everyone` - Everyone\n\* `members` - Members\n\* `agents` - Agents')+ .optional()+ .describe(+ 'Audience the rule constrains.\n\n\* `everyone` - Everyone\n\* `members` - Members\n\* `agents` - Agents'+ ),+ effect: zod+ .enum(['needs_approval', 'do_not_use'])+ .describe('\* `needs_approval` - Require approval\n\* `do_not_use` - Block')+ .optional()+ .describe(+ 'State the rule forces on matching tools.\n\n\* `needs_approval` - Require approval\n\* `do_not_use` - Block'+ ),+ tool_pattern: zod+ .string()+ .max(mcpGatewayRulesUpdateBodyToolPatternMax)+ .optional()+ .describe('fnmatch pattern against tool names. Blank matches destructive tools heuristically.'),+ enabled: zod.boolean().optional().describe('Disabled rules are kept but not evaluated.'),+})++/**+ * Team guardrails evaluated before any scope policy.+ */+export const mcpGatewayRulesPartialUpdateBodyNameMax = 200++export const mcpGatewayRulesPartialUpdateBodyToolPatternMax = 400++export const McpGatewayRulesPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(mcpGatewayRulesPartialUpdateBodyNameMax)+ .optional()+ .describe('Short rule name shown wherever the rule locks a tool.'),+ description: zod.string().optional().describe('Why this guardrail exists.'),+ applies_to: zod+ .enum(['everyone', 'members', 'agents'])+ .describe('\* `everyone` - Everyone\n\* `members` - Members\n\* `agents` - Agents')+ .optional()+ .describe(+ 'Audience the rule constrains.\n\n\* `everyone` - Everyone\n\* `members` - Members\n\* `agents` - Agents'+ ),+ effect: zod+ .enum(['needs_approval', 'do_not_use'])+ .describe('\* `needs_approval` - Require approval\n\* `do_not_use` - Block')+ .optional()+ .describe(+ 'State the rule forces on matching tools.\n\n\* `needs_approval` - Require approval\n\* `do_not_use` - Block'+ ),+ tool_pattern: zod+ .string()+ .max(mcpGatewayRulesPartialUpdateBodyToolPatternMax)+ .optional()+ .describe('fnmatch pattern against tool names. Blank matches destructive tools heuristically.'),+ enabled: zod.boolean().optional().describe('Disabled rules are kept but not evaluated.'),+})++/**+ * The team's gateway server registry. The registry is sparse: rows appear+ * through the install/share/OAuth-start flows in views.py, or when an admin+ * toggles an untouched catalog template here (`set_template_enabled`).+ * Servers with no row follow the team config's `default_servers_enabled`.+ */+export const mcpGatewayServersUpdateBodyNameMax = 200++export const McpGatewayServersUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(mcpGatewayServersUpdateBodyNameMax)+ .optional()+ .describe('Display name shown across the gateway.'),+ description: zod.string().optional().describe('Short description shown on server cards.'),+ category: zod+ .enum(['business', 'data', 'design', 'dev', 'infra', 'productivity'])+ .describe(+ '\* `business` - Business Operations\n\* `data` - Data & Analytics\n\* `design` - Design & Content\n\* `dev` - Developer Tools & APIs\n\* `infra` - Infrastructure\n\* `productivity` - Productivity & Collaboration'+ )+ .optional()+ .describe(+ 'Catalog category used for filter chips.\n\n\* `business` - Business Operations\n\* `data` - Data & Analytics\n\* `design` - Design & Content\n\* `dev` - Developer Tools & APIs\n\* `infra` - Infrastructure\n\* `productivity` - Productivity & Collaboration'+ ),+ is_team_enabled: zod+ .boolean()+ .optional()+ .describe('Whether the team can see and call the server. Turning it off also blocks agent access.'),+})++/**+ * The team's gateway server registry. The registry is sparse: rows appear+ * through the install/share/OAuth-start flows in views.py, or when an admin+ * toggles an untouched catalog template here (`set_template_enabled`).+ * Servers with no row follow the team config's `default_servers_enabled`.+ */+export const mcpGatewayServersPartialUpdateBodyNameMax = 200++export const McpGatewayServersPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(mcpGatewayServersPartialUpdateBodyNameMax)+ .optional()+ .describe('Display name shown across the gateway.'),+ description: zod.string().optional().describe('Short description shown on server cards.'),+ category: zod+ .enum(['business', 'data', 'design', 'dev', 'infra', 'productivity'])+ .describe(+ '\* `business` - Business Operations\n\* `data` - Data & Analytics\n\* `design` - Design & Content\n\* `dev` - Developer Tools & APIs\n\* `infra` - Infrastructure\n\* `productivity` - Productivity & Collaboration'+ )+ .optional()+ .describe(+ 'Catalog category used for filter chips.\n\n\* `business` - Business Operations\n\* `data` - Data & Analytics\n\* `design` - Design & Content\n\* `dev` - Developer Tools & APIs\n\* `infra` - Infrastructure\n\* `productivity` - Productivity & Collaboration'+ ),+ is_team_enabled: zod+ .boolean()+ .optional()+ .describe('Whether the team can see and call the server. Turning it off also blocks agent access.'),+})++/**+ * Upsert per-tool states for a scope, returning the re-resolved catalog.+ */+export const mcpGatewayServersPoliciesCreateBodyScopeTypeDefault = `team`+export const mcpGatewayServersPoliciesCreateBodyPoliciesItemToolNameMax = 200++export const mcpGatewayServersPoliciesCreateBodyPoliciesMax = 1000++export const McpGatewayServersPoliciesCreateBody = /* @__PURE__ */ zod.object({+ scope_type: zod+ .enum(['team', 'member', 'agent'])+ .describe('\* `team` - Team default\n\* `member` - Member\n\* `agent` - Agent')+ .default(mcpGatewayServersPoliciesCreateBodyScopeTypeDefault)+ .describe(+ 'Which scope to resolve: the team default, one member, or one agent.\n\n\* `team` - Team default\n\* `member` - Member\n\* `agent` - Agent'+ ),+ scope_user_id: zod.number().optional().describe('Member scope target. Defaults to the requesting user.'),+ scope_service_account_id: zod.uuid().optional().describe('Agent scope target. Required when scope_type is agent.'),+ policies: zod+ .array(+ zod.object({+ tool_name: zod+ .string()+ .max(mcpGatewayServersPoliciesCreateBodyPoliciesItemToolNameMax)+ .describe('Tool to set the policy for, up to 200 characters.'),+ policy_state: zod+ .enum(['approved', 'needs_approval', 'do_not_use'])+ .describe(+ 'State to apply for this scope.\n\n\* `approved` - Approved\n\* `needs_approval` - Needs approval\n\* `do_not_use` - Do not use'+ ),+ })+ )+ .max(mcpGatewayServersPoliciesCreateBodyPoliciesMax)+ .describe('Per-tool states to upsert for the scope. At most 1,000 entries per request.'),+})++/**+ * Enable or disable a catalog template for the team (admin-only),+ * materializing its gateway registration on the first toggle.+ */+export const McpGatewayServersSetTemplateEnabledCreateBody = /* @__PURE__ */ zod.object({+ template_id: zod.uuid().describe('Active catalog template to enable or disable for the team.'),+ enabled: zod+ .boolean()+ .describe('True lets the team see and call the server; false hides it from members and blocks connections.'),+})++/**+ * PostHog's built-in agents and their MCP access grants.+ *+ * The catalog is fixed. Projects can pause an agent's MCP access and grant or+ * revoke servers, but cannot create, rename, rotate, or delete agents.+ */+export const McpGatewayServiceAccountsUpdateBody = /* @__PURE__ */ zod.object({+ status: zod+ .enum(['active', 'paused'])+ .describe('\* `active` - Active\n\* `paused` - Paused')+ .optional()+ .describe('active, or paused (all MCP access off).\n\n\* `active` - Active\n\* `paused` - Paused'),+})++/**+ * PostHog's built-in agents and their MCP access grants.+ *+ * The catalog is fixed. Projects can pause an agent's MCP access and grant or+ * revoke servers, but cannot create, rename, rotate, or delete agents.+ */+export const McpGatewayServiceAccountsPartialUpdateBody = /* @__PURE__ */ zod.object({+ status: zod+ .enum(['active', 'paused'])+ .describe('\* `active` - Active\n\* `paused` - Paused')+ .optional()+ .describe('active, or paused (all MCP access off).\n\n\* `active` - Active\n\* `paused` - Paused'),+})++/**+ * Grant or revoke this agent's access to one gateway server.+ */+export const mcpGatewayServiceAccountsAccessCreateBodyPoliciesItemToolNameMax = 200++export const mcpGatewayServiceAccountsAccessCreateBodyPoliciesMax = 1000++export const McpGatewayServiceAccountsAccessCreateBody = /* @__PURE__ */ zod.object({+ gateway_server_id: zod.uuid().describe('Gateway server to grant or revoke.'),+ enabled: zod.boolean().describe('True grants access, false revokes it.'),+ policies: zod+ .array(+ zod.object({+ tool_name: zod+ .string()+ .max(mcpGatewayServiceAccountsAccessCreateBodyPoliciesItemToolNameMax)+ .describe('Tool to set the policy for, up to 200 characters.'),+ policy_state: zod+ .enum(['approved', 'needs_approval', 'do_not_use'])+ .describe(+ 'State to apply for this scope.\n\n\* `approved` - Approved\n\* `needs_approval` - Needs approval\n\* `do_not_use` - Do not use'+ ),+ })+ )+ .max(mcpGatewayServiceAccountsAccessCreateBodyPoliciesMax)+ .optional()+ .describe('Optional agent-scope tool policies to set alongside the grant. At most 1,000 entries per request.'),+})+export const mcpServerInstallationsCreateBodyDisplayNameMax = 200export const mcpServerInstallationsCreateBodyUrlMax = 2048@@ -81,6 +438,8 @@ export const mcpServerInstallationsInstallCustomCreateBodyClientSecretDefault =export const mcpServerInstallationsInstallCustomCreateBodyInstallSourceDefault = `posthog`export const mcpServerInstallationsInstallCustomCreateBodyPosthogCodeCallbackUrlDefault = ``export const mcpServerInstallationsInstallCustomCreateBodyScopeDefault = `personal`+export const mcpServerInstallationsInstallCustomCreateBodyTeamEnabledDefault = true+export const mcpServerInstallationsInstallCustomCreateBodyReturnPathDefault = ``export const McpServerInstallationsInstallCustomCreateBody = /* @__PURE__ */ zod.object({name: zod.string().max(mcpServerInstallationsInstallCustomCreateBodyNameMax),@@ -102,14 +461,30 @@ export const McpServerInstallationsInstallCustomCreateBody = /* @__PURE__ */ zod.describe('\* `personal` - personal\n\* `shared` - shared').default(mcpServerInstallationsInstallCustomCreateBodyScopeDefault).describe(- "'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).\n\n\* `personal` - personal\n\* `shared` - shared"+ "'personal' is per-user; 'shared' makes the credential available to project members. Agent access is granted separately.\n\n\* `personal` - personal\n\* `shared` - shared"),+ team_enabled: zod+ .boolean()+ .default(mcpServerInstallationsInstallCustomCreateBodyTeamEnabledDefault)+ .describe('Whether the server starts enabled for the whole team. Non-default values are admin-only.'),+ agent_ids: zod+ .array(zod.uuid())+ .optional()+ .describe(+ 'Service accounts to share the server with at install time. Available to members when team settings allow member-managed agent access.'+ ),+ return_path: zod+ .string()+ .default(mcpServerInstallationsInstallCustomCreateBodyReturnPathDefault)+ .describe('In-app path to land back on after the OAuth round-trip. Must be a same-app relative path.'),})export const mcpServerInstallationsInstallTemplateCreateBodyApiKeyDefault = ``export const mcpServerInstallationsInstallTemplateCreateBodyInstallSourceDefault = `posthog`export const mcpServerInstallationsInstallTemplateCreateBodyPosthogCodeCallbackUrlDefault = ``export const mcpServerInstallationsInstallTemplateCreateBodyScopeDefault = `personal`+export const mcpServerInstallationsInstallTemplateCreateBodyTeamEnabledDefault = true+export const mcpServerInstallationsInstallTemplateCreateBodyReturnPathDefault = ``export const McpServerInstallationsInstallTemplateCreateBody = /* @__PURE__ */ zod.object({template_id: zod.uuid(),@@ -126,6 +501,20 @@ export const McpServerInstallationsInstallTemplateCreateBody = /* @__PURE__ */ z.describe('\* `personal` - personal\n\* `shared` - shared').default(mcpServerInstallationsInstallTemplateCreateBodyScopeDefault).describe(- "'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).\n\n\* `personal` - personal\n\* `shared` - shared"+ "'personal' is per-user; 'shared' makes the credential available to project members. Agent access is granted separately.\n\n\* `personal` - personal\n\* `shared` - shared"),+ team_enabled: zod+ .boolean()+ .default(mcpServerInstallationsInstallTemplateCreateBodyTeamEnabledDefault)+ .describe('Whether the server starts enabled for the whole team. Non-default values are admin-only.'),+ agent_ids: zod+ .array(zod.uuid())+ .optional()+ .describe(+ 'Service accounts to share the server with at install time. Available to members when team settings allow member-managed agent access.'+ ),+ return_path: zod+ .string()+ .default(mcpServerInstallationsInstallTemplateCreateBodyReturnPathDefault)+ .describe('In-app path to land back on after the OAuth round-trip. Must be a same-app relative path.'),})diff --git a/products/mcp_store/frontend/mcpStoreLogic.test.ts b/products/mcp_store/frontend/mcpStoreLogic.test.tsnew file mode 100644index 000000000000..4254e300bbd0--- /dev/null+++ b/products/mcp_store/frontend/mcpStoreLogic.test.ts@@ -0,0 +1,91 @@+import api from 'lib/api'++import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import type { MCPServerInstallationApi, MCPServerInstallationToolApi } from './generated/api.schemas'+import { mcpStoreLogic } from './mcpStoreLogic'++jest.mock('lib/api')++function installation(id: string, url?: string): MCPServerInstallationApi {+ return {+ id,+ template_id: null,+ name: id,+ icon_key: '',+ icon_domain: '',+ url,+ scope: 'shared',+ is_owner: true,+ needs_reauth: false,+ pending_oauth: false,+ proxy_url: '',+ tool_count: 1,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ }+}++function tool(installationId: string): MCPServerInstallationToolApi {+ return {+ id: `${installationId}-tool`,+ tool_name: 'create_issue',+ display_name: 'Create issue',+ description: '',+ input_schema: {},+ approval_state: 'approved',+ team_state: null,+ locked: false,+ decided_by: 'default',+ last_seen_at: '2026-01-01T00:00:00Z',+ removed_at: null,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ }+}++describe('mcpStoreLogic', () => {+ let logic: ReturnType<typeof mcpStoreLogic.build>++ beforeEach(async () => {+ initKeaTests()+ jest.resetAllMocks()+ jest.spyOn(api.mcpServers, 'list').mockResolvedValue({ count: 0, results: [] })+ jest.spyOn(api.mcpServerInstallations, 'list').mockResolvedValue({ count: 0, results: [] })++ logic = mcpStoreLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ })++ it('reloads only loaded installations for the shared server whose policy changed', async () => {+ const installations = [+ installation('source', 'https://shared.example.com/mcp'),+ installation('same-server', 'https://shared.example.com/mcp'),+ installation('other-server', 'https://other.example.com/mcp'),+ installation('missing-url'),+ ]+ logic.actions.loadInstallationsSuccess(installations)+ logic.actions.loadInstallationToolsSuccess(Object.fromEntries(installations.map(({ id }) => [id, [tool(id)]])))+ jest.spyOn(api.mcpServerInstallations, 'updateToolApproval').mockResolvedValue({})+ const listTools = jest+ .spyOn(api.mcpServerInstallations, 'listTools')+ .mockImplementation(async (installationId) => ({ results: [tool(installationId)] }))++ await expectLogic(logic, () => {+ logic.actions.setToolApprovalState({+ installationId: 'source',+ toolName: 'create_issue',+ approvalState: 'needs_approval',+ })+ }).toFinishAllListeners()++ expect(listTools.mock.calls.map(([installationId]) => installationId).sort()).toEqual(['same-server', 'source'])+ })+})diff --git a/products/mcp_store/frontend/mcpStoreLogic.ts b/products/mcp_store/frontend/mcpStoreLogic.tsindex 0734382a51a1..06bb8cecb999 100644--- a/products/mcp_store/frontend/mcpStoreLogic.ts+++ b/products/mcp_store/frontend/mcpStoreLogic.ts@@ -8,6 +8,7 @@ import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { isPolicyStateAllowedByCeiling } from './gateway/gatewayPolicyUtils'import type {MCPServerInstallationApi,MCPServerInstallationToolApi,@@ -46,6 +47,24 @@ const CUSTOM_SERVER_FORM_DEFAULTS: CustomServerFormValues = {template_id: '',}+function loadedInstallationIdsForServer(+ installations: MCPServerInstallationApi[],+ installationTools: Record<string, MCPServerInstallationToolApi[]>,+ installationId: string+): string[] {+ const loadedInstallationIds = Object.keys(installationTools)+ const serverUrl = installations.find((candidate) => candidate.id === installationId)?.url++ if (!serverUrl) {+ return loadedInstallationIds.includes(installationId) ? [installationId] : []+ }++ return loadedInstallationIds.filter((loadedInstallationId) => {+ const loadedServerUrl = installations.find((candidate) => candidate.id === loadedInstallationId)?.url+ return Boolean(loadedServerUrl) && loadedServerUrl === serverUrl+ })+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpStoreLogicValues {addCustomServerModalVisible: boolean@@ -460,19 +479,6 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([),}},- setBulkApprovalState: (- state: Record<string, MCPServerInstallationToolApi[]>,- { installationId, approvalState }: { installationId: string; approvalState: ToolApprovalState }- ) => {- const existing = state[installationId]- if (!existing) {- return state- }- return {- ...state,- [installationId]: existing.map((tool) => ({ ...tool, approval_state: approvalState })),- }- },},],sceneView: [@@ -745,15 +751,29 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([// Optimistic update already applied in the reducer. Reload from server on failure.try {await api.mcpServerInstallations.updateToolApproval(installationId, toolName, approvalState)+ const installation = values.installations.find((candidate) => candidate.id === installationId)+ if (installation?.scope === 'shared') {+ const loadedInstallationIds = loadedInstallationIdsForServer(+ values.installations,+ values.installationTools,+ installationId+ )+ for (const loadedInstallationId of loadedInstallationIds) {+ actions.loadInstallationTools({ installationId: loadedInstallationId })+ }+ }} catch (e: any) {lemonToast.error(e.detail || 'Failed to update tool approval')actions.loadInstallationTools({ installationId })}},setBulkApprovalState: async ({ installationId, approvalState }) => {- // Reducer already applied the bulk change optimistically. Fire one API- // call per tool in parallel; on any failure, reload to reconcile.- const tools = values.installationTools[installationId] ?? []+ const installation = values.installations.find((candidate) => candidate.id === installationId)+ const teamScope = installation?.scope === 'shared'+ const tools = (values.installationTools[installationId] ?? []).filter(+ (tool) =>+ teamScope || (!tool.locked && isPolicyStateAllowedByCeiling(approvalState, tool.team_state ?? null))+ )try {await Promise.all(tools.map((tool) =>@@ -761,6 +781,12 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([))lemonToast.success(`Updated ${tools.length} tools`)+ const loadedInstallationIds = teamScope+ ? loadedInstallationIdsForServer(values.installations, values.installationTools, installationId)+ : [installationId]+ for (const loadedInstallationId of loadedInstallationIds) {+ actions.loadInstallationTools({ installationId: loadedInstallationId })+ }} catch (e: any) {lemonToast.error(e.detail || 'Failed to update some tools')actions.loadInstallationTools({ installationId })diff --git a/products/mcp_store/frontend/scene/ServerDetailPanel.tsx b/products/mcp_store/frontend/scene/ServerDetailPanel.tsxindex 431bd429d861..be0aac745b1f 100644--- a/products/mcp_store/frontend/scene/ServerDetailPanel.tsx+++ b/products/mcp_store/frontend/scene/ServerDetailPanel.tsx@@ -110,9 +110,9 @@ function ToolsSection({ installation, disabledReason }: ToolsSectionProps): JSX.{tools.length > 0 && (<div className="flex items-center justify-between gap-2 flex-wrap bg-surface-secondary rounded p-2"><div className="text-xs text-secondary">- <span className="font-semibold">{approvedCount}</span> approved ·{' '}- <span className="font-semibold">{pendingCount}</span> require approval ·{' '}- <span className="font-semibold">{blockedCount}</span> blocked+ <span className="font-semibold">{approvedCount}</span> Always Allow ·{' '}+ <span className="font-semibold">{pendingCount}</span> Needs Approval ·{' '}+ <span className="font-semibold">{blockedCount}</span> Blocked</div><div className="flex items-center gap-1"><span className="text-xs text-secondary mr-1">Set all:</span>@@ -128,7 +128,7 @@ function ToolsSection({ installation, disabledReason }: ToolsSectionProps): JSX.}disabledReason={disabledReason}>- Approve+ Always Allow</LemonButton><LemonButtonsize="xsmall"@@ -142,7 +142,7 @@ function ToolsSection({ installation, disabledReason }: ToolsSectionProps): JSX.}disabledReason={disabledReason}>- Require approval+ Needs Approval</LemonButton><LemonButtonsize="xsmall"@@ -183,6 +183,7 @@ function ToolsSection({ installation, disabledReason }: ToolsSectionProps): JSX.<ToolRowkey={tool.id}tool={tool}+ teamScope={installation.scope === 'shared'}disabledReason={disabledReason}onPolicyChange={(state: ToolApprovalState) =>setToolApprovalState({diff --git a/products/mcp_store/frontend/scene/ToolPolicyToggle.tsx b/products/mcp_store/frontend/scene/ToolPolicyToggle.tsxindex 7006638a8719..2392526e73ab 100644--- a/products/mcp_store/frontend/scene/ToolPolicyToggle.tsx+++ b/products/mcp_store/frontend/scene/ToolPolicyToggle.tsx@@ -8,23 +8,34 @@ interface Props {onChange: (value: ToolApprovalState) => voidsize?: 'small' | 'xsmall' | 'medium'disabledReason?: string | null+ disabledStates?: Partial<Record<ToolApprovalState, string>>fullWidth?: boolean}-// Labels map design language ("approved / ask / blocked") to the backend enum+// Labels map product language to the backend enum// (`approved` / `needs_approval` / `do_not_use`). Display-only — no schema change.const OPTIONS: { value: ToolApprovalState; label: string; icon: JSX.Element }[] = [- { value: 'approved', label: 'Approved', icon: <IconCheck /> },- { value: 'needs_approval', label: 'Requires approval', icon: <IconShieldLock /> },+ { value: 'approved', label: 'Always Allow', icon: <IconCheck /> },+ { value: 'needs_approval', label: 'Needs Approval', icon: <IconShieldLock /> },{ value: 'do_not_use', label: 'Blocked', icon: <IconX /> },]-export function ToolPolicyToggle({ value, onChange, size = 'xsmall', disabledReason, fullWidth }: Props): JSX.Element {+export function ToolPolicyToggle({+ value,+ onChange,+ size = 'xsmall',+ disabledReason,+ disabledStates,+ fullWidth,+}: Props): JSX.Element {return (<LemonSegmentedButtonsize={size}value={value}- options={OPTIONS}+ options={OPTIONS.map((option) => ({+ ...option,+ disabledReason: disabledStates?.[option.value],+ }))}onChange={onChange}disabledReason={disabledReason ?? undefined}fullWidth={fullWidth}diff --git a/products/mcp_store/frontend/scene/ToolRow.tsx b/products/mcp_store/frontend/scene/ToolRow.tsxindex 5c9cbd8902ce..6a499ecedfbc 100644--- a/products/mcp_store/frontend/scene/ToolRow.tsx+++ b/products/mcp_store/frontend/scene/ToolRow.tsx@@ -1,14 +1,16 @@import { useState } from 'react'-import { IconChevronRight } from '@posthog/icons'-import { LemonTag } from '@posthog/lemon-ui'+import { IconChevronRight, IconLock } from '@posthog/icons'+import { LemonTag, Tooltip } from '@posthog/lemon-ui'+import { isPolicyStateAllowedByCeiling } from '../gateway/gatewayPolicyUtils'import type { MCPServerInstallationToolApi } from '../generated/api.schemas'import type { ToolApprovalState } from '../mcpStoreLogic'import { ToolPolicyToggle } from './ToolPolicyToggle'interface Props {tool: MCPServerInstallationToolApi+ teamScope?: booleanonPolicyChange: (state: ToolApprovalState) => voiddisabledReason?: string | null}@@ -21,10 +23,16 @@ function formatInputSchema(schema: unknown): string {}}-export function ToolRow({ tool, onPolicyChange, disabledReason }: Props): JSX.Element {+export function ToolRow({ tool, teamScope = false, onPolicyChange, disabledReason }: Props): JSX.Element {const [expanded, setExpanded] = useState(false)const state = (tool.approval_state ?? 'needs_approval') as ToolApprovalStateconst isRemoved = !!tool.removed_at+ const setByTeamAdmin = !teamScope && (tool.decided_by === 'team' || tool.decided_by === 'preset')+ const disabledStates = Object.fromEntries(+ (['approved', 'needs_approval', 'do_not_use'] as ToolApprovalState[])+ .filter((candidate) => !teamScope && !isPolicyStateAllowedByCeiling(candidate, tool.team_state ?? null))+ .map((candidate) => [candidate, 'Unavailable because of the team admin ceiling'])+ ) as Partial<Record<ToolApprovalState, string>>return (<div@@ -51,8 +59,22 @@ export function ToolRow({ tool, onPolicyChange, disabledReason }: Props): JSX.El)}</div>{/* Clicks on the toggle shouldn't collapse the row. */}- <div onClick={(e) => e.stopPropagation()}>- <ToolPolicyToggle value={state} onChange={onPolicyChange} disabledReason={disabledReason} />+ <div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>+ {setByTeamAdmin && (+ <Tooltip title="This effective state is capped by the team admin ceiling.">+ <LemonTag icon={<IconLock />} type="muted">+ Set by team admin+ </LemonTag>+ </Tooltip>+ )}+ <ToolPolicyToggle+ value={state}+ onChange={onPolicyChange}+ disabledReason={+ disabledReason ?? (tool.locked ? 'The team admin ceiling is Blocked.' : undefined)+ }+ disabledStates={disabledStates}+ /></div></div>{expanded && (diff --git a/products/mcp_store/manifest.tsx b/products/mcp_store/manifest.tsxindex ce023391cd8f..5d12378363dd 100644--- a/products/mcp_store/manifest.tsx+++ b/products/mcp_store/manifest.tsx@@ -1,7 +1,66 @@+import { FEATURE_FLAGS } from 'lib/constants'+import { urls } from 'scenes/urls'++import { ProductItemCategory } from '~/queries/schema/schema-general'import { ProductManifest } from '~/types'export const manifest: ProductManifest = {name: 'MCP servers',+ scenes: {+ McpGateway: {+ import: () => import('./frontend/gateway/McpGatewayScene'),+ projectBased: true,+ name: 'MCP servers',+ description:+ 'Route every MCP server your team uses through one gateway: shared credentials, per-tool policies, agent identities, and an audit log.',+ layout: 'app-container',+ iconType: 'tools',+ },+ McpGatewayServer: {+ import: () => import('./frontend/gateway/GatewayServerScene'),+ projectBased: true,+ name: 'MCP server',+ },+ McpGatewayAgent: {+ import: () => import('./frontend/gateway/GatewayAgentScene'),+ projectBased: true,+ name: 'MCP agent',+ },+ McpGatewayMember: {+ import: () => import('./frontend/gateway/GatewayMemberScene'),+ projectBased: true,+ name: 'MCP member access',+ },+ },+ routes: {+ // Specific routes must precede '/mcp-servers/:tab' so 'server' etc. don't match as tabs.+ '/mcp-servers/server/:id': ['McpGatewayServer', 'mcpGatewayServer'],+ '/mcp-servers/agent/:id': ['McpGatewayAgent', 'mcpGatewayAgent'],+ '/mcp-servers/member/:id': ['McpGatewayMember', 'mcpGatewayMember'],+ '/mcp-servers': ['McpGateway', 'mcpGateway'],+ '/mcp-servers/:tab': ['McpGateway', 'mcpGatewayTab'],+ },+ redirects: {},+ urls: {+ mcpGateway: (): string => '/mcp-servers',+ mcpGatewayTab: (tab: string): string => `/mcp-servers/${tab}`,+ mcpGatewayServer: (id: string, scope?: string): string =>+ `/mcp-servers/server/${id}${scope ? `?scope=${encodeURIComponent(scope)}` : ''}`,+ mcpGatewayAgent: (id: string): string => `/mcp-servers/agent/${id}`,+ mcpGatewayMember: (id: string | number): string => `/mcp-servers/member/${id}`,+ },+ fileSystemTypes: {},treeItemsNew: [],- treeItemsProducts: [],+ treeItemsProducts: [+ {+ path: 'MCP servers',+ intents: [],+ category: ProductItemCategory.AI_ENGINEERING,+ href: urls.mcpGateway(),+ iconType: 'tools',+ flag: FEATURE_FLAGS.MCP_GATEWAY,+ tags: ['alpha'],+ sceneKey: 'McpGateway',+ },+ ],}diff --git a/products/mcp_store/mcp/tools.yaml b/products/mcp_store/mcp/tools.yamlindex 3b96696f3874..89db044d2634 100644--- a/products/mcp_store/mcp/tools.yaml+++ b/products/mcp_store/mcp/tools.yaml@@ -75,6 +75,93 @@ tools:mcp-connections-update:operation: mcp_server_installations_updateenabled: false+ mcp-gateway-audit-counts-retrieve:+ operation: mcp_gateway_audit_counts_retrieve+ enabled: false+ mcp-gateway-audit-list:+ operation: mcp_gateway_audit_list+ enabled: false+ mcp-gateway-audit-retrieve:+ operation: mcp_gateway_audit_retrieve+ enabled: false+ mcp-gateway-config-apply-preset-create:+ operation: mcp_gateway_config_apply_preset_create+ enabled: false+ mcp-gateway-config-list:+ operation: mcp_gateway_config_list+ enabled: false+ mcp-gateway-config-set-all-servers-enabled-create:+ operation: mcp_gateway_config_set_all_servers_enabled_create+ enabled: false+ mcp-gateway-config-update-settings-create:+ operation: mcp_gateway_config_update_settings_create+ enabled: false+ mcp-gateway-members-list:+ operation: mcp_gateway_members_list+ enabled: false+ mcp-gateway-members-retrieve:+ operation: mcp_gateway_members_retrieve+ enabled: false+ mcp-gateway-members-set-access-create:+ operation: mcp_gateway_members_set_access_create+ enabled: false+ mcp-gateway-rules-create:+ operation: mcp_gateway_rules_create+ enabled: false+ mcp-gateway-rules-destroy:+ operation: mcp_gateway_rules_destroy+ enabled: false+ mcp-gateway-rules-list:+ operation: mcp_gateway_rules_list+ enabled: false+ mcp-gateway-rules-partial-update:+ operation: mcp_gateway_rules_partial_update+ enabled: false+ mcp-gateway-rules-retrieve:+ operation: mcp_gateway_rules_retrieve+ enabled: false+ mcp-gateway-rules-update:+ operation: mcp_gateway_rules_update+ enabled: false+ mcp-gateway-servers-destroy:+ operation: mcp_gateway_servers_destroy+ enabled: false+ mcp-gateway-servers-list:+ operation: mcp_gateway_servers_list+ enabled: false+ mcp-gateway-servers-partial-update:+ operation: mcp_gateway_servers_partial_update+ enabled: false+ mcp-gateway-servers-policies-create:+ operation: mcp_gateway_servers_policies_create+ enabled: false+ mcp-gateway-servers-retrieve:+ operation: mcp_gateway_servers_retrieve+ enabled: false+ mcp-gateway-servers-set-template-enabled-create:+ operation: mcp_gateway_servers_set_template_enabled_create+ enabled: false+ mcp-gateway-servers-tools-retrieve:+ operation: mcp_gateway_servers_tools_retrieve+ enabled: false+ mcp-gateway-servers-update:+ operation: mcp_gateway_servers_update+ enabled: false+ mcp-gateway-service-accounts-access-create:+ operation: mcp_gateway_service_accounts_access_create+ enabled: false+ mcp-gateway-service-accounts-list:+ operation: mcp_gateway_service_accounts_list+ enabled: false+ mcp-gateway-service-accounts-partial-update:+ operation: mcp_gateway_service_accounts_partial_update+ enabled: false+ mcp-gateway-service-accounts-retrieve:+ operation: mcp_gateway_service_accounts_retrieve+ enabled: false+ mcp-gateway-service-accounts-update:+ operation: mcp_gateway_service_accounts_update+ enabled: falsemcp-server-installations-share-create:operation: mcp_server_installations_share_createenabled: falsediff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex 50436b78d09e..9b670c5cc598 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -562,6 +562,7 @@ async def _spawn_and_run(step_name=_step_name(skill),verbose=verbose,origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT,+ mcp_builtin_agent_key="scout",# Tag every scout $ai_generation with its stage AND its scout, so scout spend is both# splittable out of the ai_product='signals' bucket (scouts carry no signal_report_id)# and attributable to one scout. `ai_stage` is the only run-shaped value the harnessdiff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex d54daa828a8a..b1280e719116 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -58,6 +58,7 @@ from products.tasks.backend.models import (ChannelFeedMessage,CodeInvite,CodeInviteRedemption,+ MCPBuiltInAgentKey,SandboxCustomImage,SandboxEnvironment,SandboxSession,@@ -1056,6 +1057,7 @@ def create_task_without_run(title: str = "",description: str = "",repository: str | None = None,+ mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,) -> UUID:"""Create a Task row with no initial run, returning its id.@@ -1069,6 +1071,7 @@ def create_task_without_run(origin_product=origin_product,user_id=user_id,repository=repository,+ mcp_builtin_agent_key=mcp_builtin_agent_key,)return task.iddiff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.pyindex 8ad4f034aad0..e4d6a8c88209 100644--- a/products/tasks/backend/logic/services/custom_prompt_internals.py+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py@@ -18,7 +18,7 @@ from posthog.storage import object_storagefrom posthog.storage.object_storage import ObjectStorageErrorfrom posthog.temporal.oauth import PosthogMcpScopes-from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.models import MCPBuiltInAgentKey, Task, TaskRunif TYPE_CHECKING:from temporalio.client import WorkflowHandle@@ -205,6 +205,7 @@ async def create_task_and_trigger(ai_stage: str | None = None,internal: bool = False,workflow_id_prefix: str | None = None,+ mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,):title = f"[sandbox_prompt:{step_name}] {description[:80]}" if step_name else description[:100]team = await sync_to_async(Team.objects.get)(id=context.team_id)@@ -236,6 +237,7 @@ async def create_task_and_trigger(sandbox_timeout_seconds=context.sandbox_timeout_seconds,workflow_id_prefix=workflow_id_prefix,github_read_access=context.github_read_access,+ mcp_builtin_agent_key=mcp_builtin_agent_key,)# lambda wrap: task.latest_run is a lazy ORM property; sync_to_async needs a callabletask_run = await sync_to_async(lambda: task.latest_run)()diff --git a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.pyindex b5149739ee0c..85290cfbd9ab 100644--- a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py+++ b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py@@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, TypeVarfrom pydantic import BaseModel-from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.models import MCPBuiltInAgentKey, Task, TaskRunif TYPE_CHECKING:from temporalio.client import WorkflowHandle@@ -67,6 +67,7 @@ class MultiTurnSession:max_poll_seconds: int | None = None,fallback_from_text: Callable[[str], _ModelT] | None = None,workflow_id_prefix: str | None = None,+ mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,) -> tuple[MultiTurnSession, _ModelT]:"""Start a multi-turn sandbox session and wait for the first structured response.@@ -100,6 +101,7 @@ class MultiTurnSession:on_task_run_created=on_task_run_created,max_poll_seconds=max_poll_seconds,workflow_id_prefix=workflow_id_prefix,+ mcp_builtin_agent_key=mcp_builtin_agent_key,)try:parsed = cls._parse_and_validate(last_message, model, label="initial turn")@@ -154,6 +156,7 @@ class MultiTurnSession:on_task_run_created: Callable[[TaskRun], Awaitable[None]] | None = None,max_poll_seconds: int | None = None,workflow_id_prefix: str | None = None,+ mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,) -> tuple[MultiTurnSession, str]:"""Start a multi-turn sandbox session and return the first raw agent response.@@ -172,6 +175,7 @@ class MultiTurnSession:ai_stage=ai_stage,internal=internal,workflow_id_prefix=workflow_id_prefix,+ mcp_builtin_agent_key=mcp_builtin_agent_key,)logger.info("multi_turn: started task=%s run=%s step=%s", task.id, task_run.id, step_name or "unknown")# Get session's parent workflow to send heartbeats to keep the agent alive while waiting for turns.diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex a5655dd33232..ae67bb823b78 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -52,6 +52,12 @@ from products.tasks.backend.storage import append_jsonl_objectlogger = structlog.get_logger(__name__)LogLevel = Literal["debug", "info", "warn", "error"]+MCPBuiltInAgentKey = Literal["support", "scout"]+MCP_BUILT_IN_AGENT_STATE_KEY = "mcp_builtin_agent_key"+MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN: dict[str, MCPBuiltInAgentKey] = {+ "support_reply": "support",+ "signals_scout": "scout",+}def resolve_schema(schema: type[BaseModel] | dict) -> dict:@@ -293,6 +299,12 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):if is_new:self._track_task_created()+ @property+ def mcp_builtin_agent_key(self) -> MCPBuiltInAgentKey | None:+ expected_key = MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN.get(self.origin_product)+ marker = (self.state or {}).get(MCP_BUILT_IN_AGENT_STATE_KEY)+ return expected_key if marker == expected_key else None+@classmethoddef get_file_system_unfiled(cls, team: "Team", surface: str = DEFAULT_SURFACE) -> models.QuerySet["Task"]:# Tasks live only on the desktop surface, never the web app tree.@@ -518,6 +530,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):pending_user_message: str | None = None,custom_image_builder_id: str | None = None,custom_image_id: str | None = None,+ mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,) -> tuple["Task", dict[str, Any]]:"""Create the Task row and assemble the initial run's `extra_state`.@@ -591,6 +604,10 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):if sandbox_env is None:raise ValueError(f"Invalid sandbox_environment_id: {sandbox_environment_id}")+ expected_agent_key = MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN.get(origin_product)+ if mcp_builtin_agent_key is not None and mcp_builtin_agent_key != expected_agent_key:+ raise ValueError(f"Agent key {mcp_builtin_agent_key!r} does not match task origin {origin_product!r}")+task = Task.objects.create(team=team,title=title,@@ -603,6 +620,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):channel=channel,internal=internal,json_schema=resolve_schema(output_schema) if output_schema else None,+ state={MCP_BUILT_IN_AGENT_STATE_KEY: mcp_builtin_agent_key} if mcp_builtin_agent_key else {},**({"signal_report_id": signal_report_id} if signal_report_id else {}),)@@ -734,6 +752,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):interaction_origin: str | None = None,model: str | None = None,initial_permission_mode: str | None = None,+ mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,) -> "Task":"""Create the Task row without an initial run or workflow.@@ -758,6 +777,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):interaction_origin=interaction_origin,model=model,initial_permission_mode=initial_permission_mode,+ mcp_builtin_agent_key=mcp_builtin_agent_key,)return task@@ -799,6 +819,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):custom_image_builder_id: str | None = None,custom_image_id: str | None = None,github_read_access: bool = False,+ mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,) -> "Task":from products.tasks.backend.temporal.client import _normalize_slack_context, execute_task_processing_workflow@@ -832,6 +853,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):pending_user_message=pending_user_message,custom_image_builder_id=custom_image_builder_id,custom_image_id=custom_image_id,+ mcp_builtin_agent_key=mcp_builtin_agent_key,)run_extra_state = dict(extra_state or {})diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 307f6774d54e..53fc52c97091 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -417,7 +417,10 @@ class TaskWriteSerializer(serializers.Serializer):origin_product = serializers.ChoiceField(choices=tasks_facade.TaskOriginProduct.choices,required=False,- help_text="PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).",+ help_text=(+ "PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). "+ "Origins reserved for server-created agents cannot be set through this API."+ ),)repository = serializers.CharField(max_length=255,@@ -603,23 +606,18 @@ class TaskWriteSerializer(serializers.Serializer):def validate_origin_product(self, value):"""Reject internal-only origins that are set by server-side flows, never by API callers."""- if value == tasks_facade.TaskOriginProduct.IMAGE_BUILDER:- raise serializers.ValidationError("origin_product 'image_builder' is reserved for image-builder sessions")- if value == tasks_facade.TaskOriginProduct.EXPERIMENTS:- # Experiments tasks are team-readable, so letting API callers pick this origin- # would let them expose an arbitrary task to the whole team. The experiments- # flow creates its tasks server-side through the facade, never through here.- raise serializers.ValidationError("origin_product 'experiments' is reserved for the experiments flow")- if value == tasks_facade.TaskOriginProduct.SIGNALS_SCOUT:- # Scout tasks are created only by the signals scout harness. A forged scout origin- # would route the task's run logs into PostHog's internal Logs project- # (run_log_mirror) and inherit scout visibility semantics.- raise serializers.ValidationError("origin_product 'signals_scout' is reserved for signals scout runs")- if value == tasks_facade.TaskOriginProduct.ONBOARDING:- # This origin routes the run's LLM traffic to the unbilled `onboarding` gateway- # product, so a forged one would be free model access. Only create_wizard_cloud_run- # sets it, behind its own rate limits and daily cap.- raise serializers.ValidationError("origin_product 'onboarding' is reserved for setup wizard cloud runs")+ reserved_origins = {+ tasks_facade.TaskOriginProduct.IMAGE_BUILDER,+ tasks_facade.TaskOriginProduct.EXPERIMENTS,+ tasks_facade.TaskOriginProduct.SIGNALS_SCOUT,+ tasks_facade.TaskOriginProduct.SUPPORT_REPLY,+ # Routes the run's LLM traffic to the unbilled `onboarding` gateway product, so a+ # forged origin would be free model access. Only create_wizard_cloud_run sets it,+ # behind its own rate limits and daily cap.+ tasks_facade.TaskOriginProduct.ONBOARDING,+ }+ if value in reserved_origins:+ raise serializers.ValidationError(f"origin_product '{value}' is reserved for server-created tasks")return valuedef validate_repository(self, value):diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex eeb9049deff5..863a7eecabcf 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -30,7 +30,12 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.streaming import sse_streaming_responsefrom posthog.api.utils import ServerTimingsGatheredfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication-from posthog.permissions import APIScopePermission, get_authenticator_scoped_team_ids, get_authenticator_scopes+from posthog.permissions import (+ APIScopePermission,+ DenyMCPBuiltInAgentOAuth,+ get_authenticator_scoped_team_ids,+ get_authenticator_scopes,+)from posthog.rate_limit import CodeInviteThrottlefrom posthog.renderers import ServerSentEventRenderer@@ -823,12 +828,19 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):return Response(status=status.HTTP_204_NO_CONTENT)+class DenyBuiltInAgentTaskAutomations(DenyMCPBuiltInAgentOAuth):+ """Automations schedule future runs that resolve a member's credentials, so a+ built-in agent's sandbox token must not create or trigger them."""++ message = "Built-in agents cannot manage task automations."++@extend_schema(tags=["task-automations"])class TaskAutomationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"""API for managing scheduled task automations."""authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]- permission_classes = [IsAuthenticated, APIScopePermission]+ permission_classes = [IsAuthenticated, APIScopePermission, DenyBuiltInAgentTaskAutomations]scope_object = "task"http_method_names = ["get", "post", "patch", "delete", "head", "options"]diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.pyindex 17cdd8a01cb9..4b49fa12926e 100644--- a/products/tasks/backend/temporal/oauth.py+++ b/products/tasks/backend/temporal/oauth.py@@ -15,6 +15,7 @@ from posthog.temporal.oauth import (resolve_scopes,)+from products.mcp_store.backend.facade.api import is_builtin_agent_enforcement_enabledfrom products.tasks.backend.exceptions import OAuthTokenError, TaskInvalidStateErrorfrom products.tasks.backend.logic.services.run_actor import (get_task_run_credential_user,@@ -76,12 +77,22 @@ def create_oauth_access_token()effective_scopes: PosthogMcpScopes = _scopes_for_loop_fired_run(scopes) if loop_id else scopes- return create_oauth_access_token_for_user(- actor,- task.team_id,- scopes=effective_scopes,- application=_oauth_application_for_task(task),- )+ token_options: dict[str, Any] = {+ "scopes": effective_scopes,+ "application": _oauth_application_for_task(task),+ }+ if task.origin_product in {+ Task.OriginProduct.SIGNALS_SCOUT,+ Task.OriginProduct.SUPPORT_REPLY,+ } and is_builtin_agent_enforcement_enabled(task.team_id):+ # This scope only removes access to the human MCP Store surface. Add it+ # even when a legacy task lacks trusted provenance so an old spoofed+ # origin fails closed instead of inheriting its creator's connections.+ # Keyed to the same rollout flag as the Store facade: a legacy-resolved+ # task needs a member-capable token, or every member-proxy call it was+ # just granted would 403.+ token_options["include_mcp_builtin_agent_scope"] = True+ return create_oauth_access_token_for_user(actor, task.team_id, **token_options)def create_oauth_access_token_for_run(@@ -157,9 +168,13 @@ def create_oauth_access_token_for_user(*,scopes: PosthogMcpScopes = "read_only",application: SandboxOAuthApplication = "array",+ include_mcp_builtin_agent_scope: bool = False,) -> str:"""Create an OAuth access token for a sandbox app, scoped to a specific team."""try:- return _create_oauth_access_token_for_user(user, team_id, scopes=scopes, application=application)+ token_options: dict[str, Any] = {"scopes": scopes, "application": application}+ if include_mcp_builtin_agent_scope:+ token_options["include_mcp_builtin_agent_scope"] = True+ return _create_oauth_access_token_for_user(user, team_id, **token_options)except RuntimeError as err:raise OAuthTokenError(str(err), {"team_id": team_id}, cause=err) from errdiff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.pyindex d68fd93fd924..3b3fbf1ada45 100644--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py@@ -351,10 +351,11 @@ def _refresh_sandbox_mcp(scope = sandbox_identity_scope(run_id, state)bound_user_id = get_sandbox_mcp_session_user(scope)- if bound_user_id == actor_user.id:+ is_built_in_agent_task = task_run.task.mcp_builtin_agent_key is not None+ if bound_user_id == actor_user.id and not is_built_in_agent_task:logger.info("refresh_mcp_skipped_within_interval", run_id=run_id, user_id=actor_user.id)return True- is_transition = bound_user_id is not None+ is_transition = bound_user_id is not None and bound_user_id != actor_user.idif is_transition:logger.info("refresh_mcp_identity_transition",@@ -380,8 +381,11 @@ def _refresh_sandbox_mcp(token=access_token,team_id=task_run.team_id,user_id=actor_user.id,+ include_personal=not task_run.task.internal,interaction_origin=(state or {}).get("interaction_origin"),allowed_installation_ids=loop_mcp_installation_allowlist(state),+ origin_product=task_run.task.origin_product,+ task_agent_key=task_run.task.mcp_builtin_agent_key,)if user_mcp_configs:mcp_configs = mcp_configs + user_mcp_configsdiff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.pyindex 459c0652d200..4626866cbec8 100644--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py@@ -188,7 +188,8 @@ def _include_personal_mcp_for_task(task: Task) -> bool:"""Whether a run may pull the task creator's *personal* MCP installations.Internal/autonomous runs (support reply, signals) must never pull a- resolved member's personal creds — they get shared team connections only.+ resolved member's personal creds. Agent-specific grant filtering happens+ in the MCP Store facade.User-initiated Code runs get shared + the creator's personal installs."""return not task.internal@@ -252,6 +253,8 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandboinclude_personal=include_personal,interaction_origin=ctx.interaction_origin,allowed_installation_ids=loop_mcp_installation_allowlist(ctx.state),+ origin_product=task.origin_product,+ task_agent_key=task.mcp_builtin_agent_key,)if user_mcp_configs:mcp_configs = mcp_configs + user_mcp_configsdiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.pyindex 907390a5b75b..030259e9ac91 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py@@ -137,7 +137,7 @@ def test_ensure_repository_on_disk_skips_repo_less_runs(mocker) -> None:@pytest.mark.django_dbasync def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mocker) -> None:- context = _context(sandbox_event_ingest_enabled=True)+ context = _context(sandbox_event_ingest_enabled=True, state={"mcp_builtin_agent_key": "scout"})sandbox = mocker.Mock()sandbox.execute.return_value.stdout = ""sandbox.execute.return_value.stderr = ""@@ -146,9 +146,17 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mockerreturn_value=sandbox,)mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.emit_agent_log")- mocker.patch(+ task = mocker.Mock(+ created_by_id=None,+ team_id=1,+ internal=True,+ origin_product="support_reply",+ mcp_builtin_agent_key="support",+ )+ task_queryset = mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.Task.objects.select_related"- ).return_value.get.return_value = mocker.Mock(created_by_id=None)+ ).return_value+ task_queryset.get.return_value = taskmocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.create_oauth_access_token_for_run",return_value="oauth-token",@@ -157,6 +165,10 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mocker"products.tasks.backend.temporal.process_task.activities.start_agent_server.get_sandbox_ph_mcp_configs",return_value=[],)+ get_user_mcp_configs = mocker.patch(+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.get_user_mcp_server_configs",+ return_value=[],+ )mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.TaskRun.objects.filter",).return_value.first.return_value = mocker.Mock(state={}, imported_mcp_servers=None)@@ -178,6 +190,17 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mockerassert result.connect_token == "connect-token"create_event_ingest_token.assert_called_once()assert create_event_ingest_token.call_args.kwargs == {"sandbox_id": "sandbox-id"}+ task_queryset.get.assert_called_once_with(id="task-id")+ get_user_mcp_configs.assert_called_once_with(+ token="oauth-token",+ team_id=1,+ user_id=None,+ include_personal=False,+ interaction_origin=None,+ allowed_installation_ids=None,+ origin_product="support_reply",+ task_agent_key="support",+ )sandbox.start_agent_server.assert_called_once()assert sandbox.start_agent_server.call_args.kwargs["event_ingest_token"] == "event-ingest-token"@@ -194,7 +217,13 @@ async def test_start_agent_server_forwards_imported_and_relayed_mcp_servers(mockmocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.emit_agent_log")mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.Task.objects.select_related"- ).return_value.get.return_value = mocker.Mock(created_by_id=None)+ ).return_value.get.return_value = mocker.Mock(+ created_by_id=None,+ team_id=1,+ internal=False,+ origin_product="user_created",+ mcp_builtin_agent_key=None,+ )mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.create_oauth_access_token_for_run",return_value="oauth-token",@@ -244,7 +273,13 @@ async def test_start_agent_server_passes_initial_permission_mode(mocker) -> Nonemocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.emit_agent_log")mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.Task.objects.select_related"- ).return_value.get.return_value = mocker.Mock(created_by_id=None)+ ).return_value.get.return_value = mocker.Mock(+ created_by_id=None,+ team_id=1,+ internal=False,+ origin_product="user_created",+ mcp_builtin_agent_key=None,+ )mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.create_oauth_access_token_for_run",return_value="oauth-token",diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.pyindex 09b2e8451144..3c6d282dd89e 100644--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py@@ -51,6 +51,10 @@ def _make_mcp_config(name: str = "posthog", token: str = "tok") -> McpServerConfdef _make_task_run_mock(team_id: int = 7, created_by_id: int | None = 42, state: dict | None = None) -> MagicMock:task = MagicMock()task.created_by_id = created_by_id+ task.team_id = team_id+ task.internal = False+ task.origin_product = "user_created"+ task.mcp_builtin_agent_key = Noneif created_by_id is not None:task.created_by = MagicMock(id=created_by_id, distinct_id=f"user-{created_by_id}")else:@@ -88,10 +92,15 @@ def _arm_success(mock_oauth, mock_ph_configs, mock_user_configs, mock_send_refre"products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.create_oauth_access_token_for_run")class TestRefreshSandboxMcp:- def test_success_path_single_call(self, mock_oauth, mock_ph_configs, mock_user_configs, mock_send_refresh, _sleep):+ def test_success_path_uses_persisted_task_agent_marker(+ self, mock_oauth, mock_ph_configs, mock_user_configs, mock_send_refresh, _sleep+ ):_arm_success(mock_oauth, mock_ph_configs, mock_user_configs, mock_send_refresh)- task_run = _make_task_run_mock()+ task_run = _make_task_run_mock(state={"mcp_builtin_agent_key": "scout"})+ task_run.task.internal = True+ task_run.task.origin_product = "support_reply"+ task_run.task.mcp_builtin_agent_key = "support"_refresh(task_run, auth_token="jwt")mock_oauth.assert_called_once_with(task_run.task, task_run.state, scopes="read_only")@@ -99,7 +108,14 @@ class TestRefreshSandboxMcp:token="fresh-token", project_id=7, scopes="read_only", interaction_origin=None, task_id="task-1")mock_user_configs.assert_called_once_with(- token="fresh-token", team_id=7, user_id=42, interaction_origin=None, allowed_installation_ids=None+ token="fresh-token",+ team_id=7,+ user_id=42,+ include_personal=False,+ interaction_origin=None,+ allowed_installation_ids=None,+ origin_product="support_reply",+ task_agent_key="support",)mock_send_refresh.assert_called_once()_, kwargs = mock_send_refresh.call_args@@ -271,6 +287,22 @@ class TestSessionIdentityGate:mock_oauth.assert_not_called()mock_send_refresh.assert_not_called()+ def test_built_in_agent_same_actor_refreshes_to_pick_up_new_grants(+ self, mock_oauth, mock_ph_configs, mock_user_configs, mock_send_refresh+ ):+ _arm_success(mock_oauth, mock_ph_configs, mock_user_configs, mock_send_refresh)+ task_run = _make_task_run_mock()+ task_run.task.internal = True+ task_run.task.origin_product = "support_reply"+ task_run.task.mcp_builtin_agent_key = "support"+ mark_sandbox_mcp_session("run-1", 42)++ _refresh(task_run, actor_id=42)++ mock_oauth.assert_called_once()+ mock_user_configs.assert_called_once()+ mock_send_refresh.assert_called_once()+def test_actor_change_bypasses_freshness_window(self, mock_oauth, mock_ph_configs, mock_user_configs, mock_send_refresh):@@ -526,6 +558,10 @@ class TestSendFollowupActivityRefreshOrdering:patch("products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox._refresh_sandbox_mcp") as mock_refresh,+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox._refresh_sandbox_github",+ return_value=True,+ ),patch("products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.send_user_message") as mock_user_msg,@@ -663,6 +699,10 @@ class TestSendFollowupTurnTimeout:patch("products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox._refresh_sandbox_mcp"),+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox._refresh_sandbox_github",+ return_value=True,+ ),patch("products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.send_user_message") as mock_user_msg,diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex e2cd20517513..986cd107ee64 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -364,7 +364,13 @@ class TestFetchUserMcpServerConfigs(TestCase):configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID)- mock_facade.assert_called_once_with(self.TEAM_ID, user_id=self.USER_ID, include_personal=True)+ mock_facade.assert_called_once_with(+ self.TEAM_ID,+ user_id=self.USER_ID,+ include_personal=True,+ task_origin=None,+ task_agent_key=None,+ )assert configs == [McpServerConfig(type="http",@@ -433,6 +439,50 @@ class TestFetchUserMcpServerConfigs(TestCase):assert configs[0].headers == self._expected_user_headers(consumer=expected_consumer)+ @patch(MOCK_API_URL)+ @patch(MOCK_FACADE)+ def test_agent_shared_config_uses_agent_proxy_auth_without_internal_task_header(+ self, mock_facade, mock_api_url+ ) -> None:+ mock_api_url.return_value = self.API_BASE+ mock_facade.return_value = [+ self._make_installation(+ id="shared-id",+ name="Shared",+ proxy_path="/api/mcp_store/gateway/servers/server-id/proxy/",+ scope="shared",+ proxy_token="agent-token",+ ),+ ]++ configs = get_user_mcp_server_configs(+ self.TOKEN,+ self.TEAM_ID,+ self.USER_ID,+ origin_product="support_reply",+ task_agent_key="support",+ )++ mock_facade.assert_called_once_with(+ self.TEAM_ID,+ user_id=self.USER_ID,+ include_personal=True,+ task_origin="support_reply",+ task_agent_key="support",+ )+ assert configs == [+ McpServerConfig(+ type="http",+ name="Shared",+ url=f"{self.API_BASE}/api/mcp_store/gateway/servers/server-id/proxy/",+ headers=[+ {"name": "Authorization", "value": "Bearer agent-token"},+ {"name": "x-posthog-mcp-consumer", "value": "posthog-code"},+ ],+ ),+ ]+ assert all(header["name"] != "X-PostHog-Task-Id" for header in configs[0].headers)+@parameterized.expand([(True,), (False,)])@patch(MOCK_API_URL)@patch(MOCK_FACADE)@@ -442,7 +492,13 @@ class TestFetchUserMcpServerConfigs(TestCase):get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID, include_personal=include_personal)- mock_facade.assert_called_once_with(self.TEAM_ID, user_id=self.USER_ID, include_personal=include_personal)+ mock_facade.assert_called_once_with(+ self.TEAM_ID,+ user_id=self.USER_ID,+ include_personal=include_personal,+ task_origin=None,+ task_agent_key=None,+ )@patch(MOCK_API_URL)@patch(MOCK_FACADE)diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex cec35da56fd0..0e1b422cf13d 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -513,12 +513,19 @@ def get_user_mcp_server_configs(include_personal: bool = True,interaction_origin: str | None = None,allowed_installation_ids: list[str] | None = None,+ origin_product: str | None = None,+ task_agent_key: str | None = None,) -> list[McpServerConfig]:"""Fetch MCP Store installations for sandbox use and return configs.- Always includes shared (team-wide) installations. When- ``include_personal`` is True and a ``user_id`` is provided, the user's- personal installations are included too.+ Unmapped tasks include shared team installations. Built-in agent tasks only+ include shared installations granted to that agent and never include a+ member's personal installations. A mapped origin without its persisted+ agent marker gets no Store installations. Built-in agent handling is+ gated per team on the ``mcp-gateway`` rollout flag; teams without it+ resolve mapped origins like unmapped tasks. For unmapped tasks,+ ``include_personal`` includes the user's personal installations when a+ ``user_id`` is provided.``allowed_installation_ids`` restricts the mounted connectors to a snapshotted allowlist (aloop run's selected ``mcp_installation_ids``): ``None`` leaves the set unfiltered (current@@ -538,6 +545,8 @@ def get_user_mcp_server_configs(team_id,user_id=user_id,include_personal=include_personal,+ task_origin=origin_product,+ task_agent_key=task_agent_key,)if allowed_installation_ids is not None:allowed = {str(i) for i in allowed_installation_ids}@@ -547,15 +556,16 @@ def get_user_mcp_server_configs(configs: list[McpServerConfig] = []for installation in installations:+ headers = [+ {"name": "Authorization", "value": f"Bearer {installation.proxy_token or token}"},+ {"name": "x-posthog-mcp-consumer", "value": consumer},+ ]configs.append(McpServerConfig(type="http",name=installation.name,url=f"{api_base}{installation.proxy_path}",- headers=[- {"name": "Authorization", "value": f"Bearer {token}"},- {"name": "x-posthog-mcp-consumer", "value": consumer},- ],+ headers=headers,))diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.pyindex 52a4d13aed1f..e0dd60904f78 100644--- a/products/tasks/backend/temporal/tests/test_oauth.py+++ b/products/tasks/backend/temporal/tests/test_oauth.py@@ -1,13 +1,53 @@import pytestfrom unittest.mock import MagicMock, patch+from posthog.models import Organization, Team+from posthog.models.user import User+from products.tasks.backend.exceptions import TaskInvalidStateError-from products.tasks.backend.models import Task+from products.tasks.backend.models import MCPBuiltInAgentKey, Taskfrom products.tasks.backend.temporal.oauth import create_oauth_access_token, create_oauth_access_token_for_run+ ("origin_product", "application"),+ [+ (Task.OriginProduct.SIGNALS_SCOUT, "array"),+ (Task.OriginProduct.SUPPORT_REPLY, "array"),+ ],+)+@patch("products.tasks.backend.temporal.oauth.is_builtin_agent_enforcement_enabled", return_value=True)+@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")+def test_built_in_agent_origins_use_restricted_oauth_scope(+ mock_create: MagicMock,+ mock_enforcement: MagicMock,+ origin_product: Task.OriginProduct,+ application: str,+) -> None:+ task = MagicMock(+ id="task-id",+ created_by=MagicMock(),+ team_id=123,+ origin_product=origin_product,+ )++ assert create_oauth_access_token(task) == "token"++ mock_create.assert_called_once_with(+ task.created_by,+ 123,+ scopes="read_only",+ application=application,+ include_mcp_builtin_agent_scope=True,+ )+++@patch("products.tasks.backend.temporal.oauth.is_builtin_agent_enforcement_enabled", return_value=True)@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")-def test_posthog_ai_task_uses_posthog_ai_oauth_application(mock_create: MagicMock) -> None:+def test_posthog_ai_task_keeps_member_token_and_posthog_ai_oauth_application(+ mock_create: MagicMock,+ mock_enforcement: MagicMock,+) -> None:task = MagicMock(id="task-id",created_by=MagicMock(),@@ -25,6 +65,29 @@ def test_posthog_ai_task_uses_posthog_ai_oauth_application(mock_create: MagicMoc)+@patch("products.tasks.backend.temporal.oauth.is_builtin_agent_enforcement_enabled", return_value=False)+@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")+def test_built_in_agent_origin_keeps_member_token_until_gateway_flag_rollout(+ mock_create: MagicMock,+ mock_enforcement: MagicMock,+) -> None:+ task = MagicMock(+ id="task-id",+ created_by=MagicMock(),+ team_id=123,+ origin_product=Task.OriginProduct.SUPPORT_REPLY,+ )++ assert create_oauth_access_token(task) == "token"++ mock_create.assert_called_once_with(+ task.created_by,+ 123,+ scopes="read_only",+ application="array",+ )++@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")def test_default_task_uses_array_oauth_application(mock_create: MagicMock) -> None:task = MagicMock(@@ -56,12 +119,63 @@ def test_oauth_token_can_disable_task_creator_fallback() -> None:create_oauth_access_token(task, user=None, allow_task_creator_fallback=False)+ ("origin_product", "agent_key"),+ [+ (Task.OriginProduct.SIGNALS_SCOUT, "scout"),+ (Task.OriginProduct.SUPPORT_REPLY, "support"),+ ],+)+def test_server_created_task_persists_trusted_mcp_agent_marker(+ origin_product: Task.OriginProduct, agent_key: MCPBuiltInAgentKey+) -> None:+ organization = Organization.objects.create(name=f"agent-marker-{agent_key}")+ team = Team.objects.create(organization=organization, name="agent-marker-team")+ creator = User.objects.create(email=f"agent-marker-{agent_key}@example.com")++ task = Task.create_without_run(+ team=team,+ title="Agent task",+ description="Run the agent",+ origin_product=origin_product,+ user_id=creator.id,+ mcp_builtin_agent_key=agent_key,+ )++ assert task.state == {"mcp_builtin_agent_key": agent_key}+ assert task.mcp_builtin_agent_key == agent_key+++def test_reserved_origin_without_matching_server_marker_is_untrusted() -> None:+ organization = Organization.objects.create(name="legacy-agent-marker")+ team = Team.objects.create(organization=organization, name="legacy-agent-marker-team")+ creator = User.objects.create(email="[email protected]")+ legacy_task = Task.objects.create(+ team=team,+ created_by=creator,+ title="Legacy",+ description="Untrusted origin",+ origin_product=Task.OriginProduct.SUPPORT_REPLY,+ )++ assert legacy_task.mcp_builtin_agent_key is None++ with pytest.raises(ValueError, match="does not match task origin"):+ Task.create_without_run(+ team=team,+ title="Mismatch",+ description="Mismatched marker",+ origin_product=Task.OriginProduct.SUPPORT_REPLY,+ user_id=creator.id,+ mcp_builtin_agent_key="scout",+ )++@pytest.mark.django_db@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")def test_run_token_fails_closed_for_slack_run_with_unresolvable_actor(mock_create: MagicMock) -> None:- from posthog.models import Organization, Team- from posthog.models.user import User-organization = Organization.objects.create(name="oauth-run-org")team = Team.objects.create(organization=organization, name="oauth-run-team")creator = User.objects.create(email="[email protected]")diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 2e3d7914ee1c..9a9da890cdf1 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -25,9 +25,11 @@ from rest_framework import statusfrom rest_framework.test import APIClientfrom posthog.models import Integration, Organization, OrganizationMembership, PersonalAPIKey, Team, User+from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import hash_key_valuefrom posthog.models.user_integration import UserIntegrationfrom posthog.models.utils import generate_random_token_personal+from posthog.scopes import MCP_BUILT_IN_AGENT_SCOPEfrom posthog.storage import object_storagefrom products.slack_app.backend.models import SlackThreadTaskMapping@@ -232,6 +234,67 @@ class BaseTaskAPITest(TestCase):)+class TestBuiltInAgentTaskAccess(BaseTaskAPITest):+ def _built_in_agent_client(self) -> APIClient:+ application = OAuthApplication.objects.create(+ name="Built-in agent sandbox",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ organization=self.organization,+ user=self.user,+ )+ access_token = OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token=f"pha_task_agent_{uuid.uuid4().hex}",+ expires=django_timezone.now() + timedelta(hours=1),+ scope=f"task:read task:write {MCP_BUILT_IN_AGENT_SCOPE}",+ scoped_teams=[self.team.id],+ )+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")+ return client++ def test_can_read_and_create_tasks(self) -> None:+ self.create_task()+ client = self._built_in_agent_client()++ assert client.get("/api/projects/@current/tasks/").status_code == status.HTTP_200_OK+ response = client.post(+ "/api/projects/@current/tasks/",+ {"title": "Child task", "description": "Follow-up work"},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED+ assert Task.objects.filter(title="Child task").exists()++ def test_cannot_create_or_run_task_automations(self) -> None:+ automation = self.create_automation()+ client = self._built_in_agent_client()++ assert (+ client.post(+ "/api/projects/@current/task_automations/",+ {+ "name": "Scheduled child",+ "prompt": "Escape agent grants later",+ "repository": "posthog/posthog",+ "cron_expression": "0 9 * * *",+ "timezone": "UTC",+ },+ format="json",+ ).status_code+ == status.HTTP_403_FORBIDDEN+ )+ assert (+ client.post(f"/api/projects/@current/task_automations/{automation.id}/run/").status_code+ == status.HTTP_403_FORBIDDEN+ )+ assert not TaskAutomation.objects.filter(task__title="Scheduled child").exists()++class TestTaskCreatorScoping(BaseTaskAPITest):def _create_legacy_task(self, title: str = "Legacy") -> Task:return Task.objects.create(@@ -1338,20 +1401,38 @@ class TestTaskAPI(BaseTaskAPITest):task = Task.objects.get(id=data["id"])self.assertEqual(task.origin_product, Task.OriginProduct.HOGDESK)+ def test_create_task_with_posthog_ai_origin_product(self):+ response = self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": "New PostHog AI task",+ "description": "Created from the PostHog AI task tracker",+ "origin_product": Task.OriginProduct.POSTHOG_AI,+ "repository": "posthog/posthog",+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ task = Task.objects.get(id=response.json()["id"])+ self.assertEqual(task.origin_product, Task.OriginProduct.POSTHOG_AI)+@parameterized.expand([- ("image_builder",),- ("experiments",),- ("onboarding",),+ (Task.OriginProduct.IMAGE_BUILDER,),+ (Task.OriginProduct.EXPERIMENTS,),+ (Task.OriginProduct.SIGNALS_SCOUT,),+ (Task.OriginProduct.SUPPORT_REPLY,),+ (Task.OriginProduct.ONBOARDING,),])- def test_create_task_rejects_internal_origin(self, origin: str):+ def test_create_task_rejects_server_created_origin(self, origin_product: Task.OriginProduct):response = self.client.post("/api/projects/@current/tasks/",{"title": "New Task","description": "New Description",- "origin_product": origin,+ "origin_product": origin_product,"repository": "posthog/posthog",},format="json",diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex d8b12cd4c05c..e5eaea9e4ce2 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1505,7 +1505,7 @@ export interface TaskCreateApi {title_manually_set?: boolean/** Free-form description of the work to be done. Used as the prompt passed to the agent. */description?: string- /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).+ /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.** * `onboarding` - Onboarding* * `error_tracking` - Error Tracking@@ -1642,7 +1642,7 @@ export interface TaskWriteApi {title_manually_set?: boolean/** Free-form description of the work to be done. Used as the prompt passed to the agent. */description?: string- /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).+ /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.** * `onboarding` - Onboarding* * `error_tracking` - Error Tracking@@ -1764,7 +1764,7 @@ export interface PatchedTaskWriteApi {title_manually_set?: boolean/** Free-form description of the work to be done. Used as the prompt passed to the agent. */description?: string- /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).+ /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.** * `onboarding` - Onboarding* * `error_tracking` - Error Trackingdiff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 918eef075705..6983188247a7 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -1111,7 +1111,7 @@ export const TasksCreateBody = /* @__PURE__ */ zod).optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'),repository: zod.string()@@ -1266,7 +1266,7 @@ export const TasksUpdateBody = /* @__PURE__ */ zod).optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'),repository: zod.string()@@ -1406,7 +1406,7 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod).optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'),repository: zod.string()diff --git a/pyproject.toml b/pyproject.tomlindex 098525f7ee6d..13294cde5789 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -527,8 +527,20 @@ ignore_imports = ["products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.logic","products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.models","products.mcp_analytics.backend.presentation.serializers -> products.mcp_analytics.backend.models",+ "products.mcp_store.backend.presentation.agent_views -> products.mcp_store.backend.agents",+ "products.mcp_store.backend.presentation.agent_views -> products.mcp_store.backend.gateway",+ "products.mcp_store.backend.presentation.agent_views -> products.mcp_store.backend.models",+ "products.mcp_store.backend.presentation.agent_views -> products.mcp_store.backend.policy",+ "products.mcp_store.backend.presentation.agent_views -> products.mcp_store.backend.proxy",+ "products.mcp_store.backend.presentation.gateway_views -> products.mcp_store.backend.agents",+ "products.mcp_store.backend.presentation.gateway_views -> products.mcp_store.backend.gateway",+ "products.mcp_store.backend.presentation.gateway_views -> products.mcp_store.backend.models",+ "products.mcp_store.backend.presentation.gateway_views -> products.mcp_store.backend.policy",+ "products.mcp_store.backend.presentation.views -> products.mcp_store.backend.agents",+ "products.mcp_store.backend.presentation.views -> products.mcp_store.backend.gateway","products.mcp_store.backend.presentation.views -> products.mcp_store.backend.models","products.mcp_store.backend.presentation.views -> products.mcp_store.backend.oauth",+ "products.mcp_store.backend.presentation.views -> products.mcp_store.backend.policy","products.mcp_store.backend.presentation.views -> products.mcp_store.backend.proxy","products.mcp_store.backend.presentation.views -> products.mcp_store.backend.tasks","products.mcp_store.backend.presentation.views -> products.mcp_store.backend.tools",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 57dee3105442..215031f3075a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8044,6 +8044,14 @@ export namespace Schemas {readonly window_days: number;}+ export type AgentKeyEnum = typeof AgentKeyEnum[keyof typeof AgentKeyEnum];+++ export const AgentKeyEnum = {+ Support: 'support',+ Scout: 'scout',+ } as const;+/*** * `product_analytics` - product_analytics* * `sql` - sql@@ -9222,6 +9230,63 @@ export namespace Schemas {date: string | null;}+ /**+ * * `everyone` - Everyone+ * * `members` - Members+ * * `agents` - Agents+ */+ export type AppliesToEnum = typeof AppliesToEnum[keyof typeof AppliesToEnum];+++ export const AppliesToEnum = {+ Everyone: 'everyone',+ Members: 'members',+ Agents: 'agents',+ } as const;++ /**+ * * `members` - members+ * * `agents` - agents+ */+ export type AudienceEnum = typeof AudienceEnum[keyof typeof AudienceEnum];+++ export const AudienceEnum = {+ Members: 'members',+ Agents: 'agents',+ } as const;++ /**+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive+ */+ export type MCPPolicyPresetEnum = typeof MCPPolicyPresetEnum[keyof typeof MCPPolicyPresetEnum];+++ export const MCPPolicyPresetEnum = {+ Allow: 'allow',+ User: 'user',+ Ask: 'ask',+ Block: 'block',+ } as const;++ export interface ApplyPreset {+ /** Which audience's baseline to overwrite.+ *+ * * `members` - members+ * * `agents` - agents */+ audience: AudienceEnum;+ /** Preset to apply.+ *+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive */+ preset: MCPPolicyPresetEnum;+ }+export interface ApplyPromptSuggestionRequest {/** The edited config to apply, assembled from the recommendation's approved fields. Omit to apply the full suggested config unchanged. */config?: unknown;@@ -9389,6 +9454,26 @@ export namespace Schemas {PositionBased: 'position_based',} as const;+ export interface AuditActorServiceAccount {+ /** Service account id. */+ id: string;+ /** Agent display name. */+ name: string;+ /** Agent identity handle. */+ handle: string;+ }++ export interface AuditCounts {+ /** Every audited tool call. */+ all: number;+ /** Calls made by service accounts. */+ agents: number;+ /** Calls that were approved or are awaiting approval. */+ approvals: number;+ /** Calls the gateway blocked. */+ blocked: number;+ }+/*** * `oauth` - oauth* * `credentials` - credentials@@ -14555,6 +14640,24 @@ export namespace Schemas {PosthogCode: 'posthog_code',} as const;+ /**+ * * `ready` - ready+ * * `pending_oauth` - pending_oauth+ * * `needs_reauth` - needs_reauth+ * * `disabled` - disabled+ * * `missing_credential` - missing_credential+ */+ export type ConnectionStateEnum = typeof ConnectionStateEnum[keyof typeof ConnectionStateEnum];+++ export const ConnectionStateEnum = {+ Ready: 'ready',+ PendingOauth: 'pending_oauth',+ NeedsReauth: 'needs_reauth',+ Disabled: 'disabled',+ MissingCredential: 'missing_credential',+ } as const;+/*** Response containing a JWT token for direct sandbox connection*/@@ -21418,6 +21521,26 @@ export namespace Schemas {value: string | number;}+ /**+ * * `rule` - rule+ * * `scope` - scope+ * * `team` - team+ * * `preset` - preset+ * * `legacy` - legacy+ * * `default` - default+ */+ export type DecidedByEnum = typeof DecidedByEnum[keyof typeof DecidedByEnum];+++ export const DecidedByEnum = {+ Rule: 'rule',+ Scope: 'scope',+ Team: 'team',+ Preset: 'preset',+ Legacy: 'legacy',+ Default: 'default',+ } as const;+/*** * `bayesian` - Bayesian* * `frequentist` - Frequentist@@ -23612,6 +23735,18 @@ export namespace Schemas {charts_set: number | null;}+ /**+ * * `needs_approval` - Require approval+ * * `do_not_use` - Block+ */+ export type EffectEnum = typeof EffectEnum[keyof typeof EffectEnum];+++ export const EffectEnum = {+ NeedsApproval: 'needs_approval',+ DoNotUse: 'do_not_use',+ } as const;+export type EffectiveMembershipLevelEnum = typeof EffectiveMembershipLevelEnum[keyof typeof EffectiveMembershipLevelEnum];@@ -32786,6 +32921,174 @@ export namespace Schemas {readonly updated: number;}+ /**+ * * `active` - Active+ * * `paused` - Paused+ */+ export type MCPServiceAccountStatusEnum = typeof MCPServiceAccountStatusEnum[keyof typeof MCPServiceAccountStatusEnum];+++ export const MCPServiceAccountStatusEnum = {+ Active: 'active',+ Paused: 'paused',+ } as const;++ /**+ * One agent's access to a gateway server.+ */+ export interface GatewayAgentAccess {+ /** Service account granted access. */+ service_account_id: string;+ /** Agent display name. */+ name: string;+ /** Agent identity handle, e.g. posthog-support. */+ handle: string;+ /** active, or paused (all access off).+ *+ * * `active` - Active+ * * `paused` - Paused */+ status: MCPServiceAccountStatusEnum;+ /**+ * When the agent last made a call.+ * @nullable+ */+ last_active_at: string | null;+ /** Admin who shared this server with the agent. */+ granted_by: UserBasic | null;+ }++ export const GatewayConfigUpdateMemberDefaultPreset = {...MCPPolicyPresetEnum,...BlankEnum,} as const+ export const GatewayConfigUpdateAgentDefaultPreset = {...MCPPolicyPresetEnum,...BlankEnum,} as const+ export interface GatewayConfigUpdate {+ /** Whether non-admin members may register custom MCP servers. */+ allow_custom_servers?: boolean;+ /** Whether non-admin members may share their available MCP connections with agents and manage agent tool policies. */+ allow_member_agent_access?: boolean;+ /** Whether servers with no gateway registration — including catalog templates published later — are enabled for the team. A registered server's own toggle always wins. */+ default_servers_enabled?: boolean;+ /** Baseline preset for members.+ *+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive */+ member_default_preset?: typeof GatewayConfigUpdateMemberDefaultPreset[keyof typeof GatewayConfigUpdateMemberDefaultPreset];+ /** Baseline preset for agents.+ *+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive */+ agent_default_preset?: typeof GatewayConfigUpdateAgentDefaultPreset[keyof typeof GatewayConfigUpdateAgentDefaultPreset];+ }++ /**+ * One member's personal connection to a gateway server.+ */+ export interface GatewayConnection {+ /** Installation row backing this connection. */+ installation_id: string;+ /** The member who connected. */+ user: UserBasic;+ /**+ * When this connection last proxied a tool call. Null if never used.+ * @nullable+ */+ last_used_at: string | null;+ /** True when the OAuth round-trip has not completed yet. */+ pending_oauth: boolean;+ /** True when the stored token was invalidated and needs reauth. */+ needs_reauth: boolean;+ }++ /**+ * One team member's gateway posture (admin overview).+ */+ export interface GatewayMemberSummary {+ /** The member. */+ user: UserBasic;+ /** Whether the member is an organization admin or owner. */+ is_org_admin: boolean;+ /** Gateway servers the member has a personal connection to. */+ connected_server_ids: string[];+ /** Gateway servers an admin turned off for this member. */+ revoked_server_ids: string[];+ }++ /**+ * * `team` - Team default+ * * `member` - Member+ * * `agent` - Agent+ */+ export type ScopeTypeEnum = typeof ScopeTypeEnum[keyof typeof ScopeTypeEnum];+++ export const ScopeTypeEnum = {+ Team: 'team',+ Member: 'member',+ Agent: 'agent',+ } as const;++ export type MCPToolApprovalStateEnum = typeof MCPToolApprovalStateEnum[keyof typeof MCPToolApprovalStateEnum];+++ export const MCPToolApprovalStateEnum = {+ Approved: 'approved',+ NeedsApproval: 'needs_approval',+ DoNotUse: 'do_not_use',+ } as const;++ export interface ToolPolicyEntry {+ /**+ * Tool to set the policy for, up to 200 characters.+ * @maxLength 200+ */+ tool_name: string;+ /** State to apply for this scope.+ *+ * * `approved` - Approved+ * * `needs_approval` - Needs approval+ * * `do_not_use` - Do not use */+ policy_state: MCPToolApprovalStateEnum;+ }++ export interface GatewayPoliciesUpsert {+ /** Which scope to resolve: the team default, one member, or one agent.+ *+ * * `team` - Team default+ * * `member` - Member+ * * `agent` - Agent */+ scope_type?: ScopeTypeEnum;+ /** Member scope target. Defaults to the requesting user. */+ scope_user_id?: number;+ /** Agent scope target. Required when scope_type is agent. */+ scope_service_account_id?: string;+ /**+ * Per-tool states to upsert for the scope. At most 1,000 entries per request.+ * @maxItems 1000+ */+ policies: ToolPolicyEntry[];+ }++ /**+ * The requesting user's own connection to a gateway server.+ */+ export interface GatewayYourConnection {+ /** The caller's installation row for this server. */+ installation_id: string;+ /** Per-connection switch — false when self-disabled. */+ is_enabled: boolean;+ /** True when the OAuth round-trip has not completed yet. */+ pending_oauth: boolean;+ /** True when the stored token was invalidated and needs reauth. */+ needs_reauth: boolean;+ /**+ * When the caller last proxied a call through this connection.+ * @nullable+ */+ last_used_at: string | null;+ }+/*** * `last_n_days` - last_n_days* * `since_last_run` - since_last_run@@ -37195,11 +37498,17 @@ export namespace Schemas {client_secret?: string;install_source?: InstallSourceEnum;posthog_code_callback_url?: string;- /** 'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).+ /** 'personal' is per-user; 'shared' makes the credential available to project members. Agent access is granted separately.** * `personal` - personal* * `shared` - shared */scope?: MCPInstallationScopeEnum;+ /** Whether the server starts enabled for the whole team. Non-default values are admin-only. */+ team_enabled?: boolean;+ /** Service accounts to share the server with at install time. Available to members when team settings allow member-managed agent access. */+ agent_ids?: string[];+ /** In-app path to land back on after the OAuth round-trip. Must be a same-app relative path. */+ return_path?: string;}export interface InstallTemplate {@@ -37207,11 +37516,17 @@ export namespace Schemas {api_key?: string;install_source?: InstallSourceEnum;posthog_code_callback_url?: string;- /** 'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).+ /** 'personal' is per-user; 'shared' makes the credential available to project members. Agent access is granted separately.** * `personal` - personal* * `shared` - shared */scope?: MCPInstallationScopeEnum;+ /** Whether the server starts enabled for the whole team. Non-default values are admin-only. */+ team_enabled?: boolean;+ /** Service accounts to share the server with at install time. Available to members when team settings allow member-managed agent access. */+ agent_ids?: string[];+ /** In-app path to land back on after the OAuth round-trip. Must be a same-app relative path. */+ return_path?: string;}/**@@ -39837,6 +40152,44 @@ export namespace Schemas {readonly updated_at: string;}+ /**+ * * `auto` - Auto-approved+ * * `approved` - Approved+ * * `pending` - Awaiting approval+ * * `blocked` - Blocked+ */+ export type MCPAuditDecisionEnum = typeof MCPAuditDecisionEnum[keyof typeof MCPAuditDecisionEnum];+++ export const MCPAuditDecisionEnum = {+ Auto: 'auto',+ Approved: 'approved',+ Pending: 'pending',+ Blocked: 'blocked',+ } as const;++ export interface MCPAuditEvent {+ readonly id: string;+ readonly created_at: string;+ /** Gateway server name at call time (denormalized). */+ readonly server_name: string;+ /** Tool that was called. */+ readonly tool_name: string;+ /** How the gateway decided the call.+ *+ * * `auto` - Auto-approved+ * * `approved` - Approved+ * * `pending` - Awaiting approval+ * * `blocked` - Blocked */+ readonly decision: MCPAuditDecisionEnum;+ /** Member who made the call, if any. */+ readonly actor_user: UserBasic | null;+ /** Agent that made the call, if any. Null for member calls. */+ readonly actor_service_account: AuditActorServiceAccount | null;+ /** Denormalized actor label (email or handle) that survives deletion. */+ readonly actor_label: string;+ }+/*** * `api_key` - API Key* * `oauth` - OAuth@@ -39923,6 +40276,91 @@ export namespace Schemas {category?: MCPFeedbackCreateCategoryEnum;}+ /**+ * * `business` - Business Operations+ * * `data` - Data & Analytics+ * * `design` - Design & Content+ * * `dev` - Developer Tools & APIs+ * * `infra` - Infrastructure+ * * `productivity` - Productivity & Collaboration+ */+ export type MCPServerCategoryEnum = typeof MCPServerCategoryEnum[keyof typeof MCPServerCategoryEnum];+++ export const MCPServerCategoryEnum = {+ Business: 'business',+ Data: 'data',+ Design: 'design',+ Dev: 'dev',+ Infra: 'infra',+ Productivity: 'productivity',+ } as const;++ /**+ * A server registered in the team's gateway, with connection summary.+ */+ export interface MCPGatewayServer {+ readonly id: string;+ readonly name: string;+ readonly url: string;+ readonly description: string;+ readonly category: MCPServerCategoryEnum;+ /** Fixed authentication type for catalog templates. Null for custom servers, where members choose.+ *+ * * `api_key` - API Key+ * * `oauth` - OAuth */+ readonly template_auth_type: MCPAuthTypeEnum | null;+ readonly is_team_enabled: boolean;+ /** Deprecated brand icon key from the linked template. Empty for custom servers. */+ readonly icon_key: string;+ /** Brand domain from the linked template. Empty for custom servers. */+ readonly icon_domain: string;+ /** Documentation URL from the template. */+ readonly docs_url: string;+ /**+ * Linked catalog template.+ * @nullable+ */+ readonly template_id: string | null;+ /** Number of live tools known for this server. */+ readonly tool_count: number;+ /** Members with a connection to this server. Only project admins receive this list. */+ readonly connections: readonly GatewayConnection[];+ /** The requesting user's own connection, or null when not connected. */+ readonly your_connection: GatewayYourConnection | null;+ /** Agents this server is shared with. */+ readonly agents: readonly GatewayAgentAccess[];+ /** Ids of members whose access an admin has turned off. Only project admins receive this list. */+ readonly revoked_user_ids: readonly number[];+ /** True when an admin has turned this server off for the requesting user. */+ readonly is_revoked_for_you: boolean;+ /** Who registered the server. Null when that user was deleted. */+ readonly created_by: UserBasic | null;+ readonly created_at: string;+ readonly updated_at: string;+ }++ export interface MCPGatewayServerUpdate {+ /**+ * Display name shown across the gateway.+ * @maxLength 200+ */+ name?: string;+ /** Short description shown on server cards. */+ description?: string;+ /** Catalog category used for filter chips.+ *+ * * `business` - Business Operations+ * * `data` - Data & Analytics+ * * `design` - Design & Content+ * * `dev` - Developer Tools & APIs+ * * `infra` - Infrastructure+ * * `productivity` - Productivity & Collaboration */+ category?: MCPServerCategoryEnum;+ /** Whether the team can see and call the server. Turning it off also blocks agent access. */+ is_team_enabled?: boolean;+ }+export interface MCPIntentClusterToolEntry {/** MCP tool name that received calls for this cluster. */readonly tool: string;@@ -40116,6 +40554,37 @@ export namespace Schemas {blocked?: boolean;}+ export interface MCPOrgRule {+ readonly id: string;+ /**+ * Short rule name shown wherever the rule locks a tool.+ * @maxLength 200+ */+ name: string;+ /** Why this guardrail exists. */+ description?: string;+ /** Audience the rule constrains.+ *+ * * `everyone` - Everyone+ * * `members` - Members+ * * `agents` - Agents */+ applies_to?: AppliesToEnum;+ /** State the rule forces on matching tools.+ *+ * * `needs_approval` - Require approval+ * * `do_not_use` - Block */+ effect?: EffectEnum;+ /**+ * fnmatch pattern against tool names. Blank matches destructive tools heuristically.+ * @maxLength 400+ */+ tool_pattern?: string;+ /** Disabled rules are kept but not evaluated. */+ enabled?: boolean;+ readonly created_at: string;+ readonly updated_at: string;+ }+/*** * `personal` - Personal* * `shared` - Shared@@ -40157,27 +40626,20 @@ export namespace Schemas {readonly updated_at: string | null;}- /**- * * `approved` - Approved- * * `needs_approval` - Needs approval- * * `do_not_use` - Do not use- */- export type MCPServerInstallationToolApprovalStateEnum = typeof MCPServerInstallationToolApprovalStateEnum[keyof typeof MCPServerInstallationToolApprovalStateEnum];--- export const MCPServerInstallationToolApprovalStateEnum = {- Approved: 'approved',- NeedsApproval: 'needs_approval',- DoNotUse: 'do_not_use',- } as const;-export interface MCPServerInstallationTool {readonly id: string;readonly tool_name: string;readonly display_name: string;readonly description: string;readonly input_schema: unknown;- approval_state?: MCPServerInstallationToolApprovalStateEnum;+ /** Effective state after applying the team ceiling. */+ readonly approval_state: MCPToolApprovalStateEnum;+ /** Team-admin ceiling for this tool. Null when the team imposes no ceiling. */+ readonly team_state: MCPToolApprovalStateEnum | null;+ /** True when a rule or Blocked team ceiling leaves no editable state. */+ readonly locked: boolean;+ /** Policy layer that decided the effective state. */+ readonly decided_by: string;readonly last_seen_at: string;/** @nullable */readonly removed_at: string | null;@@ -40186,26 +40648,6 @@ export namespace Schemas {readonly updated_at: string | null;}- /**- * * `business` - Business Operations- * * `data` - Data & Analytics- * * `design` - Design & Content- * * `dev` - Developer Tools & APIs- * * `infra` - Infrastructure- * * `productivity` - Productivity & Collaboration- */- export type MCPServerTemplateCategoryEnum = typeof MCPServerTemplateCategoryEnum[keyof typeof MCPServerTemplateCategoryEnum];--- export const MCPServerTemplateCategoryEnum = {- Business: 'business',- Data: 'data',- Design: 'design',- Dev: 'dev',- Infra: 'infra',- Productivity: 'productivity',- } as const;-export interface MCPServerTemplate {readonly id: string;/** @maxLength 200 */@@ -40220,7 +40662,65 @@ export namespace Schemas {readonly icon_key: string;/** The vendor's brand domain (e.g. 'linear.app'), resolved to an icon at render time via the logo.dev proxy endpoint. Empty when no brand icon is known. */readonly icon_domain: string;- category?: MCPServerTemplateCategoryEnum;+ category?: MCPServerCategoryEnum;+ }++ /**+ * A credential-safe summary of a server configured for an agent.+ */+ export interface MCPServiceAccountServer {+ /** Gateway server granted to the agent. */+ id: string;+ /** Server display name. */+ name: string;+ /** Server description. */+ description: string;+ /** Deprecated brand icon key. Empty for custom servers. */+ icon_key: string;+ /** Brand domain. Empty for custom servers. */+ icon_domain: string;+ /** Whether the credential delegated to the agent is ready to use.+ *+ * * `ready` - ready+ * * `pending_oauth` - pending_oauth+ * * `needs_reauth` - needs_reauth+ * * `disabled` - disabled+ * * `missing_credential` - missing_credential */+ connection_state: ConnectionStateEnum;+ }++ export interface MCPServiceAccount {+ readonly id: string;+ readonly name: string;+ readonly description: string;+ /** Stable internal identity handle for this PostHog agent. */+ readonly handle: string;+ /** Stable PostHog agent identifier. */+ readonly agent_key: AgentKeyEnum;+ /** active, or paused (all MCP access off).+ *+ * * `active` - Active+ * * `paused` - Paused */+ readonly status: MCPServiceAccountStatusEnum;+ /** Gateway servers configured for this agent. */+ readonly server_ids: readonly string[];+ /** Credential-safe summaries of the gateway servers configured for this agent. */+ readonly servers: readonly MCPServiceAccountServer[];+ /**+ * When the agent last made a call through the gateway.+ * @nullable+ */+ readonly last_active_at: string | null;+ readonly created_at: string;+ readonly updated_at: string;+ }++ export interface MCPServiceAccountUpdate {+ /** active, or paused (all MCP access off).+ *+ * * `active` - Active+ * * `paused` - Paused */+ status?: MCPServiceAccountStatusEnum;}export interface MCPSession {@@ -40598,6 +41098,13 @@ export namespace Schemas {scraping_status?: ScrapingStatusEnum | BlankEnum | null;}+ export interface MemberAccessUpdate {+ /** Gateway server to toggle for the member. */+ gateway_server_id: string;+ /** False turns the server off for the member; true restores it. */+ enabled: boolean;+ }+export type MessageContextualTools = { [key: string]: unknown };/**@@ -43270,6 +43777,15 @@ export namespace Schemas {results: FolderInstructionsVersion[];}+ export interface PaginatedGatewayMemberSummaryList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: GatewayMemberSummary[];+ }+export interface PaginatedGroupUsageMetricList {count: number;/** @nullable */@@ -43544,6 +44060,33 @@ export namespace Schemas {results: MCPAnalyticsSubmission[];}+ export interface PaginatedMCPAuditEventList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: MCPAuditEvent[];+ }++ export interface PaginatedMCPGatewayServerList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: MCPGatewayServer[];+ }++ export interface PaginatedMCPOrgRuleList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: MCPOrgRule[];+ }+export interface PaginatedMCPServerInstallationList {count: number;/** @nullable */@@ -43571,6 +44114,15 @@ export namespace Schemas {results: MCPServerTemplate[];}+ export interface PaginatedMCPServiceAccountList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: MCPServiceAccount[];+ }+export interface PaginatedMCPSessionList {results: MCPSession[];/** Whether more results exist beyond this page; the client fetches the next page with a larger offset. */@@ -44492,6 +45044,59 @@ export namespace Schemas {results: Repo[];}+ /**+ * JSON Schema describing the tool's input arguments.+ */+ export type ResolvedToolPolicyInputSchema = { [key: string]: unknown };++ /**+ * One tool with its effective policy for the requested scope.+ */+ export interface ResolvedToolPolicy {+ /** Tool name as exposed by the upstream server. */+ tool_name: string;+ /** Tool description from the upstream server. */+ description: string;+ /** JSON Schema describing the tool's input arguments. */+ input_schema: ResolvedToolPolicyInputSchema;+ /** Effective state for the scope.+ *+ * * `approved` - Approved+ * * `needs_approval` - Needs approval+ * * `do_not_use` - Do not use */+ policy_state: MCPToolApprovalStateEnum;+ /** What the team-level chain (row or preset) yields, ignoring the scope. Null when the team imposes nothing.+ *+ * * `approved` - Approved+ * * `needs_approval` - Needs approval+ * * `do_not_use` - Do not use */+ team_state: MCPToolApprovalStateEnum | null;+ /** True when no state is editable for this scope (a rule match or a Blocked team ceiling). */+ locked: boolean;+ /** Which policy layer decided the state.+ *+ * * `rule` - rule+ * * `scope` - scope+ * * `team` - team+ * * `preset` - preset+ * * `legacy` - legacy+ * * `default` - default */+ decided_by: DecidedByEnum;+ /** Matching org rule name, when decided_by is rule. */+ rule_name: string;+ /** Matching org rule description, when decided_by is rule. */+ rule_description: string;+ }++ export interface PaginatedResolvedToolPolicyList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: ResolvedToolPolicy[];+ }+export interface ReviewQueueItem {readonly id: string;/** Review queue ID that currently owns this pending trace. */@@ -51602,12 +52207,72 @@ export namespace Schemas {triggers?: LoopTriggerWrite[];}+ export interface PatchedMCPGatewayServerUpdate {+ /**+ * Display name shown across the gateway.+ * @maxLength 200+ */+ name?: string;+ /** Short description shown on server cards. */+ description?: string;+ /** Catalog category used for filter chips.+ *+ * * `business` - Business Operations+ * * `data` - Data & Analytics+ * * `design` - Design & Content+ * * `dev` - Developer Tools & APIs+ * * `infra` - Infrastructure+ * * `productivity` - Productivity & Collaboration */+ category?: MCPServerCategoryEnum;+ /** Whether the team can see and call the server. Turning it off also blocks agent access. */+ is_team_enabled?: boolean;+ }++ export interface PatchedMCPOrgRule {+ readonly id?: string;+ /**+ * Short rule name shown wherever the rule locks a tool.+ * @maxLength 200+ */+ name?: string;+ /** Why this guardrail exists. */+ description?: string;+ /** Audience the rule constrains.+ *+ * * `everyone` - Everyone+ * * `members` - Members+ * * `agents` - Agents */+ applies_to?: AppliesToEnum;+ /** State the rule forces on matching tools.+ *+ * * `needs_approval` - Require approval+ * * `do_not_use` - Block */+ effect?: EffectEnum;+ /**+ * fnmatch pattern against tool names. Blank matches destructive tools heuristically.+ * @maxLength 400+ */+ tool_pattern?: string;+ /** Disabled rules are kept but not evaluated. */+ enabled?: boolean;+ readonly created_at?: string;+ readonly updated_at?: string;+ }+export interface PatchedMCPServerInstallationUpdate {display_name?: string;description?: string;is_enabled?: boolean;}+ export interface PatchedMCPServiceAccountUpdate {+ /** active, or paused (all MCP access off).+ *+ * * `active` - Active+ * * `paused` - Paused */+ status?: MCPServiceAccountStatusEnum;+ }+export interface PatchedMaterializedColumnSlot {readonly id?: string;team?: number;@@ -54720,7 +55385,7 @@ export namespace Schemas {title_manually_set?: boolean;/** Free-form description of the work to be done. Used as the prompt passed to the agent. */description?: string;- /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).+ /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.** * `onboarding` - Onboarding* * `error_tracking` - Error Tracking@@ -63022,6 +63687,18 @@ export namespace Schemas {send_async?: boolean;}+ export interface ServiceAccountAccessUpdate {+ /** Gateway server to grant or revoke. */+ gateway_server_id: string;+ /** True grants access, false revokes it. */+ enabled: boolean;+ /**+ * Optional agent-scope tool policies to set alongside the grant. At most 1,000 entries per request.+ * @maxItems 1000+ */+ policies?: ToolPolicyEntry[];+ }+export interface SessionGroupSummary {readonly id: string;/** Title of the group session summary */@@ -63125,6 +63802,18 @@ export namespace Schemas {custom_tags?: SessionSummariesConfigCustomTags;}+ export interface SetAllServersEnabled {+ /** True enables every MCP server for the team; false disables them all. Applies to every registered server and becomes the default for untouched and future catalog servers. */+ enabled: boolean;+ }++ export interface SetTemplateEnabled {+ /** Active catalog template to enable or disable for the team. */+ template_id: string;+ /** True lets the team see and call the server; false hides it from members and blocks connections. */+ enabled: boolean;+ }+/*** * `trace` - trace* * `debug` - debug@@ -69462,7 +70151,7 @@ export namespace Schemas {title_manually_set?: boolean;/** Free-form description of the work to be done. Used as the prompt passed to the agent. */description?: string;- /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).+ /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.** * `onboarding` - Onboarding* * `error_tracking` - Error Tracking@@ -70514,7 +71203,7 @@ export namespace Schemas {title_manually_set?: boolean;/** Free-form description of the work to be done. Used as the prompt passed to the agent. */description?: string;- /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).+ /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.** * `onboarding` - Onboarding* * `error_tracking` - Error Tracking@@ -70915,6 +71604,33 @@ export namespace Schemas {readonly email_sending_suspension_reason: string;}+ export const TeamMCPGatewayConfigMemberDefaultPreset = {...MCPPolicyPresetEnum,...BlankEnum,} as const+ export const TeamMCPGatewayConfigAgentDefaultPreset = {...MCPPolicyPresetEnum,...BlankEnum,} as const+ export interface TeamMCPGatewayConfig {+ /** Whether non-admin members may register custom MCP servers with the gateway. */+ allow_custom_servers?: boolean;+ /** Whether non-admin members may share their available MCP connections with agents and manage agent tool policies. */+ allow_member_agent_access?: boolean;+ /** Whether servers with no gateway registration — including catalog templates published later — are enabled for the team. A registered server's own toggle always wins. */+ default_servers_enabled?: boolean;+ /** Baseline preset for members. Empty until an admin applies one from Team settings.+ *+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive */+ member_default_preset?: typeof TeamMCPGatewayConfigMemberDefaultPreset[keyof typeof TeamMCPGatewayConfigMemberDefaultPreset];+ /** Baseline preset deriving default policies for tools an agent has no explicit row for.+ *+ * * `allow` - Allow all+ * * `user` - Member decides+ * * `ask` - Ask for destructive+ * * `block` - Block destructive */+ agent_default_preset?: typeof TeamMCPGatewayConfigAgentDefaultPreset[keyof typeof TeamMCPGatewayConfigAgentDefaultPreset];+ /** Whether the requesting user can administer the gateway (org admin or explicit project admin). */+ readonly is_admin: boolean;+ }+export interface TeamMergeTrendPoint {/** Start of the day bucket (team timezone), keyed on merged_at. */day: string;@@ -80482,6 +81198,114 @@ export namespace Schemas {offset?: number;};+ export type McpGatewayAuditListParams = {+ /**+ * Only calls made by this service account.+ */+ actor_service_account_id?: string;+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * all, agents (agent calls only), approvals (approved or pending), or blocked.+ *+ * * `all` - all+ * * `agents` - agents+ * * `approvals` - approvals+ * * `blocked` - blocked+ * @minLength 1+ */+ quick_filter?: McpGatewayAuditListQuickFilter;+ };++ export type McpGatewayAuditListQuickFilter = typeof McpGatewayAuditListQuickFilter[keyof typeof McpGatewayAuditListQuickFilter];+++ export const McpGatewayAuditListQuickFilter = {+ All: 'all',+ Agents: 'agents',+ Approvals: 'approvals',+ Blocked: 'blocked',+ } as const;++ export type McpGatewayMembersListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };++ export type McpGatewayRulesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };++ export type McpGatewayServersListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };++ export type McpGatewayServersToolsRetrieveParams = {+ /**+ * Agent scope target. Required when scope_type is agent.+ */+ scope_service_account_id?: string;+ /**+ * Which scope to resolve: the team default, one member, or one agent.+ *+ * * `team` - Team default+ * * `member` - Member+ * * `agent` - Agent+ * @minLength 1+ */+ scope_type?: McpGatewayServersToolsRetrieveScopeType;+ /**+ * Member scope target. Defaults to the requesting user.+ */+ scope_user_id?: number;+ };++ export type McpGatewayServersToolsRetrieveScopeType = typeof McpGatewayServersToolsRetrieveScopeType[keyof typeof McpGatewayServersToolsRetrieveScopeType];+++ export const McpGatewayServersToolsRetrieveScopeType = {+ Team: 'team',+ Member: 'member',+ Agent: 'agent',+ } as const;++ export type McpGatewayServiceAccountsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type McpServerInstallationsListParams = {/*** Number of results to return per page.@@ -80502,6 +81326,10 @@ export namespace Schemas {install_source?: McpServerInstallationsAuthorizeRetrieveInstallSource;installation_id?: string;posthog_code_callback_url?: string;+ /**+ * In-app path to land back on after the OAuth round-trip. Must be a same-app relative path.+ */+ return_path?: string;template_id?: string;};diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex 91714eab68d4..8342310f1ef2 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -865,7 +865,7 @@ export const TasksCreateBody = /* @__PURE__ */ zod).optional().describe(- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics'),repository: zod.string()