: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(workflows): pick project-shared MCP servers for create AI task (#91128)
Chris Volzer9111c783c178
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e5777e99df0a..761e07aca8c8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8832,6 +8832,22 @@ snapshots:hash: v1.k794b7964.ff693d29af19c34091c70dc0e5a22853d7f35b01ab3459f6a2bf1f2b06c57536.rM7sS7EbyqrDzgeTX1Nz6Xu63xYhT9KbpNi97rJzsmQscenes-app-web-analytics-search-ai--web-analytics-page-performance-no-ai-traffic--light:hash: v1.k794b7964.d28c10ae27c8ddbee128184c1555e0aa6aefc81ac5c6702a0721d84ca9811c46.TEn8Vcq05e1uAqQ_zoQfOvYYsE9BXU9Y0ev2W5QDSro+ scenes-app-workflows-createaitaskconnectors--no-approved-tools--dark:+ hash: v1.k794b7964.21192b03ef6f65ad46bd4fc88738669fc7b2902dcbce0db252a3d2417e10172b.lhKBZM-VPET3_AhQCAUubBUu7qAu8KlducA4WUsWhOM+ scenes-app-workflows-createaitaskconnectors--no-approved-tools--light:+ hash: v1.k794b7964.2ef38eef9a97fb5ebbccabd3b5c59937764018d0ecd0e6df726e01ff5753aa3f.Ap99-f_UIEZKxQDSIsEolrwP6NhT2-HIADTCxlkWg0s+ scenes-app-workflows-createaitaskconnectors--nothing-shared--dark:+ hash: v1.k794b7964.9cbd9161b111fecc7cad261dc5e6bbfd75deb20aa0d69b02c05a246e44ec7a6c.UjT_5YebPW2Usg9EXubOkfYJZMsisn_2m7Ebu36ygBY+ scenes-app-workflows-createaitaskconnectors--nothing-shared--light:+ hash: v1.k794b7964.1b105f553939e561a63627942374e304c8d8165dfdd77226a8d33e6655d4bbfd.sILC4AECIAyck_DFRywHO7amvHPmfy6izVVm-43_bk0+ scenes-app-workflows-createaitaskconnectors--selection--dark:+ hash: v1.k794b7964.6ee90a22653447fb963d63e2c37233bbf3ca3961ea5faf655a3b328882176b20.tV3oQdDrueTETZNukoaJYgnhWJ0KscPE3rpOv2P2u04+ scenes-app-workflows-createaitaskconnectors--selection--light:+ hash: v1.k794b7964.e481b329bdc159e079ddaabbcf802803de42f13b0c9edcb755e6825f15d03cc6.Cuyo_HzL7Sn0_nudhmwplp7jGiUnBiqwDCkK1-_nQbc+ scenes-app-workflows-createaitaskconnectors--unavailable-connector--dark:+ hash: v1.k794b7964.074d7d64c384134bfd4c223d57cd339854d39bc4283b7d9b239d4c83d78e30fb._jPmYLjyiEistYmpwqii497iwY6LHQ1WQ4nzk9aMTDs+ scenes-app-workflows-createaitaskconnectors--unavailable-connector--light:+ hash: v1.k794b7964.c4fdab3ab5190ace67d354d7010b49cbd37e9ec72feaa3fab9760d1f1010c8b0.S5qBDGrQNUo7qygcV1_MG_nu9RWeaMnoOFrYdhnV97Escenes-inbox-scout-tags--editor-and-filter--dark:hash: v1.k794b7964.b76b173ee1dc78112e700af267b53d59959164f8ebbc814df2b5f4a3811bcd49.2hfIhAW_k3BdFlo9jtUoJhOyZhS1uQmgafcdvh_CGmgscenes-inbox-scout-tags--editor-and-filter--light:diff --git a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.tsindex badcccaa3fc7..8e16de20a1a6 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts@@ -115,7 +115,7 @@ return response.bodysecret: false,required: false,description:- 'Connectors from the MCP store the agent can use. Team-shared connections and the workflow creator’s own connections are available.',+ 'MCP servers the agent can use. Only servers shared with everyone in this project can be selected.',},{key: 'posthog_mcp_scopes',diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 334762069b66..ca99c1026517 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4588,6 +4588,9 @@ importers:'@posthog/icons':specifier: 'catalog:'+ '@posthog/products-mcp-store':+ specifier: workspace:*+ version: link:../mcp_store'@storybook/react':specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])@@ -4609,6 +4612,9 @@ importers:kea-router:specifier: 'catalog:'version: 3.4.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ kea-subscriptions:+ specifier: 'catalog:'+ version: 3.0.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))react:specifier: 18.3.1version: 18.3.1diff --git a/products/mcp_store/README.md b/products/mcp_store/README.mdindex e986826db074..0721e89b079c 100644--- a/products/mcp_store/README.md+++ b/products/mcp_store/README.md@@ -37,6 +37,8 @@ The gateway experience has these pages and workflows:Users with permission can add a hosted custom server and choose OAuth or API key authentication.Admins can set its team availability.Every connection is shared with the built-in PostHog agents automatically when the connecting user may manage agent access (admins always, members while team settings allow it).+ The built-in agents are the support agent, the scout agent, and the workflow agent, which runs the "Create AI task" step of a workflow; a step picks among the servers shared with the whole project, the same way a scout does.+ An agent added to the catalog later inherits the grants its siblings already hold on the team the first time it is synced.The add-server form picks how far that share reaches: only the user's own runs (the default), or every agent run in the project.Connecting a catalog server shares it for the user's own runs; the server page widens it to the team or revokes it.Connecting starts the appropriate authorization flow, while an existing connection opens its configuration.diff --git a/products/mcp_store/backend/agents.py b/products/mcp_store/backend/agents.pyindex 42420efa75ca..1dced91d4552 100644--- a/products/mcp_store/backend/agents.py+++ b/products/mcp_store/backend/agents.py@@ -1,5 +1,6 @@from __future__ import annotations+import uuidfrom dataclasses import dataclassfrom typing import Literal@@ -15,11 +16,11 @@ from posthog.models.scoping.manager import TeamScopeErrorfrom posthog.models.utils import hash_key_valuefrom posthog.user_permissions import UserPermissions-from .models import MCPServiceAccount+from .models import MCPServiceAccount, MCPServiceAccountServerAccesslogger = structlog.get_logger(__name__)-BuiltInAgentKey = Literal["support", "scout"]+BuiltInAgentKey = Literal["support", "scout", "workflow"]GATEWAY_AGENT_TOKEN_PREFIX = "mcp_gw_"GATEWAY_AGENT_TOKEN_SALT = "mcp_store.gateway_agent"@@ -47,6 +48,12 @@ BUILT_IN_AGENTS: tuple[BuiltInAgentSpec, ...] = (description="Proactively investigates your product and reports useful findings.",handle="posthog-scout",),+ BuiltInAgentSpec(+ key="workflow",+ name="Workflow agent",+ description="Runs the AI tasks that workflows start.",+ handle="posthog-workflow",+ ),)_SPEC_BY_KEY = {spec.key: spec for spec in BUILT_IN_AGENTS}@@ -58,6 +65,7 @@ _TASK_ORIGIN_TO_AGENT: dict[str, BuiltInAgentKey] = {# The headless suggestion scan runs as the Scout agent with an empty server allowlist, so it# mounts nothing from the Store rather than the team's shared connectors."scout_suggestions": "scout",+ "workflow": "workflow",}# Signal report tasks may be created through the public Tasks API, so they# remain member-scoped instead of inheriting Scout's MCP grants.@@ -113,6 +121,7 @@ def get_built_in_agent_spec(account: MCPServiceAccount) -> BuiltInAgentSpec | Nodef sync_built_in_agents(team: Team) -> list[MCPServiceAccount]:accounts: list[MCPServiceAccount] = []changed: list[MCPServiceAccount] = []+ created_accounts: list[MCPServiceAccount] = []for spec in BUILT_IN_AGENTS:token_hash = hash_key_value(f"built-in-mcp-agent:{team.id}:{spec.key}")@@ -126,7 +135,9 @@ def sync_built_in_agents(team: Team) -> list[MCPServiceAccount]:"status": "active",},)- if not created:+ if created:+ created_accounts.append(account)+ else:account_changed = Falseif account.handle != spec.handle:account.handle = spec.handle@@ -148,9 +159,59 @@ def sync_built_in_agents(team: Team) -> list[MCPServiceAccount]:["name", "description", "handle", "updated_at"],)+ existing_accounts = [account for account in accounts if account not in created_accounts]+ for account in created_accounts:+ _seed_grants_from_existing_agents(team.id, account, existing_accounts)+return accounts+def _seed_grants_from_existing_agents(+ team_id: int, account: MCPServiceAccount, existing_accounts: list[MCPServiceAccount]+) -> None:+ """Give a built-in agent that is new to this team the grants its siblings already hold.++ Installing a connection grants every built-in agent at once, so an agent added to the+ catalog later would otherwise start with nothing on teams that connected servers before+ it existed, and every member would have to share their connections again. Copying the+ sibling grants puts the new agent where it would be had it existed at install time. One+ grant per (server, member): a team share on any sibling wins over a personal one, because+ that member already chose to lend the connection to every agent run in the project.+ """+ if not existing_accounts:+ return+ sibling_grants = (+ MCPServiceAccountServerAccess.objects.for_team(team_id)+ .filter(service_account__in=existing_accounts, user__isnull=False)+ .order_by("created_at", "id")+ )+ seeds: dict[tuple[uuid.UUID, int], MCPServiceAccountServerAccess] = {}+ for grant in sibling_grants:+ if grant.user_id is None:+ continue+ key = (grant.gateway_server_id, grant.user_id)+ current = seeds.get(key)+ if current is None or (current.scope != "team" and grant.scope == "team"):+ seeds[key] = grant+ if not seeds:+ return+ MCPServiceAccountServerAccess.objects.for_team(team_id).bulk_create(+ [+ MCPServiceAccountServerAccess(+ team_id=team_id,+ service_account=account,+ gateway_server_id=grant.gateway_server_id,+ user_id=grant.user_id,+ scope=grant.scope,+ installation_id=grant.installation_id,+ granted_by_id=grant.granted_by_id,+ )+ for grant in seeds.values()+ ],+ ignore_conflicts=True,+ )++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:diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.pyindex 9d96e1948fe3..152ca8f1fb08 100644--- a/products/mcp_store/backend/facade/api.py+++ b/products/mcp_store/backend/facade/api.py@@ -295,6 +295,7 @@ def get_installations_for_sandbox(task_origin: str | None = None,task_agent_key: str | None = None,credential_owner_id: int | None = None,+ allowed_installation_ids: list[str] | None = None,allowed_gateway_server_ids: list[str] | None = None,) -> list[ActiveInstallation]:"""Return MCP installations for sandbox agent use.@@ -319,10 +320,16 @@ def get_installations_for_sandbox(URL as a shared one, only the personal one is returned — the user acts asthemselves rather than through the shared credential.+ ``allowed_installation_ids`` narrows the member mounts to the listed+ installations (a loop run's snapshotted selection): None leaves them+ unfiltered, an empty list mounts nothing. It only applies on the member+ path, so a run whose snapshot carries no installation ids mounts nothing+ there while its gateway selection still applies.``allowed_gateway_server_ids`` narrows the mounts to the listed gateway- servers regardless of grant scope (a scout's per-scout selection); see- ``_mounts_for_agent_run``. It binds on both paths: passing ``[]`` mounts no- MCP Store servers at all, and passing ``None`` leaves the mounts unnarrowed.+ servers regardless of grant scope (a scout's per-scout selection, or a+ workflow step's connector selection); see ``_mounts_for_agent_run``. It+ binds on both paths: passing ``[]`` mounts no MCP Store servers at all, and+ passing ``None`` leaves the mounts unnarrowed."""try:base_queryset = MCPServerInstallation.objects.filter(team_id=team_id, is_enabled=True).select_related(@@ -404,6 +411,9 @@ def get_installations_for_sandbox(for installation in readyif installation.scope == "personal" or installation.url not in personal_urls]+ if allowed_installation_ids is not None:+ allowed_installations = {str(installation_id) for installation_id in allowed_installation_ids}+ ready = [installation for installation in ready if str(installation.id) in allowed_installations]results = [_to_info(installation, team_id) for installation in ready]logger.debug(@@ -425,6 +435,7 @@ def get_sandbox_mcp_server_names(task_origin: str | None = None,task_agent_key: str | None = None,credential_owner_id: int | None = None,+ allowed_installation_ids: list[str] | None = None,allowed_gateway_server_ids: list[str] | None = None,) -> list[str]:"""The names of the servers ``get_installations_for_sandbox`` would mount, in mount order.@@ -443,6 +454,57 @@ def get_sandbox_mcp_server_names(task_origin=task_origin,task_agent_key=task_agent_key,credential_owner_id=credential_owner_id,+ allowed_installation_ids=allowed_installation_ids,allowed_gateway_server_ids=allowed_gateway_server_ids,)]+++def resolve_agent_gateway_server_ids(+ team_id: int,+ *,+ agent_key: str,+ credential_owner_id: int | None,+ connector_ids: Iterable[str],+) -> dict[str, str | None]:+ """Map saved connector ids to the gateway servers a built-in agent run may mount.++ An id resolves when it names a gateway server the agent reaches (a grant of the run's+ credential owner, or any member's team share) that is enabled for the team. Health is+ not checked: a connection that needs reauthorization still resolves and drops out at+ mount time, like it does for any agent run. An id that names a Store installation on+ such a server resolves to that server, so a selection saved when connectors were keyed+ by installation keeps working. Every other id maps to None.+ """+ requested = [str(connector_id) for connector_id in connector_ids]+ if not requested:+ return {}+ account = get_built_in_agent(team_id, agent_key)+ if account is None:+ return dict.fromkeys(requested)+ reachable_server_ids = set(+ MCPServiceAccountServerAccess.objects.for_team(team_id)+ .filter(service_account=account, gateway_server__is_team_enabled=True)+ .filter(reachable_agent_grants(team_id, credential_owner_id))+ .values_list("gateway_server_id", flat=True)+ )+ reachable = {str(server_id) for server_id in reachable_server_ids}+ resolved: dict[str, str | None] = {+ connector_id: connector_id if connector_id in reachable else None for connector_id in requested+ }+ legacy_ids: dict[uuid.UUID, str] = {}+ for connector_id, server_id in resolved.items():+ if server_id is not None:+ continue+ try:+ legacy_ids[uuid.UUID(connector_id)] = connector_id+ except ValueError:+ continue+ if not legacy_ids:+ return resolved+ installations = MCPServerInstallation.objects.filter(+ team_id=team_id, id__in=legacy_ids, gateway_server_id__in=reachable_server_ids+ ).values_list("id", "gateway_server_id")+ for installation_id, server_id in installations:+ resolved[legacy_ids[installation_id]] = str(server_id)+ return resolveddiff --git a/products/mcp_store/backend/presentation/gateway_views.py b/products/mcp_store/backend/presentation/gateway_views.pyindex 0a67173b0da4..8370bd16b7f7 100644--- a/products/mcp_store/backend/presentation/gateway_views.py+++ b/products/mcp_store/backend/presentation/gateway_views.py@@ -11,7 +11,18 @@ from functools import cached_propertyfrom typing import Any, castfrom django.db import transaction-from django.db.models import Case, Count, IntegerField, Prefetch, Q, QuerySet, When, prefetch_related_objects+from django.db.models import (+ Case,+ Count,+ Exists,+ IntegerField,+ OuterRef,+ Prefetch,+ Q,+ QuerySet,+ When,+ prefetch_related_objects,+)from django.utils import timezoneimport structlog@@ -33,7 +44,7 @@ from posthog.models import Userfrom posthog.models.organization import OrganizationMembershipfrom posthog.permissions import DenyMCPBuiltInAgentOAuth-from ..agents import built_in_agent_handles, get_built_in_agent_spec, sync_built_in_agents+from ..agents import BUILT_IN_AGENTS, built_in_agent_handles, get_built_in_agent_spec, sync_built_in_agentsfrom ..gateway import installation_for_agent_access, installation_for_agent_grant, members_can_manage_agent_accessfrom ..models import (AGENT_GRANT_SCOPE_CHOICES,@@ -596,12 +607,22 @@ class MCPServiceAccountServerSerializer(serializers.Serializer):)name = serializers.CharField(help_text="Server display name.")description = serializers.CharField(help_text="Server description.")+ url = serializers.CharField(+ help_text="MCP server URL. Clients derive a brand icon from it when icon_domain is empty."+ )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.",)+ reachable = serializers.BooleanField(+ help_text=(+ "Whether agent runs can use this grant: the server is enabled for the project and an admin "+ "has not revoked the sharing member's access. Independent of connection_state, which reports "+ "credential health."+ )+ )class MCPServiceAccountSerializer(serializers.ModelSerializer):@@ -643,7 +664,7 @@ class MCPServiceAccountSerializer(serializers.ModelSerializer):"last_active_at": {"help_text": "When the agent last made a call through the gateway."},}- @extend_schema_field(serializers.ChoiceField(choices=["support", "scout"]))+ @extend_schema_field(serializers.ChoiceField(choices=[spec.key for spec in BUILT_IN_AGENTS]))def get_agent_key(self, obj: MCPServiceAccount) -> str:spec = get_built_in_agent_spec(obj)return spec.key if spec is not None else ""@@ -675,9 +696,13 @@ class MCPServiceAccountSerializer(serializers.ModelSerializer):"scope": access.scope,"name": server.name,"description": server.description,+ "url": server.url,"icon_key": server.template.icon_key if server.template else "","icon_domain": server.template.icon_domain if server.template else "","connection_state": connection_state,+ # Mirrors the run-path predicate (reachable_agent_grants plus the+ # is_team_enabled filter), so pickers can hide grants a run cannot mount.+ "reachable": server.is_team_enabled and not getattr(access, "grant_owner_revoked", False),})return servers@@ -1227,6 +1252,12 @@ class MCPServiceAccountViewSet(return sync_built_in_agents(self.team)def _server_access_prefetch(self) -> Prefetch:+ # An admin revocation makes the grant unreachable for agent runs, the+ # same way reachable_agent_grants excludes it on the mount path.+ grant_owner_revoked = MCPMemberServerRevocation.objects.for_team(self.team_id).filter(+ gateway_server_id=OuterRef("gateway_server_id"),+ user_id=OuterRef("user_id"),+ )return Prefetch("server_access",# See MCPGatewayServerViewSet.safely_get_queryset: a user-less grant@@ -1234,6 +1265,7 @@ class MCPServiceAccountViewSet(# MCPServiceAccountServerSerializer.shared_by is not nullable.queryset=MCPServiceAccountServerAccess.objects.for_team(self.team_id).exclude(user__isnull=True)+ .annotate(grant_owner_revoked=Exists(grant_owner_revoked)).select_related("gateway_server__template", "installation", "user").order_by("gateway_server__name"),)diff --git a/products/mcp_store/backend/test/test_agents.py b/products/mcp_store/backend/test/test_agents.pynew file mode 100644index 000000000000..c8ed33bd7273--- /dev/null+++ b/products/mcp_store/backend/test/test_agents.py@@ -0,0 +1,81 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from posthog.models import User++from products.mcp_store.backend.agents import BUILT_IN_AGENTS, sync_built_in_agents+from products.mcp_store.backend.models import (+ MCPGatewayServer,+ MCPServerInstallation,+ MCPServiceAccount,+ MCPServiceAccountServerAccess,+)+++class TestSyncBuiltInAgents(BaseTest):+ def _server(self, name: str) -> MCPGatewayServer:+ return MCPGatewayServer.objects.for_team(self.team.id).create(+ team_id=self.team.id, name=name, url=f"https://{name.lower()}.example.com/mcp", is_team_enabled=True+ )++ def _installation(self, server: MCPGatewayServer, user: User) -> MCPServerInstallation:+ return MCPServerInstallation.objects.create(+ team=self.team,+ user=user,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ is_enabled=True,+ scope="personal",+ gateway_server=server,+ )++ def _grant(+ self,+ account: MCPServiceAccount,+ server: MCPGatewayServer,+ *,+ user: User | None,+ installation: MCPServerInstallation | None,+ scope: str = "personal",+ ) -> None:+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ service_account=account,+ gateway_server=server,+ user=user,+ installation=installation,+ granted_by=user,+ scope=scope,+ )++ def test_an_agent_added_to_the_catalog_inherits_the_grants_its_siblings_hold(self) -> None:+ # The team connected servers while only the first two agents existed.+ with patch("products.mcp_store.backend.agents.BUILT_IN_AGENTS", BUILT_IN_AGENTS[:2]):+ support, scout = sync_built_in_agents(self.team)+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ team_server = self._server("Team")+ own_server = self._server("Own")+ legacy_server = self._server("Legacy")+ team_shared = self._installation(team_server, teammate)+ own = self._installation(own_server, self.user)+ # The same member shared one server personally with one agent and team-wide with another.+ self._grant(support, team_server, user=teammate, installation=team_shared)+ self._grant(scout, team_server, user=teammate, installation=team_shared, scope="team")+ self._grant(scout, own_server, user=self.user, installation=own)+ # A user-less row from a previous release resolves for nobody, so it is not copied.+ self._grant(support, legacy_server, user=None, installation=None)++ accounts = sync_built_in_agents(self.team)+ sync_built_in_agents(self.team)++ workflow = accounts[2]+ assert workflow.handle == "posthog-workflow"+ rows = MCPServiceAccountServerAccess.objects.for_team(self.team.id).filter(service_account=workflow)+ assert set(rows.values_list("gateway_server_id", "user_id", "scope", "installation_id")) == {+ (team_server.id, teammate.id, "team", team_shared.id),+ (own_server.id, self.user.id, "personal", own.id),+ }+ # Existing agents keep their own grants; a second sync neither duplicates nor resets.+ assert rows.count() == 2+ assert MCPServiceAccountServerAccess.objects.for_team(self.team.id).filter(service_account=support).count() == 2diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.pyindex d4980cff8314..f01dc193d3e1 100644--- a/products/mcp_store/backend/test/test_api.py+++ b/products/mcp_store/backend/test/test_api.py@@ -1207,10 +1207,10 @@ class TestMCPServiceAccountAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKresults = 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 [agent["agent_key"] for agent in results] == ["support", "scout", "workflow"]+ assert [agent["handle"] for agent in results] == ["posthog-support", "posthog-scout", "posthog-workflow"]assert all(agent["status"] == "active" for agent in results)- assert MCPServiceAccount.objects.for_team(self.team.id).count() == 2+ assert MCPServiceAccount.objects.for_team(self.team.id).count() == 3def test_list_reconciles_legacy_built_in_agent_handles(self) -> None:self._make_admin()@@ -1227,7 +1227,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):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+ assert MCPServiceAccount.objects.for_team(self.team.id).count() == 3def test_agents_cannot_be_created_or_deleted(self) -> None:self._make_admin()@@ -1424,10 +1424,12 @@ class TestMCPServiceAccountAPI(APIBaseTest):"id": str(server.id),"name": "Personal Notion","description": "",+ "url": "https://mcp.personal-notion.example.com/mcp","icon_key": "","icon_domain": "","connection_state": "ready","scope": "personal",+ "reachable": True,}]@@ -1867,10 +1869,12 @@ class TestMCPServiceAccountAPI(APIBaseTest):"id": str(server.id),"name": "Notion","description": "Notion workspace",+ "url": "https://mcp.notion-agent-summary.example.com/mcp","icon_key": "notion","icon_domain": "notion.so","connection_state": "missing_credential","scope": "personal",+ "reachable": True,}]@@ -2263,10 +2267,12 @@ class TestMCPServiceAccountAPI(APIBaseTest):"id": str(granted_server.id),"name": "Agent only","description": "",+ "url": "https://mcp.agent-only.example.com/mcp","icon_key": "","icon_domain": "","connection_state": "ready","scope": "personal",+ "reachable": False,}]@@ -2298,6 +2304,37 @@ class TestMCPServiceAccountAPI(APIBaseTest):assert revoked_catalog_response.status_code == status.HTTP_200_OKassert revoked_catalog_response.json()["results"] == []+ def test_revoked_grant_owner_serializes_reachable_false_for_their_grant_only(self) -> None:+ account = self._active_scout_account()+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Team Notion",+ url="https://mcp.revoked-grant-owner.example.com/mcp",+ )+ revoked_member = self._create_user("[email protected]")+ for grant_user in (self.user, revoked_member):+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ user=grant_user,+ service_account=account,+ gateway_server=server,+ scope="team",+ granted_by=grant_user,+ )+ MCPMemberServerRevocation.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ user=revoked_member,+ revoked_by=self.user,+ )++ 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")+ reachable_by_owner = {row["shared_by"]["id"]: row["reachable"] for row in scout["servers"]}+ assert reachable_by_owner == {self.user.id: True, revoked_member.id: False}+def test_agent_catalog_query_count_does_not_grow_with_accessible_servers(self) -> None:account = self._active_scout_account()client = self._agent_client(account)diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.pyindex c7194a7290df..8ba09b1db38f 100644--- a/products/mcp_store/backend/test/test_facade.py+++ b/products/mcp_store/backend/test/test_facade.py@@ -15,6 +15,7 @@ from products.mcp_store.backend.facade.api import (get_active_installations,get_installations_for_sandbox,get_sandbox_mcp_server_names,+ resolve_agent_gateway_server_ids,)from products.mcp_store.backend.facade.contracts import ActiveInstallationfrom products.mcp_store.backend.models import (@@ -581,6 +582,68 @@ class TestGetInstallationsForSandbox(BaseTest):assert resolve([]) == set()assert resolve(None) == {str(picked.id), str(dropped.id)}+ def test_installation_allowlist_narrows_the_member_path_only(self) -> None:+ kept = self._create_installation(scope="shared", display_name="Kept", url="https://kept.example.com/mcp")+ self._create_installation(scope="shared", display_name="Dropped", url="https://dropped.example.com/mcp")+ account = self._support_agent()+ server = self._create_gateway_server(name="Team", url="https://team.example.com/mcp")+ team_shared = self._create_installation(gateway_server=server, url=server.url)+ self._grant(account, server, user=self.user, installation=team_shared, scope="team")++ member = get_installations_for_sandbox(self.team.id, allowed_installation_ids=[str(kept.id)])+ member_empty = get_installations_for_sandbox(self.team.id, allowed_installation_ids=[])+ # A workflow run's snapshot carries no installation ids, so the agent path must not be+ # emptied by the closed member allowlist that comes with it.+ agent = get_installations_for_sandbox(+ self.team.id, task_origin="support_reply", task_agent_key="support", allowed_installation_ids=[]+ )++ assert [result.id for result in member] == [str(kept.id)]+ assert member_empty == []+ assert [result.id for result in agent] == [str(team_shared.id)]++ def test_resolves_saved_connectors_to_the_servers_an_agent_run_reaches(self) -> None:+ account = get_built_in_agent(self.team.id, "workflow")+ assert account is not None+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ team_server = self._create_gateway_server(name="Team", url="https://team.example.com/mcp")+ personal_server = self._create_gateway_server(name="Personal", url="https://personal.example.com/mcp")+ disabled_server = self._create_gateway_server(+ name="Disabled", url="https://disabled.example.com/mcp", is_team_enabled=False+ )+ unshared_server = self._create_gateway_server(name="Unshared", url="https://unshared.example.com/mcp")+ team_shared = self._create_installation(user=teammate, gateway_server=team_server, url=team_server.url)+ personal = self._create_installation(gateway_server=personal_server, url=personal_server.url)+ disabled = self._create_installation(user=teammate, gateway_server=disabled_server, url=disabled_server.url)+ self._grant(account, team_server, user=teammate, installation=team_shared, scope="team")+ self._grant(account, personal_server, user=self.user, installation=personal)+ self._grant(account, disabled_server, user=teammate, installation=disabled, scope="team")+ connector_ids = [+ str(team_server.id),+ # A selection saved before connectors were keyed by gateway server names the+ # installation; it still resolves to the server that installation sits on.+ str(team_shared.id),+ str(personal_server.id),+ str(disabled_server.id),+ str(unshared_server.id),+ "not-a-uuid",+ ]++ resolve = lambda owner_id: resolve_agent_gateway_server_ids(+ self.team.id, agent_key="workflow", credential_owner_id=owner_id, connector_ids=connector_ids+ )++ assert resolve(None) == {+ str(team_server.id): str(team_server.id),+ str(team_shared.id): str(team_server.id),+ str(personal_server.id): None,+ str(disabled_server.id): None,+ str(unshared_server.id): None,+ "not-a-uuid": None,+ }+ # A run with a credential owner also reaches that owner's personal grants.+ assert resolve(self.user.id)[str(personal_server.id)] == str(personal_server.id)+def test_sandbox_server_names_match_what_the_sandbox_mounts(self) -> None:# The names projection backs prompt steering (a scout's run prompt names its mounted# servers before launch). If it drifts from the mount resolution — a reimplementationdiff --git a/products/mcp_store/frontend/gateway/GatewayAgentScene.tsx b/products/mcp_store/frontend/gateway/GatewayAgentScene.tsxindex 4493fad4f0c5..b696dcc0ac3a 100644--- a/products/mcp_store/frontend/gateway/GatewayAgentScene.tsx+++ b/products/mcp_store/frontend/gateway/GatewayAgentScene.tsx@@ -165,6 +165,12 @@ export function GatewayAgentScene({runs. A team share covers them.</div>)}+ {account.agent_key === 'workflow' && (+ <div className="text-sm text-secondary">+ Workflow tasks always run without a person behind them, so only team shares are available to+ them. A workflow's "Create AI task" step picks among those.+ </div>+ )}<div className="border rounded overflow-hidden divide-y">{allServersLoading && allServers.length === 0 ? (<div className="flex items-center justify-center gap-2 p-4 text-sm text-secondary">diff --git a/products/mcp_store/frontend/gateway/agentServerUtils.ts b/products/mcp_store/frontend/gateway/agentServerUtils.tsnew file mode 100644index 000000000000..4fa3f038600b--- /dev/null+++ b/products/mcp_store/frontend/gateway/agentServerUtils.ts@@ -0,0 +1,42 @@+import type { LemonTagType } from '@posthog/lemon-ui'++import type { MCPServiceAccountServerApi } from '../generated/api.schemas'++/**+ * The servers an agent's ownerless runs (a scout, a workflow task) can mount: reachable team-scoped+ * grants only (the gateway refuses grants on project-disabled servers and grants whose owner an admin+ * revoked), one row per server. Several members can team-share the same server and the run mounts+ * every healthy team share, so the row carries a ready share when one exists and its health tag does+ * not report a problem the run does not have. Sorted by name, ignoring case.+ */+export function teamSharedAgentServers(servers: readonly MCPServiceAccountServerApi[]): MCPServiceAccountServerApi[] {+ const byServer = new Map<string, MCPServiceAccountServerApi>()+ for (const server of servers) {+ if (server.scope !== 'team' || !server.reachable) {+ continue+ }+ const existing = byServer.get(server.id)+ if (!existing || (existing.connection_state !== 'ready' && server.connection_state === 'ready')) {+ byServer.set(server.id, server)+ }+ }+ return [...byServer.values()].sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }))+}++/** The tag a picker row shows when the share behind a server is not ready to use. */+export function agentServerConnectionIssue(+ server: MCPServiceAccountServerApi+): { label: string; tagType: LemonTagType } | null {+ switch (server.connection_state) {+ case 'needs_reauth':+ return { label: 'Reconnect', tagType: 'danger' }+ case 'pending_oauth':+ return { label: 'Pending OAuth', tagType: 'warning' }+ case 'disabled':+ return { label: 'Disabled', tagType: 'muted' }+ case 'missing_credential':+ return { label: 'Needs connection', tagType: 'warning' }+ default:+ return null+ }+}diff --git a/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts b/products/mcp_store/frontend/gateway/gatewayServerLogic.test.tsindex 5233003a462f..6f7ba49fd4ff 100644--- a/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts+++ b/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts@@ -137,9 +137,11 @@ function serviceAccount(id: string = 'scout-id', grants: Grant[] = []): MCPServiscope,name: 'Test server',description: '',+ url: '',icon_key: '',icon_domain: '',connection_state: 'ready' as const,+ reachable: true,})),last_active_at: null,created_at: '2026-01-01T00:00:00Z',diff --git a/products/mcp_store/frontend/gateway/gatewayUtils.tsx b/products/mcp_store/frontend/gateway/gatewayUtils.tsxindex 2a373fa143df..7c0d30865353 100644--- a/products/mcp_store/frontend/gateway/gatewayUtils.tsx+++ b/products/mcp_store/frontend/gateway/gatewayUtils.tsx@@ -168,7 +168,7 @@ export function PolicySummary({ counts }: { counts: Record<MCPToolApprovalStateE</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 className="text-secondary">Blocked</span></span></div>)diff --git a/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.ts b/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.tsindex 8b1769daf402..fe8312a10d5b 100644--- a/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.ts+++ b/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.ts@@ -165,9 +165,11 @@ function serviceAccountWithShare(scope: MCPAgentGrantScopeEnumApi): MCPServiceAcscope,name: 'Test server',description: '',+ url: '',icon_key: '',icon_domain: '',connection_state: 'ready',+ reachable: true,},],last_active_at: null,@@ -424,9 +426,11 @@ describe('mcpGatewayLogic', () => {scope: 'personal' as const,name: 'Linear',description: '',+ url: '',icon_key: '',icon_domain: '',connection_state: 'ready' as const,+ reachable: true,},],}@@ -468,9 +472,11 @@ describe('mcpGatewayLogic', () => {scope: 'personal' as const,name: 'Linear',description: '',+ url: '',icon_key: '',icon_domain: '',connection_state: 'ready' as const,+ reachable: true,},],})diff --git a/products/mcp_store/frontend/generated/api.schemas.ts b/products/mcp_store/frontend/generated/api.schemas.tsindex 74fe907eee87..7e3f486a07d8 100644--- a/products/mcp_store/frontend/generated/api.schemas.ts+++ b/products/mcp_store/frontend/generated/api.schemas.ts@@ -724,6 +724,7 @@ export type AgentKeyEnumApi = (typeof AgentKeyEnumApi)[keyof typeof AgentKeyEnumexport const AgentKeyEnumApi = {Support: 'support',Scout: 'scout',+ Workflow: 'workflow',} as const/**@@ -760,6 +761,8 @@ export interface MCPServiceAccountServerApi {name: string/** Server description. */description: string+ /** MCP server URL. Clients derive a brand icon from it when icon_domain is empty. */+ url: string/** Deprecated brand icon key. Empty for custom servers. */icon_key: string/** Brand domain. Empty for custom servers. */@@ -772,6 +775,8 @@ export interface MCPServiceAccountServerApi {* * `disabled` - disabled* * `missing_credential` - missing_credential */connection_state: ConnectionStateEnumApi+ /** Whether agent runs can use this grant: the server is enabled for the project and an admin has not revoked the sharing member's access. Independent of connection_state, which reports credential health. */+ reachable: boolean}export interface MCPServiceAccountApi {diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.stories.tsxindex 031828acf460..0a3f692449c2 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.stories.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.stories.tsx@@ -38,6 +38,7 @@ function grant(icon_key: name.toLowerCase(),icon_domain: `${name.toLowerCase()}.com`,connection_state: connectionState,+ reachable: true,}}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.tsxindex 3f010a27b610..f19508ae8420 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutMcpServersPicker.tsx@@ -2,13 +2,14 @@ import { useMountedLogic, useValues } from 'kea'import { useState } from 'react'import { IconChevronRight, IconServer } from '@posthog/icons'-import { LemonSwitch, LemonTag, LemonTagType, Link, Spinner } from '@posthog/lemon-ui'+import { LemonSwitch, LemonTag, Link, Spinner } from '@posthog/lemon-ui'import { ServerIcon } from '@posthog/products-mcp-store/frontend/scene/icons'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { urls } from 'scenes/urls'+import { agentServerConnectionIssue } from 'products/mcp_store/frontend/gateway/agentServerUtils'import type { MCPServiceAccountServerApi } from 'products/mcp_store/frontend/generated/api.schemas'import { scoutMcpServersLogic } from '../../../logics/scoutMcpServersLogic'@@ -39,21 +40,6 @@ export function ScoutMcpServersPicker(props: ScoutMcpServersPickerProps): JSX.Elreturn props.compact ? <CompactPicker {...props} /> : <FullPicker {...props} />}-function connectionIssue(server: MCPServiceAccountServerApi): { label: string; tagType: LemonTagType } | null {- switch (server.connection_state) {- case 'needs_reauth':- return { label: 'Reconnect', tagType: 'danger' }- case 'pending_oauth':- return { label: 'Pending OAuth', tagType: 'warning' }- case 'disabled':- return { label: 'Disabled', tagType: 'muted' }- case 'missing_credential':- return { label: 'Needs connection', tagType: 'warning' }- default:- return null- }-}-interface PickerState {hiddenCount: numberinitialLoading: boolean@@ -138,7 +124,7 @@ function FullPicker(props: ScoutMcpServersPickerProps): JSX.Element {<div className="rounded border bg-bg-light overflow-hidden"><div className="divide-y">{state.visibleServers.map((server) => {- const issue = connectionIssue(server)+ const issue = agentServerConnectionIssue(server)return (<div key={server.id} className="flex items-center gap-3 px-3 py-2.5"><ServerIcon iconDomain={server.icon_domain} size={28} />diff --git a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.tsindex 2f7352e143f6..969a84117f77 100644--- a/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutCreateModalLogic.test.ts@@ -73,9 +73,11 @@ function teamServer(id: string, name: string): MCPServiceAccountServerApi {scope: 'team',name,description: `${name} workspace`,+ url: `https://mcp.${name.toLowerCase()}.example.com/mcp`,icon_key: name.toLowerCase(),icon_domain: `${name.toLowerCase()}.com`,connection_state: 'ready',+ reachable: true,}}diff --git a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.ts b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.tsindex 1f3e991478ec..3f98b3e54411 100644--- a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.ts@@ -42,9 +42,11 @@ function server(scope,name,description: `${name} workspace`,+ url: `https://mcp.${name.toLowerCase()}.example.com/mcp`,icon_key: name.toLowerCase(),icon_domain: `${name.toLowerCase()}.com`,connection_state: connectionState,+ reachable: true,}}diff --git a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.ts b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.tsindex a86710ab4486..fda90e4f1bd0 100644--- a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.ts@@ -4,6 +4,7 @@ import { subscriptions } from 'kea-subscriptions'import { teamLogic } from 'scenes/teamLogic'+import { teamSharedAgentServers } from 'products/mcp_store/frontend/gateway/agentServerUtils'import { mcpGatewayServiceAccountsList } from 'products/mcp_store/frontend/generated/api'import type {MCPServiceAccountApi,@@ -88,27 +89,12 @@ export const scoutMcpServersLogic = kea<scoutMcpServersLogicType>([...(scoutAccount?.servers ?? []),],],- // Scout runs mount only team-scoped grants, so the picker offers exactly those. Several- // members can team-share the same server; the picker selects servers, not shares, so- // collapse to one row per server. Prefer a ready share for the row so the health tag- // reflects the best backing credential, since the run mounts every healthy team share.+ // Scout runs mount only team-scoped grants, so the picker offers exactly those, one row+ // per server (the picker selects servers, not shares).teamScoutServers: [(s) => [s.scoutServers],- (scoutServers: MCPServiceAccountServerApi[]): MCPServiceAccountServerApi[] => {- const byServer = new Map<string, MCPServiceAccountServerApi>()- for (const server of scoutServers) {- if (server.scope !== 'team') {- continue- }- const existing = byServer.get(server.id)- if (!existing || (existing.connection_state !== 'ready' && server.connection_state === 'ready')) {- byServer.set(server.id, server)- }- }- return [...byServer.values()].sort((a, b) =>- a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })- )- },+ (scoutServers: MCPServiceAccountServerApi[]): MCPServiceAccountServerApi[] =>+ teamSharedAgentServers(scoutServers),],scoutServersLoading: [(s) => [s.serviceAccountsLoading],diff --git a/products/tasks/backend/facade/workflow_tasks.py b/products/tasks/backend/facade/workflow_tasks.pyindex 1b83a49f6f2b..a31943db9771 100644--- a/products/tasks/backend/facade/workflow_tasks.py+++ b/products/tasks/backend/facade/workflow_tasks.py@@ -14,7 +14,7 @@ from products.tasks.backend.logic.services.workflow_tasks import (WorkflowTaskTeamRateCapped,WorkflowTaskUsageLimited,create_workflow_task,- validate_connectors,+ resolve_connectors,)__all__ = [@@ -28,5 +28,5 @@ __all__ = ["WorkflowTaskTeamRateCapped","WorkflowTaskUsageLimited","create_workflow_task",- "validate_connectors",+ "resolve_connectors",]diff --git a/products/tasks/backend/logic/services/workflow_tasks.py b/products/tasks/backend/logic/services/workflow_tasks.pyindex 91d3a891f8ff..3bc1b6c049ad 100644--- a/products/tasks/backend/logic/services/workflow_tasks.py+++ b/products/tasks/backend/logic/services/workflow_tasks.py@@ -21,7 +21,7 @@ from posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.team.team import Teamfrom posthog.temporal.oauth import PosthogMcpScopes-from products.mcp_store.backend.facade.api import get_active_installations+from products.mcp_store.backend.facade.api import resolve_agent_gateway_server_idsfrom products.slack_app.backend.facade.api import slack_channel_is_approvedfrom products.slack_app.backend.models import SlackThreadTaskMappingfrom products.slack_app.backend.slack_thread import SlackThreadContext@@ -70,7 +70,7 @@ WORKFLOW_FRAMING_BLOCK = (class WorkflowTaskConnectorsInvalid(Exception):def __init__(self, invalid_ids: list[str]) -> None:self.invalid_ids = invalid_ids- super().__init__(f"MCP installation(s) not found or inactive: {invalid_ids}")+ super().__init__(f"MCP server(s) not shared with the project or disabled: {invalid_ids}")class WorkflowTaskLimitExceeded(Exception):@@ -116,7 +116,7 @@ def create_workflow_task(repository: str | None = None,model: str | None = None,reasoning_effort: str | None = None,- mcp_installation_ids: list[str] | None = None,+ connector_ids: list[str] | None = None,posthog_mcp_scopes: PosthogMcpScopes = "read_only",max_parallel_tasks: int = 5,origin_key: str | None = None,@@ -129,8 +129,8 @@ def create_workflow_task(A repeated `origin_key` returns the existing task with `created=False`, before anyother check so a retry always succeeds once the first attempt did. Raises`WorkflowTaskOriginKeyConflict` when the key belongs to a different workflow,- `WorkflowTaskConnectorsInvalid` when the requested connectors aren't ones the owner- can mount, `WorkflowTaskOwnerIneligible` when the owner lost access to the project,+ `WorkflowTaskConnectorsInvalid` when a requested connector isn't an MCP server shared+ with the whole project, `WorkflowTaskOwnerIneligible` when the owner lost access to the project,and `WorkflowTaskLimitExceeded` when the workflow already has `max_parallel_tasks`runs in flight. Also raises `WorkflowTaskUsageLimited` when the owner is over theAI usage limit, and `WorkflowTaskRateCapped` / `WorkflowTaskTeamRateCapped` when@@ -163,7 +163,7 @@ def create_workflow_task(else WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY)- validate_connectors(team.id, owner_id, mcp_installation_ids)+ gateway_server_ids = resolve_connectors(team.id, connector_ids)gate_owner = User.objects.filter(id=owner_id).first()if gate_owner is None:@@ -197,13 +197,15 @@ def create_workflow_task(observe_workflow_task_create(reason="gate_blocked")raise WorkflowTaskUsageLimited()- # Snapshot the connector allowlist onto the run: the sandbox mounts only what's here- # (see loop_mcp_installation_allowlist), so a later edit of the workflow can't change- # what an already-queued run may reach.+ # Snapshot the connector selection onto the run, next to the PostHog MCP scopes the token+ # minter reads back. The mounts themselves follow the same list stamped on the task as its+ # gateway server allowlist below, so a later edit of the workflow can't change what an+ # already-queued run may reach. No installation ids on purpose: see+ # loop_mcp_installation_allowlist for why that keeps the member path closed.extra_run_state = {"config_snapshot": {"connectors": {- "mcp_installation_ids": mcp_installation_ids or [],+ "mcp_gateway_server_ids": gateway_server_ids,"posthog_mcp_scopes": posthog_mcp_scopes,}},@@ -305,6 +307,14 @@ def create_workflow_task(reasoning_effort=reasoning_effort,slack_thread_context=thread_context,interaction_origin=interaction_origin,+ # The run mounts MCP servers as the workflow agent, like a scout does. No+ # credential owner: a workflow is a team resource that anyone may edit, so+ # its runs reach only the connections members shared with the whole project,+ # never the creator's personal ones, and the selection means the same thing+ # no matter who saved it.+ mcp_builtin_agent_key="workflow",+ mcp_credential_owner_id=None,+ mcp_gateway_server_ids=gateway_server_ids,)if slack_binding is not None:@@ -365,19 +375,28 @@ def _daily_task_counts(team_id: int, hog_flow_id: uuid.UUID) -> _DailyTaskCountsreturn _DailyTaskCounts(workflow=workflow_count, team=team_count)-def validate_connectors(team_id: int, owner_id: int, mcp_installation_ids: list[str] | None) -> None:- """Raise `WorkflowTaskConnectorsInvalid` for any id the owner can't mount.+def resolve_connectors(team_id: int, connector_ids: list[str] | None) -> list[str]:+ """The gateway servers a "Create AI task" step's connector selection names, in order.- Called both when a run actually starts and, from the workflows product, when a- "Create AI task" action is saved - so a stale or foreign connector id fails at save- time instead of only on the workflow's next fire.+ Raises `WorkflowTaskConnectorsInvalid` for any id that isn't an MCP server shared with+ the whole project (a team-scoped grant to the workflow agent). Called both when a run+ actually starts and, from the workflows product, when the action is saved - so a stale+ connector fails at save time instead of only on the workflow's next fire."""- if not mcp_installation_ids:- return- valid_ids = {installation.id for installation in get_active_installations(team_id, owner_id, include_shared=True)}- invalid = sorted(set(mcp_installation_ids) - valid_ids)+ if not connector_ids:+ return []+ resolved = resolve_agent_gateway_server_ids(+ team_id, agent_key="workflow", credential_owner_id=None, connector_ids=connector_ids+ )+ invalid = sorted(connector_id for connector_id, server_id in resolved.items() if server_id is None)if invalid:raise WorkflowTaskConnectorsInvalid(invalid)+ gateway_server_ids: list[str] = []+ for connector_id in connector_ids:+ server_id = resolved[connector_id]+ if server_id is not None and server_id not in gateway_server_ids:+ gateway_server_ids.append(server_id)+ return gateway_server_idsdef _render_run_message(prompt: str, event: dict[str, Any] | None) -> str:diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex a959e1b13982..fb0db4fc410a 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -61,7 +61,7 @@ def execute_after_commit(callback: Callable[[], object]) -> None:LogLevel = Literal["debug", "info", "warn", "error"]-MCPBuiltInAgentKey = Literal["support", "scout"]+MCPBuiltInAgentKey = Literal["support", "scout", "workflow"]MCP_BUILT_IN_AGENT_STATE_KEY = "mcp_builtin_agent_key"MCP_CREDENTIAL_OWNER_STATE_KEY = "mcp_credential_owner_id"MCP_GATEWAY_SERVER_ALLOWLIST_STATE_KEY = "mcp_gateway_server_ids"@@ -70,6 +70,7 @@ MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN: dict[str, MCPBuiltInAgentKey] = {"support_reply": "support","signals_scout": "scout","scout_suggestions": "scout",+ "workflow": "workflow",}diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.pyindex e0518b27c632..fe618ceaa374 100644--- a/products/tasks/backend/temporal/oauth.py+++ b/products/tasks/backend/temporal/oauth.py@@ -153,6 +153,7 @@ def create_oauth_access_token(Task.OriginProduct.SIGNALS_SCOUT,Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS,Task.OriginProduct.SUPPORT_REPLY,+ Task.OriginProduct.WORKFLOW,} 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 spoofeddiff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex 60a4ebc03ceb..ce47ab20eaa9 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -452,6 +452,7 @@ class TestFetchUserMcpServerConfigs(TestCase):task_origin=None,task_agent_key=None,credential_owner_id=None,+ allowed_installation_ids=None,allowed_gateway_server_ids=None,)assert configs == [@@ -477,28 +478,21 @@ class TestFetchUserMcpServerConfigs(TestCase):assert configs[0].description == "Manage Linear issues, projects, and workflows."+ @parameterized.expand([("selection", ["keep"]), ("empty_selection", [])])@patch(MOCK_API_URL)@patch(MOCK_FACADE)- def test_allowlist_restricts_mounted_connectors(self, mock_facade, mock_api_url) -> None:- # A loop run snapshots the connectors its owner selected. Without enforcement the sandbox- # mounts every shared team connector; the allowlist must keep only the selected ones.+ def test_installation_allowlist_is_forwarded_to_the_facade(+ self, _name: str, allowed: list[str], mock_facade, mock_api_url+ ) -> None:+ # A loop run snapshots the connectors its owner selected. The facade applies the list on+ # the member path (and only there), so this layer must hand it over untouched, an empty+ # selection included.mock_api_url.return_value = self.API_BASE- mock_facade.return_value = [- self._make_installation(id="keep", name="Kept"),- self._make_installation(id="drop", name="Dropped"),- ]-- configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID, allowed_installation_ids=["keep"])-- assert [config.name for config in configs] == ["Kept"]+ mock_facade.return_value = []- @patch(MOCK_API_URL)- @patch(MOCK_FACADE)- def test_empty_allowlist_mounts_nothing(self, mock_facade, mock_api_url) -> None:- mock_api_url.return_value = self.API_BASE- mock_facade.return_value = [self._make_installation()]+ get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID, allowed_installation_ids=allowed)- assert get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID, allowed_installation_ids=[]) == []+ assert mock_facade.call_args.kwargs["allowed_installation_ids"] == allowed@parameterized.expand([@@ -572,6 +566,7 @@ class TestFetchUserMcpServerConfigs(TestCase):task_origin="support_reply",task_agent_key="support",credential_owner_id=self.CREDENTIAL_OWNER_ID,+ allowed_installation_ids=None,allowed_gateway_server_ids=["server-1"],)assert configs == [@@ -603,6 +598,7 @@ class TestFetchUserMcpServerConfigs(TestCase):task_origin=None,task_agent_key=None,credential_owner_id=None,+ allowed_installation_ids=None,allowed_gateway_server_ids=None,)diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex 8aebb1ef8224..9aad7aea528b 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -593,7 +593,10 @@ def loop_mcp_installation_allowlist(state: dict | None) -> list[str] | None:state) so the caller keeps its current unfiltered behavior. Once a loop snapshot exists, amissing or malformed id list fails closed to an empty allowlist (mount nothing) — a loop thatselected no connectors, or whose config omitted the key, must not fall back to mounting every- connector the owner has."""+ connector the owner has. A workflow snapshot keys its connectors by gateway server+ (``mcp_gateway_server_ids``) and carries no installation ids, so it lands here too: the run+ mounts nothing through the member path, and its selection applies through+ ``Task.mcp_gateway_server_allowlist`` on the agent path."""config_snapshot = (state or {}).get("config_snapshot")if not isinstance(config_snapshot, dict):return None@@ -629,16 +632,17 @@ def get_user_mcp_server_configs(``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 (a+ ``allowed_installation_ids`` restricts the member-path mounts to a snapshotted allowlist (aloop run's selected ``mcp_installation_ids``): ``None`` leaves the set unfiltered (currentbehavior for regular tasks), an empty list mounts nothing, and a populated list keeps onlythose installations. Without it, an unattended loop run would mount every shared team connectorrather than only the ones its owner chose.- ``allowed_gateway_server_ids`` is the built-in agent counterpart (a scout's per-scout- selection, from ``Task.mcp_gateway_server_allowlist``): it narrows the agent's mounts to- the listed gateway servers regardless of grant scope. ``None`` leaves them unfiltered;- an empty list mounts nothing.+ ``allowed_gateway_server_ids`` is the built-in agent counterpart (a scout's or workflow+ step's selection, from ``Task.mcp_gateway_server_allowlist``): it narrows the agent's+ mounts to the listed gateway servers regardless of grant scope. ``None`` leaves them+ unfiltered; an empty list mounts nothing. The facade applies each allowlist on its own+ path, so an agent run is never filtered by installation ids it does not mount by.The `x-posthog-mcp-consumer` header is set on every config so the agent'sidentity propagates through the MCP Store proxy to whichever upstream MCP@@ -655,11 +659,9 @@ def get_user_mcp_server_configs(task_origin=origin_product,task_agent_key=task_agent_key,credential_owner_id=credential_owner_id,+ allowed_installation_ids=allowed_installation_ids,allowed_gateway_server_ids=allowed_gateway_server_ids,)- if allowed_installation_ids is not None:- allowed = {str(i) for i in allowed_installation_ids}- installations = [installation for installation in installations if str(installation.id) in allowed]api_base = get_sandbox_api_url().rstrip("/")consumer = _resolve_mcp_consumer(interaction_origin)diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.pyindex f97d84dc9d62..d4e0824e9f07 100644--- a/products/tasks/backend/temporal/tests/test_oauth.py+++ b/products/tasks/backend/temporal/tests/test_oauth.py@@ -15,6 +15,7 @@ from products.tasks.backend.temporal.oauth import create_oauth_access_token, cre[(Task.OriginProduct.SIGNALS_SCOUT, "signals"),(Task.OriginProduct.SUPPORT_REPLY, "array"),+ (Task.OriginProduct.WORKFLOW, "array"),],)@patch("products.tasks.backend.temporal.oauth.is_builtin_agent_enforcement_enabled", return_value=True)@@ -205,6 +206,7 @@ def test_oauth_token_can_disable_task_creator_fallback() -> None:[(Task.OriginProduct.SIGNALS_SCOUT, "scout"),(Task.OriginProduct.SUPPORT_REPLY, "support"),+ (Task.OriginProduct.WORKFLOW, "workflow"),],)def test_server_created_task_persists_trusted_mcp_agent_marker(diff --git a/products/tasks/backend/tests/test_workflow_tasks_api.py b/products/tasks/backend/tests/test_workflow_tasks_api.pyindex 57a362ce3955..965ec72d21fc 100644--- a/products/tasks/backend/tests/test_workflow_tasks_api.py+++ b/products/tasks/backend/tests/test_workflow_tasks_api.py@@ -1,5 +1,4 @@from datetime import datetime, timedelta-from types import SimpleNamespacefrom typing import Anyfrom uuid import UUID, uuid4@@ -120,6 +119,10 @@ class TestWorkflowTasksAPI(APIBaseTest):run = TaskRun.objects.get(id=body["run_id"])assert run.task_id == task.idassert run.status == TaskRun.Status.QUEUED+ # No connectors selected means the run mounts no MCP servers, rather than every server+ # shared with the project.+ assert task.mcp_builtin_agent_key == "workflow"+ assert task.mcp_gateway_server_allowlist == []def test_dispatches_the_agent_run_after_the_task_commits(self) -> None:with (@@ -181,43 +184,76 @@ class TestWorkflowTasksAPI(APIBaseTest):# so the run must carry only the boot-path override.assert "pending_user_message" not in run.state- def test_accepts_a_team_shared_connector(self) -> None:- from products.mcp_store.backend.models import MCPServerInstallation+ def test_accepts_an_mcp_server_shared_with_the_project(self) -> None:+ from products.mcp_store.backend.facade.api import get_built_in_agent+ from products.mcp_store.backend.models import (+ MCPGatewayServer,+ MCPServerInstallation,+ MCPServiceAccountServerAccess,+ )- other_user = self._create_user("[email protected]")- shared = MCPServerInstallation.objects.create(+ teammate = self._create_user("[email protected]")+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team_id=self.team.id, name="Linear", url="https://mcp.linear.app/mcp", is_team_enabled=True+ )+ installation = MCPServerInstallation.objects.create(team=self.team,- user=other_user,+ user=teammate,display_name="Linear",- url="https://mcp.linear.app/mcp",+ url=server.url,auth_type="api_key",is_enabled=True,- scope="shared",+ scope="personal",+ gateway_server=server,+ )+ workflow_agent = get_built_in_agent(self.team.id, "workflow")+ assert workflow_agent is not None+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ service_account=workflow_agent,+ gateway_server=server,+ user=teammate,+ installation=installation,+ granted_by=teammate,+ scope="team",)- response = self._post({"connectors": [str(shared.id)]})+ response = self._post({"connectors": [str(server.id)]})assert response.status_code == status.HTTP_201_CREATED, response.json()+ task = Task.objects.get(id=response.json()["id"])+ # The run mounts as the workflow agent with exactly this selection. No credential owner:+ # the workflow's runs reach the project's team shares only, never the creator's own grants.+ assert task.mcp_builtin_agent_key == "workflow"+ assert task.mcp_credential_owner_id is None+ assert task.mcp_gateway_server_allowlist == [str(server.id)]run = TaskRun.objects.get(id=response.json()["run_id"])- assert run.state["config_snapshot"]["connectors"]["mcp_installation_ids"] == [str(shared.id)]+ assert run.state["config_snapshot"]["connectors"]["mcp_gateway_server_ids"] == [str(server.id)]- @patch("products.tasks.backend.logic.services.workflow_tasks.get_active_installations")- def test_snapshots_validated_connectors_into_the_run(self, get_active_installations) -> None:- get_active_installations.return_value = [SimpleNamespace(id="inst-1"), SimpleNamespace(id="inst-2")]+ @patch("products.tasks.backend.logic.services.workflow_tasks.resolve_agent_gateway_server_ids")+ def test_snapshots_resolved_connectors_into_the_run(self, resolve_ids) -> None:+ # A connector saved as a Store installation id resolves to its gateway server.+ resolve_ids.return_value = {"inst-1": "server-1", "server-2": "server-2"}- response = self._post({"connectors": ["inst-1"]})+ response = self._post({"connectors": ["inst-1", "server-2"]})assert response.status_code == status.HTTP_201_CREATED, response.json()+ resolve_ids.assert_called_once_with(+ self.team.id, agent_key="workflow", credential_owner_id=None, connector_ids=["inst-1", "server-2"]+ )+ task = Task.objects.get(id=response.json()["id"])+ assert task.mcp_gateway_server_allowlist == ["server-1", "server-2"]run = TaskRun.objects.get(id=response.json()["run_id"])- assert run.state["config_snapshot"]["connectors"]["mcp_installation_ids"] == ["inst-1"]+ assert run.state["config_snapshot"]["connectors"]["mcp_gateway_server_ids"] == ["server-1", "server-2"]- @patch("products.tasks.backend.logic.services.workflow_tasks.get_active_installations")- def test_rejects_connectors_the_workflow_owner_cannot_mount(self, get_active_installations) -> None:- get_active_installations.return_value = [SimpleNamespace(id="inst-1")]+ @patch("products.tasks.backend.logic.services.workflow_tasks.resolve_agent_gateway_server_ids")+ def test_rejects_a_connector_not_shared_with_the_project(self, resolve_ids) -> None:+ resolve_ids.return_value = {"server-1": "server-1", "server-unknown": None}- response = self._post({"connectors": ["inst-1", "inst-unknown"]})+ response = self._post({"connectors": ["server-1", "server-unknown"]})assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "server-unknown" in response.json()["detail"]assert not Task.objects.filter(hog_flow_id=self.hog_flow.id).exists()@parameterized.expand(@@ -427,21 +463,21 @@ class TestWorkflowTasksAPI(APIBaseTest):assert replay.json()["run_id"] == first.json()["run_id"]assert Task.objects.filter(hog_flow_id=self.hog_flow.id).count() == 1- @patch("products.tasks.backend.logic.services.workflow_tasks.get_active_installations")- def test_a_replay_succeeds_even_after_connectors_and_the_limit_would_reject_it(- self, get_active_installations- ) -> None:- get_active_installations.return_value = [SimpleNamespace(id="inst-1")]- first = self._post({"idempotency_key": "invocation-1", "connectors": ["inst-1"], "max_parallel_tasks": 1})+ @patch("products.tasks.backend.logic.services.workflow_tasks.resolve_agent_gateway_server_ids")+ def test_a_replay_succeeds_even_after_connectors_and_the_limit_would_reject_it(self, resolve_ids) -> None:+ resolve_ids.return_value = {"server-1": "server-1"}+ first = self._post({"idempotency_key": "invocation-1", "connectors": ["server-1"], "max_parallel_tasks": 1})assert first.status_code == status.HTTP_201_CREATED, first.json()# The connector is gone, the workflow is at its in-flight and daily limits, and the# owner is over the usage limit; the retry of the already-created request must# still return the existing task.- get_active_installations.return_value = []+ resolve_ids.return_value = {"server-1": None}self._seed_created_tasks(WORKFLOW_TASK_RATE_CAP_PER_DAY, hog_flow_id=self.hog_flow.id)with patch("products.tasks.backend.logic.services.workflow_tasks.usage_limit_response", return_value=object()):- replay = self._post({"idempotency_key": "invocation-1", "connectors": ["inst-1"], "max_parallel_tasks": 1})+ replay = self._post(+ {"idempotency_key": "invocation-1", "connectors": ["server-1"], "max_parallel_tasks": 1}+ )assert replay.status_code == status.HTTP_200_OK, replay.json()assert replay.json()["id"] == first.json()["id"]@@ -461,16 +497,16 @@ class TestWorkflowTasksAPI(APIBaseTest):assert response.status_code == status.HTTP_409_CONFLICT, response.json()assert not Task.objects.filter(hog_flow_id=self.hog_flow.id).exists()- @patch("products.tasks.backend.logic.services.workflow_tasks.get_active_installations")- def test_a_later_run_inherits_the_connector_snapshot(self, get_active_installations) -> None:- get_active_installations.return_value = [SimpleNamespace(id="inst-1")]- response = self._post({"connectors": ["inst-1"]})+ @patch("products.tasks.backend.logic.services.workflow_tasks.resolve_agent_gateway_server_ids")+ def test_a_later_run_inherits_the_connector_snapshot(self, resolve_ids) -> None:+ resolve_ids.return_value = {"server-1": "server-1"}+ response = self._post({"connectors": ["server-1"]})assert response.status_code == status.HTTP_201_CREATED, response.json()task = Task.objects.get(id=response.json()["id"])later_run = task.create_run(mode="background")- assert later_run.state["config_snapshot"]["connectors"]["mcp_installation_ids"] == ["inst-1"]+ assert later_run.state["config_snapshot"]["connectors"]["mcp_gateway_server_ids"] == ["server-1"]@parameterized.expand([("with_repository", True), ("without_repository", False)])def test_pr_creation_follows_the_repository(self, _name: str, with_repository: bool) -> None:diff --git a/products/tasks/frontend/components/TaskConnectorsPicker/CyclotronJobInputTaskConnectors.stories.tsx b/products/tasks/frontend/components/TaskConnectorsPicker/CyclotronJobInputTaskConnectors.stories.tsxnew file mode 100644index 000000000000..4bd23762218c--- /dev/null+++ b/products/tasks/frontend/components/TaskConnectorsPicker/CyclotronJobInputTaskConnectors.stories.tsx@@ -0,0 +1,154 @@+import type { Meta, StoryObj } from '@storybook/react'+import { useState } from 'react'++import { FEATURE_FLAGS } from 'lib/constants'++import { mswDecorator } from '~/mocks/browser'++import type {+ MCPServiceAccountApi,+ MCPServiceAccountServerApi,+ MCPToolApprovalStateEnumApi,+ ResolvedToolPolicyApi,+} from 'products/mcp_store/frontend/generated/api.schemas'++import CyclotronJobInputTaskConnectors from './CyclotronJobInputTaskConnectors'++// The "Connectors" input of a workflow's "Create AI task" step: one switch per MCP server shared+// with everyone in the project.++const SHARED_BY = { id: 2, uuid: 'teammate-uuid', email: '[email protected]', hedgehog_config: null }++function server(+ id: string,+ name: string,+ connectionState: MCPServiceAccountServerApi['connection_state'] = 'ready'+): MCPServiceAccountServerApi {+ return {+ id,+ shared_by: SHARED_BY,+ scope: 'team',+ name,+ description: `${name} workspace`,+ // Empty keeps the icon fallback deterministic in stories: no logo request, no onError race.+ url: '',+ icon_key: '',+ icon_domain: '',+ connection_state: connectionState,+ reachable: true,+ }+}++function workflowAccount(servers: MCPServiceAccountServerApi[]): MCPServiceAccountApi {+ return {+ id: 'workflow-id',+ name: 'Workflow agent',+ description: 'Runs the AI tasks that workflows start.',+ handle: 'posthog-workflow',+ agent_key: 'workflow',+ status: 'active',+ server_ids: servers.map(({ id }) => id),+ servers,+ last_active_at: null,+ created_at: '2026-08-28T00:00:00Z',+ updated_at: '2026-08-28T00:00:00Z',+ }+}++const SERVERS = [+ server('incident-id', 'Incident.io'),+ server('datadog-id', 'Datadog', 'needs_reauth'),+ server('linear-id', 'Linear'),+]++function resolvedTool(toolName: string, policyState: MCPToolApprovalStateEnumApi): ResolvedToolPolicyApi {+ return {+ tool_name: toolName,+ description: `${toolName} tool`,+ input_schema: {},+ is_destructive: policyState === 'do_not_use',+ policy_state: policyState,+ team_state: null,+ locked: false,+ decided_by: 'default',+ rule_name: '',+ rule_description: '',+ }+}++// Incident.io has a mixed policy spread; every other server sits on the needs-approval default.+const TOOLS_BY_SERVER: Record<string, MCPToolApprovalStateEnumApi[]> = {+ 'incident-id': ['approved', 'approved', 'needs_approval', 'needs_approval', 'needs_approval', 'do_not_use'],+ 'datadog-id': ['needs_approval', 'needs_approval'],+ 'linear-id': ['needs_approval', 'needs_approval', 'needs_approval', 'do_not_use'],+}++function toolsResponse(serverId: string): [number, Record<string, unknown>] {+ const tools = (TOOLS_BY_SERVER[serverId] ?? []).map((state, index) => resolvedTool(`tool_${index}`, state))+ return [200, { count: tools.length, next: null, previous: null, results: tools }]+}++function Picker({ initialValue }: { initialValue: string[] }): JSX.Element {+ const [value, setValue] = useState<string[]>(initialValue)+ return (+ <div className="w-[420px] p-2">+ <CyclotronJobInputTaskConnectors+ schema={{ key: 'connectors', type: 'task_mcp_installations', label: 'Connectors' }}+ value={value}+ onChange={setValue}+ />+ </div>+ )+}++const meta: Meta<typeof CyclotronJobInputTaskConnectors> = {+ title: 'Scenes-App/Workflows/CreateAiTaskConnectors',+ component: CyclotronJobInputTaskConnectors,+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/mcp_gateway/service_accounts/': () => [+ 200,+ { count: 1, next: null, previous: null, results: [workflowAccount(SERVERS)] },+ ],+ '/api/projects/:team_id/mcp_gateway/servers/:server_id/tools/': (req) =>+ toolsResponse(String(req.params.server_id)),+ },+ }),+ ],+ parameters: {+ featureFlags: { [FEATURE_FLAGS.MCP_GATEWAY]: true },+ testOptions: { waitForLoadersToDisappear: true },+ },+}+export default meta++type Story = StoryObj<typeof CyclotronJobInputTaskConnectors>++export const Selection: Story = {+ render: () => <Picker initialValue={['incident-id']} />,+}++// An enabled server with nothing approved warns that task runs can't use it yet.+export const NoApprovedTools: Story = {+ render: () => <Picker initialValue={['linear-id']} />,+}++// A saved id that no team share backs anymore keeps a row, so it can be switched off.+export const UnavailableConnector: Story = {+ render: () => <Picker initialValue={['incident-id', 'gone-id']} />,+}++export const NothingShared: Story = {+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/mcp_gateway/service_accounts/': () => [+ 200,+ { count: 1, next: null, previous: null, results: [workflowAccount([])] },+ ],+ },+ }),+ ],+ render: () => <Picker initialValue={[]} />,+}diff --git a/products/tasks/frontend/components/TaskConnectorsPicker/CyclotronJobInputTaskConnectors.tsx b/products/tasks/frontend/components/TaskConnectorsPicker/CyclotronJobInputTaskConnectors.tsxindex d7870f6f7436..cd7c7b6be909 100644--- a/products/tasks/frontend/components/TaskConnectorsPicker/CyclotronJobInputTaskConnectors.tsx+++ b/products/tasks/frontend/components/TaskConnectorsPicker/CyclotronJobInputTaskConnectors.tsx@@ -1,54 +1,212 @@import { useValues } from 'kea'-import { LemonInputSelect, LemonTag } from '@posthog/lemon-ui'+import { IconServer } from '@posthog/icons'+import { LemonSwitch, LemonTag, Link, Spinner } from '@posthog/lemon-ui'+import { ServerIcon } from '@posthog/products-mcp-store/frontend/scene/icons'import type { CustomInputRendererProps } from 'lib/components/CyclotronJob/customInputRenderers'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { urls } from 'scenes/urls'-import { taskConnectorsPickerLogic } from './taskConnectorsPickerLogic'+import { agentServerConnectionIssue } from 'products/mcp_store/frontend/gateway/agentServerUtils'-export default function CyclotronJobInputTaskConnectors({ value, onChange }: CustomInputRendererProps): JSX.Element {- const { installations, installationsLoading } = useValues(taskConnectorsPickerLogic)+import { ServerToolPolicyCounts, taskConnectorsPickerLogic } from './taskConnectorsPickerLogic'++/**+ * Per-step selection among the MCP servers shared with everyone in the project, saved as the+ * "Create AI task" step's `connectors` input (gateway server ids). The run mounts the selection as+ * the workflow agent, so the list is the same for every editor and matches what the run reaches.+ * Sharing a server with the project happens on the MCP servers page, not here.+ */+export default function CyclotronJobInputTaskConnectors(props: CustomInputRendererProps): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)++ if (!featureFlags[FEATURE_FLAGS.MCP_GATEWAY]) {+ return (+ <span className="text-xs text-secondary">+ MCP servers for workflow tasks aren't available in this project yet.+ </span>+ )+ }++ // Mount the picker's data logic only inside the enabled branch, so a project outside the rollout+ // never requests the service-account catalog. Mirrors ScoutMcpServersPicker.+ return <TaskConnectorsPicker {...props} />+}++function TaskConnectorsPicker({ value, onChange }: CustomInputRendererProps): JSX.Element {+ const {+ workflowAccount,+ teamWorkflowServers,+ serviceAccountsLoading,+ serviceAccountsFailed,+ toolPolicyCountsByServer,+ } = useValues(taskConnectorsPickerLogic)const selectedIds: string[] = Array.isArray(value) ? value : []- // The run mounts the team's shared connectors and the workflow creator's own personal ones.- // A teammate's personal installation can't mount (the run only borrows the creator's- // credentials), so offering it here would pass the picker but fail the run.- const enabledInstallations = installations.filter(- (installation) =>- installation.is_enabled !== false &&- (installation.scope === 'shared' || (installation.scope === 'personal' && installation.is_owner))- )+ const toggleServer = (serverId: string, selected: boolean): void => {+ onChange(selected ? [...selectedIds, serverId] : selectedIds.filter((id) => id !== serverId))+ }- const options = enabledInstallations.map((installation) => {- const label = installation.display_name || installation.name- return {- key: installation.id,- label,- labelComponent: installation.needs_reauth ? (- <span className="inline-flex items-center gap-1.5">- {label}- <LemonTag type="warning">Needs reauthorization</LemonTag>- </span>- ) : undefined,- }- })- // Stored ids whose installation has since been removed or disabled still need to render,- // so the person editing can see and remove them.- for (const id of selectedIds) {- if (!options.some((option) => option.key === id)) {- options.push({ key: id, label: `Unavailable connector (${id})`, labelComponent: undefined })- }+ // Stored ids with no team share behind them (a server no longer shared with the project, or a+ // selection saved before connectors were keyed by server) stay visible so they can be turned off.+ const unavailableIds = selectedIds.filter((id) => !teamWorkflowServers.some((server) => server.id === id))+ const initialLoading = serviceAccountsLoading && workflowAccount === null++ let body: JSX.Element+ if (initialLoading) {+ body = (+ <div className="flex items-center gap-2 rounded border border-dashed px-3 py-3 text-xs text-secondary">+ <Spinner /> Loading MCP servers...+ </div>+ )+ } else if (serviceAccountsFailed) {+ body = (+ <div className="rounded border border-dashed px-3 py-3 text-xs text-secondary">+ Couldn't load MCP servers. Refresh the page to try again.+ </div>+ )+ } else if (teamWorkflowServers.length === 0 && unavailableIds.length === 0) {+ body = (+ <div className="flex items-start gap-3 rounded border border-dashed 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 the project yet</div>+ <p className="text-xs text-secondary mt-0.5 mb-0">+ <Link to={urls.mcpGateway()}>Share an MCP server with everyone in this project</Link> to let+ this task use it.+ </p>+ </div>+ </div>+ )+ } else {+ body = (+ <div className="rounded border bg-bg-light overflow-hidden">+ <div className="divide-y">+ {teamWorkflowServers.map((server) => {+ const issue = agentServerConnectionIssue(server)+ const selected = selectedIds.includes(server.id)+ return (+ <div key={server.id} className="flex items-center gap-3 px-3 py-3">+ <ServerIcon iconDomain={server.icon_domain} serverUrl={server.url} size={24} />+ <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>+ )}+ {selected && workflowAccount && (+ <ServerToolPolicyNote+ counts={toolPolicyCountsByServer[server.id]}+ serverId={server.id}+ accountId={workflowAccount.id}+ />+ )}+ </div>+ {issue && (+ <LemonTag type={issue.tagType} size="small">+ {issue.label}+ </LemonTag>+ )}+ <LemonSwitch+ size="small"+ checked={selected}+ onChange={(checked) => toggleServer(server.id, checked)}+ aria-label={`Let this task use ${server.name}`}+ data-attr="task-connectors-picker-server"+ />+ </div>+ )+ })}+ {unavailableIds.map((id) => (+ <div key={id} className="flex items-center gap-3 px-3 py-2">+ <IconServer className="size-6 shrink-0 text-secondary" />+ <div className="min-w-0 flex-1">+ <div className="font-medium text-sm text-default truncate">Unavailable connector</div>+ <div className="text-xs text-secondary truncate">+ No longer shared with the project. Turn it off.+ </div>+ </div>+ <LemonSwitch+ size="small"+ checked+ onChange={() => toggleServer(id, false)}+ aria-label="Remove unavailable connector"+ data-attr="task-connectors-picker-server"+ />+ </div>+ ))}+ </div>+ {workflowAccount?.status === 'paused' && (+ <div className="border-t border-primary px-3 py-2 text-xs text-secondary">+ MCP access for the workflow agent is paused. Selected servers won't be available to the task+ until an admin resumes it.+ </div>+ )}+ <Link+ to={urls.mcpGateway()}+ className="flex items-center justify-between gap-3 border-t border-primary px-3 py-2 text-xs"+ >+ Manage MCP servers+ </Link>+ </div>+ )+ }++ return <div data-attr="task-connectors-picker">{body}</div>+}++/** Per-state tool counts under an enabled server, so a selection with no approved tools is visible here. */+function ServerToolPolicyNote({+ counts,+ serverId,+ accountId,+}: {+ counts: ServerToolPolicyCounts | 'error' | undefined+ serverId: string+ accountId: string+}): JSX.Element | null {+ if (counts === undefined) {+ return null}+ return (+ <div className="mt-1" data-attr="task-connectors-picker-tool-policy-note">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs text-secondary">+ {counts === 'error' ? (+ <span>Couldn't load tool approvals. Refresh the page to try again.</span>+ ) : (+ <span className="flex flex-wrap items-center gap-x-2.5 gap-y-0.5">+ <PolicyDot color="bg-success" label={`${counts.approved} always allow`} />+ {counts.needs_approval > 0 && (+ <PolicyDot color="bg-warning" label={`${counts.needs_approval} needs approval`} />+ )}+ {counts.do_not_use > 0 && (+ <PolicyDot color="bg-danger" label={`${counts.do_not_use} blocked`} />+ )}+ </span>+ )}+ <Link+ to={urls.mcpGatewayServer(serverId, `agent:${accountId}`)}+ className="shrink-0"+ data-attr="task-connectors-picker-tool-policies"+ >+ Tool policies+ </Link>+ </div>+ {counts !== 'error' && counts.approved === 0 && (+ <div className="mt-0.5 text-xs text-warning">+ No tools approved yet, so task runs can't use this server.+ </div>+ )}+ </div>+ )+}+function PolicyDot({ color, label }: { color: string; label: string }): JSX.Element {return (- <LemonInputSelect- mode="multiple"- value={selectedIds}- onChange={(ids) => onChange(ids)}- options={options}- loading={installationsLoading}- placeholder="No connectors"- data-attr="task-connectors-picker"- />+ <span className="flex items-center gap-1 whitespace-nowrap">+ <span className={`size-1.5 shrink-0 rounded-full ${color}`} />+ {label}+ </span>)}diff --git a/products/tasks/frontend/components/TaskConnectorsPicker/taskConnectorsPickerLogic.test.ts b/products/tasks/frontend/components/TaskConnectorsPicker/taskConnectorsPickerLogic.test.tsnew file mode 100644index 000000000000..e5f11da12f56--- /dev/null+++ b/products/tasks/frontend/components/TaskConnectorsPicker/taskConnectorsPickerLogic.test.ts@@ -0,0 +1,160 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */+import { MOCK_DEFAULT_USER } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type {+ ConnectionStateEnumApi,+ MCPServiceAccountApi,+ MCPServiceAccountServerApi,+ MCPToolApprovalStateEnumApi,+ ResolvedToolPolicyApi,+ UserBasicApi,+} from 'products/mcp_store/frontend/generated/api.schemas'++import { taskConnectorsPickerLogic } from './taskConnectorsPickerLogic'++const YOU: UserBasicApi = {+ id: MOCK_DEFAULT_USER.id,+ uuid: MOCK_DEFAULT_USER.uuid,+ email: MOCK_DEFAULT_USER.email,+ hedgehog_config: null,+}++const TEAMMATE: UserBasicApi = {+ id: MOCK_DEFAULT_USER.id + 1,+ uuid: 'teammate-uuid',+ email: '[email protected]',+ hedgehog_config: null,+}++function server(+ id: string,+ name: string,+ connectionState: ConnectionStateEnumApi,+ sharedBy: UserBasicApi = YOU,+ scope: MCPServiceAccountServerApi['scope'] = 'team',+ reachable: boolean = true+): MCPServiceAccountServerApi {+ return {+ id,+ shared_by: sharedBy,+ scope,+ name,+ description: `${name} workspace`,+ url: `https://mcp.${name.toLowerCase()}.example.com/mcp`,+ icon_key: name.toLowerCase(),+ icon_domain: `${name.toLowerCase()}.com`,+ connection_state: connectionState,+ reachable,+ }+}++function account(+ agentKey: MCPServiceAccountApi['agent_key'],+ servers: MCPServiceAccountServerApi[]+): MCPServiceAccountApi {+ return {+ id: `${agentKey}-id`,+ name: agentKey,+ description: `${agentKey} agent`,+ handle: `svc-${agentKey}`,+ agent_key: agentKey,+ status: 'active',+ server_ids: servers.map(({ id }) => id),+ servers,+ last_active_at: null,+ created_at: '2026-08-28T00:00:00Z',+ updated_at: '2026-08-28T00:00:00Z',+ }+}++function listResponse<T>(results: T[]): [number, { count: number; next: null; previous: null; results: T[] }] {+ return [200, { count: results.length, next: null, previous: null, results }]+}++function resolvedTool(toolName: string, policyState: MCPToolApprovalStateEnumApi): ResolvedToolPolicyApi {+ return {+ tool_name: toolName,+ description: '',+ input_schema: {},+ is_destructive: false,+ policy_state: policyState,+ team_state: null,+ locked: false,+ decided_by: 'default',+ rule_name: '',+ rule_description: '',+ }+}++describe('taskConnectorsPickerLogic', () => {+ let logic: ReturnType<typeof taskConnectorsPickerLogic.build> | undefined++ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('offers the team shares of the workflow agent, not another agent, a personal share, or an unreachable grant', async () => {+ const personalIncident = server('incident-id', 'Incident.io', 'ready', YOU, 'personal')+ const teamIncident = server('incident-id', 'Incident.io', 'ready', TEAMMATE)+ const datadog = server('datadog-id', 'Datadog', 'needs_reauth', TEAMMATE)+ const disabledLinear = server('linear-id', 'Linear', 'ready', TEAMMATE, 'team', false)+ const scoutOnlyNotion = server('notion-id', 'Notion', 'ready')+ useMocks({+ get: {+ '/api/projects/:team_id/mcp_gateway/service_accounts/': () =>+ listResponse([+ account('scout', [scoutOnlyNotion]),+ account('workflow', [personalIncident, teamIncident, datadog, disabledLinear]),+ ]),+ '/api/projects/:team_id/mcp_gateway/servers/:server_id/tools/': (req) =>+ req.params.server_id === 'incident-id'+ ? listResponse([+ resolvedTool('search', 'approved'),+ resolvedTool('create_incident', 'needs_approval'),+ resolvedTool('delete_incident', 'do_not_use'),+ ])+ : [500, { detail: 'boom' }],+ },+ })++ logic = taskConnectorsPickerLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.workflowAccount?.agent_key).toEqual('workflow')+ // A grant to another agent never backs a workflow run, and neither does a personal share or a+ // grant the gateway refuses (server disabled for the project, or the sharing member revoked).+ expect(logic.values.teamWorkflowServers).toEqual([datadog, teamIncident])+ expect(logic.values.serviceAccountsFailed).toBe(false)+ // Agent-scope tool approvals load for exactly the offered servers; a failed load is marked+ // rather than mistaken for a server with no tools.+ expect(logic.values.toolPolicyCountsByServer).toEqual({+ 'incident-id': { approved: 1, needs_approval: 1, do_not_use: 1 },+ 'datadog-id': 'error',+ })+ })++ it('records a failed load apart from an empty one', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/mcp_gateway/service_accounts/': () => [500, { detail: 'boom' }],+ },+ })++ logic = taskConnectorsPickerLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.teamWorkflowServers).toEqual([])+ expect(logic.values.serviceAccountsFailed).toBe(true)+ })+})diff --git a/products/tasks/frontend/components/TaskConnectorsPicker/taskConnectorsPickerLogic.ts b/products/tasks/frontend/components/TaskConnectorsPicker/taskConnectorsPickerLogic.tsindex 5bd124b5268b..cf3cbeef02e2 100644--- a/products/tasks/frontend/components/TaskConnectorsPicker/taskConnectorsPickerLogic.ts+++ b/products/tasks/frontend/components/TaskConnectorsPicker/taskConnectorsPickerLogic.ts@@ -1,59 +1,178 @@-import { MakeLogicType, afterMount, connect, kea, path } from 'kea'+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'-import { projectLogic } from 'scenes/projectLogic'+import { teamLogic } from 'scenes/teamLogic'-import { mcpServerInstallationsList } from 'products/mcp_store/frontend/generated/api'-import type { MCPServerInstallationApi } from 'products/mcp_store/frontend/generated/api.schemas'+import { teamSharedAgentServers } from 'products/mcp_store/frontend/gateway/agentServerUtils'+import {+ mcpGatewayServersToolsRetrieve,+ mcpGatewayServiceAccountsList,+} from 'products/mcp_store/frontend/generated/api'+import type {+ MCPServiceAccountApi,+ MCPServiceAccountServerApi,+ MCPToolApprovalStateEnumApi,+ ResolvedToolPolicyApi,+} from 'products/mcp_store/frontend/generated/api.schemas'++export type ServerToolPolicyCounts = Record<MCPToolApprovalStateEnumApi, number>// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface taskConnectorsPickerLogicValues {- currentProjectId: number | null // projectLogic- installations: MCPServerInstallationApi[]- installationsLoading: boolean+ currentTeamId: number | null // teamLogic+ serviceAccounts: MCPServiceAccountApi[]+ serviceAccountsFailed: boolean+ serviceAccountsLoading: boolean+ teamWorkflowServers: MCPServiceAccountServerApi[]+ toolPoliciesByServer: Record<string, ResolvedToolPolicyApi[] | 'error'>+ toolPolicyCountsByServer: Record<string, ServerToolPolicyCounts | 'error'>+ workflowAccount: MCPServiceAccountApi | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface taskConnectorsPickerLogicActions {- loadInstallations: () => any- loadInstallationsFailure: (+ loadServiceAccounts: () => any+ loadServiceAccountsFailure: (error: string,errorObject?: any) => {error: stringerrorObject?: any}- loadInstallationsSuccess: (- installations: MCPServerInstallationApi[],+ loadServiceAccountsSuccess: (+ serviceAccounts: MCPServiceAccountApi[],payload?: any) => {- installations: MCPServerInstallationApi[]+ serviceAccounts: MCPServiceAccountApi[]payload?: any}+ loadToolPolicies: (serverId: string) => { serverId: string }+ loadToolPoliciesFailure: (serverId: string) => { serverId: string }+ loadToolPoliciesSuccess: (+ serverId: string,+ tools: ResolvedToolPolicyApi[]+ ) => { serverId: string; tools: ResolvedToolPolicyApi[] }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taskConnectorsPickerLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ workflowAccount: (serviceAccounts: MCPServiceAccountApi[]) => MCPServiceAccountApi | null+ teamWorkflowServers: (workflowAccount: MCPServiceAccountApi | null) => MCPServiceAccountServerApi[]+ toolPolicyCountsByServer: (+ toolPoliciesByServer: Record<string, ResolvedToolPolicyApi[] | 'error'>+ ) => Record<string, ServerToolPolicyCounts | 'error'>+ }}export type taskConnectorsPickerLogicType = MakeLogicType<taskConnectorsPickerLogicValues,- taskConnectorsPickerLogicActions+ taskConnectorsPickerLogicActions,+ Record<string, any>,+ taskConnectorsPickerLogicMeta>+/** The MCP servers a workflow's "Create AI task" step can pick from: what the workflow agent reaches. */export const taskConnectorsPickerLogic = kea<taskConnectorsPickerLogicType>([path(['products', 'tasks', 'frontend', 'components', 'TaskConnectorsPicker', 'taskConnectorsPickerLogic']),connect(() => ({- values: [projectLogic, ['currentProjectId']],+ values: [teamLogic, ['currentTeamId']],})),+ actions({+ loadToolPolicies: (serverId: string) => ({ serverId }),+ loadToolPoliciesSuccess: (serverId: string, tools: ResolvedToolPolicyApi[]) => ({ serverId, tools }),+ loadToolPoliciesFailure: (serverId: string) => ({ serverId }),+ }),loaders(({ values }) => ({- installations: [- [] as MCPServerInstallationApi[],+ serviceAccounts: [+ [] as MCPServiceAccountApi[],{- loadInstallations: async (): Promise<MCPServerInstallationApi[]> => {- const response = await mcpServerInstallationsList(String(values.currentProjectId))+ loadServiceAccounts: async (): Promise<MCPServiceAccountApi[]> => {+ if (values.currentTeamId === null) {+ return []+ }+ const response = await mcpGatewayServiceAccountsList(String(values.currentTeamId), { limit: 500 })return response.results},},],})),- afterMount(({ actions }) => {- actions.loadInstallations()+ reducers({+ // Kept apart from "loaded nothing" so the empty state never shows after a failed load.+ serviceAccountsFailed: [+ false,+ {+ loadServiceAccounts: () => false,+ loadServiceAccountsFailure: () => true,+ },+ ],+ toolPoliciesByServer: [+ {} as Record<string, ResolvedToolPolicyApi[] | 'error'>,+ {+ // A team switch reloads the catalog, so stale per-server results reset with it.+ loadServiceAccounts: () => ({}),+ loadToolPoliciesSuccess: (state, { serverId, tools }) => ({ ...state, [serverId]: tools }),+ loadToolPoliciesFailure: (state, { serverId }) => ({ ...state, [serverId]: 'error' }),+ },+ ],}),+ selectors({+ workflowAccount: [+ (s) => [s.serviceAccounts],+ (serviceAccounts: MCPServiceAccountApi[]): MCPServiceAccountApi | null =>+ serviceAccounts.find((account) => account.agent_key === 'workflow') ?? null,+ ],+ // Workflow runs have no credential owner, so they mount team shares only: offer exactly those.+ teamWorkflowServers: [+ (s) => [s.workflowAccount],+ (workflowAccount: MCPServiceAccountApi | null): MCPServiceAccountServerApi[] =>+ teamSharedAgentServers(workflowAccount?.servers ?? []),+ ],+ toolPolicyCountsByServer: [+ (s) => [s.toolPoliciesByServer],+ (+ toolPoliciesByServer: Record<string, ResolvedToolPolicyApi[] | 'error'>+ ): Record<string, ServerToolPolicyCounts | 'error'> =>+ Object.fromEntries(+ Object.entries(toolPoliciesByServer).map(([serverId, tools]) => {+ if (tools === 'error') {+ return [serverId, 'error']+ }+ const counts: ServerToolPolicyCounts = { approved: 0, needs_approval: 0, do_not_use: 0 }+ for (const tool of tools) {+ counts[tool.policy_state] += 1+ }+ return [serverId, counts]+ })+ ),+ ],+ }),+ listeners(({ actions, values }) => ({+ loadServiceAccountsSuccess: () => {+ for (const server of values.teamWorkflowServers) {+ actions.loadToolPolicies(server.id)+ }+ },+ loadToolPolicies: async ({ serverId }) => {+ const account = values.workflowAccount+ if (values.currentTeamId === null || account === null) {+ return+ }+ try {+ const response = await mcpGatewayServersToolsRetrieve(String(values.currentTeamId), serverId, {+ scope_type: 'agent',+ scope_service_account_id: account.id,+ })+ actions.loadToolPoliciesSuccess(serverId, [...response.results])+ } catch {+ actions.loadToolPoliciesFailure(serverId)+ }+ },+ })),+ subscriptions(({ actions }) => ({+ currentTeamId: () => {+ actions.loadServiceAccounts()+ },+ })),])diff --git a/products/tasks/package.json b/products/tasks/package.jsonindex 707272ae35d3..936a59a685c9 100644--- a/products/tasks/package.json+++ b/products/tasks/package.json@@ -3,7 +3,9 @@"scripts": {"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/logic backend/management backend/temporal -v --tb=short"},- "dependencies": {},+ "dependencies": {+ "@posthog/products-mcp-store": "workspace:*"+ },"devDependencies": {"kea-test-utils": "catalog:"},@@ -16,6 +18,7 @@"kea": "catalog:","kea-loaders": "catalog:","kea-router": "catalog:",+ "kea-subscriptions": "catalog:","react": "*","react-dom": "*"}diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex ec56c3c3392e..50719c67cf09 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -112,7 +112,7 @@ from products.messaging.backend.models import MessageTemplatefrom products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError, render_design_htmlfrom products.notifications.backend.facade.api import publish_resource_editedfrom products.tasks.backend.facade.model_catalogue import TASK_RUN_GATEWAY_PRODUCT, available_model_choices-from products.tasks.backend.facade.workflow_tasks import WorkflowTaskConnectorsInvalid, validate_connectors+from products.tasks.backend.facade.workflow_tasks import WorkflowTaskConnectorsInvalid, resolve_connectorsfrom products.workflows.backend.api.action_redirects import compute_action_redirectsfrom products.workflows.backend.api.graph_operations import _deep_merge, apply_graph_operationsfrom products.workflows.backend.api.graph_validation import validate_graph@@ -1310,15 +1310,20 @@ class HogFlowActionSerializer(serializers.Serializer):connectors = (inputs.get("connectors") or {}).get("value")if connectors:get_team = self.context.get("get_team")- owner_id = self.context.get("workflow_owner_id")- # No team/owner to check against outside a request (internal re-saves) - nothing- # new is being authored there, so there is nothing to validate.- if get_team is not None and owner_id is not None:+ # No team to check against outside a request (internal re-saves) - nothing new is+ # being authored there, so there is nothing to validate.+ if get_team is not None:try:- validate_connectors(get_team().id, owner_id, connectors)+ resolve_connectors(get_team().id, connectors)except WorkflowTaskConnectorsInvalid as e:raise serializers.ValidationError(- {"inputs": {"connectors": f"MCP installation(s) not found or inactive: {e.invalid_ids}"}}+ {+ "inputs": {+ "connectors": (+ f"MCP server(s) not shared with the project or disabled: {e.invalid_ids}"+ )+ }+ })repository = (inputs.get("repository") or {}).get("value")@@ -2565,17 +2570,6 @@ class HogFlowSerializer(HogFlowMinimalSerializer):# binds `self.instance`, so fall back to the flow passed in via context so recovery still works.instance = cast(Optional[HogFlow], self.instance) or self.context.get("instance")- # Who a "Create AI task" step runs as: the existing creator for an update, or the- # requesting user for a brand-new flow (matches the `created_by` a create() actually- # writes). None outside a request (internal re-saves), where connector checks are skipped.- owner = instance.created_by if instance else None- if owner is None:- request = self.context.get("request")- user = getattr(request, "user", None)- if user is not None and getattr(user, "is_authenticated", False):- owner = user- self.context["workflow_owner_id"] = owner.id if owner else None-# Wait conditions the live flow already carries, so per-action validation can tell a newly# introduced clock condition from one we have been storing all along. Seeded here because# nested action validation runs during field processing, before validate() is reached.diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex b0331107bb4e..949cad61a393 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -5507,8 +5507,8 @@ class TestCreateTaskActionValidation(APIBaseTest):def test_accepts_a_connector_the_workflow_owner_can_mount(self):# products.workflows may not depend on products.mcp_store's models directly (tach# boundary) - mocking at the same seam the model-catalogue tests below use.- with patch("products.workflows.backend.api.hog_flow.validate_connectors", return_value=None):- response = self._post_flow({"connectors": {"value": ["some-installation-id"]}})+ with patch("products.workflows.backend.api.hog_flow.resolve_connectors", return_value=["some-server-id"]):+ response = self._post_flow({"connectors": {"value": ["some-server-id"]}})assert response.status_code == status.HTTP_201_CREATED, response.json()diff --git a/products/workflows/backend/api/workflow_tasks.py b/products/workflows/backend/api/workflow_tasks.pyindex 29e68a4b3383..66d2e83b3448 100644--- a/products/workflows/backend/api/workflow_tasks.py+++ b/products/workflows/backend/api/workflow_tasks.py@@ -103,7 +103,7 @@ class WorkflowTaskCreateSerializer(serializers.Serializer):connectors = serializers.ListField(child=serializers.CharField(max_length=64),required=False,- help_text="MCP server installation IDs the run may mount. Must be active team-shared installations or personal ones of the workflow owner.",+ help_text="MCP gateway server IDs the run may mount. Each must be a server shared with everyone in the project.",)posthog_mcp_scopes = serializers.ChoiceField(choices=["read_only", "full"],@@ -197,7 +197,7 @@ class WorkflowTaskViewSet(viewsets.GenericViewSet):repository=data.get("repository") or None,model=data.get("model") or None,reasoning_effort=data.get("reasoning_effort") or None,- mcp_installation_ids=data.get("connectors"),+ connector_ids=data.get("connectors"),posthog_mcp_scopes=data["posthog_mcp_scopes"],max_parallel_tasks=data["max_parallel_tasks"],origin_key=data.get("idempotency_key"),@@ -209,7 +209,7 @@ class WorkflowTaskViewSet(viewsets.GenericViewSet):)except WorkflowTaskConnectorsInvalid as error:raise serializers.ValidationError(- {"connectors": f"MCP installation(s) not found or inactive: {error.invalid_ids}"}+ {"connectors": f"MCP server(s) not shared with the project or disabled: {error.invalid_ids}"})except WorkflowTaskOwnerIneligible:return _rejected("Workflow has no owner who can run tasks.", status.HTTP_422_UNPROCESSABLE_ENTITY)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2098ad1c828c..47870cd5ebb8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9276,6 +9276,7 @@ export namespace Schemas {export const AgentKeyEnum = {Support: 'support',Scout: 'scout',+ Workflow: 'workflow',} as const;/**@@ -50470,6 +50471,8 @@ export namespace Schemas {name: string;/** Server description. */description: string;+ /** MCP server URL. Clients derive a brand icon from it when icon_domain is empty. */+ url: string;/** Deprecated brand icon key. Empty for custom servers. */icon_key: string;/** Brand domain. Empty for custom servers. */@@ -50482,6 +50485,8 @@ export namespace Schemas {* * `disabled` - disabled* * `missing_credential` - missing_credential */connection_state: ConnectionStateEnum;+ /** Whether agent runs can use this grant: the server is enabled for the project and an admin has not revoked the sharing member's access. Independent of connection_state, which reports credential health. */+ reachable: boolean;}export interface MCPServiceAccount {