:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp_store): make agent-level MCP grants personal per-user (#77856)
Chris Volzer3af0cb2cff52
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 89a657d99d2b..bd3f17f6d652 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2073,7 +2073,7 @@ snapshots:errortracking-stacktracedisplay--generic-display-with-stacktrace--light:hash: v1.k794b7964.ae0c08aecfbd10220b331128d6ec8e198a41797b1395076232f7e424e24dd755.UfVTetDNuBKEM3LJ-ZYHVKo-1UDriQklgCRKleHSyMgerrortracking-volumesparkline--compact-issues-list--dark:- hash: v1.k794b7964.bb0dfbb32407e11c00536d45a728f893ad87111830a80eb9753aea7f358fc812.-ezzLGQJjrkNFmi8Nzk5jhR2NG_DDzCS8j9_rnyK99M+ hash: v1.k794b7964.317541200525e015cdb55bc324a804b1e0bb7cc3b893f196e93e2874a46a1b2e.5LUEQXmO_kvqYkwYT-oPy7ZxYQ4QoU7tKLRp9Of3duUerrortracking-volumesparkline--compact-issues-list--light:hash: v1.k794b7964.24c7b32430b53240b2dd850722f89c410377ae29d1c89ba93bd860b581d787c1.bHZSqU3ooYQagaYxml8Rtj7ddEAekUWSvCyFshr-0mUerrortracking-volumesparkline--detailed-full-axis-with-events--dark:@@ -2081,7 +2081,7 @@ snapshots:errortracking-volumesparkline--detailed-full-axis-with-events--light:hash: v1.k794b7964.bdbb4d8591a096fa9da4adc0e99d5ce240f7aaa49783f2d3b9df1bdfceea03bb.gtH820unXuGFwObQJt1i0pKq94v8gHJ5ghayzNzR2L4errortracking-volumesparkline--detailed-mostly-zeros--dark:- hash: v1.k794b7964.63bfcb25f18ca809144f3da86933e6c904bcc1fbaa201e5303a4516c419532dd.P9K9O-Lzyy3HQEVhxOyt4MBRetl2v-cBGcuUurirmCo+ hash: v1.k794b7964.b137a40817f3558f9233f5d259c7d3f67718add0796f4549ea809b6fe084c1ba.mTvfbk7__prwtp76WA-94KSGrrfNF9sJ5jU-M-npYSgerrortracking-volumesparkline--detailed-mostly-zeros--light:hash: v1.k794b7964.4c5e28989a0459c30a10cfd4b094eb968b2c7f8a90d2b4150b68fd07e1f0d723.p9TXOg4rWilz8F-xPv4MTWAdoeuTfC168hULwamX26Yerrortracking-volumesparkline--detailed-overlapping-event-dates--dark:@@ -2093,7 +2093,7 @@ snapshots:errortracking-volumesparkline--detailed-with-spikes--light:hash: v1.k794b7964.c67d13aa6395db8e1f05ce65af76cd198176824962a021d1e461cad73301a928.0PWC4wVqzvPhtBTe0JHZgK-4Ggh0KyWkmupevkyO6Hwerrortracking-volumesparkline--detailed-zeros-and-ones--dark:- hash: v1.k794b7964.664a3161d35020814151df60c77f8d4e45978f48801583ddcda1f8d3555c3149.tjPI1XETiveDpLAmwxdkSCMw7Pmt0mBDz1L3SO0MxeY+ hash: v1.k794b7964.59b176245d6004222d886102238787862c3403e63b8adc3523f37de3f81c9da3.CR1BMTHS6CKOj6ZhcbU1Ifif0SDNqnJ_cawXmXn-8iserrortracking-volumesparkline--detailed-zeros-and-ones--light:hash: v1.k794b7964.b7d1f95e1492bdc399321cc8de1a7c7ee95a421aaf1135717eef2233f0f36621.bSKXY_IbYl5PLJnhRFt2jAelLAPgBH1suxwc-R9h75werrortracking-volumesparkline--events-before-data-range--dark:diff --git a/products/mcp_store/backend/agents.py b/products/mcp_store/backend/agents.pyindex 120dbe6ec9e2..4211dbdd78f2 100644--- a/products/mcp_store/backend/agents.py+++ b/products/mcp_store/backend/agents.py@@ -158,12 +158,25 @@ def get_built_in_agent(team_id: int, agent_key: str) -> MCPServiceAccount | Nonereturn next(account for account in sync_built_in_agents(team) if account.handle == spec.handle)-def create_gateway_agent_token(account: MCPServiceAccount) -> str:- payload = {"service_account_id": str(account.id), "team_id": account.team_id}+@dataclass(frozen=True, kw_only=True)+class GatewayAgentPrincipal:+ """Who a gateway agent token authenticates as: the agent, plus the person+ whose MCP grants the run may use."""++ account: MCPServiceAccount+ credential_owner_id: int+++def create_gateway_agent_token(account: MCPServiceAccount, *, credential_owner_id: int) -> str:+ payload = {+ "service_account_id": str(account.id),+ "team_id": account.team_id,+ "user_id": credential_owner_id,+ }return GATEWAY_AGENT_TOKEN_PREFIX + signing.dumps(payload, salt=GATEWAY_AGENT_TOKEN_SALT)-def resolve_gateway_agent_token(token: str) -> MCPServiceAccount | None:+def resolve_gateway_agent_token(token: str) -> GatewayAgentPrincipal | None:if not token.startswith(GATEWAY_AGENT_TOKEN_PREFIX):return Nonesigned_value = token.removeprefix(GATEWAY_AGENT_TOKEN_PREFIX)@@ -179,14 +192,19 @@ def resolve_gateway_agent_token(token: str) -> MCPServiceAccount | None:return Noneaccount_id = payload.get("service_account_id")team_id = payload.get("team_id")- if not account_id or not isinstance(team_id, int):+ credential_owner_id = payload.get("user_id")+ # Grants are per person, so a token that names no credential owner can+ # authorize nothing. Tokens minted before the claim existed resolve to+ # nothing and expire within GATEWAY_AGENT_TOKEN_MAX_AGE_SECONDS.+ if not account_id or not isinstance(team_id, int) or not isinstance(credential_owner_id, int):return Nonetry:# TeamScopeError: the token can outlive its team — treat a deleted team# like any other invalid token instead of erroring at the auth layer.- return MCPServiceAccount.objects.for_team(team_id).get(+ account = MCPServiceAccount.objects.for_team(team_id).get(id=account_id,handle__in=built_in_agent_handles(),)except (MCPServiceAccount.DoesNotExist, TeamScopeError, ValueError):return None+ return GatewayAgentPrincipal(account=account, credential_owner_id=credential_owner_id)diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.pyindex 926ad37ec22f..3db5e5247f1e 100644--- a/products/mcp_store/backend/facade/api.py+++ b/products/mcp_store/backend/facade/api.py@@ -18,6 +18,7 @@ from products.mcp_store.backend.agents import (is_builtin_agent_enforcement_enabled,)from products.mcp_store.backend.facade.contracts import ActiveInstallationInfo+from products.mcp_store.backend.gateway import installation_for_agent_accessfrom products.mcp_store.backend.models import (MCPServerInstallation,MCPServerInstallationTool,@@ -177,15 +178,18 @@ def get_installations_for_sandbox(include_personal: bool = False,task_origin: str | None = None,task_agent_key: str | None = None,+ credential_owner_id: int | None = None,) -> list[ActiveInstallationInfo]:"""Return MCP installations for sandbox agent use.Generic tasks retain the legacy team-shared installation behavior. Aserver-stamped built-in agent task gets only the credentials explicitly- delegated through its service-account grants, and only while the gateway- server stays enabled for the team. Origin alone is not trusted:- the persisted task agent key must match the origin mapping. A mapped origin- without that marker gets no MCP Store installations. Built-in agent+ delegated through its service-account grants by ``credential_owner_id``,+ the person the run acts for, and only while the gateway server stays+ enabled for the team. Grants are personal, so an agent task without a+ credential owner gets no Store installations at all. Origin alone is not+ trusted: the persisted task agent key must match the origin mapping. A+ mapped origin without that marker gets no MCP Store installations. Built-in agenthandling is gated per team on the `mcp-gateway` rollout flag; teamswithout it resolve mapped origins like unmapped tasks. Unmapped originsretain the legacy member behavior and optionally include the user's@@ -217,28 +221,30 @@ def get_installations_for_sandbox(if agent_key is not None and agent_account is not None and agent_account.status != "active":return []+ installations: list[MCPServerInstallation]if agent_key is not None:- if agent_account is None:+ if agent_account is None or credential_owner_id is None:installations = []else:access_rows = list(MCPServiceAccountServerAccess.objects.for_team(team_id)- .filter(service_account=agent_account)- .values_list("installation_id", "gateway_server_id")+ .filter(service_account=agent_account, user_id=credential_owner_id)+ .select_related("installation__template", "installation__gateway_server"))- bound_servers = {- installation_id: gateway_server_id- for installation_id, gateway_server_id in access_rows- if installation_id is not None- }- # The admin kill switch overrides grants: a server turned off- # for the team is withheld from agents too.- candidates = list(base_queryset.filter(id__in=bound_servers, gateway_server__is_team_enabled=True))- installations = [- installation- for installation in candidates- if bound_servers.get(installation.id) == installation.gateway_server_id- ]+ installations = []+ for access in access_rows:+ # Same resolution the gateway proxy and the API serializers+ # use, so a grant whose credential drifted off its team,+ # server, or owner is dropped here too instead of being+ # mounted into the sandbox.+ installation = installation_for_agent_access(access)+ if installation is None or not installation.is_enabled:+ continue+ # The admin kill switch overrides grants: a server turned+ # off for the team is withheld from agents too.+ if installation.gateway_server is None or not installation.gateway_server.is_team_enabled:+ continue+ installations.append(installation)else:shared_queryset = base_queryset.filter(scope="shared")shared_queryset = shared_queryset.filter(@@ -268,7 +274,11 @@ def get_installations_for_sandbox(if installation.scope == "personal" or installation.url not in personal_urls]- agent_proxy_token = create_gateway_agent_token(agent_account) if agent_account is not None and ready else None+ agent_proxy_token = (+ create_gateway_agent_token(agent_account, credential_owner_id=credential_owner_id)+ if agent_account is not None and credential_owner_id is not None and ready+ else None+ )results = [_to_info(installation,diff --git a/products/mcp_store/backend/gateway.py b/products/mcp_store/backend/gateway.pyindex 26f05759b5b4..d1c2f7adcb60 100644--- a/products/mcp_store/backend/gateway.py+++ b/products/mcp_store/backend/gateway.py@@ -90,11 +90,16 @@ def installation_for_agent_grant(def installation_for_agent_access(access: MCPServiceAccountServerAccess) -> MCPServerInstallation | None:- """Resolve the exact credential bound to an access row."""+ """Resolve the exact credential bound to an access row, which must still be+ the granting person's own connection to that server."""installation = access.installationif installation is None:return None- if installation.team_id != access.team_id or installation.gateway_server_id != access.gateway_server_id:+ if (+ installation.team_id != access.team_id+ or installation.gateway_server_id != access.gateway_server_id+ or installation.user_id != access.user_id+ ):logger.warning("Refusing mismatched agent MCP credential",access_id=str(access.id),diff --git a/products/mcp_store/backend/migrations/0022_mcpserviceaccountserveraccess_user.py b/products/mcp_store/backend/migrations/0022_mcpserviceaccountserveraccess_user.pynew file mode 100644index 000000000000..fe8769580b71--- /dev/null+++ b/products/mcp_store/backend/migrations/0022_mcpserviceaccountserveraccess_user.py@@ -0,0 +1,24 @@+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ("mcp_store", "0021_mcpserverinstallationtool_annotations"),+ ]++ operations = [+ migrations.AddField(+ model_name="mcpserviceaccountserveraccess",+ name="user",+ field=models.ForeignKey(+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ]diff --git a/products/mcp_store/backend/migrations/0023_backfill_agent_access_user.py b/products/mcp_store/backend/migrations/0023_backfill_agent_access_user.pynew file mode 100644index 000000000000..a29eba2adf3a--- /dev/null+++ b/products/mcp_store/backend/migrations/0023_backfill_agent_access_user.py@@ -0,0 +1,35 @@+from django.db import migrations+from django.db.models import OuterRef, Subquery+++def backfill_agent_access_user(apps, schema_editor):+ """Attribute each agent grant to the owner of its bound credential.++ This is an exact attribution, not a guess: every pre-personal-grant write+ path bound the granter's own personal installation, and installation.user+ is non-nullable. Grants whose credential has since been deleted stay+ unattributed on purpose. They can never mount a credential under per-user+ resolution (fail closed), and inventing an owner for them, for example from+ granted_by, would reinstate a share the person may have ended by deleting+ the connection. Whoever wants the sharing back re-shares, which creates a+ fresh attributed row; the NULL row lingers harmlessly (nulls are distinct+ under the 0024 unique index and every read path excludes them) until the+ SET NOT NULL follow-up deletes whatever is still unattributed after the+ rollout window.+ """+ MCPServiceAccountServerAccess = apps.get_model("mcp_store", "MCPServiceAccountServerAccess")+ MCPServerInstallation = apps.get_model("mcp_store", "MCPServerInstallation")++ MCPServiceAccountServerAccess.objects.filter(user__isnull=True, installation__isnull=False).update(+ user_id=Subquery(MCPServerInstallation.objects.filter(pk=OuterRef("installation_id")).values("user_id")[:1])+ )+++class Migration(migrations.Migration):+ dependencies = [+ ("mcp_store", "0022_mcpserviceaccountserveraccess_user"),+ ]++ operations = [+ migrations.RunPython(backfill_agent_access_user, migrations.RunPython.noop),+ ]diff --git a/products/mcp_store/backend/migrations/0024_personal_agent_server_access.py b/products/mcp_store/backend/migrations/0024_personal_agent_server_access.pynew file mode 100644index 000000000000..9a0ec71bea6c--- /dev/null+++ b/products/mcp_store/backend/migrations/0024_personal_agent_server_access.py@@ -0,0 +1,58 @@+from django.db import migrations, models++from posthog.migration_helpers import CreateIndexConcurrently+++class Migration(migrations.Migration):+ """Widen the agent-grant uniqueness key so each member holds their own grant+ for an (agent, server) pair. The old team-wide constraint is dropped in the+ next migration, once this index enforces the widened key.++ ``user`` stays nullable through this release: pods on the previous release+ keep inserting grants without it during the rolling deploy. Nulls are+ distinct under a Postgres unique index, so such a row does not collide+ with the granter's real row. That is an acceptable transient state because+ new code always writes ``user`` and every read path either filters on an+ explicit user id or excludes ``user__isnull=True``, so a null row can+ neither be mounted by an agent nor reach the non-nullable ``user`` /+ ``shared_by`` serializer fields.+ """++ # CREATE INDEX CONCURRENTLY cannot run inside a transaction.+ atomic = False++ dependencies = [+ ("mcp_store", "0023_backfill_agent_access_user"),+ ]++ operations = [+ # Built CONCURRENTLY because this table is written by both old and new+ # pods during the rolling deploy this migration runs in, and a plain+ # AddConstraint would build its backing index under an ACCESS EXCLUSIVE+ # lock that blocks those writes. Built before the old constraint is+ # dropped so the table is never left without uniqueness protection; the+ # old, narrower key implies this one, so the build cannot fail on+ # duplicates. The helper disables lock_timeout and recovers from an+ # invalid leftover build, so bin/migrate retries are safe. Django state+ # gets the matching UniqueConstraint while the database enforces it via+ # the unique index alone.+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddConstraint(+ model_name="mcpserviceaccountserveraccess",+ constraint=models.UniqueConstraint(+ fields=("service_account", "gateway_server", "user"),+ name="uniq_agent_server_access_per_user",+ ),+ ),+ ],+ database_operations=[+ CreateIndexConcurrently(+ index_name="uniq_agent_server_access_per_user",+ table_name="mcp_store_mcpserviceaccountserveraccess",+ columns="(service_account_id, gateway_server_id, user_id)",+ unique=True,+ ),+ ],+ ),+ ]diff --git a/products/mcp_store/backend/migrations/0025_drop_old_agent_server_access.py b/products/mcp_store/backend/migrations/0025_drop_old_agent_server_access.pynew file mode 100644index 000000000000..3ec9405cb54d--- /dev/null+++ b/products/mcp_store/backend/migrations/0025_drop_old_agent_server_access.py@@ -0,0 +1,28 @@+from django.db import migrations+++class Migration(migrations.Migration):+ """Drop the old team-wide (service_account, gateway_server) uniqueness now+ that the per-user unique index from 0024 enforces the widened key.++ Reversing this is only safe while at most one member holds a grant per+ (agent, server). Once a second member has shared the same server with the+ same agent, restoring uniq_agent_server_access fails on duplicate keys, and+ the rows would have to be deduplicated by hand first.++ Kept separate from 0024 so this regular DDL keeps transaction rollback+ safety while the concurrent index build runs with atomic = False.+ """++ dependencies = [+ ("mcp_store", "0024_personal_agent_server_access"),+ ]++ operations = [+ # DROP CONSTRAINT is a fast metadata-only change (brief ACCESS+ # EXCLUSIVE lock, no table scan), so it needs no concurrent variant.+ migrations.RemoveConstraint(+ model_name="mcpserviceaccountserveraccess",+ name="uniq_agent_server_access",+ ),+ ]diff --git a/products/mcp_store/backend/migrations/max_migration.txt b/products/mcp_store/backend/migrations/max_migration.txtindex b6efd88b9ff6..43f83954a3ea 100644--- a/products/mcp_store/backend/migrations/max_migration.txt+++ b/products/mcp_store/backend/migrations/max_migration.txt@@ -1 +1 @@-0021_mcpserverinstallationtool_annotations+0025_drop_old_agent_server_accessdiff --git a/products/mcp_store/backend/models.py b/products/mcp_store/backend/models.pyindex a35e78e40051..60232941af67 100644--- a/products/mcp_store/backend/models.py+++ b/products/mcp_store/backend/models.py@@ -382,11 +382,23 @@ class MCPServiceAccount(TeamScopedRootMixin, UUIDModel):class MCPServiceAccountServerAccess(TeamScopedRootMixin, UUIDModel):- """Grant row: this agent may call this gateway server using one credential."""+ """Grant row: this agent may call this gateway server using one person's+ credential, and only while acting on behalf of that person."""team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)service_account = models.ForeignKey(MCPServiceAccount, on_delete=models.CASCADE, related_name="server_access")gateway_server = models.ForeignKey(MCPGatewayServer, on_delete=models.CASCADE, related_name="agent_access")+ # The person the grant belongs to. An agent run mounts a grant only when+ # this user is the run's credential owner, so one member's connection never+ # backs another member's agent run.+ #+ # Nullable only for the rolling deploy: pods running the previous release+ # write grants without this column, so a NOT NULL constraint would make+ # their inserts fail mid-deploy. Every read path filters on an explicit user+ # id or excludes user__isnull=True, so a transient null row resolves+ # nowhere. NOT NULL is deferred to a follow-up once no deployed code writes+ # grants without a user.+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False, null=True)# Null preserves the grant when its exact credential is deleted, so the UI# can surface that the agent needs a new connection.installation = models.ForeignKey(@@ -411,7 +423,10 @@ class MCPServiceAccountServerAccess(TeamScopedRootMixin, UUIDModel):class Meta:db_table = "mcp_store_mcpserviceaccountserveraccess"constraints = [- models.UniqueConstraint(fields=["service_account", "gateway_server"], name="uniq_agent_server_access"),+ models.UniqueConstraint(+ fields=["service_account", "gateway_server", "user"],+ name="uniq_agent_server_access_per_user",+ ),]diff --git a/products/mcp_store/backend/presentation/agent_views.py b/products/mcp_store/backend/presentation/agent_views.pyindex 7fa1fcc73e7f..ea08fe64fc87 100644--- a/products/mcp_store/backend/presentation/agent_views.py+++ b/products/mcp_store/backend/presentation/agent_views.py@@ -5,9 +5,9 @@ token resolves the team, so there is no project in the URL. Deliberatelyoutside the OpenAPI spec (like the OAuth redirect): it is an external tokensurface, not part of the app schema.-Each grant binds the credential its administrator delegated to the agent.-Every tools/call resolves through the same policy engine as members, under the-agent's own scope.+Grants are personal: the token names the person the run acts for, and only that+person's grants are visible or callable. Every tools/call resolves through the+same policy engine as members, under the agent's own scope."""from collections import defaultdict@@ -32,7 +32,7 @@ from rest_framework.views import APIViewfrom posthog.rate_limit import MCPProxyBurstThrottle, MCPProxySustainedThrottle-from ..agents import resolve_gateway_agent_token+from ..agents import GatewayAgentPrincipal, resolve_gateway_agent_tokenfrom ..gateway import installation_for_agent_accessfrom ..models import MCPServerInstallationTool, MCPServiceAccount, MCPServiceAccountServerAccessfrom ..policy import GatewayCaller, PolicyContext@@ -44,10 +44,16 @@ logger = structlog.get_logger(__name__)class _MCPGatewayAgentThrottle(SimpleRateThrottle):def get_cache_key(self, request: Request, view: APIView) -> str | None:- account = request.auth- if not isinstance(account, MCPServiceAccount):+ principal = request.auth+ if not isinstance(principal, GatewayAgentPrincipal):return None- return self.cache_format % {"scope": self.scope, "ident": account.id}+ # The rate is sized for one person's traffic, so the key includes the+ # credential owner: keyed on the shared agent account alone, one+ # member's burst would throttle every teammate using the same agent.+ return self.cache_format % {+ "scope": self.scope,+ "ident": f"{principal.account.id}:{principal.credential_owner_id}",+ }class MCPGatewayAgentBurstThrottle(_MCPGatewayAgentThrottle):@@ -66,17 +72,17 @@ class GatewayAgentAuthentication(BaseAuthentication):Returns no user — the agent is the principal; downstream code reads it from`request.auth`."""- def authenticate(self, request: Request) -> tuple[Any, MCPServiceAccount] | None:+ def authenticate(self, request: Request) -> tuple[Any, GatewayAgentPrincipal] | None:header = request.headers.get("Authorization", "")if not header.startswith("Bearer "):return Nonetoken = header.split(" ", 1)[1].strip()- account = resolve_gateway_agent_token(token)- if account is None:+ principal = resolve_gateway_agent_token(token)+ if principal is None:raise AuthenticationFailed("Invalid gateway token.")- if account.status != "active":+ if principal.account.status != "active":raise AuthenticationFailed("This agent is paused.")- return (None, account)+ return (None, principal)def authenticate_header(self, request: Request) -> str:return "Bearer"@@ -86,7 +92,7 @@ class GatewayAgentPermission(BasePermission):message = "A valid gateway token is required."def has_permission(self, request: Request, view: Any) -> bool:- return isinstance(request.auth, MCPServiceAccount)+ return isinstance(request.auth, GatewayAgentPrincipal)class MCPGatewayAgentViewSet(viewsets.ViewSet):@@ -96,12 +102,17 @@ class MCPGatewayAgentViewSet(viewsets.ViewSet):permission_classes = [GatewayAgentPermission]throttle_classes = [MCPGatewayAgentBurstThrottle, MCPGatewayAgentSustainedThrottle]- def _accessible_server_access(self, account: MCPServiceAccount) -> list[MCPServiceAccountServerAccess]:+ def _accessible_server_access(self, principal: GatewayAgentPrincipal) -> list[MCPServiceAccountServerAccess]:# The admin kill switch overrides grants: a server turned off for the# team disappears from the agent catalog like it does for members.+ account = principal.accountreturn list(MCPServiceAccountServerAccess.objects.for_team(account.team_id)- .filter(service_account=account, gateway_server__is_team_enabled=True)+ .filter(+ service_account=account,+ user_id=principal.credential_owner_id,+ gateway_server__is_team_enabled=True,+ ).select_related("gateway_server__template", "installation").order_by("gateway_server__name"))@@ -114,9 +125,10 @@ class MCPGatewayAgentViewSet(viewsets.ViewSet):def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:"""The agent's server catalog: every enabled server it has access to,with each tool's effective policy state."""- account = cast(MCPServiceAccount, request.auth)+ principal = cast(GatewayAgentPrincipal, request.auth)+ account = principal.accountcatalog_entries = [- (access, installation_for_agent_access(access)) for access in self._accessible_server_access(account)+ (access, installation_for_agent_access(access)) for access in self._accessible_server_access(principal)]active_entries = [(access, installation)@@ -181,14 +193,19 @@ class MCPGatewayAgentViewSet(viewsets.ViewSet):@action(detail=True, methods=["post"], url_path="proxy", renderer_classes=[MCPProxyRenderer])def proxy(self, request: Request, pk: str | None = None, *args: Any, **kwargs: Any) -> HttpResponseBase:"""Proxy one MCP request to the server as this agent."""- account = cast(MCPServiceAccount, request.auth)+ principal = cast(GatewayAgentPrincipal, request.auth)+ account = principal.accountif not pk:return HttpResponse('{"error": "Server not found"}', content_type="application/json", status=404)try:access = (MCPServiceAccountServerAccess.objects.for_team(account.team_id).select_related("gateway_server", "installation")- .get(service_account=account, gateway_server_id=pk)+ .get(+ service_account=account,+ gateway_server_id=pk,+ user_id=principal.credential_owner_id,+ ))except (MCPServiceAccountServerAccess.DoesNotExist, ValueError):return HttpResponse(@@ -216,6 +233,7 @@ class MCPGatewayAgentViewSet(viewsets.ViewSet):team_id=account.team_id,gateway_server_id=str(server.id),service_account_id=str(account.id),+ credential_owner_id=principal.credential_owner_id,)ok, error_response = validate_installation_auth(installation)diff --git a/products/mcp_store/backend/presentation/gateway_views.py b/products/mcp_store/backend/presentation/gateway_views.pyindex 615d8aa41a3d..93cd7ee72603 100644--- a/products/mcp_store/backend/presentation/gateway_views.py+++ b/products/mcp_store/backend/presentation/gateway_views.py@@ -196,16 +196,17 @@ class GatewayYourConnectionSerializer(serializers.Serializer):class GatewayAgentAccessSerializer(serializers.Serializer):- """One agent's access to a gateway server."""+ """One agent's access to a gateway server, on behalf of one member."""service_account_id = serializers.UUIDField(help_text="Service account granted access.")+ user = UserBasicSerializer(help_text="The member whose connection the agent uses.")name = serializers.CharField(help_text="Agent display name.")handle = serializers.CharField(help_text="Agent identity handle, e.g. posthog-support.")status = serializers.ChoiceField(choices=SERVICE_ACCOUNT_STATUS_CHOICES, help_text="active, or paused (all access off).")last_active_at = serializers.DateTimeField(allow_null=True, help_text="When the agent last made a call.")- granted_by = UserBasicSerializer(allow_null=True, help_text="Admin who shared this server with the agent.")+ granted_by = UserBasicSerializer(allow_null=True, help_text="Member who shared this server with the agent.")def _installation_pending_oauth(installation: MCPServerInstallation) -> bool:@@ -354,13 +355,20 @@ class MCPGatewayServerSerializer(serializers.ModelSerializer):return [{"service_account_id": access.service_account_id,+ "user": UserBasicSerializer(access.user).data,"name": access.service_account.name,"handle": access.service_account.handle,"status": access.service_account.status,"last_active_at": access.service_account.last_active_at,"granted_by": UserBasicSerializer(access.granted_by).data if access.granted_by else None,}+ # A grant written by a pod on the previous release can still be+ # missing its user while the deploy rolls. It resolves for nobody,+ # and `user` is not nullable on the serializer. The list queryset+ # already excludes those, but this serializer is also used on+ # objects fetched without that prefetch.for access in obj.agent_access.all()+ if access.user_id is not None]@extend_schema_field(serializers.ListField(child=serializers.IntegerField()))@@ -569,6 +577,7 @@ class MCPServiceAccountServerSerializer(serializers.Serializer):"""A credential-safe summary of a server configured for an agent."""id = serializers.UUIDField(help_text="Gateway server granted to the agent.")+ shared_by = UserBasicSerializer(help_text="The member whose connection the agent uses.")name = serializers.CharField(help_text="Server display name.")description = serializers.CharField(help_text="Server description.")icon_key = serializers.CharField(help_text="Deprecated brand icon key. Empty for custom servers.")@@ -646,6 +655,7 @@ class MCPServiceAccountSerializer(serializers.ModelSerializer):servers.append({"id": server.id,+ "shared_by": UserBasicSerializer(access.user).data,"name": server.name,"description": server.description,"icon_key": server.template.icon_key if server.template else "",@@ -666,8 +676,18 @@ class MCPServiceAccountUpdateSerializer(serializers.ModelSerializer):class ServiceAccountAccessUpdateSerializer(serializers.Serializer):- gateway_server_id = serializers.UUIDField(help_text="Gateway server to grant or revoke.")- enabled = serializers.BooleanField(help_text="True grants access, false revokes it.")+ gateway_server_id = serializers.UUIDField(help_text="Gateway server to share or stop sharing.")+ enabled = serializers.BooleanField(+ help_text="True shares the caller's own connection with the agent, false removes the caller's share."+ )+ all = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Only valid with enabled=false. Removes every member's share of this server with this agent, "+ "along with the agent's tool policies for it. Project admins only."+ ),+ )policies = serializers.ListField(child=ToolPolicyEntrySerializer(),max_length=MAX_TOOL_POLICIES_PER_REQUEST,@@ -679,6 +699,11 @@ class ServiceAccountAccessUpdateSerializer(serializers.Serializer):),)+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ if attrs.get("all") and attrs["enabled"]:+ raise serializers.ValidationError({"all": "Removing every member's share requires enabled=false."})+ return attrs+class MCPOrgRuleSerializer(serializers.ModelSerializer):class Meta:@@ -833,9 +858,13 @@ class MCPGatewayServerViewSet(),Prefetch("agent_access",- queryset=MCPServiceAccountServerAccess.objects.unscoped().select_related(- "service_account", "granted_by"- ),+ # A grant written by a pod on the previous release can still+ # be missing its user while the deploy rolls. Such a row+ # resolves for nobody, and GatewayAgentAccessSerializer.user+ # is not nullable, so it must not reach the serializer.+ queryset=MCPServiceAccountServerAccess.objects.unscoped()+ .exclude(user__isnull=True)+ .select_related("service_account", "granted_by", "user"),),"member_revocations",)@@ -1144,8 +1173,12 @@ class MCPServiceAccountViewSet(def _server_access_prefetch(self) -> Prefetch:return Prefetch("server_access",+ # See MCPGatewayServerViewSet.safely_get_queryset: a user-less grant+ # from a previous-release pod resolves for nobody, and+ # MCPServiceAccountServerSerializer.shared_by is not nullable.queryset=MCPServiceAccountServerAccess.objects.for_team(self.team_id)- .select_related("gateway_server__template", "installation")+ .exclude(user__isnull=True)+ .select_related("gateway_server__template", "installation", "user").order_by("gateway_server__name"),)@@ -1185,7 +1218,17 @@ class MCPServiceAccountViewSet()@action(detail=True, methods=["post"], url_path="access")def access(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Grant or revoke this agent's access to one gateway server."""+ """Share, or stop sharing, one gateway server with this agent.++ Sharing is personal. `enabled=true` delegates the caller's own+ connection, and the agent may use it only when acting for the caller.+ `enabled=false` removes the caller's own share and leaves other members'+ shares, and the agent's tool policies, in place.++ Project admins can send `all=true` alongside `enabled=false` to remove+ every member's share of this server with this agent, along with the+ agent's tool policies for it.+ """self._require_agent_access_manager()account = self.get_object()data = request.validated_data@@ -1236,6 +1279,7 @@ class MCPServiceAccountViewSet(MCPServiceAccountServerAccess.objects.for_team(self.team_id).update_or_create(service_account=account,gateway_server=server,+ user=user,defaults={"team_id": self.team_id,"installation": installation,@@ -1252,7 +1296,8 @@ class MCPServiceAccountViewSet(scope_service_account=account,defaults={"state": entry["policy_state"]},)- else:+ elif data.get("all"):+ self._require_project_admin()with transaction.atomic():MCPServiceAccountServerAccess.objects.for_team(self.team_id).filter(service_account=account,@@ -1261,11 +1306,25 @@ class MCPServiceAccountViewSet(MCPToolPolicy.objects.for_team(self.team_id).filter(gateway_server=server, scope_type="agent", scope_service_account=account).delete()+ else:+ # Agent-scope tool policies describe what the agent may call for+ # every member sharing this server, so one member withdrawing their+ # own connection must leave them alone.+ MCPServiceAccountServerAccess.objects.for_team(self.team_id).filter(+ service_account=account,+ gateway_server=server,+ user=cast(User, request.user),+ ).delete()report_user_action(cast(User, request.user),"mcp_gateway agent access changed",- properties={"handle": account.handle, "server_name": server.name, "enabled": data["enabled"]},+ properties={+ "handle": account.handle,+ "server_name": server.name,+ "enabled": data["enabled"],+ "all_members": bool(data.get("all")),+ },team=self.team,)prefetch_related_objects([account], self._server_access_prefetch())diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.pyindex 68aa72e9cdea..fbcd3a4ac6d2 100644--- a/products/mcp_store/backend/presentation/views.py+++ b/products/mcp_store/backend/presentation/views.py@@ -852,6 +852,26 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetdef _wants_team_gateway_options(data: dict) -> bool:return not data.get("team_enabled", True)+ def _install_target_owner_id(self, data: dict) -> int | None:+ """Owner of the connection this install flow would end up delegating.++ A personal install is keyed on the caller, so it is always the caller's.+ A shared install reuses a row keyed on (team, url) that another member+ may own, and there is no such row yet when the install creates one.+ """+ user_id = cast(User, self.request.user).id+ if data.get("scope", "personal") != "shared":+ return user_id+ url = (data.get("url") or "").strip()+ template_id = data.get("template_id")+ if not url and template_id:+ template = MCPServerTemplate.objects.filter(id=template_id, is_active=True).first()+ url = template.url if template is not None else ""+ if not url:+ return user_id+ existing = MCPServerInstallation.objects.filter(team_id=self.team_id, url=url, scope="shared").first()+ return existing.user_id if existing is not None else user_id+def _validate_gateway_options(self, data: dict) -> None:"""Validate team-level options and agent grants before creating rows."""if self._wants_team_gateway_options(data) and not self._is_project_admin():@@ -867,6 +887,14 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetif not agent_ids.issubset(built_in_agent_ids):raise serializers.ValidationError({"agent_ids": "Select only the PostHog agents listed for this project."})+ # Rejected here rather than while applying the grants: by then the+ # install has already written the gateway rows and the credential, and+ # a 4xx would leave that half-finished install behind.+ if self._install_target_owner_id(data) != cast(User, self.request.user).id:+ raise serializers.ValidationError(+ {"agent_ids": "You can only share a connection you set up yourself with an agent."}+ )+def _apply_gateway_options(self, installation: MCPServerInstallation, data: dict) -> None:"""Register the installation with the gateway and apply install-timeteam options (enablement, personal connections, agent shares).@@ -883,7 +911,8 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet{"agent_ids": "One or more selected PostHog agents are no longer available. Refresh and try again."})- server = link_installation_to_gateway(installation, created_by=cast(User, self.request.user))+ user = cast(User, self.request.user)+ server = link_installation_to_gateway(installation, created_by=user)if self._wants_team_gateway_options(data):team_enabled = data.get("team_enabled", True)@@ -895,10 +924,11 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetMCPServiceAccountServerAccess.objects.for_team(self.team_id).update_or_create(service_account=account,gateway_server=server,+ user=user,defaults={"team_id": self.team_id,"installation": installation,- "granted_by": cast(User, self.request.user),+ "granted_by": user,},)diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.pyindex 540da9a15ffe..07c9a1e64be3 100644--- a/products/mcp_store/backend/test/test_api.py+++ b/products/mcp_store/backend/test/test_api.py@@ -1137,12 +1137,19 @@ class TestMCPServiceAccountAPI(APIBaseTest):def _active_scout_account(self) -> MCPServiceAccount:return next(agent for agent in sync_built_in_agents(self.team) if agent.handle == "posthog-scout")- @staticmethod- def _agent_client(account: MCPServiceAccount, token: str | None = None) -> APIClient:+ def _agent_client(self, account: MCPServiceAccount, token: str | None = None) -> APIClient:client = APIClient()- client.credentials(HTTP_AUTHORIZATION=f"Bearer {token or create_gateway_agent_token(account)}")+ client.credentials(+ HTTP_AUTHORIZATION=f"Bearer {token or self._agent_token(account)}",+ )return client+ def _agent_token(self, account: MCPServiceAccount, *, credential_owner_id: int | None = None) -> str:+ return create_gateway_agent_token(+ account,+ credential_owner_id=credential_owner_id if credential_owner_id is not None else self.user.id,+ )+def _oauth_client(self, *, built_in_agent: bool) -> APIClient:application = OAuthApplication.objects.create(name="Sandbox agent",@@ -1354,6 +1361,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):member_response = self.client.get(self._api_url())scout = next(row for row in member_response.json()["results"] if row["agent_key"] == "scout")+ assert [server.pop("shared_by")["id"] for server in scout["servers"]] == [self.user.id]assert scout["servers"] == [{"id": str(server.id),@@ -1468,6 +1476,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):)access = MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(team=self.team,+ user=self.user,service_account=account,gateway_server=server,installation=installation,@@ -1503,6 +1512,101 @@ class TestMCPServiceAccountAPI(APIBaseTest):assert admin_revoke_response.status_code == status.HTTP_200_OKassert not MCPServiceAccountServerAccess.objects.for_team(self.team.id).filter(id=access.id).exists()+ def _server_shared_by_two_members(self, account: MCPServiceAccount) -> tuple[MCPGatewayServer, User]:+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Team Notion",+ url="https://mcp.team-notion.example.com/mcp",+ )+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ for owner in (self.user, teammate):+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=owner,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "secret"},+ scope="personal",+ gateway_server=server,+ )+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ user=owner,+ service_account=account,+ gateway_server=server,+ installation=installation,+ granted_by=owner,+ )+ MCPToolPolicy.objects.for_team(self.team.id).create(+ team=self.team,+ gateway_server=server,+ tool_name="create_issue",+ scope_type="agent",+ scope_service_account=account,+ state="do_not_use",+ )+ return server, teammate++ def _agent_grant_user_ids(self, account: MCPServiceAccount, server: MCPGatewayServer) -> list[int]:+ return sorted(+ MCPServiceAccountServerAccess.objects.for_team(self.team.id)+ .filter(service_account=account, gateway_server=server)+ .values_list("user_id", flat=True)+ )++ def _agent_policy_exists(self, account: MCPServiceAccount, server: MCPGatewayServer) -> bool:+ return (+ MCPToolPolicy.objects.for_team(self.team.id)+ .filter(gateway_server=server, scope_type="agent", scope_service_account=account)+ .exists()+ )++ def test_member_unshare_leaves_teammate_shares_and_agent_tool_policies_alone(self) -> None:+ self._make_member()+ account = self._active_scout_account()+ server, teammate = self._server_shared_by_two_members(account)++ response = self.client.post(+ self._api_url(f"{account.id}/access/"),+ data={"gateway_server_id": str(server.id), "enabled": False},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ assert self._agent_grant_user_ids(account, server) == [teammate.id]+ assert self._agent_policy_exists(account, server)++ def test_admin_can_remove_every_members_share_of_a_server(self) -> None:+ self._make_admin()+ account = self._active_scout_account()+ server, _teammate = self._server_shared_by_two_members(account)++ response = self.client.post(+ self._api_url(f"{account.id}/access/"),+ data={"gateway_server_id": str(server.id), "enabled": False, "all": True},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ assert self._agent_grant_user_ids(account, server) == []+ assert not self._agent_policy_exists(account, server)++ def test_member_cannot_remove_every_members_share_of_a_server(self) -> None:+ self._make_member()+ account = self._active_scout_account()+ server, teammate = self._server_shared_by_two_members(account)++ response = self.client.post(+ self._api_url(f"{account.id}/access/"),+ data={"gateway_server_id": str(server.id), "enabled": False, "all": True},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert self._agent_grant_user_ids(account, server) == sorted([self.user.id, teammate.id])+ assert self._agent_policy_exists(account, server)+def test_only_admin_can_update_member_agent_access_setting(self) -> None:self._make_member()config_url = f"/api/projects/{self.team.id}/mcp_gateway/config/"@@ -1557,6 +1661,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):)MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(team=self.team,+ user=self.user,service_account=account,gateway_server=server,granted_by=self.user,@@ -1567,6 +1672,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKscout = next(row for row in response.json()["results"] if row["agent_key"] == "scout")+ assert [server.pop("shared_by")["id"] for server in scout["servers"]] == [self.user.id]assert scout["servers"] == [{"id": str(server.id),@@ -1607,6 +1713,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):)access = MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(team=self.team,+ user=self.user,service_account=account,gateway_server=server,installation=personal_installation,@@ -1624,7 +1731,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):def test_agent_endpoint_rejects_tampered_signed_token(self) -> None:account = self._active_scout_account()- token = create_gateway_agent_token(account)+ token = self._agent_token(account)tampered_token = f"{token[:-1]}{'a' if token[-1] != 'a' else 'b'}"response = self._agent_client(account, tampered_token).get("/api/mcp_store/gateway/servers/")@@ -1668,7 +1775,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):def test_agent_endpoint_rechecks_pause_after_mint(self) -> None:account = self._active_scout_account()- token = create_gateway_agent_token(account)+ token = self._agent_token(account)client = self._agent_client(account, token)account.status = "paused"@@ -1694,14 +1801,18 @@ class TestMCPServiceAccountAPI(APIBaseTest):),])- def test_agent_gateway_rate_limits_are_scoped_per_service_account(+ def test_agent_gateway_rate_limits_are_scoped_per_account_and_credential_owner(self, _name: str, method: str, url: str, allowed_status: int) -> None:accounts = sync_built_in_agents(self.team)primary_account = next(account for account in accounts if account.handle == "posthog-scout")secondary_account = next(account for account in accounts if account.handle == "posthog-support")+ other_member = User.objects.create_and_join(self.organization, "[email protected]", "password")primary_client = self._agent_client(primary_account)secondary_client = self._agent_client(secondary_account)+ other_owner_client = self._agent_client(+ primary_account, self._agent_token(primary_account, credential_owner_id=other_member.id)+ )cache.clear()self.addCleanup(cache.clear)@@ -1718,10 +1829,12 @@ class TestMCPServiceAccountAPI(APIBaseTest):first_response = primary_client.generic(method, url, REMOTE_ADDR="192.0.2.1")throttled_response = primary_client.generic(method, url, REMOTE_ADDR="192.0.2.2")secondary_response = secondary_client.generic(method, url, REMOTE_ADDR="192.0.2.1")+ other_owner_response = other_owner_client.generic(method, url, REMOTE_ADDR="192.0.2.1")assert first_response.status_code == allowed_statusassert throttled_response.status_code == status.HTTP_429_TOO_MANY_REQUESTSassert secondary_response.status_code == allowed_status+ assert other_owner_response.status_code == allowed_status@parameterized.expand([@@ -1744,6 +1857,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):if scenario == "revoked":access = MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(team=self.team,+ user=self.user,service_account=account,gateway_server=server,granted_by=self.user,@@ -1759,6 +1873,47 @@ class TestMCPServiceAccountAPI(APIBaseTest):assert response.status_code == status.HTTP_404_NOT_FOUNDmock_proxy.assert_not_called()+ @patch("products.mcp_store.backend.presentation.agent_views.proxy_mcp_request")+ def test_agent_cannot_use_a_grant_belonging_to_another_member(self, mock_proxy) -> None:+ account = self._active_scout_account()+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Personal grant",+ url="https://mcp.personal-grant.example.com/mcp",+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=self.user,+ display_name="Personal",+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "secret"},+ scope="personal",+ gateway_server=server,+ )+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ user=self.user,+ service_account=account,+ gateway_server=server,+ installation=installation,+ granted_by=self.user,+ )+ client = self._agent_client(account, self._agent_token(account, credential_owner_id=other_user.id))++ catalog_response = client.get("/api/mcp_store/gateway/servers/")+ proxy_response = client.post(+ f"/api/mcp_store/gateway/servers/{server.id}/proxy/",+ data={"jsonrpc": "2.0", "method": "tools/list", "id": 1},+ format="json",+ )++ assert catalog_response.status_code == status.HTTP_200_OK+ assert catalog_response.json()["results"] == []+ assert proxy_response.status_code == status.HTTP_404_NOT_FOUND+ mock_proxy.assert_not_called()+@patch("products.mcp_store.backend.presentation.agent_views.proxy_mcp_request")def test_agent_proxy_rejects_server_disabled_for_team(self, mock_proxy) -> None:account = self._active_scout_account()@@ -1780,6 +1935,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):)MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(team=self.team,+ user=self.user,service_account=account,gateway_server=server,installation=installation,@@ -1821,6 +1977,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):)MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(team=self.team,+ user=self.user,service_account=account,gateway_server=server,installation=installation,@@ -1905,7 +2062,9 @@ class TestMCPServiceAccountAPI(APIBaseTest):gateway_server=granted_server,)assert access.installation == personal_installation- assert grant_response.json()["servers"] == [+ granted_servers = grant_response.json()["servers"]+ assert [server.pop("shared_by")["id"] for server in granted_servers] == [self.user.id]+ assert granted_servers == [{"id": str(granted_server.id),"name": "Agent only",@@ -1918,7 +2077,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):account = MCPServiceAccount.objects.for_team(self.team.id).get(id=scout["id"])agent_client = APIClient()- agent_client.credentials(HTTP_AUTHORIZATION=f"Bearer {create_gateway_agent_token(account)}")+ agent_client.credentials(HTTP_AUTHORIZATION=f"Bearer {self._agent_token(account)}")dormant_response = agent_client.get("/api/mcp_store/gateway/servers/")assert dormant_response.status_code == status.HTTP_200_OK@@ -1972,6 +2131,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):)MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(team=self.team,+ user=self.user,service_account=account,gateway_server=server,installation=installation,diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.pyindex 93c25b4d339d..623677699ec2 100644--- a/products/mcp_store/backend/test/test_facade.py+++ b/products/mcp_store/backend/test/test_facade.py@@ -281,6 +281,7 @@ class TestGetInstallationsForSandbox(BaseTest):)MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(team_id=self.team.id,+ user=self.user,service_account=account,gateway_server=granted_server,installation=personal,@@ -293,6 +294,7 @@ class TestGetInstallationsForSandbox(BaseTest):include_personal=True,task_origin="support_reply",task_agent_key="support",+ credential_owner_id=self.user.id,)assert [result.id for result in results] == [str(personal.id)]@@ -307,6 +309,7 @@ class TestGetInstallationsForSandbox(BaseTest):self.team.id,task_origin="support_reply",task_agent_key="support",+ credential_owner_id=self.user.id,)== [])@@ -319,6 +322,7 @@ class TestGetInstallationsForSandbox(BaseTest):user_id=self.user.id,include_personal=True,task_origin="support_reply",+ credential_owner_id=self.user.id,)assert unstamped_results == []@@ -328,9 +332,36 @@ class TestGetInstallationsForSandbox(BaseTest):include_personal=True,task_origin="support_reply",task_agent_key="scout",+ credential_owner_id=self.user.id,)assert mismatched_results == []+ def test_built_in_agent_only_gets_the_run_credential_owner_s_grants(self) -> None:+ account = self._support_agent()+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")+ server = self._create_gateway_server(name="Granted", url="https://granted.example.com/mcp")+ delegated = self._create_installation(scope="personal", gateway_server=server, url=server.url)+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ user=self.user,+ service_account=account,+ gateway_server=server,+ installation=delegated,+ granted_by=self.user,+ )++ def resolve(credential_owner_id: int | None) -> list[ActiveInstallationInfo]:+ return get_installations_for_sandbox(+ self.team.id,+ task_origin="support_reply",+ task_agent_key="support",+ credential_owner_id=credential_owner_id,+ )++ assert [result.id for result in resolve(self.user.id)] == [str(delegated.id)]+ assert resolve(other_user.id) == []+ assert resolve(None) == []+def test_built_in_agent_does_not_fall_back_after_delegated_credential_is_deleted(self) -> None:account = self._support_agent()server = self._create_gateway_server(@@ -351,6 +382,7 @@ class TestGetInstallationsForSandbox(BaseTest):)access = MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(team_id=self.team.id,+ user=self.user,service_account=account,gateway_server=server,installation=delegated,@@ -366,6 +398,7 @@ class TestGetInstallationsForSandbox(BaseTest):self.team.id,task_origin="support_reply",task_agent_key="support",+ credential_owner_id=self.user.id,)== [])@@ -376,6 +409,7 @@ class TestGetInstallationsForSandbox(BaseTest):delegated = self._create_installation(scope="personal", gateway_server=server, url=server.url)MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(team_id=self.team.id,+ user=self.user,service_account=account,gateway_server=server,installation=delegated,@@ -386,6 +420,7 @@ class TestGetInstallationsForSandbox(BaseTest):self.team.id,task_origin="support_reply",task_agent_key="support",+ credential_owner_id=self.user.id,)assert [result.id for result in results] == [str(delegated.id)]@@ -397,6 +432,7 @@ class TestGetInstallationsForSandbox(BaseTest):self.team.id,task_origin="support_reply",task_agent_key="support",+ credential_owner_id=self.user.id,)== [])diff --git a/products/mcp_store/backend/test/test_gateway.py b/products/mcp_store/backend/test/test_gateway.pynew file mode 100644index 000000000000..366c350f705f--- /dev/null+++ b/products/mcp_store/backend/test/test_gateway.py@@ -0,0 +1,55 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.models import User++from products.mcp_store.backend.gateway import installation_for_agent_access+from products.mcp_store.backend.models import (+ MCPGatewayServer,+ MCPServerInstallation,+ MCPServiceAccount,+ MCPServiceAccountServerAccess,+)+++class TestInstallationForAgentAccess(BaseTest):+ @parameterized.expand([("same_owner", True), ("other_member", False)])+ def test_resolves_only_a_credential_owned_by_the_granting_member(+ self, _name: str, installation_owned_by_granter: bool+ ) -> None:+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Notion",+ url="https://mcp.agent-access.example.com/mcp",+ )+ installation_owner = self.user if installation_owned_by_granter else teammate+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=installation_owner,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "secret"},+ scope="personal",+ gateway_server=server,+ )+ account = MCPServiceAccount.objects.for_team(self.team.id).create(+ team=self.team,+ name="Scout",+ handle="posthog-scout",+ token_hash="agent-access-token-hash",+ )+ access = MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ user=self.user,+ service_account=account,+ gateway_server=server,+ installation=installation,+ granted_by=self.user,+ )++ resolved = installation_for_agent_access(access)++ assert resolved == (installation if installation_owned_by_granter else None)diff --git a/products/mcp_store/frontend/gateway/GatewayAgentScene.tsx b/products/mcp_store/frontend/gateway/GatewayAgentScene.tsxindex d3fa2126b80e..5d0dc9c90914 100644--- a/products/mcp_store/frontend/gateway/GatewayAgentScene.tsx+++ b/products/mcp_store/frontend/gateway/GatewayAgentScene.tsx@@ -15,8 +15,8 @@ import type { ConnectionStateEnumApi, MCPGatewayServerApi } from '../generated/aimport { ServerIcon } from '../scene/icons'import { GatewayAgentLogicProps, gatewayAgentLogic } from './gatewayAgentLogic'import { GatewayRouteGuard } from './GatewayRouteGuard'-import { DecisionTag } from './gatewayUtils'-import { agentServerAccessKey } from './mcpGatewayLogic'+import { DecisionTag, RemoveAllSharesButton, sharedByLabel } from './gatewayUtils'+import { AgentServerShare, agentServerAccessKey } from './mcpGatewayLogic'export const scene: SceneExport<(typeof gatewayAgentLogic)['props']> = {component: GatewayAgentRouteScene,@@ -51,9 +51,11 @@ export function GatewayAgentScene({agentServerAccessLoadingKeys,allServers,allServersLoading,+ currentUserId,recentCalls,recentCallsLoading,sharedServers,+ sharesByServerId,unsharedServers,visibleRecentCalls,} = useValues(gatewayAgentLogic)@@ -83,6 +85,11 @@ export function GatewayAgentScene({const paused = account.status === 'paused'const statusLoading = accountStatusLoadingIds.has(account.id)+ const yourConnectionState = (serverId: string): ConnectionStateEnumApi | undefined =>+ account.servers.find(+ (accountServer) => accountServer.id === serverId && accountServer.shared_by.id === currentUserId+ )?.connection_state+return (<SceneContent><BackToTeamButton onBack={onBack} />@@ -140,6 +147,9 @@ export function GatewayAgentScene({{sharedServers.length} of {allServers.length}</LemonTag></div>+ <div className="text-sm text-secondary">+ Sharing is personal. {account.name} uses your connection only when it runs for you.+ </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">@@ -158,10 +168,8 @@ export function GatewayAgentScene({accountId={account.id}accountName={account.name}shared- connectionState={- account.servers.find((accountServer) => accountServer.id === server.id)- ?.connection_state- }+ share={sharesByServerId[server.id]}+ connectionState={yourConnectionState(server.id)}loading={agentServerAccessLoadingKeys.has(agentServerAccessKey(account.id, server.id))}@@ -181,6 +189,7 @@ export function GatewayAgentScene({accountId={account.id}accountName={account.name}shared={false}+ share={sharesByServerId[server.id]}loading={agentServerAccessLoadingKeys.has(agentServerAccessKey(account.id, server.id))}@@ -261,6 +270,7 @@ function ServerAccessRow({accountId,accountName,shared,+ share,connectionState,loading,onSetAccess,@@ -270,12 +280,16 @@ function ServerAccessRow({accountId: stringaccountName: stringshared: boolean+ share?: AgentServerShareconnectionState?: ConnectionStateEnumApiloading: booleanonSetAccess: (accountId: string, serverId: string, enabled: boolean) => voidonOpenServer?: (serverId: string, scope: string) => void}): JSX.Element {- const connectionDisabledReason = shared ? undefined : agentShareDisabledReason(server)+ const sharedByYou = Boolean(share?.sharedByYou)+ const sharedByOthers = share?.sharedByOthers ?? []+ const attribution = sharedByLabel(sharedByOthers)+ const connectionDisabledReason = sharedByYou ? undefined : agentShareDisabledReason(server)const toolLabel = `${server.tool_count} ${server.tool_count === 1 ? 'tool' : 'tools'}`const connectionStatus = connectionState ? agentConnectionStatus(connectionState) : null@@ -284,15 +298,14 @@ function ServerAccessRow({<ServerIcon iconDomain={server.icon_domain} serverUrl={server.url} size={28} /><div className="flex-1 min-w-0"><div className="font-semibold truncate">{server.name}</div>- <div className="text-xs text-secondary">- {toolLabel}- {shared ? ' available to this agent' : ''}+ <div className="text-xs text-secondary truncate">+ {sharedByYou ? `${toolLabel} available to this agent` : (attribution ?? toolLabel)}</div>- {shared && connectionStatus && connectionState !== 'ready' && (+ {sharedByYou && connectionStatus && connectionState !== 'ready' && (<div className="text-xs text-warning">{connectionStatus.detail}</div>)}</div>- {shared && connectionStatus && (+ {sharedByYou && connectionStatus && (<LemonTag type={connectionState === 'ready' ? 'success' : 'warning'} size="small">{connectionStatus.label}</LemonTag>@@ -307,11 +320,20 @@ function ServerAccessRow({Tool policies</LemonButton>)}+ {sharedByOthers.length > 0 && (+ <RemoveAllSharesButton+ accountId={accountId}+ accountName={accountName}+ serverId={server.id}+ serverName={server.name}+ shareCount={sharedByOthers.length + (sharedByYou ? 1 : 0)}+ />+ )}<LemonSwitch- checked={shared}+ checked={sharedByYou}loading={loading}disabledReason={connectionDisabledReason}- aria-label={`${shared ? 'Revoke' : 'Grant'} ${accountName} access to ${server.name}`}+ aria-label={`${sharedByYou ? 'Stop sharing' : 'Share'} your ${server.name} connection with ${accountName}`}onChange={(checked) => {if (!loading && (!checked || !connectionDisabledReason)) {onSetAccess(accountId, server.id, checked)diff --git a/products/mcp_store/frontend/gateway/GatewayServerAccess.tsx b/products/mcp_store/frontend/gateway/GatewayServerAccess.tsxindex 935031e60759..5618d5b293e7 100644--- a/products/mcp_store/frontend/gateway/GatewayServerAccess.tsx+++ b/products/mcp_store/frontend/gateway/GatewayServerAccess.tsx@@ -16,7 +16,7 @@ import { dayjs } from 'lib/dayjs'import { defaultAgentGrantPolicy, isPolicyStateAllowedByCeiling } from './gatewayPolicyUtils'import { AgentToolPolicyState, gatewayServerLogic } from './gatewayServerLogic'-import { toProfileUser } from './gatewayUtils'+import { RemoveAllSharesButton, toProfileUser } from './gatewayUtils'import { agentServerAccessKey, mcpGatewayLogic, memberServerAccessKey } from './mcpGatewayLogic'const AGENT_POLICY_OPTIONS = [@@ -31,6 +31,7 @@ export function GatewayAccessSection(): JSX.Element | null {agentServerAccessLoadingKeys,allServersEnabledLoading,canManageAgentAccess,+ currentUserId,isAdmin,memberServerAccessLoadingKeys,serverEnabledLoadingIds,@@ -151,6 +152,10 @@ export function GatewayAccessSection(): JSX.Element | null {Share access with an agent</LemonButton></div>+ <div className="text-sm text-secondary">+ Sharing is personal. Only your agents use your {server.name} connection, and each teammate shares their+ own.+ </div>{server.agents.length === 0 ? (<div className="border border-dashed rounded p-3 text-sm text-secondary">@@ -158,41 +163,60 @@ export function GatewayAccessSection(): JSX.Element | null {</div>) : (<div className="border rounded divide-y">- {server.agents.map((agent) => (- <div key={agent.service_account_id} className="flex items-center gap-3 p-2">- <div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-surface-secondary">- <IconSparkles />- </div>- <div className="flex-1 min-w-0">- <div className="font-semibold truncate">{agent.name}</div>- <div className="text-xs text-secondary truncate">- <span className="font-mono">{agent.handle}</span>- {agent.granted_by- ? ` · shared by ${agent.granted_by.first_name || agent.granted_by.email}`- : ' · shared with this agent'}+ {server.agents.map((agent) => {+ const sharedByYou = agent.user.id === currentUserId+ const agentShareCount = server.agents.filter(+ (candidate) => candidate.service_account_id === agent.service_account_id+ ).length+ return (+ <div+ key={`${agent.service_account_id}:${agent.user.id}`}+ className="flex items-center gap-3 p-2"+ >+ <div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-surface-secondary">+ <IconSparkles /></div>- </div>- <LemonButton- size="xsmall"- type="tertiary"- status="danger"- icon={<IconX />}- loading={agentServerAccessLoadingKeys.has(- agentServerAccessKey(agent.service_account_id, server.id)+ <div className="flex-1 min-w-0">+ <div className="font-semibold truncate">{agent.name}</div>+ <div className="text-xs text-secondary truncate">+ <span className="font-mono">{agent.handle}</span>+ {sharedByYou+ ? ' · shared by you'+ : ` · shared by ${agent.user.first_name || agent.user.email}`}+ </div>+ </div>+ {sharedByYou ? (+ <LemonButton+ size="xsmall"+ type="tertiary"+ status="danger"+ icon={<IconX />}+ loading={agentServerAccessLoadingKeys.has(+ agentServerAccessKey(agent.service_account_id, server.id)+ )}+ onClick={() => setAgentServerAccess(agent.service_account_id, server.id, false)}+ >+ Revoke+ </LemonButton>+ ) : (+ <RemoveAllSharesButton+ accountId={agent.service_account_id}+ accountName={agent.name}+ serverId={server.id}+ serverName={server.name}+ shareCount={agentShareCount}+ />)}- onClick={() => setAgentServerAccess(agent.service_account_id, server.id, false)}- >- Revoke- </LemonButton>- <LemonTag type={agent.status === 'active' ? 'success' : 'muted'} size="small">- {agent.status === 'active'- ? agent.last_active_at- ? `Active ${dayjs(agent.last_active_at).fromNow()}`- : 'Active'- : 'Paused'}- </LemonTag>- </div>- ))}+ <LemonTag type={agent.status === 'active' ? 'success' : 'muted'} size="small">+ {agent.status === 'active'+ ? agent.last_active_at+ ? `Active ${dayjs(agent.last_active_at).fromNow()}`+ : 'Active'+ : 'Paused'}+ </LemonTag>+ </div>+ )+ })}</div>)}</div>@@ -285,7 +309,7 @@ function GatewayAgentAccessModal(): JSX.Element | null {: undefined: availableAgentAccounts.length? 'Choose an agent'- : 'Every available agent already has access')+ : 'You already share this server with every available agent')}>Share accessdiff --git a/products/mcp_store/frontend/gateway/GatewayServersHome.tsx b/products/mcp_store/frontend/gateway/GatewayServersHome.tsxindex d43ea8f974bd..7fdfd5e61bcb 100644--- a/products/mcp_store/frontend/gateway/GatewayServersHome.tsx+++ b/products/mcp_store/frontend/gateway/GatewayServersHome.tsx@@ -460,7 +460,8 @@ function PeopleRow({ server }: { server: GatewayServerEntry }): JSX.Element {return <div className="text-xs text-secondary mt-1">Disabled. Enable it in Team settings.</div>}const connections = server.connections ?? []- const agentCount = (server.agents ?? []).length+ // `agents` holds one row per member grant, so an agent repeats once per member sharing it.+ const agentCount = new Set((server.agents ?? []).map((agent) => agent.service_account_id)).sizereturn (<div className="flex items-center gap-2 text-xs text-secondary mt-1"><div className="flex -space-x-1">diff --git a/products/mcp_store/frontend/gateway/GatewayTeamAndAgents.tsx b/products/mcp_store/frontend/gateway/GatewayTeamAndAgents.tsxindex 2e1eb1ba9b14..22fb02c28d2c 100644--- a/products/mcp_store/frontend/gateway/GatewayTeamAndAgents.tsx+++ b/products/mcp_store/frontend/gateway/GatewayTeamAndAgents.tsx@@ -58,6 +58,7 @@ export interface GatewayTeamAndAgentsProps {export function GatewayTeamAndAgents({ onOpenAgent, onOpenMember }: GatewayTeamAndAgentsProps = {}): JSX.Element {const {+ agentSharedServerCounts,serviceAccounts,servers,members,@@ -124,6 +125,9 @@ export function GatewayTeamAndAgents({ onOpenAgent, onOpenMember }: GatewayTeamAconst active = account.status === 'active'const statusLoading = accountStatusLoadingIds.has(account.id)const toolCount = agentToolCount(account, servers)+ // `server_ids` carries one entry per member grant, so the raw+ // length overcounts servers shared by several members.+ const serverCount = agentSharedServerCounts[account.id] ?? 0return (<div key={account.id} className="flex items-center gap-3 p-3">@@ -140,8 +144,8 @@ export function GatewayTeamAndAgents({ onOpenAgent, onOpenMember }: GatewayTeamA<div className="flex flex-col items-start min-w-0"><span className="font-semibold truncate max-w-full">{account.name}</span><span className="text-xs text-secondary">- {account.server_ids.length} server- {account.server_ids.length === 1 ? '' : 's'} · {toolCount} tool+ {serverCount} server+ {serverCount === 1 ? '' : 's'} · {toolCount} tool{toolCount === 1 ? '' : 's'}</span></div>diff --git a/products/mcp_store/frontend/gateway/gatewayAgentLogic.ts b/products/mcp_store/frontend/gateway/gatewayAgentLogic.tsindex f785e697a511..e13f64b5c0a9 100644--- a/products/mcp_store/frontend/gateway/gatewayAgentLogic.ts+++ b/products/mcp_store/frontend/gateway/gatewayAgentLogic.ts@@ -8,7 +8,7 @@ import { Breadcrumb } from '~/types'import { mcpGatewayAuditList } from '../generated/api'import { MCPAuditEventApi, MCPGatewayServerApi, MCPServiceAccountApi } from '../generated/api.schemas'-import { mcpGatewayLogic } from './mcpGatewayLogic'+import { AgentServerShare, agentServerShare, mcpGatewayLogic } from './mcpGatewayLogic'export interface GatewayAgentLogicProps {id: string@@ -26,13 +26,16 @@ export interface gatewayAgentLogicValues {agentServerAccessLoadingKeys: Set<string> // mcpGatewayLogicallServers: MCPGatewayServerApi[] // mcpGatewayLogicallServersLoading: boolean // mcpGatewayLogic+ currentUserId: number | null // mcpGatewayLogicserviceAccounts: MCPServiceAccountApi[] // mcpGatewayLogicaccount: MCPServiceAccountApi | nullbreadcrumbs: Breadcrumb[]recentCalls: MCPAuditEventApi[]recentCallsLoading: boolean+ sharedByYouCount: numbersharedServerIds: Set<string>sharedServers: MCPGatewayServerApi[]+ sharesByServerId: Record<string, AgentServerShare>shownRecentCalls: numberunsharedServers: MCPGatewayServerApi[]visibleRecentCalls: MCPAuditEventApi[]@@ -85,6 +88,12 @@ export interface gatewayAgentLogicMeta {account: (serviceAccounts: MCPServiceAccountApi[], arg: any) => MCPServiceAccountApi | nullbreadcrumbs: (account: MCPServiceAccountApi | null) => Breadcrumb[]sharedServerIds: (account: MCPServiceAccountApi | null) => Set<string>+ sharesByServerId: (+ account: MCPServiceAccountApi | null,+ allServers: MCPGatewayServerApi[],+ currentUserId: number | null+ ) => Record<string, AgentServerShare>+ sharedByYouCount: (sharesByServerId: Record<string, AgentServerShare>) => numbersharedServers: (allServers: MCPGatewayServerApi[], sharedServerIds: Set<string>) => MCPGatewayServerApi[]unsharedServers: (allServers: MCPGatewayServerApi[], sharedServerIds: Set<string>) => MCPGatewayServerApi[]visibleRecentCalls: (recentCalls: MCPAuditEventApi[], shownRecentCalls: number) => MCPAuditEventApi[]@@ -109,6 +118,7 @@ export const gatewayAgentLogic = kea<gatewayAgentLogicType>([['accountStatusLoadingIds','agentServerAccessLoadingKeys',+ 'currentUserId','servers as allServers','serversLoading as allServersLoading','serviceAccounts',@@ -159,6 +169,24 @@ export const gatewayAgentLogic = kea<gatewayAgentLogicType>([(s) => [s.account],(account: MCPServiceAccountApi | null): Set<string> => new Set(account?.server_ids ?? []),],+ sharesByServerId: [+ (s) => [s.account, s.allServers, s.currentUserId],+ (+ account: MCPServiceAccountApi | null,+ allServers: MCPGatewayServerApi[],+ currentUserId: number | null+ ): Record<string, AgentServerShare> =>+ Object.fromEntries(+ allServers.map((server) => [server.id, agentServerShare(account, server.id, currentUserId)])+ ),+ ],+ // Viewer's own share count. `sharedServerIds` spans every member's grants,+ // so it would overcount next to the personal share switches.+ sharedByYouCount: [+ (s) => [s.sharesByServerId],+ (sharesByServerId: Record<string, AgentServerShare>): number =>+ Object.values(sharesByServerId).filter((share) => share.sharedByYou).length,+ ],sharedServers: [(s) => [s.allServers, s.sharedServerIds],(allServers: MCPGatewayServerApi[], sharedServerIds: Set<string>): MCPGatewayServerApi[] =>diff --git a/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts b/products/mcp_store/frontend/gateway/gatewayServerLogic.test.tsindex d2cd2d6fd131..a6e1bd7346c8 100644--- a/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts+++ b/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts@@ -1,10 +1,11 @@-import { MOCK_DEFAULT_BASIC_USER } from '~/lib/api.mock'+import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_USER } from '~/lib/api.mock'import { router } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { initKeaTests } from '~/test/init'import { expectLogic } from '~/test/keaTestUtils'@@ -26,6 +27,7 @@ import type {MCPGatewayServerApi,MCPServiceAccountApi,ResolvedToolPolicyApi,+ UserBasicApi,} from '../generated/api.schemas'import { gatewayServerLogic } from './gatewayServerLogic'import { mcpGatewayLogic } from './mcpGatewayLogic'@@ -101,6 +103,46 @@ function gatewayServer(overrides: Partial<MCPGatewayServerApi> = {}): MCPGateway}}+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',+ first_name: 'Ada',+ last_name: 'Lovelace',+ email: '[email protected]',+ hedgehog_config: null,+}++function serviceAccount(id: string = 'scout-id', sharedBy: UserBasicApi[] = []): MCPServiceAccountApi {+ return {+ id,+ name: `Agent ${id}`,+ description: '',+ handle: `svc-${id}`,+ agent_key: 'scout',+ status: 'active',+ server_ids: sharedBy.map(() => 'server-id'),+ servers: sharedBy.map((user) => ({+ id: 'server-id',+ shared_by: user,+ name: 'Test server',+ description: '',+ icon_key: '',+ icon_domain: '',+ connection_state: 'ready' as const,+ })),+ last_active_at: null,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ }+}+function toolPolicy(toolName: string, overrides: Partial<ResolvedToolPolicyApi> = {}): ResolvedToolPolicyApi {return {tool_name: toolName,@@ -117,22 +159,6 @@ function toolPolicy(toolName: string, overrides: Partial<ResolvedToolPolicyApi>}}-function serviceAccount(): MCPServiceAccountApi {- return {- id: 'scout-id',- name: 'Scout',- description: 'Product analyst',- handle: 'posthog-scout',- agent_key: 'scout',- status: 'active',- server_ids: [],- servers: [],- last_active_at: null,- created_at: '2026-01-01T00:00:00Z',- updated_at: '2026-01-01T00:00:00Z',- }-}-function gatewayMember(userId: number): GatewayMemberSummaryApi {return {user: {@@ -194,6 +220,31 @@ describe('gatewayServerLogic', () => {jest.restoreAllMocks()})+ it('attributes each agent grant to the member backing it', () => {+ parentLogic.actions.loadServiceAccountsSuccess([+ serviceAccount('yours-only', [YOU]),+ serviceAccount('teammate-only', [TEAMMATE]),+ serviceAccount('both', [YOU, TEAMMATE]),+ serviceAccount('unshared', []),+ ])++ expect(logic.values.agentSharesByAccountId).toEqual({+ 'yours-only': { sharedByYou: true, sharedByOthers: [] },+ 'teammate-only': { sharedByYou: false, sharedByOthers: [TEAMMATE] },+ both: { sharedByYou: true, sharedByOthers: [TEAMMATE] },+ unshared: { sharedByYou: false, sharedByOthers: [] },+ })+ })++ it('attributes no grant while the current user is still loading', () => {+ userLogic.actions.loadUserSuccess(null)+ parentLogic.actions.loadServiceAccountsSuccess([serviceAccount('both', [YOU, TEAMMATE])])++ expect(logic.values.agentSharesByAccountId).toEqual({+ both: { sharedByYou: false, sharedByOthers: [] },+ })+ })+it('uses the policy mutation response while keeping the loader in flight', async () => {const pendingResponse = deferred<Awaited<ReturnType<typeof mcpGatewayServersPoliciesCreate>>>()const updatedPolicy = toolPolicy('create_issue', { policy_state: 'needs_approval' })diff --git a/products/mcp_store/frontend/gateway/gatewayServerLogic.ts b/products/mcp_store/frontend/gateway/gatewayServerLogic.tsindex 11e5fcd8add9..2703cab930c2 100644--- a/products/mcp_store/frontend/gateway/gatewayServerLogic.ts+++ b/products/mcp_store/frontend/gateway/gatewayServerLogic.ts@@ -37,7 +37,7 @@ import {import type { MCPServiceAccountApi } from '../generated/api.schemas'import type { TeamMCPGatewayConfigApi } from '../generated/api.schemas'import { defaultAgentGrantPolicy, isPolicyStateAllowedByCeiling } from './gatewayPolicyUtils'-import { mcpGatewayLogic } from './mcpGatewayLogic'+import { AgentServerShare, agentServerShare, mcpGatewayLogic } from './mcpGatewayLogic'export interface GatewayServerLogicProps {id: string@@ -116,6 +116,7 @@ export interface gatewayServerLogicValues {agentServerAccessLoadingKeys: Set<string> // mcpGatewayLogiccanManageAgentAccess: boolean // mcpGatewayLogicconfig: TeamMCPGatewayConfigApi | null // mcpGatewayLogic+ currentUserId: number | null // mcpGatewayLogicisAdmin: boolean // mcpGatewayLogicmembers: GatewayMemberSummaryApi[] // mcpGatewayLogicmembersInitialized: boolean // mcpGatewayLogic@@ -132,6 +133,7 @@ export interface gatewayServerLogicValues {agentAccessPolicyMap: Record<string, AgentToolPolicyState>agentAccessSelectedId: string | nullagentShareDisabledReason: string | undefined+ agentSharesByAccountId: Record<string, AgentServerShare>availableAgentAccounts: MCPServiceAccountApi[]availableScopes: PolicyScope[]breadcrumbs: Breadcrumb[]@@ -380,13 +382,18 @@ export interface gatewayServerLogicMeta {__keaTypeGenInternalSelectorTypes: {server: (servers: MCPGatewayServerApi[], arg: any) => MCPGatewayServerApi | nullbreadcrumbs: (server: MCPGatewayServerApi | null) => Breadcrumb[]+ agentSharesByAccountId: (+ server: MCPGatewayServerApi | null,+ serviceAccounts: MCPServiceAccountApi[],+ currentUserId: number | null+ ) => Record<string, AgentServerShare>policyCounts: (toolPolicies: ResolvedToolPolicyApi[],scope: PolicyScope) => Record<MCPToolApprovalStateEnumApi, number>availableAgentAccounts: (- server: MCPGatewayServerApi | null,- serviceAccounts: MCPServiceAccountApi[]+ serviceAccounts: MCPServiceAccountApi[],+ agentSharesByAccountId: Record<string, AgentServerShare>) => MCPServiceAccountApi[]agentShareDisabledReason: (server: MCPGatewayServerApi | null) => string | undefinedrefreshInstallationId: (server: MCPGatewayServerApi | null) => string | null@@ -432,6 +439,7 @@ export const gatewayServerLogic = kea<gatewayServerLogicType>([['canManageAgentAccess','config',+ 'currentUserId','isAdmin','members','membersInitialized',@@ -650,6 +658,20 @@ export const gatewayServerLogic = kea<gatewayServerLogicType>([{ key: 'mcp-gateway-server', name: server?.name ?? 'Server' },],],+ agentSharesByAccountId: [+ (s) => [s.server, s.serviceAccounts, s.currentUserId],+ (+ server: MCPGatewayServerApi | null,+ serviceAccounts: MCPServiceAccountApi[],+ currentUserId: number | null+ ): Record<string, AgentServerShare> =>+ Object.fromEntries(+ serviceAccounts.map((account) => [+ account.id,+ agentServerShare(account, server?.id ?? '', currentUserId),+ ])+ ),+ ],policyCounts: [(s) => [s.toolPolicies, s.scope],(@@ -672,11 +694,14 @@ export const gatewayServerLogic = kea<gatewayServerLogicType>([},],availableAgentAccounts: [- (s) => [s.server, s.serviceAccounts],- (server: MCPGatewayServerApi | null, serviceAccounts: MCPServiceAccountApi[]): MCPServiceAccountApi[] => {- const grantedAgentIds = new Set(server?.agents.map((agent) => agent.service_account_id) ?? [])- return serviceAccounts.filter((account) => !grantedAgentIds.has(account.id))- },+ (s) => [s.serviceAccounts, s.agentSharesByAccountId],+ (+ serviceAccounts: MCPServiceAccountApi[],+ agentSharesByAccountId: Record<string, AgentServerShare>+ ): MCPServiceAccountApi[] =>+ // Sharing is personal, so an agent a teammate already shares with+ // stays available for the viewer to share their own connection.+ serviceAccounts.filter((account) => !agentSharesByAccountId[account.id]?.sharedByYou),],agentShareDisabledReason: [(s) => [s.server],diff --git a/products/mcp_store/frontend/gateway/gatewayUtils.tsx b/products/mcp_store/frontend/gateway/gatewayUtils.tsxindex 87e70cdf7816..8a974b9d04f1 100644--- a/products/mcp_store/frontend/gateway/gatewayUtils.tsx+++ b/products/mcp_store/frontend/gateway/gatewayUtils.tsx@@ -1,7 +1,12 @@+import { useActions, useValues } from 'kea'+import { IconCheck, IconShieldLock, IconX } from '@posthog/icons'-import { LemonBadge, LemonTag } from '@posthog/lemon-ui'+import { LemonBadge, LemonButton, LemonDialog, LemonTag } from '@posthog/lemon-ui'++import { fullName } from 'lib/utils/strings'import { MCPToolApprovalStateEnumApi, UserBasicApi } from '../generated/api.schemas'+import { agentServerAccessKey, mcpGatewayLogic } from './mcpGatewayLogic'/** ProfilePicture wants a UserBasicType-ish shape; the generated UserBasicApi's* `hedgehog_config` type isn't assignable, so pass the fields it actually reads. */@@ -9,6 +14,74 @@ export function toProfileUser(user: UserBasicApi): { first_name?: string; last_nreturn { first_name: user.first_name, last_name: user.last_name, email: user.email }}+/** Attributes a grant backed by someone else's connection, so a member never reads+ * a teammate's share as their own. */+export function sharedByLabel(users: UserBasicApi[]): string | null {+ if (users.length === 0) {+ return null+ }+ const [first, ...rest] = users+ const name = fullName(first) || first.email+ if (rest.length === 0) {+ return `Shared by ${name}`+ }+ return `Shared by ${name} and ${rest.length} other${rest.length === 1 ? '' : 's'}`+}++/** Admin-only escape hatch: the share switch only ever controls the viewer's own+ * grant, so removing an agent's access for the whole project needs its own action.+ * It stays available to an admin who never connected the server themselves. */+export function RemoveAllSharesButton({+ accountId,+ accountName,+ serverId,+ serverName,+ shareCount,+}: {+ accountId: string+ accountName: string+ serverId: string+ serverName: string+ shareCount: number+}): JSX.Element | null {+ const { agentServerAccessLoadingKeys, isAdmin } = useValues(mcpGatewayLogic)+ const { removeAllAgentServerShares } = useActions(mcpGatewayLogic)++ if (!isAdmin || shareCount === 0) {+ return null+ }++ return (+ <LemonButton+ type="secondary"+ status="danger"+ size="small"+ loading={agentServerAccessLoadingKeys.has(agentServerAccessKey(accountId, serverId))}+ onClick={() =>+ LemonDialog.open({+ title: `Remove all shares of ${serverName}?`,+ description: (+ <div className="max-w-120">+ {shareCount} {shareCount === 1 ? 'member has' : 'members have'} shared a {serverName}{' '}+ connection with {accountName}. Removing them stops {accountName} using {serverName} for+ everyone in this project, and clears its tool settings for this server.+ </div>+ ),+ secondaryButton: { type: 'secondary', children: 'Cancel' },+ primaryButton: {+ type: 'primary',+ status: 'danger',+ children: 'Remove all shares',+ onClick: () => removeAllAgentServerShares(accountId, serverId),+ },+ })+ }+ >+ Remove all shares+ </LemonButton>+ )+}+export const POLICY_LABELS: Record<MCPToolApprovalStateEnumApi, string> = {approved: 'Always allow',needs_approval: 'Needs approval',diff --git a/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.ts b/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.tsindex 59961142a6c1..fdd6bd0b0041 100644--- a/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.ts+++ b/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.ts@@ -1,4 +1,4 @@-import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_TEAM } from '~/lib/api.mock'+import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from '~/lib/api.mock'import { lemonToast } from '@posthog/lemon-ui'@@ -27,9 +27,17 @@ import type {MCPServerInstallationApi,MCPServerTemplateApi,MCPServiceAccountApi,+ UserBasicApi,} from '../generated/api.schemas'import { CONNECTED_SERVERS_FILTER, GATEWAY_MEMBERS_PAGE_SIZE, mcpGatewayLogic } from './mcpGatewayLogic'+const YOU: UserBasicApi = {+ id: MOCK_DEFAULT_USER.id,+ uuid: MOCK_DEFAULT_USER.uuid,+ email: MOCK_DEFAULT_USER.email,+ hedgehog_config: null,+}+jest.mock('../generated/api', () => ({mcpGatewayConfigApplyPresetCreate: jest.fn(),mcpGatewayConfigList: jest.fn(),@@ -386,6 +394,7 @@ describe('mcpGatewayLogic', () => {servers: [{id: 'linear-id',+ shared_by: YOU,name: 'Linear',description: '',icon_key: '',@@ -421,7 +430,21 @@ describe('mcpGatewayLogic', () => {const server = gatewayServer({ id: 'linear-id' })logic.actions.loadServiceAccountsSuccess([account])logic.actions.loadServersSuccess([server])- mockServiceAccountAccess.mockResolvedValue({ ...account, server_ids: ['linear-id'] })+ mockServiceAccountAccess.mockResolvedValue({+ ...account,+ server_ids: ['linear-id'],+ servers: [+ {+ id: 'linear-id',+ shared_by: YOU,+ name: 'Linear',+ description: '',+ icon_key: '',+ icon_domain: '',+ connection_state: 'ready' as const,+ },+ ],+ })const pendingReload = deferred<Awaited<ReturnType<typeof mcpGatewayServersList>>>()mockServersList.mockClear()mockServersList.mockReturnValue(pendingReload.promise)diff --git a/products/mcp_store/frontend/gateway/mcpGatewayLogic.ts b/products/mcp_store/frontend/gateway/mcpGatewayLogic.tsindex 528308d0d1d1..f4e889b51e78 100644--- a/products/mcp_store/frontend/gateway/mcpGatewayLogic.ts+++ b/products/mcp_store/frontend/gateway/mcpGatewayLogic.ts@@ -1,10 +1,13 @@-import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { router } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'++import { UserType } from '~/types'import {mcpGatewayConfigApplyPresetCreate,@@ -41,6 +44,7 @@ import {MCPServiceAccountApi,TeamMCPGatewayConfigApi,ToolPolicyEntryApi,+ UserBasicApi,} from '../generated/api.schemas'import {buildGatewayInstallRequest,@@ -129,11 +133,38 @@ export function memberServerAccessKey(userId: number, serverId: string): stringreturn `${userId}:${serverId}`}+/** Who backs an agent's access to one server. A grant delegates one person's own+ * connection, so the same agent and server can carry one grant per member. */+export interface AgentServerShare {+ sharedByYou: boolean+ sharedByOthers: UserBasicApi[]+}++export function agentServerShare(+ account: MCPServiceAccountApi | null,+ serverId: string,+ currentUserId: number | null+): AgentServerShare {+ // Until the user loads there is no way to tell your own grants from anyone+ // else's, and calling them all teammates' would misattribute your own.+ if (currentUserId === null) {+ return { sharedByYou: false, sharedByOthers: [] }+ }+ const grants = (account?.servers ?? []).filter((server) => server.id === serverId)+ return {+ sharedByYou: grants.some((server) => server.shared_by.id === currentUserId),+ sharedByOthers: grants+ .filter((server) => server.shared_by.id !== currentUserId)+ .map((server) => server.shared_by),+ }+}+export const GATEWAY_MEMBERS_PAGE_SIZE = 500export const GATEWAY_CONNECTION_REFRESH_DELAYS_MS = [1500, 5000] as const// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpGatewayLogicValues {+ user: UserType | null // userLogicaccountStatusLoadingIds: Set<string>activeAgentCount: numberaddServerForm: GatewayAddServerValues@@ -141,6 +172,7 @@ export interface mcpGatewayLogicValues {addServerSubmitDisabledReason: string | nulladdingServer: booleanagentServerAccessLoadingKeys: Set<string>+ agentSharedServerCounts: Record<string, number>allServersEnabledLoading: booleanallServersEnabledTarget: boolean | nullallowCustomServers: boolean@@ -164,6 +196,7 @@ export interface mcpGatewayLogicValues {connectionModalServer: GatewayServerEntry | nullconnectionModalServerId: string | nullconnectionSubmitDisabledReason: string | null+ currentUserId: number | nulldefaultServersEnabled: booleandisconnectingInstallationIds: Set<string>enabledServerCount: number@@ -376,6 +409,13 @@ export interface mcpGatewayLogicActions {refreshServersAfterConnection: () => {value: true}+ removeAllAgentServerShares: (+ accountId: string,+ serverId: string+ ) => {+ accountId: string+ serverId: string+ }removeServer: (serverId: string) => {serverId: string}@@ -542,6 +582,7 @@ export interface mcpGatewayLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpGatewayLogicMeta {__keaTypeGenInternalSelectorTypes: {+ currentUserId: (user: UserType | null) => number | nulladdServerSubmitDisabledReason: (addServerForm: GatewayAddServerValues, addingServer: boolean) => string | nullisAdmin: (config: TeamMCPGatewayConfigApi | null) => booleanallowCustomServers: (config: TeamMCPGatewayConfigApi | null) => boolean@@ -586,6 +627,7 @@ export interface mcpGatewayLogicMeta {categoryFilter: string | null) => GatewayServerEntry[]activeAgentCount: (serviceAccounts: MCPServiceAccountApi[]) => number+ agentSharedServerCounts: (serviceAccounts: MCPServiceAccountApi[]) => Record<string, number>enabledServerCount: (mergedServers: MCPGatewayServerApi[]) => number}}@@ -600,6 +642,10 @@ export type mcpGatewayLogicType = MakeLogicType<export const mcpGatewayLogic = kea<mcpGatewayLogicType>([path(['products', 'mcp_store', 'frontend', 'gateway', 'mcpGatewayLogic']),+ connect(() => ({+ values: [userLogic, ['user']],+ })),+actions({openAddServerModal: true,closeAddServerModal: true,@@ -682,6 +728,7 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([}),setAgentServerAccessSuccess: (accountId: string, serverId: string) => ({ accountId, serverId }),setAgentServerAccessComplete: (accountId: string, serverId: string) => ({ accountId, serverId }),+ removeAllAgentServerShares: (accountId: string, serverId: string) => ({ accountId, serverId }),setAllServersEnabled: (enabled: boolean) => ({ enabled }),setAllServersEnabledComplete: true,setTemplateEnabled: (templateId: string, enabled: boolean) => ({ templateId, enabled }),@@ -909,6 +956,8 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([{setAgentServerAccess: (state, { accountId, serverId }) =>new Set(state).add(agentServerAccessKey(accountId, serverId)),+ removeAllAgentServerShares: (state, { accountId, serverId }) =>+ new Set(state).add(agentServerAccessKey(accountId, serverId)),setAgentServerAccessComplete: (state, { accountId, serverId }) => {const next = new Set(state)next.delete(agentServerAccessKey(accountId, serverId))@@ -1003,6 +1052,7 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([}),selectors({+ currentUserId: [(s) => [s.user], (user: UserType | null): number | null => user?.id ?? null],addServerSubmitDisabledReason: [(s) => [s.addServerForm, s.addingServer],(addServerForm: GatewayAddServerValues, addingServer: boolean): string | null => {@@ -1162,6 +1212,13 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([(serviceAccounts: MCPServiceAccountApi[]): number =>serviceAccounts.filter((account) => account.status === 'active').length,],+ agentSharedServerCounts: [+ (s) => [s.serviceAccounts],+ // `server_ids` carries one entry per member grant, so the same server repeats+ // once per member who shared it.+ (serviceAccounts: MCPServiceAccountApi[]): Record<string, number> =>+ Object.fromEntries(serviceAccounts.map((account) => [account.id, new Set(account.server_ids).size])),+ ],enabledServerCount: [(s) => [s.mergedServers],(mergedServers: GatewayServerEntry[]): number =>@@ -1443,6 +1500,8 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([const account = values.serviceAccounts.find((candidate) => candidate.id === accountId)const server = values.servers.find((candidate) => candidate.id === serverId)try {+ // The response carries the account's grants after the change, including who+ // backs each one, which a local merge cannot reconstruct.const updatedAccount = await mcpGatewayServiceAccountsAccessCreate(currentProjectId(), accountId, {gateway_server_id: serverId,enabled,@@ -1451,16 +1510,22 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([actions.loadServiceAccountsSuccess(values.serviceAccounts.map((candidate) => (candidate.id === accountId ? updatedAccount : candidate)))- // The access section renders server.agents, so patch it immediately.- // The background reload fills in granted_by for newly shared agents.+ // The access section renders one server.agents row per member grant, so+ // patch the caller's own row immediately. The background reload fills in+ // granted_by for newly shared agents.+ const yourGrant = updatedAccount.servers.find(+ (grant) => grant.id === serverId && grant.shared_by.id === values.currentUserId+ )actions.loadServersSuccess(values.servers.map((candidate) => {if (candidate.id !== serverId) {return candidate}- const alreadyListed = candidate.agents.some((agent) => agent.service_account_id === accountId)+ const yourRowListed = candidate.agents.some(+ (agent) => agent.service_account_id === accountId && agent.user.id === values.currentUserId+ )if (enabled) {- return alreadyListed+ return !yourGrant || yourRowListed? candidate: {...candidate,@@ -1468,6 +1533,7 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([...candidate.agents,{service_account_id: updatedAccount.id,+ user: yourGrant.shared_by,name: updatedAccount.name,handle: updatedAccount.handle,status: updatedAccount.status,@@ -1477,9 +1543,14 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([],}}+ // Shares are personal, so withdrawing yours removes only your own+ // row and leaves teammates' grants listed.return {...candidate,- agents: candidate.agents.filter((agent) => agent.service_account_id !== accountId),+ agents: candidate.agents.filter(+ (agent) =>+ !(agent.service_account_id === accountId && agent.user.id === values.currentUserId)+ ),}}))@@ -1487,8 +1558,8 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([actions.setAgentServerAccessSuccess(accountId, serverId)lemonToast[enabled ? 'success' : 'info'](enabled- ? `${server?.name ?? 'Server'} shared with ${account?.name ?? 'agent'}`- : `${account?.name ?? 'Agent'} can no longer access ${server?.name ?? 'server'}`+ ? `${server?.name ?? 'Server'} shared with ${account?.name ?? 'agent'}. Only your agents use your connection.`+ : `Your ${server?.name ?? 'server'} connection is no longer shared with ${account?.name ?? 'this agent'}. Your teammates' shares are unchanged.`)} catch (error: unknown) {lemonToast.error(@@ -1498,6 +1569,30 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([actions.setAgentServerAccessComplete(accountId, serverId)}},+ removeAllAgentServerShares: async ({ accountId, serverId }) => {+ const account = values.serviceAccounts.find((candidate) => candidate.id === accountId)+ const server = values.servers.find((candidate) => candidate.id === serverId)+ try {+ const updatedAccount = await mcpGatewayServiceAccountsAccessCreate(currentProjectId(), accountId, {+ gateway_server_id: serverId,+ enabled: false,+ all: true,+ })+ actions.loadServiceAccountsSuccess(+ values.serviceAccounts.map((candidate) => (candidate.id === accountId ? updatedAccount : candidate))+ )+ actions.loadServers()+ lemonToast.info(+ `${account?.name ?? 'This agent'} can no longer use anyone's ${server?.name ?? 'server'} connection`+ )+ } catch (error: unknown) {+ lemonToast.error(+ errorDetail(error) ?? `Could not remove the shares of ${server?.name ?? 'this server'}`+ )+ } finally {+ actions.setAgentServerAccessComplete(accountId, serverId)+ }+ },toggleRuleEnabled: async ({ ruleId, enabled }) => {const rule = values.rules.find((candidate) => candidate.id === ruleId)try {diff --git a/products/mcp_store/frontend/generated/api.schemas.ts b/products/mcp_store/frontend/generated/api.schemas.tsindex 277308470afb..6f28fe464788 100644--- a/products/mcp_store/frontend/generated/api.schemas.ts+++ b/products/mcp_store/frontend/generated/api.schemas.ts@@ -436,11 +436,13 @@ export const MCPServiceAccountStatusEnumApi = {} as const/**- * One agent's access to a gateway server.+ * One agent's access to a gateway server, on behalf of one member.*/export interface GatewayAgentAccessApi {/** Service account granted access. */service_account_id: string+ /** The member whose connection the agent uses. */+ user: UserBasicApi/** Agent display name. */name: string/** Agent identity handle, e.g. posthog-support. */@@ -455,7 +457,7 @@ export interface GatewayAgentAccessApi {* @nullable*/last_active_at: string | null- /** Admin who shared this server with the agent. */+ /** Member who shared this server with the agent. */granted_by: UserBasicApi | null}@@ -723,6 +725,8 @@ export const ConnectionStateEnumApi = {export interface MCPServiceAccountServerApi {/** Gateway server granted to the agent. */id: string+ /** The member whose connection the agent uses. */+ shared_by: UserBasicApi/** Server display name. */name: string/** Server description. */@@ -793,10 +797,12 @@ export interface PatchedMCPServiceAccountUpdateApi {}export interface ServiceAccountAccessUpdateApi {- /** Gateway server to grant or revoke. */+ /** Gateway server to share or stop sharing. */gateway_server_id: string- /** True grants access, false revokes it. */+ /** True shares the caller's own connection with the agent, false removes the caller's share. */enabled: boolean+ /** Only valid with enabled=false. Removes every member's share of this server with this agent, along with the agent's tool policies for it. Project admins only. */+ all?: boolean/*** Optional agent-scope tool policies to set alongside the grant. At most 1,000 entries per request.* @maxItems 1000diff --git a/products/mcp_store/frontend/generated/api.ts b/products/mcp_store/frontend/generated/api.tsindex fc7568934218..49c0b5ec4e5a 100644--- a/products/mcp_store/frontend/generated/api.ts+++ b/products/mcp_store/frontend/generated/api.ts@@ -741,7 +741,16 @@ export const getMcpGatewayServiceAccountsAccessCreateUrl = (projectId: string, i}/**- * Grant or revoke this agent's access to one gateway server.+ * Share, or stop sharing, one gateway server with this agent.+ *+ * Sharing is personal. `enabled=true` delegates the caller's own+ * connection, and the agent may use it only when acting for the caller.+ * `enabled=false` removes the caller's own share and leaves other members'+ * shares, and the agent's tool policies, in place.+ *+ * Project admins can send `all=true` alongside `enabled=false` to remove+ * every member's share of this server with this agent, along with the+ * agent's tool policies for it.*/export const mcpGatewayServiceAccountsAccessCreate = async (projectId: string,diff --git a/products/mcp_store/frontend/generated/api.zod.ts b/products/mcp_store/frontend/generated/api.zod.tsindex c1fff8bb97bc..d3c0c476ad0a 100644--- a/products/mcp_store/frontend/generated/api.zod.ts+++ b/products/mcp_store/frontend/generated/api.zod.ts@@ -341,15 +341,33 @@ export const McpGatewayServiceAccountsPartialUpdateBody = /* @__PURE__ */ zod.ob})/**- * Grant or revoke this agent's access to one gateway server.+ * Share, or stop sharing, one gateway server with this agent.+ *+ * Sharing is personal. `enabled=true` delegates the caller's own+ * connection, and the agent may use it only when acting for the caller.+ * `enabled=false` removes the caller's own share and leaves other members'+ * shares, and the agent's tool policies, in place.+ *+ * Project admins can send `all=true` alongside `enabled=false` to remove+ * every member's share of this server with this agent, along with the+ * agent's tool policies for it.*/+export const mcpGatewayServiceAccountsAccessCreateBodyAllDefault = falseexport const mcpGatewayServiceAccountsAccessCreateBodyPoliciesItemToolNameMax = 200export const mcpGatewayServiceAccountsAccessCreateBodyPoliciesMax = 1000export const McpGatewayServiceAccountsAccessCreateBody = /* @__PURE__ */ zod.object({- gateway_server_id: zod.uuid().describe('Gateway server to grant or revoke.'),- enabled: zod.boolean().describe('True grants access, false revokes it.'),+ gateway_server_id: zod.uuid().describe('Gateway server to share or stop sharing.'),+ enabled: zod+ .boolean()+ .describe("True shares the caller's own connection with the agent, false removes the caller's share."),+ all: zod+ .boolean()+ .default(mcpGatewayServiceAccountsAccessCreateBodyAllDefault)+ .describe(+ "Only valid with enabled=false. Removes every member's share of this server with this agent, along with the agent's tool policies for it. Project admins only."+ ),policies: zod.array(zod.object({diff --git a/products/signals/frontend/inbox/components/config/McpServersSection.tsx b/products/signals/frontend/inbox/components/config/McpServersSection.tsxindex 7dc69af7a908..07142856f8b8 100644--- a/products/signals/frontend/inbox/components/config/McpServersSection.tsx+++ b/products/signals/frontend/inbox/components/config/McpServersSection.tsx@@ -4,6 +4,7 @@ import { IconChevronRight, IconServer } from '@posthog/icons'import { LemonTag, LemonTagType, Link, Spinner } from '@posthog/lemon-ui'import { ServerIcon } from '@posthog/products-mcp-store/frontend/scene/icons'+import { fullName } from 'lib/utils/strings'import { urls } from 'scenes/urls'import type { MCPServiceAccountServerApi } from 'products/mcp_store/frontend/generated/api.schemas'@@ -23,7 +24,8 @@ const CONNECTION_STATE: Record<export function McpServersSection(): JSX.Element {useMountedLogic(scoutMcpServersLogic)- const { scoutAccount, scoutServers, scoutServersLoading } = useValues(scoutMcpServersLogic)+ const { scoutAccount, scoutServersLoading, teammateScoutServers, yourScoutServers } =+ useValues(scoutMcpServersLogic)if (scoutServersLoading && scoutAccount === null) {return (@@ -35,35 +37,34 @@ export function McpServersSection(): JSX.Element {return (<div className="rounded border bg-bg-light overflow-hidden">- {scoutServers.length === 0 ? (+ {yourScoutServers.length === 0 ? (<div className="flex items-start gap-3 px-3 py-3"><IconServer className="size-5 shrink-0 mt-0.5 text-secondary" /><div className="min-w-0">- <div className="font-medium text-sm text-default">No MCP servers shared with Scout</div>+ <div className="font-medium text-sm text-default">+ You have not shared any MCP servers with Scout+ </div><p className="text-xs text-secondary mt-0.5 mb-0">- A project admin can share a connection with the Scout agent.+ Share one of your connections in MCP server settings. Your scouts only use connections you+ shared yourself.</p></div></div>) : (<div className="divide-y">- {scoutServers.map((server) => {- const state = CONNECTION_STATE[server.connection_state]- return (- <div key={server.id} className="flex items-center gap-3 px-3 py-2.5">- <ServerIcon iconDomain={server.icon_domain} size={28} />- <div className="min-w-0 flex-1">- <div className="font-medium text-sm text-default truncate">{server.name}</div>- {server.description && (- <div className="text-xs text-secondary truncate">{server.description}</div>- )}- </div>- <LemonTag type={state.tagType} size="small">- {state.label}- </LemonTag>- </div>- )- })}+ {yourScoutServers.map((server) => (+ <ScoutServerRow key={server.id} server={server} />+ ))}+ </div>+ )}+ {teammateScoutServers.length > 0 && (+ <div className="border-t">+ <div className="px-3 py-2 text-xs text-secondary">Shared by teammates for their own scouts.</div>+ <div className="divide-y border-t">+ {teammateScoutServers.map((server) => (+ <ScoutServerRow key={`${server.id}-${server.shared_by.id}`} server={server} attributed />+ ))}+ </div></div>)}<Link@@ -79,3 +80,32 @@ export function McpServersSection(): JSX.Element {</div>)}++function ScoutServerRow({+ server,+ attributed,+}: {+ server: MCPServiceAccountServerApi+ attributed?: boolean+}): JSX.Element {+ const state = CONNECTION_STATE[server.connection_state]+ const sharedBy = fullName(server.shared_by) || server.shared_by.email+ return (+ <div className="flex items-center gap-3 px-3 py-2.5">+ <ServerIcon iconDomain={server.icon_domain} size={28} />+ <div className="min-w-0 flex-1">+ <div className="font-medium text-sm text-default truncate">{server.name}</div>+ {attributed ? (+ <div className="text-xs text-secondary truncate">Shared by {sharedBy}</div>+ ) : (+ server.description && <div className="text-xs text-secondary truncate">{server.description}</div>+ )}+ </div>+ {!attributed && (+ <LemonTag type={state.tagType} size="small">+ {state.label}+ </LemonTag>+ )}+ </div>+ )+}diff --git a/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx b/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsxindex 675683a46a26..599263f4cf28 100644--- a/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx+++ b/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx@@ -223,7 +223,7 @@ function CodeAccessWidget(): JSX.Element {function McpServersWidget(): JSX.Element {useMountedLogic(scoutMcpServersLogic)- const { availableScoutServers, scoutAccount, scoutServers, scoutServersLoading, scoutServersNeedingSetup } =+ const { availableScoutServers, scoutAccount, scoutServersLoading, scoutServersNeedingSetup, yourScoutServers } =useValues(scoutMcpServersLogic)const { openSetupModal } = useActions(agentSetupModalLogic)const availableCount = availableScoutServers.length@@ -236,7 +236,7 @@ function McpServersWidget(): JSX.Element {status = `${availableCount} available · ${needsSetupCount} need setup`tone = 'done'} else if (availableCount > 0) {- status = `${availableCount} available to Scout`+ status = `${availableCount} available to your scouts`tone = 'done'} else if (needsSetupCount > 0) {status = `${needsSetupCount} need setup`@@ -248,17 +248,17 @@ function McpServersWidget(): JSX.Element {title="MCP servers"size="md"tone={tone}- loading={scoutServersLoading && scoutServers.length === 0}+ loading={scoutServersLoading && yourScoutServers.length === 0}status={status}onClick={() => openSetupModal('mcp-servers')}>- {scoutServers.length > 0 && (+ {yourScoutServers.length > 0 && (<div className="flex items-center gap-1 pt-1">- {scoutServers.slice(0, 6).map((server) => (+ {yourScoutServers.slice(0, 6).map((server) => (<ServerIcon key={server.id} iconDomain={server.icon_domain} size={16} />))}- {scoutServers.length > 6 && (- <span className="text-[11px] text-muted">+{scoutServers.length - 6}</span>+ {yourScoutServers.length > 6 && (+ <span className="text-[11px] text-muted">+{yourScoutServers.length - 6}</span>)}</div>)}@@ -340,7 +340,7 @@ const SETUP_MODALS: Record<},'mcp-servers': {title: 'MCP servers',- description: 'Shared external tools available to scheduled Scouts.',+ description: 'Connections you share with your scheduled scouts.',width: 560,body: <McpServersSection />,},diff --git a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.ts b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.tsindex 8038f4c79bfa..0e04b38a0183 100644--- a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.ts@@ -1,6 +1,10 @@/* 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 { userLogic } from 'scenes/userLogic'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -8,13 +12,34 @@ import type {ConnectionStateEnumApi,MCPServiceAccountApi,MCPServiceAccountServerApi,+ UserBasicApi,} from 'products/mcp_store/frontend/generated/api.schemas'import { scoutMcpServersLogic } from './scoutMcpServersLogic'-function server(id: string, name: string, connectionState: ConnectionStateEnumApi): MCPServiceAccountServerApi {+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+): MCPServiceAccountServerApi {return {id,+ shared_by: sharedBy,name,description: `${name} workspace`,icon_key: name.toLowerCase(),@@ -54,9 +79,10 @@ describe('scoutMcpServersLogic', () => {logic?.unmount()})- it('shows Scout grants and separates servers that still need setup', async () => {+ it('separates your Scout grants from teammate grants and flags the ones needing setup', async () => {const notion = server('notion-id', 'Notion', 'missing_credential')const linear = server('linear-id', 'Linear', 'ready')+ const teammateGithub = server('github-id', 'GitHub', 'ready', TEAMMATE)const zendesk = server('zendesk-id', 'Zendesk', 'ready')useMocks({get: {@@ -66,7 +92,7 @@ describe('scoutMcpServersLogic', () => {count: 2,next: null,previous: null,- results: [account('support', [zendesk]), account('scout', [notion, linear])],+ results: [account('support', [zendesk]), account('scout', [notion, linear, teammateGithub])],},],},@@ -76,13 +102,44 @@ describe('scoutMcpServersLogic', () => {logic.mount()await expectLogic(logic).toFinishAllListeners()- expect(logic.values.scoutServers).toEqual([notion, linear])+ expect(logic.values.scoutServers).toEqual([notion, linear, teammateGithub])+ expect(logic.values.yourScoutServers).toEqual([notion, linear])+ expect(logic.values.teammateScoutServers).toEqual([teammateGithub])expect(logic.values.isScoutMcpAccessEnabled).toBe(true)expect(logic.values.readyScoutServers).toEqual([linear])expect(logic.values.availableScoutServers).toEqual([linear])expect(logic.values.scoutServersNeedingSetup).toEqual([notion])})+ it('attributes no grants while the current user is still loading', async () => {+ const linear = server('linear-id', 'Linear', 'ready')+ const teammateGithub = server('github-id', 'GitHub', 'ready', TEAMMATE)+ useMocks({+ get: {+ '/api/projects/:team_id/mcp_gateway/service_accounts/': () => [+ 200,+ {+ count: 1,+ next: null,+ previous: null,+ results: [account('scout', [linear, teammateGithub])],+ },+ ],+ },+ })++ logic = scoutMcpServersLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ userLogic.actions.loadUserSuccess(null)++ expect(logic.values.currentUserId).toBeNull()+ expect(logic.values.yourScoutServers).toEqual([])+ expect(logic.values.teammateScoutServers).toEqual([])+ expect(logic.values.availableScoutServers).toEqual([])+ expect(logic.values.scoutServersNeedingSetup).toEqual([])+ })+it('does not expose ready servers when MCP access is paused', async () => {const linear = server('linear-id', 'Linear', 'ready')useMocks({diff --git a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.ts b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.tsindex 8788d46ddf1c..f31150810f34 100644--- a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.ts@@ -3,6 +3,9 @@ import { loaders } from 'kea-loaders'import { subscriptions } from 'kea-subscriptions'import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'++import { UserType } from '~/types'import { mcpGatewayServiceAccountsList } from 'products/mcp_store/frontend/generated/api'import type {@@ -13,7 +16,9 @@ import type {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scoutMcpServersLogicValues {currentTeamId: number | null // teamLogic+ user: UserType | null // userLogicavailableScoutServers: MCPServiceAccountServerApi[]+ currentUserId: number | nullisScoutMcpAccessEnabled: booleanreadyScoutServers: MCPServiceAccountServerApi[]scoutAccount: MCPServiceAccountApi | null@@ -22,6 +27,8 @@ export interface scoutMcpServersLogicValues {scoutServersNeedingSetup: MCPServiceAccountServerApi[]serviceAccounts: MCPServiceAccountApi[]serviceAccountsLoading: boolean+ teammateScoutServers: MCPServiceAccountServerApi[]+ yourScoutServers: MCPServiceAccountServerApi[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -46,15 +53,24 @@ export interface scoutMcpServersLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scoutMcpServersLogicMeta {__keaTypeGenInternalSelectorTypes: {+ currentUserId: (user: UserType | null) => number | nullscoutAccount: (serviceAccounts: MCPServiceAccountApi[]) => MCPServiceAccountApi | nullisScoutMcpAccessEnabled: (scoutAccount: MCPServiceAccountApi | null) => booleanscoutServers: (scoutAccount: MCPServiceAccountApi | null) => MCPServiceAccountServerApi[]- readyScoutServers: (scoutServers: MCPServiceAccountServerApi[]) => MCPServiceAccountServerApi[]+ yourScoutServers: (+ scoutServers: MCPServiceAccountServerApi[],+ currentUserId: number | null+ ) => MCPServiceAccountServerApi[]+ teammateScoutServers: (+ scoutServers: MCPServiceAccountServerApi[],+ currentUserId: number | null+ ) => MCPServiceAccountServerApi[]+ readyScoutServers: (yourScoutServers: MCPServiceAccountServerApi[]) => MCPServiceAccountServerApi[]availableScoutServers: (readyScoutServers: MCPServiceAccountServerApi[],isScoutMcpAccessEnabled: boolean) => MCPServiceAccountServerApi[]- scoutServersNeedingSetup: (scoutServers: MCPServiceAccountServerApi[]) => MCPServiceAccountServerApi[]+ scoutServersNeedingSetup: (yourScoutServers: MCPServiceAccountServerApi[]) => MCPServiceAccountServerApi[]scoutServersLoading: (serviceAccountsLoading: boolean) => boolean}}@@ -69,7 +85,7 @@ export type scoutMcpServersLogicType = MakeLogicType<export const scoutMcpServersLogic = kea<scoutMcpServersLogicType>([path(['scenes', 'inbox', 'logics', 'scoutMcpServersLogic']),connect({- values: [teamLogic, ['currentTeamId']],+ values: [teamLogic, ['currentTeamId'], userLogic, ['user']],}),loaders(({ values }) => ({serviceAccounts: [@@ -86,6 +102,7 @@ export const scoutMcpServersLogic = kea<scoutMcpServersLogicType>([],})),selectors({+ currentUserId: [(s) => [s.user], (user: UserType | null): number | null => user?.id ?? null],scoutAccount: [(s) => [s.serviceAccounts],(serviceAccounts: MCPServiceAccountApi[]): MCPServiceAccountApi | null =>@@ -101,10 +118,25 @@ export const scoutMcpServersLogic = kea<scoutMcpServersLogicType>([...(scoutAccount?.servers ?? []),],],+ // A grant belongs to one member and a scout run mounts only the grants of the person it+ // runs for, so a teammate's grant never backs the viewer's scouts. Readiness and setup+ // below therefore look at the viewer's own grants alone. While the user is still loading+ // neither partition can be attributed, so both stay empty rather than reading the+ // viewer's own grants as teammates'.+ yourScoutServers: [+ (s) => [s.scoutServers, s.currentUserId],+ (scoutServers: MCPServiceAccountServerApi[], currentUserId: number | null): MCPServiceAccountServerApi[] =>+ currentUserId === null ? [] : scoutServers.filter((server) => server.shared_by.id === currentUserId),+ ],+ teammateScoutServers: [+ (s) => [s.scoutServers, s.currentUserId],+ (scoutServers: MCPServiceAccountServerApi[], currentUserId: number | null): MCPServiceAccountServerApi[] =>+ currentUserId === null ? [] : scoutServers.filter((server) => server.shared_by.id !== currentUserId),+ ],readyScoutServers: [- (s) => [s.scoutServers],- (scoutServers: MCPServiceAccountServerApi[]): MCPServiceAccountServerApi[] =>- scoutServers.filter((server) => server.connection_state === 'ready'),+ (s) => [s.yourScoutServers],+ (yourScoutServers: MCPServiceAccountServerApi[]): MCPServiceAccountServerApi[] =>+ yourScoutServers.filter((server) => server.connection_state === 'ready'),],availableScoutServers: [(s) => [s.readyScoutServers, s.isScoutMcpAccessEnabled],@@ -114,9 +146,9 @@ export const scoutMcpServersLogic = kea<scoutMcpServersLogicType>([): MCPServiceAccountServerApi[] => (isScoutMcpAccessEnabled ? readyScoutServers : []),],scoutServersNeedingSetup: [- (s) => [s.scoutServers],- (scoutServers: MCPServiceAccountServerApi[]): MCPServiceAccountServerApi[] =>- scoutServers.filter((server) => server.connection_state !== 'ready'),+ (s) => [s.yourScoutServers],+ (yourScoutServers: MCPServiceAccountServerApi[]): MCPServiceAccountServerApi[] =>+ yourScoutServers.filter((server) => server.connection_state !== 'ready'),],scoutServersLoading: [(s) => [s.serviceAccountsLoading],diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex ed7ab16c7378..b62195adecaa 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -578,9 +578,11 @@ def get_user_mcp_server_configs("""Fetch MCP Store installations for sandbox use and return configs.Unmapped tasks include shared team installations. Built-in agent tasks only- include shared installations granted to that agent and never include a- member's personal installations. A mapped origin without its persisted- agent marker gets no Store installations. Built-in agent handling is+ include the connections granted to that agent by the person the run acts+ for, and never include a member's personal installations. This path does+ not resolve that person yet, so built-in agent tasks currently get no Store+ installations. A mapped origin without its persisted agent marker gets no+ Store installations. Built-in agent handling isgated per team on the ``mcp-gateway`` rollout flag; teams without itresolve mapped origins like unmapped tasks. For unmapped tasks,``include_personal`` includes the user's personal installations when adiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e2a5c4ff5f1b..0abae31ab81d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -35935,11 +35935,13 @@ export namespace Schemas {} as const;/**- * One agent's access to a gateway server.+ * One agent's access to a gateway server, on behalf of one member.*/export interface GatewayAgentAccess {/** Service account granted access. */service_account_id: string;+ /** The member whose connection the agent uses. */+ user: UserBasic;/** Agent display name. */name: string;/** Agent identity handle, e.g. posthog-support. */@@ -35954,7 +35956,7 @@ export namespace Schemas {* @nullable*/last_active_at: string | null;- /** Admin who shared this server with the agent. */+ /** Member who shared this server with the agent. */granted_by: UserBasic | null;}@@ -44600,6 +44602,8 @@ export namespace Schemas {export interface MCPServiceAccountServer {/** Gateway server granted to the agent. */id: string;+ /** The member whose connection the agent uses. */+ shared_by: UserBasic;/** Server display name. */name: string;/** Server description. */@@ -68998,10 +69002,12 @@ export namespace Schemas {} as const;export interface ServiceAccountAccessUpdate {- /** Gateway server to grant or revoke. */+ /** Gateway server to share or stop sharing. */gateway_server_id: string;- /** True grants access, false revokes it. */+ /** True shares the caller's own connection with the agent, false removes the caller's share. */enabled: boolean;+ /** Only valid with enabled=false. Removes every member's share of this server with this agent, along with the agent's tool policies for it. Project admins only. */+ all?: boolean;/*** Optional agent-scope tool policies to set alongside the grant. At most 1,000 entries per request.* @maxItems 1000