: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): add team-level scope to agent MCP grants (#77985)
Chris Volzer64c11a92c27f
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 6380b496b3cb..ac8932f122d6 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -621,6 +621,8 @@ SPECTACULAR_SETTINGS = {# Shared by ConversionGoalSummary.kind and GoalExplanation.kind (same choice set)."ConversionGoalKindEnum": "products.marketing_analytics.backend.hogql_queries.constants.CONVERSION_GOAL_KIND_CHOICES","MCPInstallationScopeEnum": ["personal", "shared"],+ # Same field name as the installation scope above, different values.+ "MCPAgentGrantScopeEnum": "products.mcp_store.backend.models.AGENT_GRANT_SCOPE_CHOICES","MCPServiceAccountStatusEnum": "products.mcp_store.backend.models.SERVICE_ACCOUNT_STATUS_CHOICES","MCPServerCategoryEnum": "products.mcp_store.backend.models.CATEGORY_CHOICES","MCPToolApprovalStateEnum": "products.mcp_store.backend.models.APPROVAL_STATES",diff --git a/products/mcp_store/backend/agents.py b/products/mcp_store/backend/agents.pyindex 50d90d187b2b..7a3947843746 100644--- a/products/mcp_store/backend/agents.py+++ b/products/mcp_store/backend/agents.py@@ -162,10 +162,15 @@ def get_built_in_agent(team_id: int, agent_key: str) -> MCPServiceAccount | None@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."""+ whose MCP grants the run may use.++ `credential_owner_id` is None for a run nobody owns (an autonomous support+ reply, a creatorless scout). Such a principal reaches team-scoped grants+ only, never a member's personal grant.+ """account: MCPServiceAccount- credential_owner_id: int+ credential_owner_id: int | Nonedef credential_owner_eligible(credential_owner_id: int, team_id: int) -> bool:@@ -190,12 +195,15 @@ def credential_owner_eligible(credential_owner_id: int, team_id: int) -> bool:return UserPermissions(user=owner, team=team).current_team.effective_membership_level is not None-def create_gateway_agent_token(account: MCPServiceAccount, *, credential_owner_id: int) -> str:- payload = {+def create_gateway_agent_token(account: MCPServiceAccount, *, credential_owner_id: int | None) -> str:+ payload: dict[str, str | int] = {"service_account_id": str(account.id),"team_id": account.team_id,- "user_id": credential_owner_id,}+ # Omitted rather than set to null so the claim's presence alone means "this+ # run has an owner", which is what the resolver keys off.+ if credential_owner_id is not None:+ payload["user_id"] = credential_owner_idreturn GATEWAY_AGENT_TOKEN_PREFIX + signing.dumps(payload, salt=GATEWAY_AGENT_TOKEN_SALT)@@ -216,10 +224,13 @@ def resolve_gateway_agent_token(token: str) -> GatewayAgentPrincipal | None:account_id = payload.get("service_account_id")team_id = payload.get("team_id")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):+ if not account_id or not isinstance(team_id, int):+ return None+ # A token with no owner claim runs in the team lane: it reaches team-scoped+ # grants and nothing else. A claim that is present but not an int is+ # malformed rather than absent, so it fails closed instead of being widened+ # into the team lane.+ if credential_owner_id is not None and not isinstance(credential_owner_id, int):return Nonetry:# TeamScopeError: the token can outlive its team — treat a deleted team@@ -232,6 +243,7 @@ def resolve_gateway_agent_token(token: str) -> GatewayAgentPrincipal | None:return None# A token outlives offboarding (its max age is hours), so the owner's# eligibility is re-checked on every resolution, not just at mint time.- if not credential_owner_eligible(credential_owner_id, team_id):+ # A personless token names nobody, so there is no owner to re-check.+ if credential_owner_id is not None and not credential_owner_eligible(credential_owner_id, team_id):return Nonereturn 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 cb530099f5f9..d5508d27d284 100644--- a/products/mcp_store/backend/facade/api.py+++ b/products/mcp_store/backend/facade/api.py@@ -5,6 +5,7 @@ This is the ONLY module other apps are allowed to import."""import uuid+from collections import Counter, defaultdictfrom collections.abc import Iterablefrom django.db.models import Q@@ -19,10 +20,16 @@ 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_access+from products.mcp_store.backend.gateway import (+ agent_grant_owner_label,+ agent_grant_proxy_path,+ installation_for_agent_access,+ reachable_agent_grants,+)from products.mcp_store.backend.models import (MCPServerInstallation,MCPServerInstallationTool,+ MCPServiceAccount,MCPServiceAccountServerAccess,)from products.mcp_store.backend.policy import GatewayCaller, PolicyContext@@ -120,26 +127,105 @@ def _is_oauth_ready(installation: MCPServerInstallation) -> bool:return True-def _to_info(- installation: MCPServerInstallation,- team_id: int,- *,- agent_proxy_token: str | None = None,-) -> ActiveInstallationInfo:- if agent_proxy_token is not None and installation.gateway_server_id is not None:- proxy_path = f"/api/mcp_store/gateway/servers/{installation.gateway_server_id}/proxy/"- else:- proxy_path = f"/api/environments/{team_id}/mcp_server_installations/{installation.id}/proxy/"-+def _to_info(installation: MCPServerInstallation, team_id: int) -> ActiveInstallationInfo:return ActiveInstallationInfo(id=str(installation.id),name=_resolve_name(installation),- proxy_path=proxy_path,+ proxy_path=f"/api/environments/{team_id}/mcp_server_installations/{installation.id}/proxy/",scope=installation.scope,- proxy_token=agent_proxy_token,)+def _mounts_for_agent_run(+ team_id: int,+ agent_account: MCPServiceAccount,+ credential_owner_id: int | None,+) -> list[tuple[MCPServiceAccountServerAccess, MCPServerInstallation]]:+ """The (grant, credential) pairs this run mounts.++ Health resolution runs before per-server precedence, not after. A grant only+ becomes a candidate once its credential still resolves, is enabled, sits on a+ server the team has left on, and (for OAuth) holds a usable token. Precedence+ is then applied over what survived, so a broken credential of the run's own+ owner falls out of the way of teammates' working team shares instead of+ suppressing them and mounting nothing for that server.++ Among the survivors of one server, the run's own credential owner wins+ outright, so the run acts through its own person's connection rather than+ borrowing one. Servers the owner has no working grant for mount every+ surviving team share side by side.++ That precedence is the default mount choice, not a gateway invariant: the+ agent catalog lists every reachable grant and the proxy's `credential_owner`+ query parameter lets a run name a teammate's team share instead. Selection+ is confined to the grants the run already reaches, so it never escalates.+ """+ rows = (+ MCPServiceAccountServerAccess.objects.for_team(team_id)+ .filter(service_account=agent_account)+ .filter(reachable_agent_grants(team_id, credential_owner_id))+ .select_related("installation__template", "installation__gateway_server", "user")+ .order_by("created_at", "id")+ )++ healthy_by_server: dict[uuid.UUID, list[tuple[MCPServiceAccountServerAccess, MCPServerInstallation]]] = defaultdict(+ list+ )+ for access in 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+ if not _is_oauth_ready(installation):+ continue+ healthy_by_server[access.gateway_server_id].append((access, installation))++ mounts: list[tuple[MCPServiceAccountServerAccess, MCPServerInstallation]] = []+ for server_mounts in healthy_by_server.values():+ own = (+ [(access, installation) for access, installation in server_mounts if access.user_id == credential_owner_id]+ if credential_owner_id+ else []+ )+ mounts.extend(own or server_mounts)+ return mounts+++def _agent_installation_infos(+ agent_account: MCPServiceAccount,+ mounts: list[tuple[MCPServiceAccountServerAccess, MCPServerInstallation]],+ credential_owner_id: int | None,+) -> list[ActiveInstallationInfo]:+ if not mounts:+ return []+ proxy_token = create_gateway_agent_token(agent_account, credential_owner_id=credential_owner_id)+ mounts_per_server = Counter(access.gateway_server_id for access, _installation in mounts)++ infos: list[ActiveInstallationInfo] = []+ for access, installation in mounts:+ name = _resolve_name(installation)+ if mounts_per_server[access.gateway_server_id] > 1:+ # Sandboxes key MCP servers by name, so two members' credentials for+ # the same server need distinct ones.+ name = f"{name} ({agent_grant_owner_label(access)})"+ infos.append(+ ActiveInstallationInfo(+ id=str(installation.id),+ name=name,+ proxy_path=agent_grant_proxy_path(access),+ scope=installation.scope,+ proxy_token=proxy_token,+ )+ )+ return infos++def get_active_installations(team_id: int, user_id: int) -> list[ActiveInstallationInfo]:"""Return active, ready-to-use personal MCP installations for a user.@@ -185,14 +271,14 @@ def get_installations_for_sandbox(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 by ``credential_owner_id``,- the person whose credentials the run may borrow (not necessarily the user- it acts as), 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, and the owner's eligibility (active user with- current effective team access) is re-checked on every call, so an- offboarded owner's grants stop mounting even though the grant rows- persist. Origin alone is not+ delegated through its service-account grants: those granted by+ ``credential_owner_id`` (the person whose credentials the run may borrow,+ not necessarily the user it acts as) plus any member's team-scoped grants,+ and only while the gateway server stays enabled for the team. An agent task+ with no credential owner mounts team-scoped grants alone. A named owner's+ eligibility (active user with current effective team access) is re-checked+ on every call, so an offboarded owner's grants stop mounting even though+ the grant rows persist. Origin alone is nottrusted: the persisted task agent key must match the origin mapping. Amapped origin without that marker gets no MCP Store installations. Built-in agenthandling is gated per team on the `mcp-gateway` rollout flag; teams@@ -226,39 +312,20 @@ 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]+ installations: list[MCPServerInstallation] = []+ agent_mounts: list[tuple[MCPServiceAccountServerAccess, MCPServerInstallation]] = []if agent_key is not None:- if agent_account is None or credential_owner_id is None:- installations = []- elif not credential_owner_eligible(credential_owner_id, team_id):- # Grants survive offboarding, so an owner who was deactivated- # or lost team access since delegating mounts nothing.- logger.warning(- "Refusing MCP installations for an ineligible credential owner",- team_id=team_id,- task_origin=task_origin,- )- installations = []- else:- access_rows = list(- MCPServiceAccountServerAccess.objects.for_team(team_id)- .filter(service_account=agent_account, user_id=credential_owner_id)- .select_related("installation__template", "installation__gateway_server")- )- 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)+ if agent_account is not None:+ if credential_owner_id is not None and not credential_owner_eligible(credential_owner_id, team_id):+ # Grants survive offboarding, so an owner who was deactivated+ # or lost team access since delegating mounts nothing.+ logger.warning(+ "Refusing MCP installations for an ineligible credential owner",+ team_id=team_id,+ task_origin=task_origin,+ )+ else:+ agent_mounts = _mounts_for_agent_run(team_id, agent_account, credential_owner_id)else:shared_queryset = base_queryset.filter(scope="shared")shared_queryset = shared_queryset.filter(@@ -279,28 +346,23 @@ def get_installations_for_sandbox(logger.warning("Error fetching MCP installations for sandbox", error=str(e), team_id=team_id)return []- ready = [installation for installation in installations if _is_oauth_ready(installation)]- if include_personal and user_id is not None:- personal_urls = {installation.url for installation in ready if installation.scope == "personal"}- ready = [- installation- for installation in ready- if installation.scope == "personal" or installation.url not in personal_urls- ]-- 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,- team_id,- agent_proxy_token=agent_proxy_token if agent_account is not None else None,+ results: list[ActiveInstallationInfo]+ if agent_key is not None:+ results = (+ _agent_installation_infos(agent_account, agent_mounts, credential_owner_id)+ if agent_account is not None+ else [])- for installation in ready- ]+ else:+ ready = [installation for installation in installations if _is_oauth_ready(installation)]+ if include_personal and user_id is not None:+ personal_urls = {installation.url for installation in ready if installation.scope == "personal"}+ ready = [+ installation+ for installation in ready+ if installation.scope == "personal" or installation.url not in personal_urls+ ]+ results = [_to_info(installation, team_id) for installation in ready]logger.debug("Found MCP installations for sandbox",diff --git a/products/mcp_store/backend/gateway.py b/products/mcp_store/backend/gateway.pyindex d1c2f7adcb60..aa27ca88e777 100644--- a/products/mcp_store/backend/gateway.py+++ b/products/mcp_store/backend/gateway.py@@ -7,16 +7,29 @@ an untouched catalog template when they toggle it (the gateway API'sset_template_enabled action). Servers with no row follow the team's`default_servers_enabled` posture."""+from django.db.models import Exists, OuterRef, Q+import structlogfrom posthog.models import User-from .models import MCPGatewayServer, MCPServerInstallation, MCPServiceAccountServerAccess, TeamMCPGatewayConfig+from .models import (+ MCPGatewayServer,+ MCPMemberServerRevocation,+ MCPServerInstallation,+ MCPServiceAccountServerAccess,+ TeamMCPGatewayConfig,+)logger = structlog.get_logger(__name__)_GATEWAY_SERVER_NAME_MAX_LENGTH = 200+# Query-string key naming whose credential a proxy call rides. Several members+# can team-share the same server with the same agent, so the gateway server id+# alone does not identify one grant.+AGENT_GRANT_CREDENTIAL_OWNER_PARAM = "credential_owner"+def members_can_manage_agent_access(team_id: int) -> bool:"""Whether regular members may grant MCP access to agents and tune it."""@@ -89,6 +102,48 @@ def installation_for_agent_grant()+def reachable_agent_grants(team_id: int, credential_owner_id: int | None) -> Q:+ """The grants an agent run may use: the run's own credential owner's grants+ at any scope, plus every member's team-scoped grants.++ A run with no credential owner (an autonomous support reply, a creatorless+ scout) reaches team-scoped grants only. Grant rows with no user resolve for+ nobody, so they are excluded from every lane.++ An admin's per-member revocation of the server applies here as well as on+ the member paths. Otherwise a member whose access an admin turned off would+ keep lending that credential to every agent run through a team-scoped grant.+ """+ revoked_for_grant_owner = MCPMemberServerRevocation.objects.for_team(team_id).filter(+ gateway_server_id=OuterRef("gateway_server_id"),+ user_id=OuterRef("user_id"),+ )+ reachable = Q(scope="team")+ if credential_owner_id is not None:+ reachable |= Q(user_id=credential_owner_id)+ return reachable & Q(user__isnull=False) & ~Q(Exists(revoked_for_grant_owner))+++def agent_grant_owner_label(access: MCPServiceAccountServerAccess) -> str:+ """Whose connection a grant lends, for telling two members' shares of the+ same server apart. The label lands in sandbox configs, model prompts, and+ logs, so it carries the owner's numeric id — the same discriminator as the+ proxy path's credential_owner parameter — rather than an email or display+ name. Blank only for the user-less legacy rows, which no read path mounts.+ """+ return f"#{access.user_id}" if access.user_id is not None else ""+++def agent_grant_proxy_path(access: MCPServiceAccountServerAccess) -> str:+ """Where an agent sends calls for one grant. The credential owner is named+ explicitly so that teammates' team shares of the same server stay+ addressable as separate servers."""+ return (+ f"/api/mcp_store/gateway/servers/{access.gateway_server_id}/proxy/"+ f"?{AGENT_GRANT_CREDENTIAL_OWNER_PARAM}={access.user_id}"+ )++def installation_for_agent_access(access: MCPServiceAccountServerAccess) -> MCPServerInstallation | None:"""Resolve the exact credential bound to an access row, which must still bethe granting person's own connection to that server."""diff --git a/products/mcp_store/backend/migrations/0026_agent_grant_scope.py b/products/mcp_store/backend/migrations/0026_agent_grant_scope.pynew file mode 100644index 000000000000..10ff7a4f6138--- /dev/null+++ b/products/mcp_store/backend/migrations/0026_agent_grant_scope.py@@ -0,0 +1,49 @@+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ """Add team scope to agent grants, plus the audit columns recording which+ member's credential an agent call rode.++ Additive only. Every new column is nullable or carries a Postgres-level+ default, so pods on the previous release keep inserting grants and audit+ rows without them while the deploy rolls.+ """++ dependencies = [+ ("mcp_store", "0025_drop_old_agent_server_access"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AddField(+ model_name="mcpauditevent",+ name="credential_owner",+ field=models.ForeignKey(+ blank=True,+ db_constraint=False,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.DO_NOTHING,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ migrations.AddField(+ model_name="mcpauditevent",+ name="grant_scope",+ field=models.CharField(blank=True, db_default="", default="", max_length=20),+ ),+ migrations.AddField(+ model_name="mcpserviceaccountserveraccess",+ name="scope",+ field=models.CharField(+ choices=[("personal", "Personal"), ("team", "Team")],+ db_default="personal",+ default="personal",+ max_length=20,+ ),+ ),+ ]diff --git a/products/mcp_store/backend/migrations/max_migration.txt b/products/mcp_store/backend/migrations/max_migration.txtindex 43f83954a3ea..63f332a4cee2 100644--- a/products/mcp_store/backend/migrations/max_migration.txt+++ b/products/mcp_store/backend/migrations/max_migration.txt@@ -1 +1 @@-0025_drop_old_agent_server_access+0026_agent_grant_scopediff --git a/products/mcp_store/backend/models.py b/products/mcp_store/backend/models.pyindex 60232941af67..5f905e02595b 100644--- a/products/mcp_store/backend/models.py+++ b/products/mcp_store/backend/models.py@@ -36,6 +36,16 @@ SCOPE_CHOICES = [("shared", "Shared"),]+# How far an agent grant reaches. "personal" applies only to runs whose+# credential owner is the granting member; "team" lets any of the team's agent+# runs borrow that member's credential, including runs with no owner at all+# (autonomous support replies, creatorless scouts). It never lets another human+# use the credential.+AGENT_GRANT_SCOPE_CHOICES = [+ ("personal", "Personal"),+ ("team", "Team"),+]+SERVICE_ACCOUNT_STATUS_CHOICES = [("active", "Active"),("paused", "Paused"),@@ -167,6 +177,9 @@ class MCPServerInstallation(CreatedMetaFields, UpdatedMetaFields, UUIDModel):description = models.TextField(blank=True, default="")auth_type = models.CharField(max_length=20, choices=AUTH_TYPE_CHOICES, default="oauth")is_enabled = models.BooleanField(default=True)+ # Deprecated: "shared" let teammates borrow one member's credential, which is being+ # removed in favor of per-member connections plus agent grants. The column drop is a+ # follow-up.# db_default keeps a real Postgres DEFAULT so inserts from code predating# this column (old pods during a rolling deploy) don't hit the NOT NULL.scope = models.CharField(max_length=20, choices=SCOPE_CHOICES, default="personal", db_default="personal")@@ -399,6 +412,14 @@ class MCPServiceAccountServerAccess(TeamScopedRootMixin, UUIDModel):# 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)+ # Who the grant reaches (see AGENT_GRANT_SCOPE_CHOICES). Deliberately not part of any+ # uniqueness constraint: several members may each team-share the same (agent, server),+ # and every one of those credentials mounts side by side for a run that has none of its+ # own. db_default keeps a real Postgres DEFAULT so grant inserts from pods running the+ # previous release don't hit the NOT NULL mid-deploy.+ scope = models.CharField(+ max_length=20, choices=AGENT_GRANT_SCOPE_CHOICES, default="personal", db_default="personal"+ )# 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(@@ -502,6 +523,26 @@ class MCPAuditEvent(TeamScopedRootMixin, UUIDModel):MCPServiceAccount, on_delete=models.SET_NULL, null=True, blank=True, related_name="audit_events")actor_label = models.CharField(max_length=254, blank=True, default="")+ # Whose credential an agent call rode, and under which grant scope. Without these,+ # a team-scoped grant makes "which member's connection did this agent use"+ # unanswerable after the fact. Both stay empty for member calls.+ # db_index=False: nothing filters the trail by credential owner, and building an+ # index on an existing audit table would lock it for the length of the build.+ # DO_NOTHING with db_constraint=False because the alternatives both cost more than+ # the dangling id does: SET_NULL would make every user deletion (SCIM+ # deprovisioning included) seq-scan and rewrite this whole unindexed table, and it+ # would erase the attribution the column exists to preserve. Read paths render a+ # deleted owner as absent, and actor_label keeps the denormalized identity.+ credential_owner = models.ForeignKey(+ "posthog.User",+ on_delete=models.DO_NOTHING,+ null=True,+ blank=True,+ related_name="+",+ db_constraint=False,+ db_index=False,+ )+ grant_scope = models.CharField(max_length=20, blank=True, default="", db_default="")server_name = models.CharField(max_length=200, blank=True, default="")tool_name = models.CharField(max_length=200, blank=True, default="")decision = models.CharField(max_length=20, choices=AUDIT_DECISION_CHOICES)diff --git a/products/mcp_store/backend/presentation/agent_views.py b/products/mcp_store/backend/presentation/agent_views.pyindex ea08fe64fc87..efd53dafa2a6 100644--- a/products/mcp_store/backend/presentation/agent_views.py+++ b/products/mcp_store/backend/presentation/agent_views.py@@ -5,16 +5,19 @@ 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.-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.+Grants are per person: the token names the person whose credentials the run may+use, and only that person's grants plus the team's team-scoped grants are+visible or callable. A token with no credential owner reaches team-scoped grants+alone. Every tools/call resolves through the same policy engine as members,+under the agent's own scope."""-from collections import defaultdict+from collections import Counter, defaultdictfrom datetime import timedeltafrom typing import Any, castfrom uuid import UUID+from django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.http import HttpResponsefrom django.http.response import HttpResponseBasefrom django.utils import timezone@@ -33,7 +36,13 @@ from rest_framework.views import APIViewfrom posthog.rate_limit import MCPProxyBurstThrottle, MCPProxySustainedThrottlefrom ..agents import GatewayAgentPrincipal, resolve_gateway_agent_token-from ..gateway import installation_for_agent_access+from ..gateway import (+ AGENT_GRANT_CREDENTIAL_OWNER_PARAM,+ agent_grant_owner_label,+ agent_grant_proxy_path,+ installation_for_agent_access,+ reachable_agent_grants,+)from ..models import MCPServerInstallationTool, MCPServiceAccount, MCPServiceAccountServerAccessfrom ..policy import GatewayCaller, PolicyContextfrom ..proxy import proxy_mcp_request, validate_installation_auth@@ -108,13 +117,10 @@ class MCPGatewayAgentViewSet(viewsets.ViewSet):account = principal.accountreturn list(MCPServiceAccountServerAccess.objects.for_team(account.team_id)- .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")+ .filter(service_account=account, gateway_server__is_team_enabled=True)+ .filter(reachable_agent_grants(account.team_id, principal.credential_owner_id))+ .select_related("gateway_server__template", "installation", "user")+ .order_by("gateway_server__name", "created_at"))def _touch(self, account: MCPServiceAccount) -> None:@@ -152,6 +158,7 @@ class MCPGatewayAgentViewSet(viewsets.ViewSet):):tools_by_installation[tool.installation_id].append(tool)+ grants_per_server = Counter(access.gateway_server_id for access, _installation in catalog_entries)results = []for access, installation in catalog_entries:server = access.gateway_server@@ -177,19 +184,55 @@ class MCPGatewayAgentViewSet(viewsets.ViewSet):.state,})+ # Teammates who team-shared the same server each contribute their own+ # credential, so the catalog carries one entry per grant and the name+ # says whose connection it is.+ name = (+ f"{server.name} ({agent_grant_owner_label(access)})"+ if grants_per_server[server.id] > 1+ else server.name+ )results.append({"id": str(server.id),- "name": server.name,+ "name": name,"url": server.url,"description": server.description,- "proxy_path": f"/api/mcp_store/gateway/servers/{server.id}/proxy/",+ "credential_owner_id": access.user_id,+ "proxy_path": agent_grant_proxy_path(access),"tools": tools,})self._touch(account)return Response({"results": results})+ def _grant_for_proxy(+ self, principal: GatewayAgentPrincipal, gateway_server_id: str, credential_owner_param: str | None+ ) -> MCPServiceAccountServerAccess | None:+ """Resolve which member's credential this call rides.++ `credential_owner` in the query string picks between several members'+ team shares of one server; it can only ever select a grant this+ principal already reaches, so it selects rather than escalates. Without+ it, the run's own credential owner wins and a team share is the+ fallback, matching how the sandbox mounts them.+ """+ account = principal.account+ candidates = (+ MCPServiceAccountServerAccess.objects.for_team(account.team_id)+ .filter(service_account=account, gateway_server_id=gateway_server_id)+ .filter(reachable_agent_grants(account.team_id, principal.credential_owner_id))+ .select_related("gateway_server", "installation")+ .order_by("created_at", "id")+ )+ if credential_owner_param:+ if not credential_owner_param.isdigit():+ return None+ return candidates.filter(user_id=int(credential_owner_param)).first()+ rows = list(candidates)+ own = [row for row in rows if row.user_id == principal.credential_owner_id]+ return next(iter(own or rows), None)+@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."""@@ -198,16 +241,10 @@ class MCPGatewayAgentViewSet(viewsets.ViewSet):if not pk:return HttpResponse('{"error": "Server not found"}', content_type="application/json", status=404)try:- access = (- MCPServiceAccountServerAccess.objects.for_team(account.team_id)- .select_related("gateway_server", "installation")- .get(- service_account=account,- gateway_server_id=pk,- user_id=principal.credential_owner_id,- )- )- except (MCPServiceAccountServerAccess.DoesNotExist, ValueError):+ access = self._grant_for_proxy(principal, pk, request.query_params.get(AGENT_GRANT_CREDENTIAL_OWNER_PARAM))+ except (DjangoValidationError, ValueError):+ access = None+ if access is None:return HttpResponse('{"error": "Server not found or not shared with this agent"}',content_type="application/json",@@ -233,7 +270,8 @@ 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,+ credential_owner_id=access.user_id,+ grant_scope=access.scope,)ok, error_response = validate_installation_auth(installation)@@ -248,4 +286,6 @@ class MCPGatewayAgentViewSet(viewsets.ViewSet):caller=caller,gateway_server=server,actor_label=account.handle,+ credential_owner_id=access.user_id,+ grant_scope=access.scope,)diff --git a/products/mcp_store/backend/presentation/gateway_views.py b/products/mcp_store/backend/presentation/gateway_views.pyindex 93cd7ee72603..0645d6932f82 100644--- a/products/mcp_store/backend/presentation/gateway_views.py+++ b/products/mcp_store/backend/presentation/gateway_views.py@@ -36,6 +36,7 @@ from posthog.permissions import DenyMCPBuiltInAgentOAuthfrom ..agents import built_in_agent_handles, get_built_in_agent_spec, sync_built_in_agentsfrom ..gateway import installation_for_agent_access, installation_for_agent_grant, members_can_manage_agent_accessfrom ..models import (+ AGENT_GRANT_SCOPE_CHOICES,APPROVAL_STATES,AUTH_TYPE_CHOICES,POLICY_PRESET_CHOICES,@@ -200,6 +201,13 @@ class GatewayAgentAccessSerializer(serializers.Serializer):service_account_id = serializers.UUIDField(help_text="Service account granted access.")user = UserBasicSerializer(help_text="The member whose connection the agent uses.")+ scope = serializers.ChoiceField(+ choices=AGENT_GRANT_SCOPE_CHOICES,+ help_text=(+ "'personal' lets the agent use this connection only when working for the member who shared it. "+ "'team' lets it use the connection for the whole project's agent runs."+ ),+ )name = serializers.CharField(help_text="Agent display name.")handle = serializers.CharField(help_text="Agent identity handle, e.g. posthog-support.")status = serializers.ChoiceField(@@ -356,6 +364,7 @@ class MCPGatewayServerSerializer(serializers.ModelSerializer):{"service_account_id": access.service_account_id,"user": UserBasicSerializer(access.user).data,+ "scope": access.scope,"name": access.service_account.name,"handle": access.service_account.handle,"status": access.service_account.status,@@ -578,6 +587,13 @@ class MCPServiceAccountServerSerializer(serializers.Serializer):id = serializers.UUIDField(help_text="Gateway server granted to the agent.")shared_by = UserBasicSerializer(help_text="The member whose connection the agent uses.")+ scope = serializers.ChoiceField(+ choices=AGENT_GRANT_SCOPE_CHOICES,+ help_text=(+ "'personal' lets the agent use this connection only when working for the member who shared it. "+ "'team' lets it use the connection for the whole project's agent runs."+ ),+ )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.")@@ -656,6 +672,7 @@ class MCPServiceAccountSerializer(serializers.ModelSerializer):{"id": server.id,"shared_by": UserBasicSerializer(access.user).data,+ "scope": access.scope,"name": server.name,"description": server.description,"icon_key": server.template.icon_key if server.template else "",@@ -680,6 +697,18 @@ class ServiceAccountAccessUpdateSerializer(serializers.Serializer):enabled = serializers.BooleanField(help_text="True shares the caller's own connection with the agent, false removes the caller's share.")+ scope = serializers.ChoiceField(+ choices=AGENT_GRANT_SCOPE_CHOICES,+ required=False,+ default="personal",+ help_text=(+ "Applies to the caller's own share, and only alongside enabled=true. "+ "'personal' lets the agent use the connection when it works for the caller. "+ "'team' lets it use the connection for the whole project's agent runs, including "+ "runs nobody started. It never lets another person use the connection. "+ "Defaults to personal, so re-sharing without this field resets the caller's share to personal."+ ),+ )all = serializers.BooleanField(required=False,default=False,@@ -744,6 +773,20 @@ class MCPAuditEventSerializer(serializers.ModelSerializer):actor_service_account = serializers.SerializerMethodField(help_text="Agent that made the call, if any. Null for member calls.")+ credential_owner = UserBasicSerializer(+ read_only=True,+ allow_null=True,+ help_text=(+ "Member whose connection an agent call used. Null for member calls "+ "and for owners whose account has since been deleted."+ ),+ )+ grant_scope = serializers.ChoiceField(+ choices=AGENT_GRANT_SCOPE_CHOICES,+ allow_blank=True,+ read_only=True,+ help_text="Scope of the agent grant the call used. Blank for member calls.",+ )class Meta:model = MCPAuditEvent@@ -756,8 +799,17 @@ class MCPAuditEventSerializer(serializers.ModelSerializer):"actor_user","actor_service_account","actor_label",+ "credential_owner",+ "grant_scope",+ ]+ read_only_fields = [+ "id",+ "created_at",+ "server_name",+ "tool_name",+ "decision",+ "actor_label",]- read_only_fields = ["id", "created_at", "server_name", "tool_name", "decision", "actor_label"]extra_kwargs = {"server_name": {"help_text": "Gateway server name at call time (denormalized)."},"tool_name": {"help_text": "Tool that was called."},@@ -1221,7 +1273,11 @@ class MCPServiceAccountViewSet("""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.+ connection, and the agent may use it only when acting for the caller,+ unless the caller sends `scope=team` to lend it to the project's agent+ runs generally. Scope only ever applies to the caller's own share: it is+ their credential to lend, so no admin permission is involved and no+ member can change someone else's share.`enabled=false` removes the caller's own share and leaves other members'shares, and the agent's tool policies, in place.@@ -1284,6 +1340,7 @@ class MCPServiceAccountViewSet("team_id": self.team_id,"installation": installation,"granted_by": user,+ "scope": data.get("scope", "personal"),},)for entry in policies:@@ -1323,6 +1380,7 @@ class MCPServiceAccountViewSet("handle": account.handle,"server_name": server.name,"enabled": data["enabled"],+ "scope": data.get("scope", "personal"),"all_members": bool(data.get("all")),},team=self.team,@@ -1395,7 +1453,7 @@ class MCPAuditEventViewSet(events = MCPAuditEvent.objects.for_team(self.team_id)if not self._is_project_admin():events = events.filter(installation__user_id=cast(User, self.request.user).id)- return events.select_related("actor_user", "actor_service_account").order_by("-created_at")+ return events.select_related("actor_user", "actor_service_account", "credential_owner").order_by("-created_at")@validated_request(query_serializer=AuditQuerySerializer,diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.pyindex 7930e40102ca..97a4616fbe7e 100644--- a/products/mcp_store/backend/proxy.py+++ b/products/mcp_store/backend/proxy.py@@ -412,6 +412,8 @@ def _write_audit_events(caller: GatewayCaller,actor_label: str,entries: list[tuple[str, str]],+ credential_owner_id: int | None = None,+ grant_scope: str = "",) -> None:"""Best-effort audit trail — a failed insert must never break the proxy."""try:@@ -424,6 +426,8 @@ def _write_audit_events(actor_user_id=caller.user_id,actor_service_account_id=caller.service_account_id,actor_label=actor_label,+ credential_owner_id=credential_owner_id,+ grant_scope=grant_scope,server_name=gateway_server.name,tool_name=tool_name,decision=decision,@@ -444,7 +448,15 @@ def proxy_mcp_request(caller: GatewayCaller | None = None,gateway_server: MCPGatewayServer | None = None,actor_label: str = "",+ credential_owner_id: int | None = None,+ grant_scope: str = "",) -> HttpResponseBase:+ """Forward one MCP request upstream, enforcing tool policy and auditing it.++ `credential_owner_id` and `grant_scope` describe the agent grant the call+ rides, so the audit trail answers whose connection an agent used. Both are+ empty for member calls, where the actor already is the credential owner.+ """allowed, error = is_url_allowed(installation.url)if not allowed:logger.warning("SSRF: blocked proxy request", url=installation.url, reason=error)@@ -475,7 +487,15 @@ def proxy_mcp_request(enforcement_response = enforce_tool_approval(installation, data, policy_context, audit_entries)if gateway_server is not None and caller is not None and audit_entries:- _write_audit_events(installation, gateway_server, caller, actor_label, audit_entries)+ _write_audit_events(+ installation,+ gateway_server,+ caller,+ actor_label,+ audit_entries,+ credential_owner_id=credential_owner_id,+ grant_scope=grant_scope,+ )if enforcement_response:return enforcement_responsediff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.pyindex 07c9a1e64be3..69a7028848e1 100644--- a/products/mcp_store/backend/test/test_api.py+++ b/products/mcp_store/backend/test/test_api.py@@ -24,6 +24,7 @@ from posthog.models.organization import OrganizationMembershipfrom products.mcp_store.backend.agents import create_gateway_agent_token, sync_built_in_agentsfrom products.mcp_store.backend.models import (+ MCPAuditEvent,MCPGatewayServer,MCPMemberServerRevocation,MCPOAuthState,@@ -867,6 +868,30 @@ class TestMCPGatewayServerAPI(APIBaseTest):.exists())+ def test_deleting_a_credential_owner_leaves_the_audit_trail_intact(self) -> None:+ self._make_admin()+ owner = User.objects.create_and_join(self.organization, "[email protected]", "password")+ event = MCPAuditEvent.objects.for_team(self.team.id).create(+ team=self.team,+ credential_owner=owner,+ grant_scope="team",+ actor_label="posthog-scout",+ server_name="Notion",+ tool_name="search",+ decision="allowed",+ )++ owner_id = owner.id+ owner.delete()++ # SET_NULL would rewrite the row and erase the attribution the column exists for,+ # on top of seq-scanning this deliberately unindexed table on every user deletion.+ event.refresh_from_db()+ assert (event.credential_owner_id, event.actor_label) == (owner_id, "posthog-scout")+ response = self.client.get(f"/api/projects/{self.team.id}/mcp_gateway/audit/")+ assert response.status_code == status.HTTP_200_OK+ assert [(row["id"], row["credential_owner"]) for row in response.json()["results"]] == [(str(event.id), None)]+class TestMCPGatewayConfigAPI(APIBaseTest):def _api_url(self, suffix: str = "") -> str:@@ -1370,6 +1395,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):"icon_key": "","icon_domain": "","connection_state": "ready",+ "scope": "personal",}]@@ -1607,6 +1633,137 @@ class TestMCPServiceAccountAPI(APIBaseTest):assert self._agent_grant_user_ids(account, server) == sorted([self.user.id, teammate.id])assert self._agent_policy_exists(account, server)+ def test_member_team_scopes_their_own_share_and_leaves_a_teammates_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": True, "scope": "team"},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ scopes = dict(+ MCPServiceAccountServerAccess.objects.for_team(self.team.id)+ .filter(service_account=account, gateway_server=server)+ .values_list("user_id", "scope")+ )+ assert scopes == {self.user.id: "team", teammate.id: "personal"}++ def _server_granted_by(+ self, account: MCPServiceAccount, owner: User, *, scope: str, url: str+ ) -> tuple[MCPGatewayServer, MCPServerInstallation]:+ server = MCPGatewayServer.objects.for_team(self.team.id).filter(url=url).first()+ if server is None:+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Lane server",+ url=url,+ )+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=owner,+ display_name="Lane",+ url=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,+ scope=scope,+ )+ return server, installation++ @parameterized.expand(+ [+ ("nobodys_run_cannot_reach_a_personal_share", False, "personal", status.HTTP_404_NOT_FOUND),+ ("nobodys_run_reaches_a_team_share", False, "team", status.HTTP_200_OK),+ ("another_members_run_reaches_a_team_share", True, "team", status.HTTP_200_OK),+ ]+ )+ @patch("products.mcp_store.backend.presentation.agent_views.proxy_mcp_request")+ def test_agent_grant_scope_decides_which_runs_reach_it(+ self, _name: str, run_has_owner: bool, scope: str, expected_status: int, mock_proxy+ ) -> None:+ mock_proxy.return_value = HttpResponse('{"jsonrpc": "2.0"}', content_type="application/json")+ account = self._active_scout_account()+ server, _installation = self._server_granted_by(+ account, self.user, scope=scope, url="https://mcp.lane.example.com/mcp"+ )+ runner_id = None+ if run_has_owner:+ runner = User.objects.create_and_join(self.organization, "[email protected]", "password")+ runner_id = runner.id+ client = self._agent_client(account, create_gateway_agent_token(account, credential_owner_id=runner_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",+ )++ reachable = expected_status == status.HTTP_200_OK+ assert proxy_response.status_code == expected_status+ assert mock_proxy.called is reachable+ assert [entry["id"] for entry in catalog_response.json()["results"]] == ([str(server.id)] if reachable else [])++ @parameterized.expand([("nobodys_run", False), ("owners_own_run", True)])+ @patch("products.mcp_store.backend.presentation.agent_views.proxy_mcp_request")+ def test_agent_lane_honors_an_admins_per_member_revocation(+ self, _name: str, run_has_owner: bool, mock_proxy+ ) -> None:+ mock_proxy.return_value = HttpResponse('{"jsonrpc": "2.0"}', content_type="application/json")+ account = self._active_scout_account()+ server, _installation = self._server_granted_by(+ account, self.user, scope="team", url="https://mcp.revoked.example.com/mcp"+ )+ admin = User.objects.create_and_join(self.organization, "[email protected]", "password")+ MCPMemberServerRevocation.objects.for_team(self.team.id).create(+ team_id=self.team.id, gateway_server=server, user=self.user, revoked_by=admin+ )+ owner_id = self.user.id if run_has_owner else None+ client = self._agent_client(account, create_gateway_agent_token(account, credential_owner_id=owner_id))++ catalog_response = client.get("/api/mcp_store/gateway/servers/")+ proxy_response = client.post(+ f"/api/mcp_store/gateway/servers/{server.id}/proxy/?credential_owner={self.user.id}",+ data={"jsonrpc": "2.0", "method": "tools/list", "id": 1},+ format="json",+ )++ assert catalog_response.json()["results"] == []+ assert proxy_response.status_code == status.HTTP_404_NOT_FOUND+ assert not mock_proxy.called++ @patch("products.mcp_store.backend.presentation.agent_views.proxy_mcp_request")+ def test_proxy_uses_the_credential_named_in_the_query_string(self, mock_proxy) -> None:+ mock_proxy.return_value = HttpResponse('{"jsonrpc": "2.0"}', content_type="application/json")+ account = self._active_scout_account()+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ url = "https://mcp.two-shares.example.com/mcp"+ server, _mine = self._server_granted_by(account, self.user, scope="team", url=url)+ _server, theirs = self._server_granted_by(account, teammate, scope="team", url=url)+ client = self._agent_client(account, create_gateway_agent_token(account, credential_owner_id=None))++ response = client.post(+ f"/api/mcp_store/gateway/servers/{server.id}/proxy/?credential_owner={teammate.id}",+ data={"jsonrpc": "2.0", "method": "tools/list", "id": 1},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ assert mock_proxy.call_args.args[1].id == theirs.id+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/"@@ -1681,6 +1838,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):"icon_key": "notion","icon_domain": "notion.so","connection_state": "missing_credential",+ "scope": "personal",}]@@ -2006,6 +2164,10 @@ class TestMCPServiceAccountAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json()["error"]["code"] == -32002mock_http_client.assert_not_called()+ # Whose credential an agent rode has to survive in the trail, or a team-scoped+ # grant makes the question unanswerable after the fact.+ audit_event = MCPAuditEvent.objects.for_team(self.team.id).get(gateway_server=server)+ assert (audit_event.credential_owner_id, audit_event.grant_scope) == (self.user.id, "personal")def test_agent_grant_on_disabled_server_stays_dormant_until_team_enabled(self) -> None:self._make_admin()@@ -2072,6 +2234,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):"icon_key": "","icon_domain": "","connection_state": "ready",+ "scope": "personal",}]diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.pyindex 11be4df67fbb..6021429c6de9 100644--- a/products/mcp_store/backend/test/test_facade.py+++ b/products/mcp_store/backend/test/test_facade.py@@ -15,6 +15,7 @@ from products.mcp_store.backend.facade.api import get_active_installations, get_from products.mcp_store.backend.facade.contracts import ActiveInstallationInfofrom products.mcp_store.backend.models import (MCPGatewayServer,+ MCPMemberServerRevocation,MCPServerInstallation,MCPServerTemplate,MCPServiceAccount,@@ -303,7 +304,10 @@ class TestGetInstallationsForSandbox(BaseTest):)assert [result.id for result in results] == [str(personal.id)]- assert results[0].proxy_path == f"/api/mcp_store/gateway/servers/{granted_server.id}/proxy/"+ assert (+ results[0].proxy_path+ == f"/api/mcp_store/gateway/servers/{granted_server.id}/proxy/?credential_owner={self.user.id}"+ )assert results[0].proxy_token is not Noneassert results[0].proxy_token.startswith("mcp_gw_")@@ -414,6 +418,155 @@ class TestGetInstallationsForSandbox(BaseTest):assert resolve_gateway_agent_token(token) is None+ def _grant(+ self,+ account: MCPServiceAccount,+ server: MCPGatewayServer,+ *,+ user: User | None,+ installation: MCPServerInstallation,+ scope: str = "personal",+ ) -> MCPServiceAccountServerAccess:+ return MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ user=user,+ service_account=account,+ gateway_server=server,+ installation=installation,+ granted_by=user,+ scope=scope,+ )++ def _agent_results(self, 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,+ )++ def test_agent_run_mounts_its_owners_grants_plus_teammates_team_shares(self) -> None:+ account = self._support_agent()+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ own_server = self._create_gateway_server(name="Own", url="https://own.example.com/mcp")+ team_server = self._create_gateway_server(name="Team", url="https://team.example.com/mcp")+ private_server = self._create_gateway_server(name="Private", url="https://private.example.com/mcp")+ own = self._create_installation(gateway_server=own_server, url=own_server.url)+ team_shared = self._create_installation(user=teammate, gateway_server=team_server, url=team_server.url)+ teammate_private = self._create_installation(+ user=teammate, gateway_server=private_server, url=private_server.url+ )+ self._grant(account, own_server, user=self.user, installation=own)+ self._grant(account, team_server, user=teammate, installation=team_shared, scope="team")+ self._grant(account, private_server, user=teammate, installation=teammate_private)++ results = self._agent_results(self.user.id)++ assert {result.id for result in results} == {str(own.id), str(team_shared.id)}++ def test_agent_run_without_a_credential_owner_mounts_only_team_shares(self) -> None:+ account = self._support_agent()+ team_server = self._create_gateway_server(name="Team", url="https://team.example.com/mcp")+ personal_server = self._create_gateway_server(name="Personal", url="https://personal.example.com/mcp")+ team_shared = self._create_installation(gateway_server=team_server, url=team_server.url)+ personal = self._create_installation(gateway_server=personal_server, url=personal_server.url)+ self._grant(account, team_server, user=self.user, installation=team_shared, scope="team")+ self._grant(account, personal_server, user=self.user, installation=personal)++ results = self._agent_results(None)++ assert [result.id for result in results] == [str(team_shared.id)]+ principal = resolve_gateway_agent_token(results[0].proxy_token or "")+ assert principal is not None+ assert principal.credential_owner_id is None++ def test_owner_credential_wins_over_a_teammates_team_share_of_the_same_server(self) -> None:+ account = self._support_agent()+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ server = self._create_gateway_server(name="Shared server", url="https://shared.example.com/mcp")+ own = self._create_installation(gateway_server=server, url=server.url)+ teammate_installation = self._create_installation(user=teammate, gateway_server=server, url=server.url)+ self._grant(account, server, user=self.user, installation=own)+ self._grant(account, server, user=teammate, installation=teammate_installation, scope="team")++ results = self._agent_results(self.user.id)++ assert [result.id for result in results] == [str(own.id)]++ def test_every_team_share_of_one_server_mounts_under_its_owners_id(self) -> None:+ account = self._support_agent()+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ server = self._create_gateway_server(name="Shared server", url="https://shared.example.com/mcp")+ mine = self._create_installation(gateway_server=server, url=server.url, display_name="Notion")+ theirs = self._create_installation(user=teammate, gateway_server=server, url=server.url, display_name="Notion")+ self._grant(account, server, user=self.user, installation=mine, scope="team")+ self._grant(account, server, user=teammate, installation=theirs, scope="team")++ results = self._agent_results(None)++ assert {result.id for result in results} == {str(mine.id), str(theirs.id)}+ # Sandboxes key servers by name and the gateway resolves a credential from the+ # proxy path, so both have to be unique per mounted grant.+ assert {result.name for result in results} == {+ f"Notion (#{self.user.id})",+ f"Notion (#{teammate.id})",+ }+ assert {result.proxy_path for result in results} == {+ f"/api/mcp_store/gateway/servers/{server.id}/proxy/?credential_owner={self.user.id}",+ f"/api/mcp_store/gateway/servers/{server.id}/proxy/?credential_owner={teammate.id}",+ }++ @parameterized.expand(+ [+ ("credential_deleted", "deleted"),+ ("oauth_needs_reauth", "unready_oauth"),+ ("installation_disabled", "disabled"),+ ]+ )+ def test_broken_own_grant_does_not_suppress_a_working_team_share(self, _name: str, breakage: str) -> None:+ account = self._support_agent()+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ server = self._create_gateway_server(name="Shared server", url="https://shared.example.com/mcp")+ own_kwargs: dict = {"gateway_server": server, "url": server.url}+ if breakage == "unready_oauth":+ own_kwargs |= {"auth_type": "oauth", "sensitive_configuration": {"needs_reauth": True}}+ if breakage == "disabled":+ own_kwargs |= {"is_enabled": False}+ own = self._create_installation(**own_kwargs)+ teammate_installation = self._create_installation(user=teammate, gateway_server=server, url=server.url)+ own_grant = self._grant(account, server, user=self.user, installation=own)+ self._grant(account, server, user=teammate, installation=teammate_installation, scope="team")+ if breakage == "deleted":+ own.delete()+ own_grant.refresh_from_db()+ assert own_grant.installation_id is None++ results = self._agent_results(self.user.id)++ assert [result.id for result in results] == [str(teammate_installation.id)]++ @parameterized.expand([("nobodys_run", False), ("owners_own_run", True)])+ def test_revoked_members_team_share_is_not_mounted(self, _name: str, run_has_owner: bool) -> None:+ account = self._support_agent()+ server = self._create_gateway_server(name="Revoked", url="https://revoked.example.com/mcp")+ installation = self._create_installation(gateway_server=server, url=server.url)+ self._grant(account, server, user=self.user, installation=installation, scope="team")+ admin = User.objects.create_and_join(self.organization, "[email protected]", "password")+ MCPMemberServerRevocation.objects.for_team(self.team.id).create(+ team_id=self.team.id, gateway_server=server, user=self.user, revoked_by=admin+ )++ assert self._agent_results(self.user.id if run_has_owner else None) == []++ def test_team_scoped_grant_without_a_user_is_never_mounted(self) -> None:+ account = self._support_agent()+ server = self._create_gateway_server(name="Orphaned", url="https://orphaned.example.com/mcp")+ installation = self._create_installation(gateway_server=server, url=server.url)+ self._grant(account, server, user=None, installation=installation, scope="team")++ assert self._agent_results(None) == []+ assert self._agent_results(self.user.id) == []+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(diff --git a/products/mcp_store/frontend/gateway/GatewayAgentScene.tsx b/products/mcp_store/frontend/gateway/GatewayAgentScene.tsxindex 5d0dc9c90914..4493fad4f0c5 100644--- a/products/mcp_store/frontend/gateway/GatewayAgentScene.tsx+++ b/products/mcp_store/frontend/gateway/GatewayAgentScene.tsx@@ -15,7 +15,13 @@ import type { ConnectionStateEnumApi, MCPGatewayServerApi } from '../generated/aimport { ServerIcon } from '../scene/icons'import { GatewayAgentLogicProps, gatewayAgentLogic } from './gatewayAgentLogic'import { GatewayRouteGuard } from './GatewayRouteGuard'-import { DecisionTag, RemoveAllSharesButton, sharedByLabel } from './gatewayUtils'+import {+ AgentGrantScopeControl,+ DecisionTag,+ RemoveAllSharesButton,+ credentialOwnerLabel,+ sharedByOthersLabel,+} from './gatewayUtils'import { AgentServerShare, agentServerAccessKey } from './mcpGatewayLogic'export const scene: SceneExport<(typeof gatewayAgentLogic)['props']> = {@@ -148,8 +154,17 @@ export function GatewayAgentScene({</LemonTag></div><div className="text-sm text-secondary">- Sharing is personal. {account.name} uses your connection only when it runs for you.+ You share your own connections. A personal share lets {account.name} use one when it runs for you. A+ team share lets it use one for every {account.name} run in this project, including runs nobody+ started. Teammates can't use the connection directly, but a team share means agents act through it+ on their runs too.</div>+ {account.agent_key === 'support' && (+ <div className="text-sm text-secondary">+ Support replies often run without a person behind them. A personal share goes unused on those+ runs. A team share covers them.+ </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">@@ -218,9 +233,18 @@ export function GatewayAgentScene({title: 'MCP server · tool called',key: 'server',render: (_, row) => (- <div className="flex items-baseline gap-2 min-w-0">- <span className="font-semibold text-xs truncate">{row.server_name}</span>- <span className="font-mono text-xs text-secondary truncate">{row.tool_name}()</span>+ <div className="min-w-0">+ <div className="flex items-baseline gap-2 min-w-0">+ <span className="font-semibold text-xs truncate">{row.server_name}</span>+ <span className="font-mono text-xs text-secondary truncate">+ {row.tool_name}()+ </span>+ </div>+ {row.credential_owner && (+ <div className="text-xs text-secondary">+ {credentialOwnerLabel(row.credential_owner, row.grant_scope)}+ </div>+ )}</div>),},@@ -288,7 +312,7 @@ function ServerAccessRow({}): JSX.Element {const sharedByYou = Boolean(share?.sharedByYou)const sharedByOthers = share?.sharedByOthers ?? []- const attribution = sharedByLabel(sharedByOthers)+ const attribution = share ? sharedByOthersLabel(share) : nullconst connectionDisabledReason = sharedByYou ? undefined : agentShareDisabledReason(server)const toolLabel = `${server.tool_count} ${server.tool_count === 1 ? 'tool' : 'tools'}`const connectionStatus = connectionState ? agentConnectionStatus(connectionState) : null@@ -310,6 +334,9 @@ function ServerAccessRow({{connectionStatus.label}</LemonTag>)}+ {sharedByYou && share && (+ <AgentGrantScopeControl accountId={accountId} serverId={server.id} scope={share.yourScope} />+ )}{shared && (<LemonButtonsize="xsmall"diff --git a/products/mcp_store/frontend/gateway/GatewayAuditLog.tsx b/products/mcp_store/frontend/gateway/GatewayAuditLog.tsxindex f05d7ed378be..7164be883a5b 100644--- a/products/mcp_store/frontend/gateway/GatewayAuditLog.tsx+++ b/products/mcp_store/frontend/gateway/GatewayAuditLog.tsx@@ -15,7 +15,7 @@ import { TZLabel } from 'lib/components/TZLabel'import { AuditCountsApi } from '../generated/api.schemas'import { AUDIT_PAGE_SIZE, AuditQuickFilter, gatewayAuditLogic } from './gatewayAuditLogic'-import { DecisionTag, toProfileUser } from './gatewayUtils'+import { DecisionTag, credentialOwnerLabel, toProfileUser } from './gatewayUtils'import { mcpGatewayLogic } from './mcpGatewayLogic'const FILTERS: { key: AuditQuickFilter; label: string; countKey: keyof AuditCountsApi }[] = [@@ -125,25 +125,36 @@ export function GatewayAuditLog(): JSX.Element {title: 'Caller',key: 'caller',render: (_, row) => (- <div className="flex items-center gap-2 min-w-0">- {row.actor_service_account ? (- <span className="flex items-center gap-1 min-w-0">- <IconSparkles />- <span className="truncate">{row.actor_service_account.name}</span>- </span>- ) : row.actor_user ? (- <ProfilePicture user={toProfileUser(row.actor_user)} size="sm" showName />- ) : (- <span className="text-secondary truncate">{row.actor_label || 'Unknown'}</span>+ <div className="min-w-0">+ <div className="flex items-center gap-2 min-w-0">+ {row.actor_service_account ? (+ <span className="flex items-center gap-1 min-w-0">+ <IconSparkles />+ <span className="truncate">{row.actor_service_account.name}</span>+ </span>+ ) : row.actor_user ? (+ <ProfilePicture user={toProfileUser(row.actor_user)} size="sm" showName />+ ) : (+ <span className="text-secondary truncate">{row.actor_label || 'Unknown'}</span>+ )}+ <LemonTag+ size="small"+ type={+ row.actor_service_account+ ? 'completion'+ : row.actor_user+ ? 'muted'+ : 'warning'+ }+ >+ {row.actor_service_account ? 'Agent' : row.actor_user ? 'Human' : 'Deleted'}+ </LemonTag>+ </div>+ {row.actor_service_account && row.credential_owner && (+ <div className="text-xs text-secondary">+ {credentialOwnerLabel(row.credential_owner, row.grant_scope)}+ </div>)}- <LemonTag- size="small"- type={- row.actor_service_account ? 'completion' : row.actor_user ? 'muted' : 'warning'- }- >- {row.actor_service_account ? 'Agent' : row.actor_user ? 'Human' : 'Deleted'}- </LemonTag></div>),},diff --git a/products/mcp_store/frontend/gateway/GatewayServerAccess.tsx b/products/mcp_store/frontend/gateway/GatewayServerAccess.tsxindex 5618d5b293e7..6cd59373a96b 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 { RemoveAllSharesButton, toProfileUser } from './gatewayUtils'+import { AgentGrantScopeControl, RemoveAllSharesButton, toProfileUser } from './gatewayUtils'import { agentServerAccessKey, mcpGatewayLogic, memberServerAccessKey } from './mcpGatewayLogic'const AGENT_POLICY_OPTIONS = [@@ -153,8 +153,9 @@ export function GatewayAccessSection(): JSX.Element | null {</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.+ You share your own {server.name} connection, and each teammate shares theirs. Pick whether an agent uses+ it only for your runs or for every agent run in this project. Teammates can't use the connection+ directly, but agents can act through it on their runs.</div>{server.agents.length === 0 ? (@@ -182,9 +183,16 @@ export function GatewayAccessSection(): JSX.Element | null {<span className="font-mono">{agent.handle}</span>{sharedByYou? ' · shared by you'- : ` · shared by ${agent.user.first_name || agent.user.email}`}+ : ` · shared ${agent.scope === 'team' ? 'to the team ' : ''}by ${agent.user.first_name || agent.user.email}`}</div></div>+ {sharedByYou && (+ <AgentGrantScopeControl+ accountId={agent.service_account_id}+ serverId={server.id}+ scope={agent.scope}+ />+ )}{sharedByYou ? (<LemonButtonsize="xsmall"diff --git a/products/mcp_store/frontend/gateway/gatewayAgentLogic.test.ts b/products/mcp_store/frontend/gateway/gatewayAgentLogic.test.tsindex a5d67483878b..5a4df41032cb 100644--- a/products/mcp_store/frontend/gateway/gatewayAgentLogic.test.ts+++ b/products/mcp_store/frontend/gateway/gatewayAgentLogic.test.ts@@ -88,6 +88,8 @@ function auditEvent(index: number): MCPAuditEventApi {handle: 'posthog-support',},actor_label: 'posthog-support',+ credential_owner: null,+ grant_scope: '',}}diff --git a/products/mcp_store/frontend/gateway/gatewayAgentLogic.ts b/products/mcp_store/frontend/gateway/gatewayAgentLogic.tsindex e13f64b5c0a9..70302d58e2b0 100644--- a/products/mcp_store/frontend/gateway/gatewayAgentLogic.ts+++ b/products/mcp_store/frontend/gateway/gatewayAgentLogic.ts@@ -47,11 +47,13 @@ export interface gatewayAgentLogicActions {accountId: string,serverId: string,enabled: boolean,+ scope?: import('../generated/api.schemas').MCPAgentGrantScopeEnumApi | undefined,policies?: import('../generated/api.schemas').ToolPolicyEntryApi[] | undefined) => {accountId: stringenabled: booleanpolicies: import('../generated/api.schemas').ToolPolicyEntryApi[] | undefined+ scope: import('../generated/api.schemas').MCPAgentGrantScopeEnumApiserverId: string} // mcpGatewayLogictoggleAccountStatus: (diff --git a/products/mcp_store/frontend/gateway/gatewayAuditLogic.test.ts b/products/mcp_store/frontend/gateway/gatewayAuditLogic.test.tsindex 60500ab99991..d15ffb76a05b 100644--- a/products/mcp_store/frontend/gateway/gatewayAuditLogic.test.ts+++ b/products/mcp_store/frontend/gateway/gatewayAuditLogic.test.ts@@ -23,6 +23,8 @@ function auditEvent(id: string): MCPAuditEventApi {actor_user: null,actor_service_account: null,actor_label: '[email protected]',+ credential_owner: null,+ grant_scope: '',}}diff --git a/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts b/products/mcp_store/frontend/gateway/gatewayServerLogic.test.tsindex a6e1bd7346c8..10f94ad9940f 100644--- a/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts+++ b/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts@@ -24,6 +24,7 @@ import {} from '../generated/api'import type {GatewayMemberSummaryApi,+ MCPAgentGrantScopeEnumApi,MCPGatewayServerApi,MCPServiceAccountApi,ResolvedToolPolicyApi,@@ -119,7 +120,9 @@ const TEAMMATE: UserBasicApi = {hedgehog_config: null,}-function serviceAccount(id: string = 'scout-id', sharedBy: UserBasicApi[] = []): MCPServiceAccountApi {+type Grant = { user: UserBasicApi; scope: MCPAgentGrantScopeEnumApi }++function serviceAccount(id: string = 'scout-id', grants: Grant[] = []): MCPServiceAccountApi {return {id,name: `Agent ${id}`,@@ -127,10 +130,11 @@ function serviceAccount(id: string = 'scout-id', sharedBy: UserBasicApi[] = []):handle: `svc-${id}`,agent_key: 'scout',status: 'active',- server_ids: sharedBy.map(() => 'server-id'),- servers: sharedBy.map((user) => ({+ server_ids: grants.map(() => 'server-id'),+ servers: grants.map(({ user, scope }) => ({id: 'server-id',shared_by: user,+ scope,name: 'Test server',description: '',icon_key: '',@@ -220,28 +224,53 @@ describe('gatewayServerLogic', () => {jest.restoreAllMocks()})- it('attributes each agent grant to the member backing it', () => {+ it('attributes each agent grant to the member backing it, and separates team shares', () => {parentLogic.actions.loadServiceAccountsSuccess([- serviceAccount('yours-only', [YOU]),- serviceAccount('teammate-only', [TEAMMATE]),- serviceAccount('both', [YOU, TEAMMATE]),+ serviceAccount('yours-team', [{ user: YOU, scope: 'team' }]),+ serviceAccount('teammate-personal', [{ user: TEAMMATE, scope: 'personal' }]),+ serviceAccount('teammate-team', [{ user: TEAMMATE, scope: 'team' }]),+ serviceAccount('both', [+ { user: YOU, scope: 'personal' },+ { user: TEAMMATE, scope: 'team' },+ ]),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: [] },+ 'yours-team': { sharedByYou: true, yourScope: 'team', sharedByOthers: [], teamSharedByOthers: [] },+ 'teammate-personal': {+ sharedByYou: false,+ yourScope: 'personal',+ sharedByOthers: [TEAMMATE],+ teamSharedByOthers: [],+ },+ 'teammate-team': {+ sharedByYou: false,+ yourScope: 'personal',+ sharedByOthers: [TEAMMATE],+ teamSharedByOthers: [TEAMMATE],+ },+ both: {+ sharedByYou: true,+ yourScope: 'personal',+ sharedByOthers: [TEAMMATE],+ teamSharedByOthers: [TEAMMATE],+ },+ unshared: { sharedByYou: false, yourScope: 'personal', sharedByOthers: [], teamSharedByOthers: [] },})})it('attributes no grant while the current user is still loading', () => {userLogic.actions.loadUserSuccess(null)- parentLogic.actions.loadServiceAccountsSuccess([serviceAccount('both', [YOU, TEAMMATE])])+ parentLogic.actions.loadServiceAccountsSuccess([+ serviceAccount('both', [+ { user: YOU, scope: 'team' },+ { user: TEAMMATE, scope: 'team' },+ ]),+ ])expect(logic.values.agentSharesByAccountId).toEqual({- both: { sharedByYou: false, sharedByOthers: [] },+ both: { sharedByYou: false, yourScope: 'personal', sharedByOthers: [], teamSharedByOthers: [] },})})@@ -352,6 +381,7 @@ describe('gatewayServerLogic', () => {expect(mockServiceAccountAccess).toHaveBeenCalledWith(expect.any(String), account.id, {gateway_server_id: 'server-id',enabled: true,+ scope: 'personal',policies: [{ tool_name: 'list_issues', policy_state: 'approved' },{ tool_name: 'create_issue', policy_state: 'do_not_use' },diff --git a/products/mcp_store/frontend/gateway/gatewayServerLogic.ts b/products/mcp_store/frontend/gateway/gatewayServerLogic.tsindex 2703cab930c2..917ac52db9fc 100644--- a/products/mcp_store/frontend/gateway/gatewayServerLogic.ts+++ b/products/mcp_store/frontend/gateway/gatewayServerLogic.ts@@ -215,11 +215,13 @@ export interface gatewayServerLogicActions {accountId: string,serverId: string,enabled: boolean,+ scope?: import('../generated/api.schemas').MCPAgentGrantScopeEnumApi | undefined,policies?: import('../generated/api.schemas').ToolPolicyEntryApi[] | undefined) => {accountId: stringenabled: booleanpolicies: import('../generated/api.schemas').ToolPolicyEntryApi[] | undefined+ scope: import('../generated/api.schemas').MCPAgentGrantScopeEnumApiserverId: string} // mcpGatewayLogicsetAgentServerAccessSuccess: (@@ -845,7 +847,7 @@ export const gatewayServerLogic = kea<gatewayServerLogicType>([values.agentAccessPolicyMap[policy.tool_name] ??defaultAgentGrantPolicy(policy.tool_name, policy.team_state, policy.is_destructive),}))- actions.setAgentServerAccess(values.agentAccessSelectedId, values.server.id, true, policies)+ actions.setAgentServerAccess(values.agentAccessSelectedId, values.server.id, true, 'personal', policies)},syncScopeFromUrl: async ({ scopeParam }, breakpoint) => {await breakpoint(0)diff --git a/products/mcp_store/frontend/gateway/gatewayUtils.tsx b/products/mcp_store/frontend/gateway/gatewayUtils.tsxindex 8a974b9d04f1..a6244b9414e6 100644--- a/products/mcp_store/frontend/gateway/gatewayUtils.tsx+++ b/products/mcp_store/frontend/gateway/gatewayUtils.tsx@@ -1,12 +1,12 @@import { useActions, useValues } from 'kea'import { IconCheck, IconShieldLock, IconX } from '@posthog/icons'-import { LemonBadge, LemonButton, LemonDialog, LemonTag } from '@posthog/lemon-ui'+import { LemonBadge, LemonButton, LemonDialog, LemonSegmentedButton, LemonTag } from '@posthog/lemon-ui'import { fullName } from 'lib/utils/strings'-import { MCPToolApprovalStateEnumApi, UserBasicApi } from '../generated/api.schemas'-import { agentServerAccessKey, mcpGatewayLogic } from './mcpGatewayLogic'+import { MCPAgentGrantScopeEnumApi, MCPToolApprovalStateEnumApi, UserBasicApi } from '../generated/api.schemas'+import { AgentServerShare, 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. */@@ -14,18 +14,72 @@ 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- }+function memberNames(users: UserBasicApi[]): string {const [first, ...rest] = usersconst name = fullName(first) || first.emailif (rest.length === 0) {- return `Shared by ${name}`+ return name+ }+ return `${name} and ${rest.length} other${rest.length === 1 ? '' : 's'}`+}++/** Attributes grants backed by other members' connections, so a member never reads+ * a teammate's share as their own. Team shares take the line when both kinds exist,+ * because those are the ones that also back the viewer's own agent runs. */+export function sharedByOthersLabel(share: AgentServerShare): string | null {+ if (share.teamSharedByOthers.length > 0) {+ return `Shared to the team by ${memberNames(share.teamSharedByOthers)}`}- return `Shared by ${name} and ${rest.length} other${rest.length === 1 ? '' : 's'}`+ if (share.sharedByOthers.length > 0) {+ return `Shared by ${memberNames(share.sharedByOthers)}`+ }+ return null+}++/** Whose connection an agent call rode, for audit rows. */+export function credentialOwnerLabel(owner: UserBasicApi, grantScope: string): string {+ const name = fullName(owner) || owner.email+ return grantScope === 'team' ? `via ${name}'s connection (team share)` : `via ${name}'s connection`+}++const AGENT_GRANT_SCOPE_OPTIONS: { value: MCPAgentGrantScopeEnumApi; label: string; tooltip: string }[] = [+ {+ value: 'personal',+ label: 'Just my agents',+ tooltip: 'The agent uses your connection only when it runs for you.',+ },+ {+ value: 'team',+ label: 'All team agents',+ tooltip:+ "The agent uses your connection for every run in this project, including runs nobody started. Teammates can't use the connection directly, but agents act through it on their runs too.",+ },+]++/** Scope picker for the viewer's own grant. Changing it re-sends the share with the+ * new scope, so it shares the share's in-flight key and cannot be double-submitted. */+export function AgentGrantScopeControl({+ accountId,+ serverId,+ scope,+}: {+ accountId: string+ serverId: string+ scope: MCPAgentGrantScopeEnumApi+}): JSX.Element {+ const { agentServerAccessLoadingKeys } = useValues(mcpGatewayLogic)+ const { setAgentServerAccess } = useActions(mcpGatewayLogic)+ const saving = agentServerAccessLoadingKeys.has(agentServerAccessKey(accountId, serverId))++ return (+ <LemonSegmentedButton+ size="xsmall"+ value={scope}+ options={AGENT_GRANT_SCOPE_OPTIONS}+ disabledReason={saving ? 'Saving your change' : undefined}+ onChange={(next) => setAgentServerAccess(accountId, serverId, true, next)}+ />+ )}/** Admin-only escape hatch: the share switch only ever controls the viewer's owndiff --git a/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.ts b/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.tsindex fdd6bd0b0041..9d47704a79d3 100644--- a/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.ts+++ b/products/mcp_store/frontend/gateway/mcpGatewayLogic.test.ts@@ -23,6 +23,7 @@ import {} from '../generated/api'import type {GatewayMemberSummaryApi,+ MCPAgentGrantScopeEnumApi,MCPGatewayServerApi,MCPServerInstallationApi,MCPServerTemplateApi,@@ -148,6 +149,33 @@ function serverTemplate(overrides: Partial<MCPServerTemplateApi>): MCPServerTemp}}+function serviceAccountWithShare(scope: MCPAgentGrantScopeEnumApi): MCPServiceAccountApi {+ return {+ id: 'account-id',+ name: 'Scout agent',+ description: '',+ handle: 'posthog-scout',+ agent_key: 'scout',+ status: 'active',+ server_ids: ['server-id'],+ servers: [+ {+ id: 'server-id',+ shared_by: YOU,+ scope,+ name: 'Test server',+ description: '',+ icon_key: '',+ icon_domain: '',+ connection_state: 'ready',+ },+ ],+ 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: {@@ -395,6 +423,7 @@ describe('mcpGatewayLogic', () => {{id: 'linear-id',shared_by: YOU,+ scope: 'personal' as const,name: 'Linear',description: '',icon_key: '',@@ -412,12 +441,13 @@ describe('mcpGatewayLogic', () => {mockServiceAccountAccess.mockResolvedValue(updatedAccount)await expectLogic(logic, () => {- logic.actions.setAgentServerAccess(account.id, 'linear-id', true, policies)+ logic.actions.setAgentServerAccess(account.id, 'linear-id', true, 'personal', policies)}).toFinishAllListeners()expect(mockServiceAccountAccess).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), account.id, {gateway_server_id: 'linear-id',enabled: true,+ scope: 'personal',policies,})expect(logic.values.agentServerAccessLoadingKeys).toEqual(new Set())@@ -437,6 +467,7 @@ describe('mcpGatewayLogic', () => {{id: 'linear-id',shared_by: YOU,+ scope: 'personal' as const,name: 'Linear',description: '',icon_key: '',@@ -667,4 +698,23 @@ describe('mcpGatewayLogic', () => {expect(logic.values.memberCount).toBe(101)expect(logic.values.members).toEqual([secondPageMember])})++ // The endpoint defaults an omitted scope back to personal, so a share sent without+ // one silently demotes a team share.+ it.each([+ ['team' as const, 'team'],+ [undefined, 'personal'],+ ])('sends scope %s as %s when sharing a server with an agent', async (requested, expected) => {+ mockServiceAccountAccess.mockResolvedValue(serviceAccountWithShare(expected as MCPAgentGrantScopeEnumApi))++ await expectLogic(logic, () => {+ logic.actions.setAgentServerAccess('account-id', 'server-id', true, requested)+ }).toFinishAllListeners()++ expect(mockServiceAccountAccess).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'account-id', {+ gateway_server_id: 'server-id',+ enabled: true,+ scope: expected,+ })+ })})diff --git a/products/mcp_store/frontend/gateway/mcpGatewayLogic.ts b/products/mcp_store/frontend/gateway/mcpGatewayLogic.tsindex f4e889b51e78..1941737f969d 100644--- a/products/mcp_store/frontend/gateway/mcpGatewayLogic.ts+++ b/products/mcp_store/frontend/gateway/mcpGatewayLogic.ts@@ -37,6 +37,7 @@ import {AudienceEnumApi,GatewayMemberSummaryApi,InstallCustomAuthTypeEnumApi,+ MCPAgentGrantScopeEnumApi,MCPGatewayServerApi,MCPOrgRuleApi,MCPPolicyPresetEnumApi,@@ -137,7 +138,13 @@ export function memberServerAccessKey(userId: number, serverId: string): string* connection, so the same agent and server can carry one grant per member. */export interface AgentServerShare {sharedByYou: boolean+ /** Scope of your own grant, and 'personal' when you have none, so the scope+ * control has a value to render before the first share exists. */+ yourScope: MCPAgentGrantScopeEnumApisharedByOthers: UserBasicApi[]+ /** The subset of `sharedByOthers` whose grant is team-scoped, which is the+ * only teammate grant that also backs agent runs other than the sharer's. */+ teamSharedByOthers: UserBasicApi[]}export function agentServerShare(@@ -148,14 +155,16 @@ export function 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: [] }+ return { sharedByYou: false, yourScope: 'personal', sharedByOthers: [], teamSharedByOthers: [] }}const grants = (account?.servers ?? []).filter((server) => server.id === serverId)+ const yours = grants.find((server) => server.shared_by.id === currentUserId)+ const others = grants.filter((server) => server.shared_by.id !== currentUserId)return {- sharedByYou: grants.some((server) => server.shared_by.id === currentUserId),- sharedByOthers: grants- .filter((server) => server.shared_by.id !== currentUserId)- .map((server) => server.shared_by),+ sharedByYou: yours !== undefined,+ yourScope: yours?.scope ?? 'personal',+ sharedByOthers: others.map((server) => server.shared_by),+ teamSharedByOthers: others.filter((server) => server.scope === 'team').map((server) => server.shared_by),}}@@ -436,11 +445,13 @@ export interface mcpGatewayLogicActions {accountId: string,serverId: string,enabled: boolean,+ scope?: MCPAgentGrantScopeEnumApi,policies?: ToolPolicyEntryApi[]) => {accountId: stringenabled: booleanpolicies: ToolPolicyEntryApi[] | undefined+ scope: MCPAgentGrantScopeEnumApiserverId: string}setAgentServerAccessComplete: (@@ -719,11 +730,13 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([accountId: string,serverId: string,enabled: boolean,+ scope: MCPAgentGrantScopeEnumApi = 'personal',policies?: ToolPolicyEntryApi[]) => ({accountId,serverId,enabled,+ scope,policies,}),setAgentServerAccessSuccess: (accountId: string, serverId: string) => ({ accountId, serverId }),@@ -1496,15 +1509,19 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([actions.toggleAccountStatusComplete(accountId)}},- setAgentServerAccess: async ({ accountId, serverId, enabled, policies }) => {+ setAgentServerAccess: async ({ accountId, serverId, enabled, scope, policies }) => {const account = values.serviceAccounts.find((candidate) => candidate.id === accountId)const server = values.servers.find((candidate) => candidate.id === serverId)+ const accountName = account?.name ?? 'agent'try {// The response carries the account's grants after the change, including who- // backs each one, which a local merge cannot reconstruct.+ // backs each one, which a local merge cannot reconstruct. `scope` goes on+ // every call because the endpoint defaults an omitted scope back to+ // personal, which would silently demote a team share on any re-share.const updatedAccount = await mcpGatewayServiceAccountsAccessCreate(currentProjectId(), accountId, {gateway_server_id: serverId,enabled,+ scope,policies,})actions.loadServiceAccountsSuccess(@@ -1534,6 +1551,7 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([{service_account_id: updatedAccount.id,user: yourGrant.shared_by,+ scope: yourGrant.scope,name: updatedAccount.name,handle: updatedAccount.handle,status: updatedAccount.status,@@ -1558,7 +1576,9 @@ export const mcpGatewayLogic = kea<mcpGatewayLogicType>([actions.setAgentServerAccessSuccess(accountId, serverId)lemonToast[enabled ? 'success' : 'info'](enabled- ? `${server?.name ?? 'Server'} shared with ${account?.name ?? 'agent'}. Only your agents use your connection.`+ ? scope === 'team'+ ? `${server?.name ?? 'Server'} shared with ${accountName}. Every ${accountName} run in this project can use your connection.`+ : `${server?.name ?? 'Server'} shared with ${accountName}. Only your own ${accountName} runs 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) {diff --git a/products/mcp_store/frontend/generated/api.schemas.ts b/products/mcp_store/frontend/generated/api.schemas.tsindex 6f28fe464788..14b43a18aff5 100644--- a/products/mcp_store/frontend/generated/api.schemas.ts+++ b/products/mcp_store/frontend/generated/api.schemas.ts@@ -88,6 +88,18 @@ export interface AuditActorServiceAccountApi {handle: string}+/**+ * * `personal` - Personal+ * * `team` - Team+ */+export type MCPAgentGrantScopeEnumApi = (typeof MCPAgentGrantScopeEnumApi)[keyof typeof MCPAgentGrantScopeEnumApi]++export const MCPAgentGrantScopeEnumApi = {+ Personal: 'personal',+ Team: 'team',+} as const++export const MCPAuditEventApiGrantScope = { ...MCPAgentGrantScopeEnumApi, ...BlankEnumApi } as constexport interface MCPAuditEventApi {readonly id: stringreadonly created_at: string@@ -108,6 +120,13 @@ export interface MCPAuditEventApi {readonly actor_service_account: AuditActorServiceAccountApi | null/** Denormalized actor label (email or handle) that survives deletion. */readonly actor_label: string+ /** Member whose connection an agent call used. Null for member calls and for owners whose account has since been deleted. */+ readonly credential_owner: UserBasicApi | null+ /** Scope of the agent grant the call used. Blank for member calls.+ *+ * * `personal` - Personal+ * * `team` - Team */+ readonly grant_scope: (typeof MCPAuditEventApiGrantScope)[keyof typeof MCPAuditEventApiGrantScope]}export interface PaginatedMCPAuditEventListApi {@@ -443,6 +462,11 @@ export interface GatewayAgentAccessApi {service_account_id: string/** The member whose connection the agent uses. */user: UserBasicApi+ /** 'personal' lets the agent use this connection only when working for the member who shared it. 'team' lets it use the connection for the whole project's agent runs.+ *+ * * `personal` - Personal+ * * `team` - Team */+ scope: MCPAgentGrantScopeEnumApi/** Agent display name. */name: string/** Agent identity handle, e.g. posthog-support. */@@ -727,6 +751,11 @@ export interface MCPServiceAccountServerApi {id: string/** The member whose connection the agent uses. */shared_by: UserBasicApi+ /** 'personal' lets the agent use this connection only when working for the member who shared it. 'team' lets it use the connection for the whole project's agent runs.+ *+ * * `personal` - Personal+ * * `team` - Team */+ scope: MCPAgentGrantScopeEnumApi/** Server display name. */name: string/** Server description. */@@ -801,6 +830,11 @@ export interface ServiceAccountAccessUpdateApi {gateway_server_id: string/** True shares the caller's own connection with the agent, false removes the caller's share. */enabled: boolean+ /** Applies to the caller's own share, and only alongside enabled=true. 'personal' lets the agent use the connection when it works for the caller. 'team' lets it use the connection for the whole project's agent runs, including runs nobody started. It never lets another person use the connection. Defaults to personal, so re-sharing without this field resets the caller's share to personal.+ *+ * * `personal` - Personal+ * * `team` - Team */+ scope?: MCPAgentGrantScopeEnumApi/** 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/**diff --git a/products/mcp_store/frontend/generated/api.ts b/products/mcp_store/frontend/generated/api.tsindex 49c0b5ec4e5a..794034a38eed 100644--- a/products/mcp_store/frontend/generated/api.ts+++ b/products/mcp_store/frontend/generated/api.ts@@ -744,7 +744,11 @@ export const getMcpGatewayServiceAccountsAccessCreateUrl = (projectId: string, i* 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.+ * connection, and the agent may use it only when acting for the caller,+ * unless the caller sends `scope=team` to lend it to the project's agent+ * runs generally. Scope only ever applies to the caller's own share: it is+ * their credential to lend, so no admin permission is involved and no+ * member can change someone else's share.* `enabled=false` removes the caller's own share and leaves other members'* shares, and the agent's tool policies, in place.*diff --git a/products/mcp_store/frontend/generated/api.zod.ts b/products/mcp_store/frontend/generated/api.zod.tsindex d3c0c476ad0a..0690684730bf 100644--- a/products/mcp_store/frontend/generated/api.zod.ts+++ b/products/mcp_store/frontend/generated/api.zod.ts@@ -344,7 +344,11 @@ export const McpGatewayServiceAccountsPartialUpdateBody = /* @__PURE__ */ zod.ob* 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.+ * connection, and the agent may use it only when acting for the caller,+ * unless the caller sends `scope=team` to lend it to the project's agent+ * runs generally. Scope only ever applies to the caller's own share: it is+ * their credential to lend, so no admin permission is involved and no+ * member can change someone else's share.* `enabled=false` removes the caller's own share and leaves other members'* shares, and the agent's tool policies, in place.*@@ -352,6 +356,7 @@ export const McpGatewayServiceAccountsPartialUpdateBody = /* @__PURE__ */ zod.ob* every member's share of this server with this agent, along with the* agent's tool policies for it.*/+export const mcpGatewayServiceAccountsAccessCreateBodyScopeDefault = `personal`export const mcpGatewayServiceAccountsAccessCreateBodyAllDefault = falseexport const mcpGatewayServiceAccountsAccessCreateBodyPoliciesItemToolNameMax = 200@@ -362,6 +367,13 @@ export const McpGatewayServiceAccountsAccessCreateBody = /* @__PURE__ */ zod.objenabled: zod.boolean().describe("True shares the caller's own connection with the agent, false removes the caller's share."),+ scope: zod+ .enum(['personal', 'team'])+ .describe('\* `personal` - Personal\n\* `team` - Team')+ .default(mcpGatewayServiceAccountsAccessCreateBodyScopeDefault)+ .describe(+ "Applies to the caller's own share, and only alongside enabled=true. 'personal' lets the agent use the connection when it works for the caller. 'team' lets it use the connection for the whole project's agent runs, including runs nobody started. It never lets another person use the connection. Defaults to personal, so re-sharing without this field resets the caller's share to personal.\n\n\* `personal` - Personal\n\* `team` - Team"+ ),all: zod.boolean().default(mcpGatewayServiceAccountsAccessCreateBodyAllDefault)diff --git a/products/signals/frontend/inbox/components/config/McpServersSection.tsx b/products/signals/frontend/inbox/components/config/McpServersSection.tsxindex 07142856f8b8..12d1e7757f78 100644--- a/products/signals/frontend/inbox/components/config/McpServersSection.tsx+++ b/products/signals/frontend/inbox/components/config/McpServersSection.tsx@@ -45,8 +45,8 @@ export function McpServersSection(): JSX.Element {You have not shared any MCP servers with Scout</div><p className="text-xs text-secondary mt-0.5 mb-0">- Share one of your connections in MCP server settings. Your scouts only use connections you- shared yourself.+ Share one of your connections in MCP server settings. Your scouts can also use connections+ teammates shared to the team.</p></div></div>@@ -59,7 +59,9 @@ export function McpServersSection(): JSX.Element {)}{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="px-3 py-2 text-xs text-secondary">+ Shared to the team by teammates. Your scouts use these too.+ </div><div className="divide-y border-t">{teammateScoutServers.map((server) => (<ScoutServerRow key={`${server.id}-${server.shared_by.id}`} server={server} attributed />@@ -96,16 +98,14 @@ function ScoutServerRow({<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>+ <div className="text-xs text-secondary truncate">Shared to the team 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>- )}+ <LemonTag type={state.tagType} size="small">+ {state.label}+ </LemonTag></div>)}diff --git a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.ts b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.tsindex 0e04b38a0183..04b21c9ac201 100644--- a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.test.ts@@ -35,11 +35,13 @@ function server(id: string,name: string,connectionState: ConnectionStateEnumApi,- sharedBy: UserBasicApi = YOU+ sharedBy: UserBasicApi = YOU,+ scope: MCPServiceAccountServerApi['scope'] = 'personal'): MCPServiceAccountServerApi {return {id,shared_by: sharedBy,+ scope,name,description: `${name} workspace`,icon_key: name.toLowerCase(),@@ -79,10 +81,11 @@ describe('scoutMcpServersLogic', () => {logic?.unmount()})- it('separates your Scout grants from teammate grants and flags the ones needing setup', async () => {+ it('separates your Scout grants from teammate team shares 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 teammateGithub = server('github-id', 'GitHub', 'ready', TEAMMATE, 'team')+ const teammateSentry = server('sentry-id', 'Sentry', 'ready', TEAMMATE)const zendesk = server('zendesk-id', 'Zendesk', 'ready')useMocks({get: {@@ -92,7 +95,10 @@ describe('scoutMcpServersLogic', () => {count: 2,next: null,previous: null,- results: [account('support', [zendesk]), account('scout', [notion, linear, teammateGithub])],+ results: [+ account('support', [zendesk]),+ account('scout', [notion, linear, teammateGithub, teammateSentry]),+ ],},],},@@ -102,15 +108,40 @@ describe('scoutMcpServersLogic', () => {logic.mount()await expectLogic(logic).toFinishAllListeners()- expect(logic.values.scoutServers).toEqual([notion, linear, teammateGithub])+ expect(logic.values.scoutServers).toEqual([notion, linear, teammateGithub, teammateSentry])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.readyScoutServers).toEqual([linear, teammateGithub])+ expect(logic.values.availableScoutServers).toEqual([linear, teammateGithub])expect(logic.values.scoutServersNeedingSetup).toEqual([notion])})+ it('counts a server the viewer already shares once, even when a teammate team-shares it too', async () => {+ const yourLinear = server('linear-id', 'Linear', 'ready')+ const teammateLinear = server('linear-id', 'Linear', 'ready', TEAMMATE, 'team')+ useMocks({+ get: {+ '/api/projects/:team_id/mcp_gateway/service_accounts/': () => [+ 200,+ {+ count: 1,+ next: null,+ previous: null,+ results: [account('scout', [yourLinear, teammateLinear])],+ },+ ],+ },+ })++ logic = scoutMcpServersLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.readyScoutServers).toEqual([yourLinear])+ expect(logic.values.availableScoutServers).toEqual([yourLinear])+ })+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)diff --git a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.ts b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.tsindex f31150810f34..37943d4f7f71 100644--- a/products/signals/frontend/inbox/logics/scoutMcpServersLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutMcpServersLogic.ts@@ -65,7 +65,10 @@ export interface scoutMcpServersLogicMeta {scoutServers: MCPServiceAccountServerApi[],currentUserId: number | null) => MCPServiceAccountServerApi[]- readyScoutServers: (yourScoutServers: MCPServiceAccountServerApi[]) => MCPServiceAccountServerApi[]+ readyScoutServers: (+ yourScoutServers: MCPServiceAccountServerApi[],+ teammateScoutServers: MCPServiceAccountServerApi[]+ ) => MCPServiceAccountServerApi[]availableScoutServers: (readyScoutServers: MCPServiceAccountServerApi[],isScoutMcpAccessEnabled: boolean@@ -118,9 +121,9 @@ 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+ // A grant belongs to one member. A scout run mounts the grants of the person it runs for+ // plus every team-scoped grant in the project, so a teammate's personal grant never backs+ // the viewer's scouts but a teammate's team share does. 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: [@@ -131,12 +134,27 @@ export const scoutMcpServersLogic = kea<scoutMcpServersLogicType>([teammateScoutServers: [(s) => [s.scoutServers, s.currentUserId],(scoutServers: MCPServiceAccountServerApi[], currentUserId: number | null): MCPServiceAccountServerApi[] =>- currentUserId === null ? [] : scoutServers.filter((server) => server.shared_by.id !== currentUserId),+ currentUserId === null+ ? []+ : scoutServers.filter((server) => server.shared_by.id !== currentUserId && server.scope === 'team'),],readyScoutServers: [- (s) => [s.yourScoutServers],- (yourScoutServers: MCPServiceAccountServerApi[]): MCPServiceAccountServerApi[] =>- yourScoutServers.filter((server) => server.connection_state === 'ready'),+ (s) => [s.yourScoutServers, s.teammateScoutServers],+ (+ yourScoutServers: MCPServiceAccountServerApi[],+ teammateScoutServers: MCPServiceAccountServerApi[]+ ): MCPServiceAccountServerApi[] => {+ const yoursReady = yourScoutServers.filter((server) => server.connection_state === 'ready')+ // A run's own grant for a server wins over a teammate's team share of the same+ // server, so a server the viewer already shares must not be counted twice.+ const yourServerIds = new Set(yoursReady.map((server) => server.id))+ return [+ ...yoursReady,+ ...teammateScoutServers.filter(+ (server) => server.connection_state === 'ready' && !yourServerIds.has(server.id)+ ),+ ]+ },],availableScoutServers: [(s) => [s.readyScoutServers, s.isScoutMcpAccessEnabled],diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 0c8435752fbd..0bc8c169ed98 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -373,7 +373,8 @@ class Task(DeletedMetaFields, models.Model):Only meaningful on a stamped built-in agent task, so it reads through`mcp_builtin_agent_key` — an unstamped or untrusted origin can never- borrow someone's grants, and a task with no owner mounts nothing.+ borrow someone's grants. None means the run belongs to nobody, which+ limits it to the team-scoped grants members have lent to agents."""if self.mcp_builtin_agent_key is None:return Nonediff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex eea69cc49327..595138bc89e4 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -579,9 +579,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 the connections ``credential_owner_id`` granted to that agent, and- never include a member's personal installations. Grants are personal, so an- agent task whose persisted owner is missing mounts nothing. A mapped origin+ include the connections granted to that agent: those ``credential_owner_id``+ granted, plus any member's team-scoped grants. They never include a member's+ personal installations. An agent task whose persisted owner is missing still+ mounts the team-scoped grants, which is what keeps autonomous runs+ (support replies, creatorless scouts) working. A mapped originwithout its persisted agent marker gets no Store installations. Built-inagent handling is gated per team on the ``mcp-gateway`` rollout flag; teams without itresolve mapped origins like unmapped tasks. For unmapped tasks,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 02d04d16895f..4afb739066ff 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -36131,6 +36131,18 @@ export namespace Schemas {readonly updated: number;}+ /**+ * * `personal` - Personal+ * * `team` - Team+ */+ export type MCPAgentGrantScopeEnum = typeof MCPAgentGrantScopeEnum[keyof typeof MCPAgentGrantScopeEnum];+++ export const MCPAgentGrantScopeEnum = {+ Personal: 'personal',+ Team: 'team',+ } as const;+/*** * `active` - Active* * `paused` - Paused@@ -36151,6 +36163,11 @@ export namespace Schemas {service_account_id: string;/** The member whose connection the agent uses. */user: UserBasic;+ /** 'personal' lets the agent use this connection only when working for the member who shared it. 'team' lets it use the connection for the whole project's agent runs.+ *+ * * `personal` - Personal+ * * `team` - Team */+ scope: MCPAgentGrantScopeEnum;/** Agent display name. */name: string;/** Agent identity handle, e.g. posthog-support. */@@ -44141,6 +44158,7 @@ export namespace Schemas {Blocked: 'blocked',} as const;+ export const MCPAuditEventGrantScope = {...MCPAgentGrantScopeEnum,...BlankEnum,} as constexport interface MCPAuditEvent {readonly id: string;readonly created_at: string;@@ -44161,6 +44179,13 @@ export namespace Schemas {readonly actor_service_account: AuditActorServiceAccount | null;/** Denormalized actor label (email or handle) that survives deletion. */readonly actor_label: string;+ /** Member whose connection an agent call used. Null for member calls and for owners whose account has since been deleted. */+ readonly credential_owner: UserBasic | null;+ /** Scope of the agent grant the call used. Blank for member calls.+ *+ * * `personal` - Personal+ * * `team` - Team */+ readonly grant_scope: typeof MCPAuditEventGrantScope[keyof typeof MCPAuditEventGrantScope];}/**@@ -44809,6 +44834,11 @@ export namespace Schemas {id: string;/** The member whose connection the agent uses. */shared_by: UserBasic;+ /** 'personal' lets the agent use this connection only when working for the member who shared it. 'team' lets it use the connection for the whole project's agent runs.+ *+ * * `personal` - Personal+ * * `team` - Team */+ scope: MCPAgentGrantScopeEnum;/** Server display name. */name: string;/** Server description. */@@ -69135,6 +69165,11 @@ export namespace Schemas {gateway_server_id: string;/** True shares the caller's own connection with the agent, false removes the caller's share. */enabled: boolean;+ /** Applies to the caller's own share, and only alongside enabled=true. 'personal' lets the agent use the connection when it works for the caller. 'team' lets it use the connection for the whole project's agent runs, including runs nobody started. It never lets another person use the connection. Defaults to personal, so re-sharing without this field resets the caller's share to personal.+ *+ * * `personal` - Personal+ * * `team` - Team */+ scope?: MCPAgentGrantScopeEnum;/** 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;/**