Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mcp_store): add personal and shared mcp installation scope (#69658)

Alex Vd36ff6e43783
diff --git a/ee/hogai/tools/call_mcp_server/installations.py b/ee/hogai/tools/call_mcp_server/installations.py
index d1e1f8eb87c6..87e3437a8098 100644
--- a/ee/hogai/tools/call_mcp_server/installations.py
+++ b/ee/hogai/tools/call_mcp_server/installations.py
@@ -1,21 +1,54 @@
from __future__ import annotations
+from django.db.models import Q
+
from posthog.models import Team, User
from products.mcp_store.backend.models import MCPServerInstallation, MCPServerInstallationTool
from products.mcp_store.backend.oauth import refresh_installation_token
+def _is_row_ready(row: dict) -> bool:
+ if row["auth_type"] != "oauth":
+ return True
+ sensitive = row.get("sensitive_configuration") or {}
+ return bool(sensitive.get("access_token")) and not sensitive.get("needs_reauth")
+
+
def _get_installations(team: Team, user: User) -> list[dict]:
- return list(
- MCPServerInstallation.objects.filter(team=team, user=user, is_enabled=True).values( # type: ignore[arg-type]
+ """Return the MCP installations available to this user's agent: their
+ personal installations plus team-shared ones.
+
+ Per-URL resolution matches the sandbox facade and PostHog Code: a ready
+ personal installation wins over a shared one (the agent acts as the user
+ rather than through a teammate's shared credential), but a dead personal
+ row doesn't shadow a working shared one. Unready shared rows are hidden
+ entirely — a teammate can't fix someone else's credential, while an
+ unready personal row still surfaces so Max can walk the user through
+ reauth."""
+ rows = [
+ dict(row)
+ for row in MCPServerInstallation.objects.filter(team=team, is_enabled=True)
+ .filter(Q(scope="shared") | Q(user=user))
+ .values(
"id",
"display_name",
"url",
"auth_type",
"sensitive_configuration",
+ "scope",
)
- )
+ ]
+ ready_shared_by_url = {row["url"]: row for row in rows if row["scope"] == "shared" and _is_row_ready(row)}
+ results: list[dict] = []
+ for row in rows:
+ if row["scope"] == "shared":
+ continue
+ if _is_row_ready(row) or row["url"] not in ready_shared_by_url:
+ results.append(row)
+ ready_shared_by_url.pop(row["url"], None)
+ results.extend(ready_shared_by_url.values())
+ return results
def _get_cached_tools(installation_id: str) -> list[dict]:
diff --git a/ee/hogai/tools/call_mcp_server/test/test_tool.py b/ee/hogai/tools/call_mcp_server/test/test_tool.py
index bcf53ffa6090..4edbb8ed795a 100644
--- a/ee/hogai/tools/call_mcp_server/test/test_tool.py
+++ b/ee/hogai/tools/call_mcp_server/test/test_tool.py
@@ -121,6 +121,33 @@ class TestCreateToolClass(TestCallMCPServerTool):
)
self.assertEqual(tool._installations, [])
+ async def test_sees_teammates_shared_installation(self):
+ from posthog.models import User
+
+ owner = await sync_to_async(User.objects.create_and_join)(self.organization, "[email protected]", "password")
+ await sync_to_async(MCPServerInstallation.objects.create)(
+ team=self.team,
+ user=owner,
+ display_name="Shared Linear",
+ url="https://mcp.linear.app/mcp",
+ scope="shared",
+ auth_type="oauth",
+ sensitive_configuration={"access_token": "owner-token"},
+ )
+
+ tool = await CallMCPServerTool.create_tool_class(
+ team=self.team, user=self.user, state=self.state, context_manager=self.context_manager
+ )
+
+ self.assertEqual(len(tool._installations), 1)
+ self.assertIn("https://mcp.linear.app/mcp", tool._allowed_server_urls)
+ self.assertIn("Shared Linear", tool.description)
+ # Calls ride the owner's shared credential.
+ self.assertEqual(
+ tool._server_headers["https://mcp.linear.app/mcp"]["Authorization"],
+ "Bearer owner-token",
+ )
+
class TestAuthHeaders(TestCallMCPServerTool):
async def test_oauth_token_sent_as_bearer_header(self):
@@ -289,6 +316,24 @@ class TestCallTool(TestCallMCPServerTool):
class TestGetInstallations(TestCallMCPServerTool):
+ def _create_teammate(self, email="[email protected]"):
+ from posthog.models import User
+
+ return User.objects.create_and_join(self.organization, email, "password")
+
+ def _install_shared_server(self, owner, url="https://mcp.linear.app/mcp", sensitive_configuration=None):
+ return MCPServerInstallation.objects.create(
+ team=self.team,
+ user=owner,
+ display_name="Shared Linear",
+ url=url,
+ scope="shared",
+ auth_type="oauth",
+ sensitive_configuration=(
+ sensitive_configuration if sensitive_configuration is not None else {"access_token": "owner-token"}
+ ),
+ )
+
def test_returns_installed_servers(self):
self._install_server(name="Linear", url="https://mcp.linear.app")
result = _get_installations(self.team, self.user)
@@ -300,6 +345,81 @@ class TestGetInstallations(TestCallMCPServerTool):
result = _get_installations(self.team, self.user)
self.assertEqual(result, [])
+ def test_includes_teammates_shared_installation(self):
+ owner = self._create_teammate()
+ self._install_shared_server(owner)
+
+ result = _get_installations(self.team, self.user)
+
+ self.assertEqual(len(result), 1)
+ self.assertEqual(result[0]["scope"], "shared")
+ self.assertEqual(result[0]["url"], "https://mcp.linear.app/mcp")
+
+ def test_personal_wins_over_shared_for_same_url(self):
+ owner = self._create_teammate()
+ self._install_shared_server(owner, url="https://mcp.linear.app/mcp")
+ self._install_server(name="My Linear", url="https://mcp.linear.app/mcp")
+
+ result = _get_installations(self.team, self.user)
+
+ self.assertEqual(len(result), 1)
+ self.assertEqual(result[0]["scope"], "personal")
+ self.assertEqual(result[0]["display_name"], "My Linear")
+
+ def test_hides_shared_installation_without_live_credential(self):
+ owner = self._create_teammate()
+ self._install_shared_server(owner, url="https://mcp.pending.com/mcp", sensitive_configuration={})
+ self._install_shared_server(
+ owner,
+ url="https://mcp.reauth.com/mcp",
+ sensitive_configuration={"access_token": "tok", "needs_reauth": True},
+ )
+
+ result = _get_installations(self.team, self.user)
+
+ self.assertEqual(result, [])
+
+ def test_dead_personal_does_not_shadow_ready_shared(self):
+ owner = self._create_teammate()
+ self._install_shared_server(owner, url="https://mcp.linear.app/mcp")
+ self._install_server(
+ name="My Linear",
+ url="https://mcp.linear.app/mcp",
+ auth_type="oauth",
+ sensitive_configuration={"access_token": "tok", "needs_reauth": True},
+ )
+
+ result = _get_installations(self.team, self.user)
+
+ self.assertEqual(len(result), 1)
+ self.assertEqual(result[0]["scope"], "shared")
+
+ def test_keeps_unready_personal_without_shared_alternative(self):
+ self._install_server(
+ name="My Linear",
+ url="https://mcp.linear.app/mcp",
+ auth_type="oauth",
+ sensitive_configuration={"needs_reauth": True},
+ )
+
+ result = _get_installations(self.team, self.user)
+
+ self.assertEqual(len(result), 1)
+ self.assertEqual(result[0]["display_name"], "My Linear")
+
+ def test_excludes_teammates_personal_installations(self):
+ owner = self._create_teammate()
+ MCPServerInstallation.objects.create(
+ team=self.team,
+ user=owner,
+ display_name="Their Server",
+ url="https://mcp.other.com",
+ )
+
+ result = _get_installations(self.team, self.user)
+
+ self.assertEqual(result, [])
+
def _make_oauth_installation(
*,
diff --git a/ee/hogai/tools/call_mcp_server/tool.py b/ee/hogai/tools/call_mcp_server/tool.py
index a66346c7204d..fb2a17f41921 100644
--- a/ee/hogai/tools/call_mcp_server/tool.py
+++ b/ee/hogai/tools/call_mcp_server/tool.py
@@ -277,6 +277,18 @@ class CallMCPServerTool(MaxTool):
)
# needs_approval is handled earlier via `is_dangerous_operation` + LangGraph
# interrupt; by the time we reach _call_tool we've already been approved.
+ inst = self._get_installation(server_url)
+ # Basic audit trail for who exercises which installation (especially
+ # shared credentials), mirroring the proxy path. Metadata only —
+ # never arguments or results.
+ logger.info(
+ "mcp_store max tool call",
+ team_id=self._team.id,
+ installation_id=str(inst["id"]),
+ scope=inst.get("scope", "personal"),
+ user_id=self._user.id,
+ tool_name=tool_name,
+ )
return await client.call_tool(tool_name, arguments or {})
def _validate_server_url(self, server_url: str) -> None:
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4f6d96ecf926..7430c2274265 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5975,7 +5975,7 @@ snapshots:
scenes-app-insights-side-panel-actions--saved-hog-ql-data-table--light:
hash: v1.k794b7964.a5c990eb24f7c6b1604ce80b2862d5d775743da574766533880f333e894cdd1e.PGxY8ztW21A8vlf__DrtqJtkcoD2TvLSXJOQ5DCKAHs
scenes-app-insights-side-panel-actions--saved-trends-insight--dark:
- hash: v1.k794b7964.63555c21f985bd6d886907f417d5017aa7e065638a15dd9ca8704f6ba5c13712.qebI7tVPSaTxToDhhvj1N6AkzjGymnoQimWf1D-c5_U
+ hash: v1.k794b7964.e236a1e99e95775e1e69c07f4c336f58ebc7d2a25a557271638d225368ca081a.CgTT0P5qfYJ-wavjUYdmYjcc7vrm_ZiXNjlkaEyDuKg
scenes-app-insights-side-panel-actions--saved-trends-insight--light:
hash: v1.k794b7964.8b3c5b3a6d6c40c1deffcc9295215757184925243f0ec4f1e5360947645dfe63.l8Ld6syBbfnl46gqKDLV8JMhS8G-76BsrG9ztylWhRM
scenes-app-insights-side-panel-actions--unsaved-insight--dark:
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index e0d42a531816..5116ebd9e3d2 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -4071,6 +4071,12 @@ const api = {
async delete(id: string): Promise<void> {
await new ApiRequest().mcpServerInstallation(id).delete()
},
+ async share(id: string): Promise<Record<string, any>> {
+ return await new ApiRequest().mcpServerInstallation(id).withAction('share').create({ data: {} })
+ },
+ async unshare(id: string): Promise<Record<string, any>> {
+ return await new ApiRequest().mcpServerInstallation(id).withAction('unshare').create({ data: {} })
+ },
async installCustom(data: {
name: string
url: string
@@ -4079,10 +4085,15 @@ const api = {
description?: string
client_id?: string
client_secret?: string
+ scope?: 'personal' | 'shared'
}): Promise<Record<string, any>> {
return await new ApiRequest().mcpServerInstallations().withAction('install_custom').create({ data })
},
- async installTemplate(data: { template_id: string; api_key?: string }): Promise<Record<string, any>> {
+ async installTemplate(data: {
+ template_id: string
+ api_key?: string
+ scope?: 'personal' | 'shared'
+ }): Promise<Record<string, any>> {
return await new ApiRequest().mcpServerInstallations().withAction('install_template').create({ data })
},
async listTools(
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 779f000017cb..6b96cb02ad9d 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -538,6 +538,7 @@ SPECTACULAR_SETTINGS = {
),
"HogFlowStatusEnum": "products.workflows.backend.models.hog_flow.hog_flow.HogFlow.State",
"MCPAuthTypeEnum": "products.mcp_store.backend.models.AUTH_TYPE_CHOICES",
+ "MCPInstallationScopeEnum": ["personal", "shared"],
"TaskRunStatusEnum": "products.tasks.backend.models.TaskRun.Status",
"TaskRunEnvironmentEnum": "products.tasks.backend.models.TaskRun.Environment",
"ModelEnum": "products.batch_exports.backend.models.batch_export.BatchExport.Model",
diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.py
index e09973a9cc83..bf47f7b0b9aa 100644
--- a/products/mcp_store/backend/facade/api.py
+++ b/products/mcp_store/backend/facade/api.py
@@ -4,6 +4,8 @@ Facade API for mcp_store.
This is the ONLY module other apps are allowed to import.
"""
+from django.db.models import Q
+
import structlog
from products.mcp_store.backend.facade.contracts import ActiveInstallationInfo
@@ -31,16 +33,28 @@ def _is_oauth_ready(installation: MCPServerInstallation) -> bool:
return True
+def _to_info(installation: MCPServerInstallation, team_id: int) -> ActiveInstallationInfo:
+ return ActiveInstallationInfo(
+ id=str(installation.id),
+ name=_resolve_name(installation),
+ proxy_path=f"/api/environments/{team_id}/mcp_server_installations/{installation.id}/proxy/",
+ scope=installation.scope,
+ )
+
+
def get_active_installations(team_id: int, user_id: int) -> list[ActiveInstallationInfo]:
- """Return active, ready-to-use MCP installations for a user.
+ """Return active, ready-to-use personal MCP installations for a user.
Filters out disabled installations and OAuth installations that
need reauthorization or are still pending token exchange.
"""
try:
- installations = MCPServerInstallation.objects.filter(
- team_id=team_id, user_id=user_id, is_enabled=True
- ).select_related("template")
+ # list() evaluates the lazy queryset here so DB errors hit this handler.
+ installations = list(
+ MCPServerInstallation.objects.filter(
+ team_id=team_id, user_id=user_id, is_enabled=True, scope="personal"
+ ).select_related("template")
+ )
except Exception as e:
logger.warning("Error fetching MCP installations", error=str(e), team_id=team_id)
return []
@@ -53,14 +67,57 @@ def get_active_installations(team_id: int, user_id: int) -> list[ActiveInstallat
installation_id=str(installation.id),
)
continue
+ results.append(_to_info(installation, team_id))
- results.append(
- ActiveInstallationInfo(
- id=str(installation.id),
- name=_resolve_name(installation),
- proxy_path=f"/api/environments/{team_id}/mcp_server_installations/{installation.id}/proxy/",
- )
+ logger.debug("Found active MCP installations", count=len(results), team_id=team_id)
+ return results
+
+
+def get_installations_for_sandbox(
+ team_id: int,
+ *,
+ user_id: int | None = None,
+ include_personal: bool = False,
+) -> list[ActiveInstallationInfo]:
+ """Return MCP installations for sandbox agent use.
+
+ Always includes shared (team-wide) installations. Optionally includes
+ the user's personal installations when ``include_personal`` is True
+ and a ``user_id`` is provided. When the user has a ready personal
+ installation for the same URL as a shared one, only the personal one is
+ returned — the user acts as themselves rather than through the shared
+ credential.
+ """
+ try:
+ scope_filter = Q(scope="shared")
+ if include_personal and user_id is not None:
+ scope_filter = scope_filter | Q(scope="personal", user_id=user_id)
+
+ # list() evaluates the lazy queryset here so DB errors hit this handler.
+ installations = list(
+ MCPServerInstallation.objects.filter(team_id=team_id, is_enabled=True)
+ .filter(scope_filter)
+ .select_related("template")
)
+ except Exception as e:
+ logger.warning("Error fetching MCP installations for sandbox", error=str(e), team_id=team_id)
+ return []
- logger.debug("Found active MCP installations", count=len(results), team_id=team_id)
+ 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",
+ count=len(results),
+ team_id=team_id,
+ include_personal=include_personal,
+ )
return results
diff --git a/products/mcp_store/backend/facade/contracts.py b/products/mcp_store/backend/facade/contracts.py
index 2385d2e377e7..f302d31ea256 100644
--- a/products/mcp_store/backend/facade/contracts.py
+++ b/products/mcp_store/backend/facade/contracts.py
@@ -15,3 +15,4 @@ class ActiveInstallationInfo:
id: str
name: str
proxy_path: str
+ scope: str = "personal"
diff --git a/products/mcp_store/backend/migrations/0012_alter_mcpserverinstallation_unique_together_and_more.py b/products/mcp_store/backend/migrations/0012_alter_mcpserverinstallation_unique_together_and_more.py
new file mode 100644
index 000000000000..06973439f59a
--- /dev/null
+++ b/products/mcp_store/backend/migrations/0012_alter_mcpserverinstallation_unique_together_and_more.py
@@ -0,0 +1,41 @@
+# Generated by Django 5.2.14 on 2026-07-09 11:04
+
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mcp_store", "0011_normalize_mcp_template_icon_keys"),
+ ("posthog", "1247_oauthaccesstoken_token_idx"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.AlterUniqueTogether(
+ name="mcpserverinstallation",
+ unique_together=set(),
+ ),
+ migrations.AddField(
+ model_name="mcpserverinstallation",
+ name="scope",
+ field=models.CharField(
+ choices=[("personal", "Personal"), ("shared", "Shared")],
+ db_default="personal",
+ default="personal",
+ max_length=20,
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="mcpserverinstallation",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("scope", "personal")), fields=("team", "user", "url"), name="uniq_personal_install"
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="mcpserverinstallation",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("scope", "shared")), fields=("team", "url"), name="uniq_shared_install"
+ ),
+ ),
+ ]
diff --git a/products/mcp_store/backend/migrations/max_migration.txt b/products/mcp_store/backend/migrations/max_migration.txt
index 224e04bd1ffb..738663cacdef 100644
--- a/products/mcp_store/backend/migrations/max_migration.txt
+++ b/products/mcp_store/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_normalize_mcp_template_icon_keys
+0012_alter_mcpserverinstallation_unique_together_and_more
diff --git a/products/mcp_store/backend/models.py b/products/mcp_store/backend/models.py
index fc8fa55b8862..5b027effd33a 100644
--- a/products/mcp_store/backend/models.py
+++ b/products/mcp_store/backend/models.py
@@ -1,6 +1,7 @@
from typing import Literal, TypedDict
from django.db import models
+from django.db.models import Q
from posthog.helpers.encrypted_fields import EncryptedJSONField
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
@@ -28,6 +29,11 @@ CATEGORY_CHOICES = [
("productivity", "Productivity & Collaboration"),
]
+SCOPE_CHOICES = [
+ ("personal", "Personal"),
+ ("shared", "Shared"),
+]
+
class SensitiveConfig(TypedDict, total=False):
api_key: str
@@ -102,6 +108,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)
+ # 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")
# Cached per-installation OAuth metadata for custom (non-template) installs. Non-secret.
oauth_issuer_url = models.URLField(max_length=2048, blank=True, default="")
oauth_metadata = models.JSONField(default=dict, blank=True)
@@ -109,7 +118,18 @@ class MCPServerInstallation(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
class Meta:
db_table = "mcp_store_mcpserverinstallation"
- unique_together = [("team", "user", "url")]
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team", "user", "url"],
+ condition=Q(scope="personal"),
+ name="uniq_personal_install",
+ ),
+ models.UniqueConstraint(
+ fields=["team", "url"],
+ condition=Q(scope="shared"),
+ name="uniq_shared_install",
+ ),
+ ]
class MCPServerInstallationTool(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.py
index 9cffcfebd574..b473fcd45f0d 100644
--- a/products/mcp_store/backend/presentation/views.py
+++ b/products/mcp_store/backend/presentation/views.py
@@ -7,7 +7,7 @@ from typing import Any, cast
from urllib.parse import urlencode, urlparse
from django.conf import settings
-from django.db import transaction
+from django.db import IntegrityError, transaction
from django.db.models import Count, Q, QuerySet
from django.http import HttpResponse, StreamingHttpResponse
from django.utils import timezone
@@ -17,6 +17,7 @@ from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import mixins, renderers, serializers, status, viewsets
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import action
+from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
@@ -198,6 +199,9 @@ class MCPServerInstallationSerializer(serializers.ModelSerializer):
tool_count = serializers.SerializerMethodField(
help_text="Number of live (non-removed) tools exposed by this installation."
)
+ is_owner = serializers.SerializerMethodField(
+ help_text="True when the requesting user owns this installation. Lets clients gate owner-only controls instead of surfacing 403s."
+ )
class Meta:
model = MCPServerInstallation
@@ -211,6 +215,8 @@ class MCPServerInstallationSerializer(serializers.ModelSerializer):
"description",
"auth_type",
"is_enabled",
+ "scope",
+ "is_owner",
"needs_reauth",
"pending_oauth",
"proxy_url",
@@ -218,7 +224,7 @@ class MCPServerInstallationSerializer(serializers.ModelSerializer):
"created_at",
"updated_at",
]
- read_only_fields = ["id", "template_id", "created_at", "updated_at", "tool_count"]
+ read_only_fields = ["id", "template_id", "created_at", "updated_at", "tool_count", "scope", "is_owner"]
def get_tool_count(self, obj: MCPServerInstallation) -> int:
# Prefer the annotation to avoid N+1 on list; fall back to a direct
@@ -255,6 +261,12 @@ class MCPServerInstallationSerializer(serializers.ModelSerializer):
)
return ""
+ def get_is_owner(self, obj: MCPServerInstallation) -> bool:
+ request = self.context.get("request")
+ if not request or not getattr(request, "user", None):
+ return False
+ return request.user.id == obj.user_id
+
class InstallCustomSerializer(serializers.Serializer):
name = serializers.CharField(max_length=200)
@@ -268,6 +280,12 @@ class InstallCustomSerializer(serializers.Serializer):
client_secret = serializers.CharField(required=False, allow_blank=True, default="")
install_source = serializers.ChoiceField(choices=["posthog", "posthog-code"], required=False, default="posthog")
posthog_code_callback_url = serializers.CharField(required=False, allow_blank=True, default="")
+ scope = serializers.ChoiceField(
+ choices=["personal", "shared"],
+ required=False,
+ default="personal",
+ help_text="'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).",
+ )
def validate_url(self, value: str) -> str:
allowed, error = is_url_allowed(value)
@@ -286,6 +304,12 @@ class InstallTemplateSerializer(serializers.Serializer):
api_key = serializers.CharField(required=False, allow_blank=True, default="")
install_source = serializers.ChoiceField(choices=["posthog", "posthog-code"], required=False, default="posthog")
posthog_code_callback_url = serializers.CharField(required=False, allow_blank=True, default="")
+ scope = serializers.ChoiceField(
+ choices=["personal", "shared"],
+ required=False,
+ default="personal",
+ help_text="'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).",
+ )
def validate_posthog_code_callback_url(self, value: str) -> str:
if value and not _is_valid_posthog_code_callback_url(value):
@@ -361,14 +385,16 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"install_template",
"update_tool_approval",
"refresh_tools",
+ "share",
+ "unshare",
]
queryset = MCPServerInstallation.objects.all()
serializer_class = MCPServerInstallationSerializer
lookup_field = "id"
permission_classes = [IsAuthenticated]
- # Installations are user-scoped (safely_get_queryset filters by user), so
- # write actions like install/uninstall don't need project admin access.
+ # Installations are user-scoped or shared (safely_get_queryset returns both),
+ # so write actions don't need project admin access.
# Return project:read so AccessControlPermission requires "member" not "admin".
_USER_SCOPED_ACTIONS = {
"destroy",
@@ -377,8 +403,16 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"install_template",
"update_tool_approval",
"refresh_tools",
+ # share/unshare enforce their own owner/admin checks in the action bodies.
+ "share",
+ "unshare",
}
+ # Mutations restricted to the credential owner (installer) on shared rows.
+ # Tool approval is included: it gates which tools autonomous runs may execute
+ # under the owner's credential, so a non-owner must not be able to flip it.
+ _OWNER_ONLY_ACTIONS = {"destroy", "partial_update", "refresh_tools", "update_tool_approval"}
+
def dangerously_get_required_scopes(self, request: Any, view: Any) -> list[str] | None:
if self.action in self._USER_SCOPED_ACTIONS:
return ["project:read"]
@@ -386,27 +420,96 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
return (
- queryset.filter(team_id=self.team_id, user=self.request.user)
+ queryset.filter(
+ team_id=self.team_id,
+ )
+ .filter(Q(scope="shared") | Q(user=self.request.user))
.select_related("template")
.annotate(tool_count_annotated=Count("tools", filter=Q(tools__removed_at__isnull=True)))
.order_by("-created_at")
)
+ def check_object_permissions(self, request: Request, obj: Any) -> None:
+ # Enforce owner-only mutation of shared rows centrally so every action in
+ # _OWNER_ONLY_ACTIONS is guarded via get_object() — a new owner-only action
+ # only needs to be added to the set, not to re-implement the check inline.
+ super().check_object_permissions(request, obj)
+ if (
+ self.action in self._OWNER_ONLY_ACTIONS
+ and isinstance(obj, MCPServerInstallation)
+ and obj.scope == "shared"
+ and obj.user_id != request.user.id
+ ):
+ # destroy differs from the other owner-only actions: a project admin may
+ # delete another member's shared installation, so shared credentials
+ # don't become orphaned and unremovable when the owner leaves the team.
+ # partial_update / refresh_tools / update_tool_approval reconfigure how
+ # the owner's credential is used, so they stay strictly owner-only.
+ if self.action == "destroy" and self._is_project_admin():
+ return
+ raise PermissionDenied("Only the credential owner can modify a shared server.")
+
+ def _assert_shared_mutation_allowed(self, installation: MCPServerInstallation) -> None:
+ """Owner guard for get_or_create-based install/reinstall flows.
+
+ These don't pass through get_object()/check_object_permissions, and a
+ shared row keyed on (team, url) can belong to another member. Without
+ this, any member could re-post the same shared server and overwrite the
+ owner's credentials/OAuth state that agents and the proxy rely on.
+ """
+ if installation.scope == "shared" and installation.user_id != self.request.user.id:
+ raise PermissionDenied("Only the credential owner can modify a shared server.")
+
+ def _is_project_admin(self) -> bool:
+ """True for organization admins/owners, or users explicitly granted
+ admin on this project via access controls.
+
+ Deliberately NOT `effective_membership_level`: on a project with no
+ access controls configured, that defaults to admin for every org
+ member (open-project semantics), which would let any member share,
+ unshare, or delete team-wide MCP credentials. `explicit=True` skips
+ that default, so regular members fail closed."""
+ if self.user_access_control.is_organization_admin:
+ return True
+ return bool(self.user_access_control.check_access_level_for_object(self.team, "admin", explicit=True))
+
+ def _require_admin_for_shared_scope(self, scope: str) -> None:
+ """Creating a team-wide shared MCP server is admin-only.
+
+ A shared install exposes the installer's credential to every project
+ member and all autonomous agents, and any action taken through it is
+ attributed to the credential owner (e.g. a member could write to Linear
+ as the owner). Gating creation to admins keeps a regular member from
+ standing up a shared server that others act through.
+ """
+ if scope != "shared":
+ return
+ if not self._is_project_admin():
+ raise PermissionDenied("Only project admins can create shared MCP servers.")
+
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
- def perform_destroy(self, instance: MCPServerInstallation) -> None:
+ def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ # PUT is disabled: all edits go through partial_update (PATCH), which restricts
+ # writable fields to display_name/description/is_enabled and enforces shared-row
+ # ownership. The default PUT would bypass both (full serializer + no ownership check).
+ return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
+
+ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ installation = self.get_object()
report_user_action(
- self.request.user,
+ request.user,
"mcp_store server uninstalled",
properties={
- "server_name": _installation_name(instance),
- "server_url": instance.url,
- "auth_type": instance.auth_type,
+ "server_name": _installation_name(installation),
+ "server_url": installation.url,
+ "auth_type": installation.auth_type,
},
team=self.team,
)
- super().perform_destroy(instance)
+ installation.delete()
+ return Response(status=status.HTTP_204_NO_CONTENT)
def _validate_mcp_url_or_error_response(self, mcp_url: str) -> Response | None:
allowed, reason = is_url_allowed(mcp_url)
@@ -488,6 +591,103 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
serializer = self.get_serializer(installation)
return Response(serializer.data)
+ @extend_schema(request=None, responses={200: OpenApiResponse(response=MCPServerInstallationSerializer)})
+ @action(detail=True, methods=["post"], url_path="share")
+ def share(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Escalate a personal installation to a team-wide shared one.
+
+ Owner-only AND admin-only: sharing exposes the owner's credential to
+ every project member and all autonomous agents, so it carries the same
+ gate as creating a shared install outright.
+ """
+ installation = self.get_object()
+ if installation.scope != "personal":
+ return Response(
+ {"detail": "Only personal installations can be shared."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if installation.user_id != request.user.id:
+ raise PermissionDenied("Only the installation owner can share it with the project.")
+ if not self._is_project_admin():
+ raise PermissionDenied("Only project admins can share MCP servers with the project.")
+
+ try:
+ with transaction.atomic():
+ if MCPServerInstallation.objects.filter(
+ team_id=self.team_id, url=installation.url, scope="shared"
+ ).exists():
+ return Response(
+ {"detail": "A shared connection for this server already exists in this project."},
+ status=status.HTTP_409_CONFLICT,
+ )
+ installation.scope = "shared"
+ installation.save(update_fields=["scope", "updated_at"])
+ except IntegrityError:
+ return Response(
+ {"detail": "A shared connection for this server already exists in this project."},
+ status=status.HTTP_409_CONFLICT,
+ )
+
+ report_user_action(
+ request.user,
+ "mcp_store server shared",
+ properties={
+ "server_name": _installation_name(installation),
+ "server_url": installation.url,
+ "auth_type": installation.auth_type,
+ },
+ team=self.team,
+ )
+ return Response(self.get_serializer(installation).data)
+
+ @extend_schema(request=None, responses={200: OpenApiResponse(response=MCPServerInstallationSerializer)})
+ @action(detail=True, methods=["post"], url_path="unshare")
+ def unshare(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """De-escalate a shared installation back to personal.
+
+ Allowed for the credential owner OR a project admin (the reclaim path
+ for shared credentials). The row always stays owned by the ORIGINAL
+ owner — an admin unsharing someone else's install must not capture
+ their credential.
+ """
+ installation = self.get_object()
+ if installation.scope != "shared":
+ return Response(
+ {"detail": "Only shared installations can be unshared."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if installation.user_id != request.user.id and not self._is_project_admin():
+ raise PermissionDenied("Only the credential owner or a project admin can unshare a shared server.")
+
+ try:
+ with transaction.atomic():
+ if MCPServerInstallation.objects.filter(
+ team_id=self.team_id, user_id=installation.user_id, url=installation.url, scope="personal"
+ ).exists():
+ return Response(
+ {"detail": "The owner already has a personal installation for this server."},
+ status=status.HTTP_409_CONFLICT,
+ )
+ installation.scope = "personal"
+ installation.save(update_fields=["scope", "updated_at"])
+ except IntegrityError:
+ return Response(
+ {"detail": "The owner already has a personal installation for this server."},
+ status=status.HTTP_409_CONFLICT,
+ )
+
+ report_user_action(
+ request.user,
+ "mcp_store server unshared",
+ properties={
+ "server_name": _installation_name(installation),
+ "server_url": installation.url,
+ "auth_type": installation.auth_type,
+ },
+ team=self.team,
+ )
+ return Response(self.get_serializer(installation).data)
+
@action(
detail=True,
methods=["post"],
@@ -499,6 +699,17 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
def proxy(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse | StreamingHttpResponse:
installation = self.get_object()
+ # Basic audit trail for who exercises which installation (especially
+ # shared credentials). Metadata only — never request/response bodies
+ # or headers.
+ logger.info(
+ "mcp_store proxy request",
+ team_id=self.team_id,
+ installation_id=str(installation.id),
+ scope=installation.scope,
+ user_id=request.user.id,
+ )
+
ok, error_response = validate_installation_auth(installation)
if not ok and error_response is not None:
return error_response
@@ -523,23 +734,30 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
template_id = data["template_id"]
install_source = data.get("install_source", "posthog")
posthog_code_callback_url = data.get("posthog_code_callback_url", "")
+ scope = data.get("scope", "personal")
+ self._require_admin_for_shared_scope(scope)
try:
template = MCPServerTemplate.objects.get(id=template_id, is_active=True)
except MCPServerTemplate.DoesNotExist:
return Response({"detail": "Template not found"}, status=status.HTTP_404_NOT_FOUND)
+ lookup = {"team_id": self.team_id, "url": template.url, "scope": scope}
+ if scope == "personal":
+ lookup["user"] = request.user
installation, created = MCPServerInstallation.objects.get_or_create(
- team_id=self.team_id,
- user=request.user,
- url=template.url,
+ **lookup,
defaults={
+ **({"user": request.user} if scope == "shared" else {}),
"template": template,
"display_name": template.name,
"description": template.description,
"auth_type": template.auth_type,
},
)
+ # A pre-existing shared row may belong to another member; block hijacking its creds.
+ if not created:
+ self._assert_shared_mutation_allowed(installation)
# Re-link in case a previous install pointed elsewhere (e.g. post-migration reconnect).
if installation.template_id != template.id:
installation.template = template
@@ -713,6 +931,8 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
description = data.get("description", "")
user_client_id = (data.get("client_id") or "").strip()
user_client_secret = (data.get("client_secret") or "").strip()
+ scope = data.get("scope", "personal")
+ self._require_admin_for_shared_scope(scope)
install_source = data.get("install_source", "posthog")
posthog_code_callback_url = data.get("posthog_code_callback_url", "")
@@ -727,17 +947,20 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
user_client_secret=user_client_secret,
install_source=install_source,
posthog_code_callback_url=posthog_code_callback_url,
+ scope=scope,
)
if auth_type == "api_key":
sensitive_config: SensitiveConfig = {}
if api_key:
sensitive_config["api_key"] = api_key
+ lookup: dict[str, Any] = {"team_id": self.team_id, "url": url, "scope": scope}
+ if scope == "personal":
+ lookup["user"] = request.user
installation, created = MCPServerInstallation.objects.get_or_create(
- team_id=self.team_id,
- user=request.user,
- url=url,
+ **lookup,
defaults={
+ **({"user": request.user} if scope == "shared" else {}),
"display_name": name,
"description": description,
"auth_type": "api_key",
@@ -786,6 +1009,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
user_client_secret: str = "",
install_source: str = "posthog",
posthog_code_callback_url: str = "",
+ scope: str = "personal",
) -> HttpResponse:
"""Kick off an OAuth flow for a user-added MCP server.
@@ -799,16 +1023,22 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
redirect_uri = _get_oauth_redirect_uri()
+ lookup: dict[str, Any] = {"team_id": self.team_id, "url": mcp_url, "scope": scope}
+ if scope == "personal":
+ lookup["user"] = request.user
installation, created = MCPServerInstallation.objects.get_or_create(
- team_id=self.team_id,
- user=request.user,
- url=mcp_url,
+ **lookup,
defaults={
+ **({"user": request.user} if scope == "shared" else {}),
"display_name": name,
"description": description,
"auth_type": "oauth",
},
)
+ # A pre-existing shared row may belong to another member; block a non-owner
+ # from swapping its DCR client / clearing its tokens via reinstall.
+ if not created:
+ self._assert_shared_mutation_allowed(installation)
if not created and installation.auth_type != "oauth":
installation.auth_type = "oauth"
installation.save(update_fields=["auth_type", "updated_at"])
@@ -968,23 +1198,30 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
template_id: Any,
install_source: str,
posthog_code_callback_url: str,
+ installation: MCPServerInstallation | None = None,
) -> HttpResponse:
try:
template = MCPServerTemplate.objects.get(id=template_id, is_active=True)
except MCPServerTemplate.DoesNotExist:
return Response({"detail": "Template not found"}, status=status.HTTP_404_NOT_FOUND)
- installation, _ = MCPServerInstallation.objects.get_or_create(
- team_id=self.team_id,
- user=cast(User, request.user),
- url=template.url,
- defaults={
- "template": template,
- "display_name": template.name,
- "description": template.description,
- "auth_type": template.auth_type,
- },
- )
+ if installation is None:
+ # Direct marketplace (re)connect keyed on template — always the
+ # personal row. Scope must be in the lookup: a user can own both a
+ # personal and a shared row for the same URL, so (team, user, url)
+ # alone is no longer unique and would raise MultipleObjectsReturned.
+ installation, _ = MCPServerInstallation.objects.get_or_create(
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ url=template.url,
+ scope="personal",
+ defaults={
+ "template": template,
+ "display_name": template.name,
+ "description": template.description,
+ "auth_type": template.auth_type,
+ },
+ )
if installation.template_id != template.id:
installation.template = template
installation.save(update_fields=["template", "updated_at"])
@@ -1091,6 +1328,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
template_id=installation.template_id,
install_source=install_source,
posthog_code_callback_url=posthog_code_callback_url,
+ installation=installation,
)
if blocked_response := self._validate_mcp_url_or_error_response(installation.url):
diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.py
index a258640a5840..1a4a6f56ff1f 100644
--- a/products/mcp_store/backend/test/test_api.py
+++ b/products/mcp_store/backend/test/test_api.py
@@ -192,6 +192,27 @@ class TestMCPServerInstallationAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchi
assert response.json()["name"] == "Updated"
assert response.json()["description"] == "New description"
+ def test_put_not_allowed(self):
+ # PUT is disabled: it would bypass the field allowlist and shared-row
+ # ownership guard that partial_update (PATCH) enforces.
+ installation = MCPServerInstallation.objects.create(
+ team=self.team,
+ user=self.user,
+ display_name="Original",
+ url="https://mcp.example.com",
+ auth_type="api_key",
+ )
+
+ response = self.client.put(
+ f"/api/environments/{self.team.id}/mcp_server_installations/{installation.id}/",
+ data={"display_name": "Updated", "url": "https://evil.example.com", "auth_type": "oauth"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
+ installation.refresh_from_db()
+ assert installation.url == "https://mcp.example.com"
+ assert installation.auth_type == "api_key"
+
def test_toggle_installation_enabled(self):
installation = MCPServerInstallation.objects.create(
team=self.team,
@@ -1519,3 +1540,585 @@ class TestInstallDispatchesToolSync(ClickhouseTestMixin, APIBaseTest, QueryMatch
assert response.status_code == 302
mock_task.delay.assert_called_once_with(str(installation.id))
+
+
+class TestMCPInstallationScopeAccess(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
+ def _api_url(self, suffix: str = "") -> str:
+ base = f"/api/environments/{self.team.id}/mcp_server_installations/"
+ return f"{base}{suffix}" if suffix else base
+
+ def _create_installation(self, user=None, scope="personal", **kwargs) -> MCPServerInstallation:
+ import uuid as _uuid
+
+ defaults: dict = {
+ "team": self.team,
+ "user": user or self.user,
+ "display_name": f"Server-{_uuid.uuid4().hex[:6]}",
+ "url": f"https://mcp.test-{_uuid.uuid4().hex[:8]}.example.com/mcp",
+ "auth_type": "api_key",
+ "is_enabled": True,
+ "scope": scope,
+ }
+ defaults.update(kwargs)
+ return MCPServerInstallation.objects.create(**defaults)
+
+ def test_list_shows_own_personal_and_all_shared(self) -> None:
+ from posthog.models import User
+
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ own_personal = self._create_installation(scope="personal")
+ own_shared = self._create_installation(scope="shared")
+ other_shared = self._create_installation(user=other, scope="shared")
+ self._create_installation(user=other, scope="personal")
+
+ response = self.client.get(self._api_url())
+ assert response.status_code == status.HTTP_200_OK
+ returned_ids = {r["id"] for r in response.json()["results"]}
+ assert returned_ids == {str(own_personal.id), str(own_shared.id), str(other_shared.id)}
+
+ def test_scope_returned_in_serializer(self) -> None:
+ self._create_installation(scope="shared")
+
+ response = self.client.get(self._api_url())
+ assert response.json()["results"][0]["scope"] == "shared"
+
+ def test_non_owner_cannot_delete_shared(self) -> None:
+ from posthog.models import User
+
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ shared = self._create_installation(user=other, scope="shared")
+
+ response = self.client.delete(self._api_url(f"{shared.id}/"))
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert MCPServerInstallation.objects.filter(id=shared.id).exists()
+
+ def test_owner_can_delete_shared(self) -> None:
+ shared = self._create_installation(scope="shared")
+
+ response = self.client.delete(self._api_url(f"{shared.id}/"))
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+
+ def test_non_owner_cannot_patch_shared(self) -> None:
+ from posthog.models import User
+
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ shared = self._create_installation(user=other, scope="shared")
+
+ response = self.client.patch(
+ self._api_url(f"{shared.id}/"),
+ data={"display_name": "Hijacked"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_non_owner_admin_can_delete_shared(self) -> None:
+ # Admins may delete another member's shared installation so shared
+ # credentials don't become orphaned when the owner leaves the team.
+ from posthog.models import User
+
+ self._make_admin()
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ shared = self._create_installation(user=other, scope="shared")
+
+ response = self.client.delete(self._api_url(f"{shared.id}/"))
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not MCPServerInstallation.objects.filter(id=shared.id).exists()
+
+ def test_non_owner_admin_still_cannot_patch_shared(self) -> None:
+ # The destroy override is delete-only: reconfiguring how the owner's
+ # credential is used stays strictly owner-only, even for admins.
+ from posthog.models import User
+
+ self._make_admin()
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ shared = self._create_installation(user=other, scope="shared")
+
+ response = self.client.patch(
+ self._api_url(f"{shared.id}/"),
+ data={"display_name": "Hijacked"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_admin_cannot_delete_another_members_personal(self) -> None:
+ # Personal rows behave as before: they aren't even visible to other
+ # members, admin or not.
+ from posthog.models import User
+
+ self._make_admin()
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ personal = self._create_installation(user=other, scope="personal")
+
+ response = self.client.delete(self._api_url(f"{personal.id}/"))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ assert MCPServerInstallation.objects.filter(id=personal.id).exists()
+
+ def test_share_by_owner_admin_flips_scope(self) -> None:
+ self._make_admin()
+ personal = self._create_installation(scope="personal")
+
+ response = self.client.post(self._api_url(f"{personal.id}/share/"))
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["scope"] == "shared"
+ personal.refresh_from_db()
+ assert personal.scope == "shared"
+
+ def test_share_by_owner_non_admin_forbidden(self) -> None:
+ # self.user is a MEMBER by default; sharing carries the same admin
+ # gate as creating a shared install outright.
+ personal = self._create_installation(scope="personal")
+
+ response = self.client.post(self._api_url(f"{personal.id}/share/"))
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ personal.refresh_from_db()
+ assert personal.scope == "personal"
+
+ def test_share_by_non_owner_admin_rejected(self) -> None:
+ # Another member's personal installation isn't even addressable: the
+ # queryset only exposes shared rows and your own, so a non-owner admin
+ # gets 404 before the in-action owner check (kept as defense in depth)
+ # could 403.
+ from posthog.models import User
+
+ self._make_admin()
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ personal = self._create_installation(user=other, scope="personal")
+
+ response = self.client.post(self._api_url(f"{personal.id}/share/"))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ personal.refresh_from_db()
+ assert personal.scope == "personal"
+
+ def test_share_conflicts_with_existing_shared_url(self) -> None:
+ from posthog.models import User
+
+ self._make_admin()
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ url = "https://mcp.share-conflict.example.com/mcp"
+ self._create_installation(user=other, scope="shared", url=url)
+ personal = self._create_installation(scope="personal", url=url)
+
+ response = self.client.post(self._api_url(f"{personal.id}/share/"))
+ assert response.status_code == status.HTTP_409_CONFLICT
+ personal.refresh_from_db()
+ assert personal.scope == "personal"
+
+ def test_share_already_shared_returns_400(self) -> None:
+ self._make_admin()
+ shared = self._create_installation(scope="shared")
+
+ response = self.client.post(self._api_url(f"{shared.id}/share/"))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ shared.refresh_from_db()
+ assert shared.scope == "shared"
+
+ def test_unshare_by_owner(self) -> None:
+ shared = self._create_installation(scope="shared")
+
+ response = self.client.post(self._api_url(f"{shared.id}/unshare/"))
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["scope"] == "personal"
+ shared.refresh_from_db()
+ assert shared.scope == "personal"
+ assert shared.user_id == self.user.id
+
+ def test_unshare_by_non_owner_admin_keeps_original_owner(self) -> None:
+ from posthog.models import User
+
+ self._make_admin()
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ shared = self._create_installation(user=other, scope="shared")
+
+ response = self.client.post(self._api_url(f"{shared.id}/unshare/"))
+ assert response.status_code == status.HTTP_200_OK
+ shared.refresh_from_db()
+ assert shared.scope == "personal"
+ # The row must stay owned by the ORIGINAL owner — an admin unsharing
+ # someone else's install must not capture their credential.
+ assert shared.user_id == other.id
+
+ def test_unshare_by_non_owner_member_forbidden(self) -> None:
+ from posthog.models import User
+
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ shared = self._create_installation(user=other, scope="shared")
+
+ response = self.client.post(self._api_url(f"{shared.id}/unshare/"))
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ shared.refresh_from_db()
+ assert shared.scope == "shared"
+
+ def test_unshare_conflicts_with_owner_personal_duplicate(self) -> None:
+ url = "https://mcp.unshare-conflict.example.com/mcp"
+ self._create_installation(scope="personal", url=url)
+ shared = self._create_installation(scope="shared", url=url)
+
+ response = self.client.post(self._api_url(f"{shared.id}/unshare/"))
+ assert response.status_code == status.HTTP_409_CONFLICT
+ shared.refresh_from_db()
+ assert shared.scope == "shared"
+
+ def test_unshare_personal_returns_400(self) -> None:
+ personal = self._create_installation(scope="personal")
+
+ response = self.client.post(self._api_url(f"{personal.id}/unshare/"))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ personal.refresh_from_db()
+ assert personal.scope == "personal"
+
+ def test_is_owner_flag_in_list(self) -> None:
+ from posthog.models import User
+
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ own_personal = self._create_installation(scope="personal")
+ own_shared = self._create_installation(scope="shared")
+ other_shared = self._create_installation(user=other, scope="shared")
+
+ response = self.client.get(self._api_url())
+ assert response.status_code == status.HTTP_200_OK
+ by_id = {r["id"]: r for r in response.json()["results"]}
+ assert by_id[str(own_personal.id)]["is_owner"] is True
+ assert by_id[str(own_shared.id)]["is_owner"] is True
+ assert by_id[str(other_shared.id)]["is_owner"] is False
+
+ def test_any_member_can_proxy_shared(self) -> None:
+ from unittest.mock import (
+ MagicMock,
+ patch as mock_patch,
+ )
+
+ from posthog.models import User
+
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ shared = self._create_installation(user=other, scope="shared", sensitive_configuration={"api_key": "k"})
+
+ with mock_patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None)):
+ with mock_patch("products.mcp_store.backend.proxy.httpx.Client") as mock_client_cls:
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.headers = {"content-type": "application/json"}
+ mock_resp.content = b'{"jsonrpc":"2.0","id":1,"result":{}}'
+ mock_client = MagicMock()
+ mock_client.build_request.return_value = MagicMock()
+ mock_client.send.return_value = mock_resp
+ mock_client_cls.return_value = mock_client
+
+ response = self.client.post(
+ self._api_url(f"{shared.id}/proxy/"),
+ data={"jsonrpc": "2.0", "method": "tools/list", "id": 1},
+ format="json",
+ )
+
+ assert response.status_code == 200
+
+ def _make_admin(self, user=None) -> None:
+ from posthog.models import OrganizationMembership
+
+ membership = (user or self.user).organization_memberships.get(organization=self.organization)
+ membership.level = OrganizationMembership.Level.ADMIN
+ membership.save()
+
+ @ALLOW_URL
+ def test_install_custom_shared(self, _mock) -> None:
+ self._make_admin()
+ response = self.client.post(
+ self._api_url("install_custom/"),
+ data={
+ "name": "Shared Custom",
+ "url": "https://mcp.shared-custom.example.com/mcp",
+ "auth_type": "api_key",
+ "api_key": "key123",
+ "scope": "shared",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["scope"] == "shared"
+
+ @ALLOW_URL
+ def test_install_custom_shared_requires_admin(self, _mock) -> None:
+ # self.user is a MEMBER by default; shared creation must be admin-gated.
+ response = self.client.post(
+ self._api_url("install_custom/"),
+ data={
+ "name": "Shared Custom",
+ "url": "https://mcp.member-shared.example.com/mcp",
+ "auth_type": "api_key",
+ "api_key": "key123",
+ "scope": "shared",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not MCPServerInstallation.objects.filter(
+ url="https://mcp.member-shared.example.com/mcp", scope="shared"
+ ).exists()
+
+ def test_install_template_shared_requires_admin(self) -> None:
+ template = MCPServerTemplate.objects.create(
+ name="Admin Gate Template",
+ url="https://mcp.admin-gate.example.com/mcp",
+ auth_type="api_key",
+ is_active=True,
+ )
+ response = self.client.post(
+ self._api_url("install_template/"),
+ data={"template_id": str(template.id), "api_key": "k", "scope": "shared"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not MCPServerInstallation.objects.filter(url=template.url, scope="shared").exists()
+
+ def test_install_template_shared_allowed_for_admin(self) -> None:
+ self._make_admin()
+ template = MCPServerTemplate.objects.create(
+ name="Admin OK Template",
+ url="https://mcp.admin-ok.example.com/mcp",
+ auth_type="api_key",
+ is_active=True,
+ )
+ response = self.client.post(
+ self._api_url("install_template/"),
+ data={"template_id": str(template.id), "api_key": "k", "scope": "shared"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["scope"] == "shared"
+
+ def test_non_owner_cannot_change_tool_approval_shared(self) -> None:
+ from django.utils import timezone
+
+ from posthog.models import User
+
+ from products.mcp_store.backend.models import MCPServerInstallationTool
+
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ shared = self._create_installation(user=other, scope="shared")
+ tool = MCPServerInstallationTool.objects.create(
+ installation=shared,
+ tool_name="delete_everything",
+ approval_state="needs_approval",
+ last_seen_at=timezone.now(),
+ )
+
+ response = self.client.patch(
+ self._api_url(f"{shared.id}/tools/{tool.tool_name}/"),
+ data={"approval_state": "approved"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ tool.refresh_from_db()
+ assert tool.approval_state == "needs_approval"
+
+ def test_owner_can_change_tool_approval_shared(self) -> None:
+ from django.utils import timezone
+
+ from products.mcp_store.backend.models import MCPServerInstallationTool
+
+ shared = self._create_installation(scope="shared")
+ tool = MCPServerInstallationTool.objects.create(
+ installation=shared,
+ tool_name="safe_tool",
+ approval_state="needs_approval",
+ last_seen_at=timezone.now(),
+ )
+
+ response = self.client.patch(
+ self._api_url(f"{shared.id}/tools/{tool.tool_name}/"),
+ data={"approval_state": "approved"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ tool.refresh_from_db()
+ assert tool.approval_state == "approved"
+
+ def test_non_owner_cannot_hijack_shared_via_install_template(self) -> None:
+ from posthog.models import User
+
+ # Admin so the request clears the admin gate and exercises the owner guard.
+ self._make_admin()
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ template = MCPServerTemplate.objects.create(
+ name="Shared Template",
+ url="https://mcp.shared-template.example.com/mcp",
+ auth_type="api_key",
+ is_active=True,
+ )
+ shared = self._create_installation(
+ user=other,
+ scope="shared",
+ url=template.url,
+ template=template,
+ sensitive_configuration={"api_key": "owner-key"},
+ )
+
+ response = self.client.post(
+ self._api_url("install_template/"),
+ data={"template_id": str(template.id), "api_key": "attacker-key", "scope": "shared"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ shared.refresh_from_db()
+ assert shared.sensitive_configuration["api_key"] == "owner-key"
+
+ @ALLOW_URL
+ @patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")
+ def test_non_owner_cannot_hijack_shared_via_install_custom_oauth(self, mock_discover, _allow) -> None:
+ from posthog.models import User
+
+ # Admin so the request clears the admin gate and exercises the owner guard.
+ self._make_admin()
+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ shared = self._create_installation(
+ user=other,
+ scope="shared",
+ auth_type="oauth",
+ url="https://mcp.shared-oauth.example.com/mcp",
+ sensitive_configuration={"dcr_client_id": "owner-client", "access_token": "owner-token"},
+ )
+
+ response = self.client.post(
+ self._api_url("install_custom/"),
+ data={
+ "name": "Hijack",
+ "url": shared.url,
+ "auth_type": "oauth",
+ "scope": "shared",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ # Guard must fire before any discovery/DCR work touches the row.
+ mock_discover.assert_not_called()
+ shared.refresh_from_db()
+ assert shared.sensitive_configuration["dcr_client_id"] == "owner-client"
+ assert shared.sensitive_configuration["access_token"] == "owner-token"
+
+ @ALLOW_URL
+ def test_install_custom_defaults_to_personal(self, _mock) -> None:
+ response = self.client.post(
+ self._api_url("install_custom/"),
+ data={
+ "name": "Personal Custom",
+ "url": "https://mcp.personal-custom.example.com/mcp",
+ "auth_type": "api_key",
+ "api_key": "key123",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["scope"] == "personal"
+
+
+class TestMCPScopeAdminGateWithAccessControlFeature(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
+ """Regression tests for the admin gate on shared-credential management.
+
+ With the ACCESS_CONTROL feature available and a project that has no
+ access-control rows configured, `effective_membership_level` reports
+ every org member as project admin (open-project default). The share /
+ unshare / shared-delete gate must not inherit that default: only org
+ admins and explicitly-granted project admins pass.
+ """
+
+ def setUp(self):
+ super().setUp()
+ from posthog.constants import AvailableFeature
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+
+ def _api_url(self, suffix: str = "") -> str:
+ base = f"/api/environments/{self.team.id}/mcp_server_installations/"
+ return f"{base}{suffix}" if suffix else base
+
+ def _create_installation(self, user=None, scope="personal") -> MCPServerInstallation:
+ import uuid as _uuid
+
+ return MCPServerInstallation.objects.create(
+ team=self.team,
+ user=user or self.user,
+ display_name=f"Server-{_uuid.uuid4().hex[:6]}",
+ url=f"https://mcp.test-{_uuid.uuid4().hex[:8]}.example.com/mcp",
+ auth_type="api_key",
+ is_enabled=True,
+ scope=scope,
+ )
+
+ def _other_user(self):
+ from posthog.models import User
+
+ return User.objects.create_and_join(self.organization, "[email protected]", "password")
+
+ def _make_org_admin(self) -> None:
+ from posthog.models import OrganizationMembership
+
+ membership = self.user.organization_memberships.get(organization=self.organization)
+ membership.level = OrganizationMembership.Level.ADMIN
+ membership.save()
+
+ def test_member_cannot_unshare_anothers_shared_on_open_project(self) -> None:
+ shared = self._create_installation(user=self._other_user(), scope="shared")
+
+ response = self.client.post(self._api_url(f"{shared.id}/unshare/"))
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ shared.refresh_from_db()
+ assert shared.scope == "shared"
+
+ def test_member_cannot_delete_anothers_shared_on_open_project(self) -> None:
+ shared = self._create_installation(user=self._other_user(), scope="shared")
+
+ response = self.client.delete(self._api_url(f"{shared.id}/"))
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert MCPServerInstallation.objects.filter(id=shared.id).exists()
+
+ def test_member_cannot_share_own_personal_on_open_project(self) -> None:
+ personal = self._create_installation(scope="personal")
+
+ response = self.client.post(self._api_url(f"{personal.id}/share/"))
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ personal.refresh_from_db()
+ assert personal.scope == "personal"
+
+ def test_org_admin_can_unshare_on_open_project(self) -> None:
+ self._make_org_admin()
+ shared = self._create_installation(user=self._other_user(), scope="shared")
+
+ response = self.client.post(self._api_url(f"{shared.id}/unshare/"))
+
+ assert response.status_code == status.HTTP_200_OK
+ shared.refresh_from_db()
+ assert shared.scope == "personal"
+
+ def test_explicit_project_admin_can_unshare(self) -> None:
+ from ee.models.rbac.access_control import AccessControl
+
+ membership = self.user.organization_memberships.get(organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="project",
+ resource_id=str(self.team.id),
+ access_level="admin",
+ organization_member=membership,
+ )
+ shared = self._create_installation(user=self._other_user(), scope="shared")
+
+ response = self.client.post(self._api_url(f"{shared.id}/unshare/"))
+
+ assert response.status_code == status.HTTP_200_OK
+ shared.refresh_from_db()
+ assert shared.scope == "personal"
+
+ def test_owner_can_still_unshare_own_shared_as_member(self) -> None:
+ # The credential owner reclaims their own connection regardless of role.
+ shared = self._create_installation(scope="shared")
+
+ response = self.client.post(self._api_url(f"{shared.id}/unshare/"))
+
+ assert response.status_code == status.HTTP_200_OK
+ shared.refresh_from_db()
+ assert shared.scope == "personal"
diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.py
index a28d1e1c8ef0..0e53c5f81f45 100644
--- a/products/mcp_store/backend/test/test_facade.py
+++ b/products/mcp_store/backend/test/test_facade.py
@@ -2,7 +2,9 @@ from posthog.test.base import BaseTest
from parameterized import parameterized
-from products.mcp_store.backend.facade.api import get_active_installations
+from posthog.models import User
+
+from products.mcp_store.backend.facade.api import get_active_installations, get_installations_for_sandbox
from products.mcp_store.backend.facade.contracts import ActiveInstallationInfo
from products.mcp_store.backend.models import MCPServerInstallation, MCPServerTemplate
@@ -30,6 +32,7 @@ class TestGetActiveInstallations(BaseTest):
id=str(installation.id),
name="Linear",
proxy_path=f"/api/environments/{self.team.id}/mcp_server_installations/{installation.id}/proxy/",
+ scope="personal",
)
]
@@ -115,6 +118,13 @@ class TestGetActiveInstallations(BaseTest):
assert len(results) == 1
+ def test_excludes_shared_installations(self) -> None:
+ self._create_installation(scope="shared")
+
+ results = get_active_installations(self.team.id, self.user.id)
+
+ assert len(results) == 0
+
@parameterized.expand(
[
("enabled_api_key", True, "api_key", {}, True),
@@ -134,3 +144,116 @@ class TestGetActiveInstallations(BaseTest):
results = get_active_installations(self.team.id, self.user.id)
assert (len(results) == 1) == expected_included
+
+
+class TestGetInstallationsForSandbox(BaseTest):
+ def _create_installation(self, **kwargs) -> MCPServerInstallation:
+ defaults: dict = {
+ "team": self.team,
+ "user": self.user,
+ "display_name": "Server",
+ "url": "https://mcp.example.com/mcp",
+ "auth_type": "api_key",
+ "is_enabled": True,
+ "scope": "personal",
+ }
+ defaults.update(kwargs)
+ return MCPServerInstallation.objects.create(**defaults)
+
+ def test_shared_always_returned(self) -> None:
+ shared = self._create_installation(scope="shared", display_name="Shared Server")
+
+ results = get_installations_for_sandbox(self.team.id)
+
+ assert len(results) == 1
+ assert results[0].id == str(shared.id)
+ assert results[0].scope == "shared"
+
+ def test_personal_excluded_by_default(self) -> None:
+ self._create_installation(scope="personal")
+
+ results = get_installations_for_sandbox(self.team.id)
+
+ assert len(results) == 0
+
+ def test_personal_included_when_requested(self) -> None:
+ personal = self._create_installation(scope="personal")
+
+ results = get_installations_for_sandbox(self.team.id, user_id=self.user.id, include_personal=True)
+
+ assert len(results) == 1
+ assert results[0].id == str(personal.id)
+ assert results[0].scope == "personal"
+
+ def test_shared_plus_personal_combined(self) -> None:
+ self._create_installation(scope="shared", url="https://shared.example.com/mcp", display_name="Shared")
+ self._create_installation(scope="personal", url="https://personal.example.com/mcp", display_name="Personal")
+
+ results = get_installations_for_sandbox(self.team.id, user_id=self.user.id, include_personal=True)
+
+ assert len(results) == 2
+ scopes = {r.scope for r in results}
+ assert scopes == {"shared", "personal"}
+
+ def test_shared_visible_to_any_team_member(self) -> None:
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ self._create_installation(scope="shared", user=other_user, display_name="Other's Shared")
+
+ results = get_installations_for_sandbox(self.team.id, user_id=self.user.id)
+
+ assert len(results) == 1
+
+ def test_other_users_personal_not_returned(self) -> None:
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ self._create_installation(scope="personal", user=other_user)
+
+ results = get_installations_for_sandbox(self.team.id, user_id=self.user.id, include_personal=True)
+
+ assert len(results) == 0
+
+ def test_personal_wins_over_shared_for_same_url(self) -> None:
+ # The user acts as themselves rather than through the shared credential.
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ url = "https://mcp.same.example.com/mcp"
+ self._create_installation(scope="shared", user=other_user, url=url, display_name="Shared")
+ personal = self._create_installation(scope="personal", url=url, display_name="Personal")
+
+ results = get_installations_for_sandbox(self.team.id, user_id=self.user.id, include_personal=True)
+
+ assert [r.id for r in results] == [str(personal.id)]
+ assert results[0].scope == "personal"
+
+ def test_shared_returned_for_same_url_without_include_personal(self) -> None:
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ url = "https://mcp.same.example.com/mcp"
+ shared = self._create_installation(scope="shared", user=other_user, url=url)
+ self._create_installation(scope="personal", url=url)
+
+ results = get_installations_for_sandbox(self.team.id, user_id=self.user.id, include_personal=False)
+
+ assert [r.id for r in results] == [str(shared.id)]
+ assert results[0].scope == "shared"
+
+ def test_different_urls_not_deduped(self) -> None:
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ self._create_installation(scope="shared", user=other_user, url="https://shared.example.com/mcp")
+ self._create_installation(scope="personal", url="https://personal.example.com/mcp")
+
+ results = get_installations_for_sandbox(self.team.id, user_id=self.user.id, include_personal=True)
+
+ assert {r.scope for r in results} == {"shared", "personal"}
+
+ @parameterized.expand(
+ [
+ ("shared_include_personal", "shared", True, True),
+ ("shared_no_personal", "shared", False, True),
+ ("personal_include_personal", "personal", True, True),
+ ("personal_no_personal", "personal", False, False),
+ ]
+ )
+ def test_scope_gating_matrix(self, _name: str, scope: str, include_personal: bool, expected_included: bool) -> None:
+ self._create_installation(scope=scope)
+
+ results = get_installations_for_sandbox(self.team.id, user_id=self.user.id, include_personal=include_personal)
+
+ assert (len(results) == 1) == expected_included
diff --git a/products/mcp_store/frontend/generated/api.schemas.ts b/products/mcp_store/frontend/generated/api.schemas.ts
index e5d5fe56d0ba..80681192cf1b 100644
--- a/products/mcp_store/frontend/generated/api.schemas.ts
+++ b/products/mcp_store/frontend/generated/api.schemas.ts
@@ -18,6 +18,18 @@ export const MCPAuthTypeEnumApi = {
Oauth: 'oauth',
} as const
+/**
+ * * `personal` - Personal
+ * * `shared` - Shared
+ */
+export type MCPServerInstallationScopeEnumApi =
+ (typeof MCPServerInstallationScopeEnumApi)[keyof typeof MCPServerInstallationScopeEnumApi]
+
+export const MCPServerInstallationScopeEnumApi = {
+ Personal: 'personal',
+ Shared: 'shared',
+} as const
+
export interface MCPServerInstallationApi {
readonly id: string
/** @nullable */
@@ -32,6 +44,9 @@ export interface MCPServerInstallationApi {
description?: string
auth_type?: MCPAuthTypeEnumApi
is_enabled?: boolean
+ readonly scope: MCPServerInstallationScopeEnumApi
+ /** True when the requesting user owns this installation. Lets clients gate owner-only controls instead of surfacing 403s. */
+ readonly is_owner: boolean
readonly needs_reauth: boolean
readonly pending_oauth: boolean
readonly proxy_url: string
@@ -136,6 +151,17 @@ export const InstallSourceEnumApi = {
PosthogCode: 'posthog-code',
} as const
+/**
+ * * `personal` - personal
+ * * `shared` - shared
+ */
+export type MCPInstallationScopeEnumApi = (typeof MCPInstallationScopeEnumApi)[keyof typeof MCPInstallationScopeEnumApi]
+
+export const MCPInstallationScopeEnumApi = {
+ Personal: 'personal',
+ Shared: 'shared',
+} as const
+
export interface InstallCustomApi {
/** @maxLength 200 */
name: string
@@ -148,6 +174,11 @@ export interface InstallCustomApi {
client_secret?: string
install_source?: InstallSourceEnumApi
posthog_code_callback_url?: string
+ /** 'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).
+ *
+ * * `personal` - personal
+ * * `shared` - shared */
+ scope?: MCPInstallationScopeEnumApi
}
export interface OAuthRedirectResponseApi {
@@ -159,6 +190,11 @@ export interface InstallTemplateApi {
api_key?: string
install_source?: InstallSourceEnumApi
posthog_code_callback_url?: string
+ /** 'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).
+ *
+ * * `personal` - personal
+ * * `shared` - shared */
+ scope?: MCPInstallationScopeEnumApi
}
/**
diff --git a/products/mcp_store/frontend/generated/api.ts b/products/mcp_store/frontend/generated/api.ts
index 8ffc380bb781..b1be91e993c8 100644
--- a/products/mcp_store/frontend/generated/api.ts
+++ b/products/mcp_store/frontend/generated/api.ts
@@ -169,6 +169,28 @@ export const mcpServerInstallationsProxyCreate = async (
})
}
+export const getMcpServerInstallationsShareCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/mcp_server_installations/${id}/share/`
+}
+
+/**
+ * Escalate a personal installation to a team-wide shared one.
+ *
+ * Owner-only AND admin-only: sharing exposes the owner's credential to
+ * every project member and all autonomous agents, so it carries the same
+ * gate as creating a shared install outright.
+ */
+export const mcpServerInstallationsShareCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<MCPServerInstallationApi> => {
+ return apiMutator<MCPServerInstallationApi>(getMcpServerInstallationsShareCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getMcpServerInstallationsToolsRetrieveUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/mcp_server_installations/${id}/tools/`
}
@@ -230,6 +252,29 @@ export const mcpServerInstallationsToolsRefreshCreate = async (
)
}
+export const getMcpServerInstallationsUnshareCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/mcp_server_installations/${id}/unshare/`
+}
+
+/**
+ * De-escalate a shared installation back to personal.
+ *
+ * Allowed for the credential owner OR a project admin (the reclaim path
+ * for shared credentials). The row always stays owned by the ORIGINAL
+ * owner — an admin unsharing someone else's install must not capture
+ * their credential.
+ */
+export const mcpServerInstallationsUnshareCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<MCPServerInstallationApi> => {
+ return apiMutator<MCPServerInstallationApi>(getMcpServerInstallationsUnshareCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getMcpServerInstallationsAuthorizeRetrieveUrl = (
projectId: string,
params?: McpServerInstallationsAuthorizeRetrieveParams
diff --git a/products/mcp_store/frontend/generated/api.zod.ts b/products/mcp_store/frontend/generated/api.zod.ts
index 5e81bee08727..e7875ddb9fad 100644
--- a/products/mcp_store/frontend/generated/api.zod.ts
+++ b/products/mcp_store/frontend/generated/api.zod.ts
@@ -80,6 +80,7 @@ export const mcpServerInstallationsInstallCustomCreateBodyClientIdDefault = ``
export const mcpServerInstallationsInstallCustomCreateBodyClientSecretDefault = ``
export const mcpServerInstallationsInstallCustomCreateBodyInstallSourceDefault = `posthog`
export const mcpServerInstallationsInstallCustomCreateBodyPosthogCodeCallbackUrlDefault = ``
+export const mcpServerInstallationsInstallCustomCreateBodyScopeDefault = `personal`
export const McpServerInstallationsInstallCustomCreateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(mcpServerInstallationsInstallCustomCreateBodyNameMax),
@@ -96,11 +97,19 @@ export const McpServerInstallationsInstallCustomCreateBody = /* @__PURE__ */ zod
posthog_code_callback_url: zod
.string()
.default(mcpServerInstallationsInstallCustomCreateBodyPosthogCodeCallbackUrlDefault),
+ scope: zod
+ .enum(['personal', 'shared'])
+ .describe('\* `personal` - personal\n\* `shared` - shared')
+ .default(mcpServerInstallationsInstallCustomCreateBodyScopeDefault)
+ .describe(
+ "'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).\n\n\* `personal` - personal\n\* `shared` - shared"
+ ),
})
export const mcpServerInstallationsInstallTemplateCreateBodyApiKeyDefault = ``
export const mcpServerInstallationsInstallTemplateCreateBodyInstallSourceDefault = `posthog`
export const mcpServerInstallationsInstallTemplateCreateBodyPosthogCodeCallbackUrlDefault = ``
+export const mcpServerInstallationsInstallTemplateCreateBodyScopeDefault = `personal`
export const McpServerInstallationsInstallTemplateCreateBody = /* @__PURE__ */ zod.object({
template_id: zod.uuid(),
@@ -112,4 +121,11 @@ export const McpServerInstallationsInstallTemplateCreateBody = /* @__PURE__ */ z
posthog_code_callback_url: zod
.string()
.default(mcpServerInstallationsInstallTemplateCreateBodyPosthogCodeCallbackUrlDefault),
+ scope: zod
+ .enum(['personal', 'shared'])
+ .describe('\* `personal` - personal\n\* `shared` - shared')
+ .default(mcpServerInstallationsInstallTemplateCreateBodyScopeDefault)
+ .describe(
+ "'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).\n\n\* `personal` - personal\n\* `shared` - shared"
+ ),
})
diff --git a/products/mcp_store/frontend/mcpStoreLogic.ts b/products/mcp_store/frontend/mcpStoreLogic.ts
index 906f2b4b86ff..3ff0b4ba3cff 100644
--- a/products/mcp_store/frontend/mcpStoreLogic.ts
+++ b/products/mcp_store/frontend/mcpStoreLogic.ts
@@ -18,6 +18,8 @@ export type ToolApprovalState = 'approved' | 'needs_approval' | 'do_not_use'
export type McpSceneView = 'marketplace' | 'detail'
+export type McpInstallationScope = 'personal' | 'shared'
+
export interface CustomServerFormValues {
name: string
url: string
@@ -26,6 +28,7 @@ export interface CustomServerFormValues {
api_key: string
client_id: string
client_secret: string
+ scope: McpInstallationScope
// Set when the modal is opened from a template (api_key templates reuse
// the same modal to collect the key). Empty for truly custom installs.
template_id: string
@@ -39,6 +42,7 @@ const CUSTOM_SERVER_FORM_DEFAULTS: CustomServerFormValues = {
api_key: '',
client_id: '',
client_secret: '',
+ scope: 'personal',
template_id: '',
}
@@ -180,12 +184,23 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([
name: !name ? 'Name is required' : undefined,
url: !url ? 'URL is required' : undefined,
}),
- submit: async ({ name, url, description, auth_type, api_key, client_id, client_secret, template_id }) => {
+ submit: async ({
+ name,
+ url,
+ description,
+ auth_type,
+ api_key,
+ client_id,
+ client_secret,
+ scope,
+ template_id,
+ }) => {
try {
const result = template_id
? await api.mcpServerInstallations.installTemplate({
template_id,
api_key: api_key || undefined,
+ scope,
})
: await api.mcpServerInstallations.installCustom({
name,
@@ -197,6 +212,7 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([
// falls back to DCR when both are empty.
client_id: client_id || undefined,
client_secret: client_secret || undefined,
+ scope,
})
if (result?.redirect_url) {
window.location.href = result.redirect_url
@@ -245,6 +261,31 @@ export const mcpStoreLogic = kea<mcpStoreLogicType>([
lemonToast.success('Server uninstalled')
return values.installations.filter((i: MCPServerInstallationApi) => i.id !== installationId)
},
+ // Both refetch rather than patching the row in place: unsharing another
+ // member's row (admin reclaim) makes it their personal install, which
+ // must drop out of the requester's list entirely.
+ shareInstallation: async ({ id }: { id: string }) => {
+ try {
+ await api.mcpServerInstallations.share(id)
+ lemonToast.success('Server shared with the project')
+ } catch (e: any) {
+ lemonToast.error(e.detail || 'Failed to share server')
+ throw e
+ }
+ const response = await api.mcpServerInstallations.list()
+ return response.results as MCPServerInstallationApi[]
+ },
+ unshareInstallation: async ({ id }: { id: string }) => {
+ try {
+ await api.mcpServerInstallations.unshare(id)
+ lemonToast.success('Server is now personal')
+ } catch (e: any) {
+ lemonToast.error(e.detail || 'Failed to unshare server')
+ throw e
+ }
+ const response = await api.mcpServerInstallations.list()
+ return response.results as MCPServerInstallationApi[]
+ },
},
],
installationTools: [
diff --git a/products/mcp_store/frontend/scene/AddCustomServerForm.tsx b/products/mcp_store/frontend/scene/AddCustomServerForm.tsx
index e522bae76784..89126f33519b 100644
--- a/products/mcp_store/frontend/scene/AddCustomServerForm.tsx
+++ b/products/mcp_store/frontend/scene/AddCustomServerForm.tsx
@@ -3,8 +3,11 @@ import { Form } from 'kea-forms'
import { LemonButton, LemonCollapse, LemonInput, LemonModal, LemonSelect, LemonTextArea } from '@posthog/lemon-ui'
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { OrganizationMembershipLevel } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
+import type { McpInstallationScope } from '../mcpStoreLogic'
import { mcpStoreLogic } from '../mcpStoreLogic'
const AUTH_TYPE_OPTIONS = [
@@ -12,11 +15,28 @@ const AUTH_TYPE_OPTIONS = [
{ value: 'oauth', label: 'OAuth' },
]
+const SCOPE_OPTIONS: { value: McpInstallationScope; label: string }[] = [
+ { value: 'personal', label: 'Personal (only you)' },
+ { value: 'shared', label: 'Shared (everyone in project)' },
+]
+
export function AddCustomServerForm(): JSX.Element {
const { addCustomServerModalVisible, customServerForm, isCustomServerFormSubmitting, customServerFormPrefilled } =
useValues(mcpStoreLogic)
const { setCustomServerFormValue, closeAddCustomServerModal } = useActions(mcpStoreLogic)
+ // Shared servers expose the installer's credential to every project member and all
+ // autonomous agents, so creating one is admin-only (enforced again on the backend).
+ // Members see shared servers in the list but can only add personal ones.
+ // Organization scope, not Project: on a project with no access controls
+ // configured every member reports as effective project admin, which must
+ // not open up shared-credential creation.
+ const sharedRestrictionReason = useRestrictedArea({
+ scope: RestrictionScope.Organization,
+ minimumAccessLevel: OrganizationMembershipLevel.Admin,
+ })
+ const canAddShared = !sharedRestrictionReason
+
const title = customServerFormPrefilled ? `Connect ${customServerForm.name}` : 'Add MCP server'
const subtitle = customServerFormPrefilled
? 'This server is pre-configured by PostHog. Just paste your credentials below.'
@@ -53,6 +73,22 @@ export function AddCustomServerForm(): JSX.Element {
enableFormOnSubmit
className="deprecated-space-y-3"
>
+ <LemonField
+ name="scope"
+ label="Visibility"
+ help={
+ canAddShared
+ ? 'Shared servers are available to all project members and autonomous agents.'
+ : 'Only project admins can add shared servers.'
+ }
+ >
+ <LemonSelect
+ onChange={(val) => setCustomServerFormValue('scope', val)}
+ options={canAddShared ? SCOPE_OPTIONS : [SCOPE_OPTIONS[0]]}
+ disabledReason={canAddShared ? undefined : sharedRestrictionReason}
+ fullWidth
+ />
+ </LemonField>
{!customServerFormPrefilled && (
<>
<LemonField name="name" label="Name">
diff --git a/products/mcp_store/frontend/scene/InstalledServersList.tsx b/products/mcp_store/frontend/scene/InstalledServersList.tsx
index 16e16546b79e..ea088f1c953e 100644
--- a/products/mcp_store/frontend/scene/InstalledServersList.tsx
+++ b/products/mcp_store/frontend/scene/InstalledServersList.tsx
@@ -58,7 +58,14 @@ export function InstalledServersList(): JSX.Element | null {
{installation.description ? ` · ${installation.description}` : ''}
</div>
</div>
- {statusTag}
+ <div className="flex items-center gap-1">
+ {installation.scope === 'shared' && (
+ <LemonTag type="highlight" size="small">
+ Shared
+ </LemonTag>
+ )}
+ {statusTag}
+ </div>
</div>
</LemonCard>
)
diff --git a/products/mcp_store/frontend/scene/ServerDetailPanel.tsx b/products/mcp_store/frontend/scene/ServerDetailPanel.tsx
index 8dcb28bb7a6c..6a6e95a87a3d 100644
--- a/products/mcp_store/frontend/scene/ServerDetailPanel.tsx
+++ b/products/mcp_store/frontend/scene/ServerDetailPanel.tsx
@@ -1,11 +1,11 @@
import { useActions, useValues } from 'kea'
import { useEffect, useMemo, useState } from 'react'
-import { IconCheck, IconChevronLeft, IconRefresh, IconShieldLock, IconTrash, IconX } from '@posthog/icons'
-import { LemonButton, LemonDivider, LemonSnack, LemonSwitch, LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { IconCheck, IconChevronLeft, IconRefresh, IconShare, IconShieldLock, IconTrash, IconX } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonDivider, LemonSnack, LemonSwitch, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
-import { TeamMembershipLevel } from 'lib/constants'
+import { OrganizationMembershipLevel, TeamMembershipLevel } from 'lib/constants'
import { Link } from 'lib/lemon-ui/Link'
import { teamLogic } from 'scenes/teamLogic'
@@ -206,12 +206,41 @@ interface Props {
export function ServerDetailPanel({ installation, template }: Props): JSX.Element {
const { currentTeamId } = useValues(teamLogic)
- const { selectServer, setSceneView, toggleServerEnabled, uninstallServer, installTemplate } =
- useActions(mcpStoreLogic)
+ const {
+ selectServer,
+ setSceneView,
+ toggleServerEnabled,
+ uninstallServer,
+ installTemplate,
+ shareInstallation,
+ unshareInstallation,
+ } = useActions(mcpStoreLogic)
+ const { installationsLoading } = useValues(mcpStoreLogic)
const restrictedReason = useRestrictedArea({
scope: RestrictionScope.Project,
minimumAccessLevel: TeamMembershipLevel.Member,
})
+ // Sharing carries the same admin gate as creating a shared install outright
+ // (see AddCustomServerForm); admins can also unshare or remove another
+ // member's shared server. Organization scope, not Project: on a project
+ // with no access controls configured every member reports as effective
+ // project admin, which must not open up shared-credential management.
+ // The backend applies the same gate (plus explicitly-granted project admins).
+ const adminRestrictionReason = useRestrictedArea({
+ scope: RestrictionScope.Organization,
+ minimumAccessLevel: OrganizationMembershipLevel.Admin,
+ })
+ const isAdmin = !adminRestrictionReason
+ const isOwner = installation?.is_owner === true
+ // The backend rejects owner-only mutations of shared rows (rename, toggle,
+ // tool policy) for non-owners — gate them client-side instead of surfacing 403s.
+ const ownerOnlyReason =
+ installation?.scope === 'shared' && !isOwner ? 'Only the owner can modify a shared server connection' : null
+ const mutationDisabledReason = restrictedReason ?? ownerOnlyReason
+ const removeDisabledReason =
+ installation?.scope === 'shared' && !isOwner && !isAdmin
+ ? 'Only the owner or a project admin can remove a shared server'
+ : restrictedReason
if (!installation && !template) {
return (
@@ -285,18 +314,62 @@ export function ServerDetailPanel({ installation, template }: Props): JSX.Elemen
<LemonSwitch
checked={installation.is_enabled !== false}
onChange={(checked) => toggleServerEnabled({ id: installation.id, enabled: checked })}
- disabledReason={restrictedReason ?? undefined}
+ disabledReason={mutationDisabledReason ?? undefined}
/>
</Tooltip>
)}
+ {installation?.scope === 'personal' && isOwner && isAdmin && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconShare />}
+ loading={installationsLoading}
+ onClick={() =>
+ LemonDialog.open({
+ title: `Share "${installation.name}" with the project?`,
+ description: (
+ <div className="max-w-120">
+ Everyone in this project, including the PostHog agent, can use{' '}
+ <strong>{installation.name}</strong> via your connection. Their actions will
+ be attributed to your account. For better security, connect a service
+ account. You can unshare anytime.
+ </div>
+ ),
+ secondaryButton: {
+ type: 'secondary',
+ children: 'Cancel',
+ },
+ primaryButton: {
+ type: 'primary',
+ children: 'Share with project',
+ onClick: () => shareInstallation({ id: installation.id }),
+ },
+ })
+ }
+ >
+ Share with project
+ </LemonButton>
+ )}
+ {installation?.scope === 'shared' && (isOwner || isAdmin) && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ loading={installationsLoading}
+ onClick={() => unshareInstallation({ id: installation.id })}
+ tooltip="Convert back to a personal server, visible only to its owner."
+ >
+ Unshare
+ </LemonButton>
+ )}
{installation && (
<LemonButton
type="secondary"
status="danger"
size="small"
icon={<IconTrash />}
+ loading={installationsLoading}
onClick={() => uninstallServer(installation.id)}
- disabledReason={restrictedReason}
+ disabledReason={removeDisabledReason}
>
Remove
</LemonButton>
diff --git a/products/mcp_store/mcp/tools.yaml b/products/mcp_store/mcp/tools.yaml
index 3580fea88ba8..a7b3a22bcf8f 100644
--- a/products/mcp_store/mcp/tools.yaml
+++ b/products/mcp_store/mcp/tools.yaml
@@ -75,6 +75,12 @@ tools:
mcp-connections-update:
operation: mcp_server_installations_update
enabled: false
+ mcp-server-installations-share-create:
+ operation: mcp_server_installations_share_create
+ enabled: false
+ mcp-server-installations-unshare-create:
+ operation: mcp_server_installations_unshare_create
+ enabled: false
mcp-servers-list:
operation: mcp_servers_list
enabled: false
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 7019d589fa68..19c6581b8c71 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -176,6 +176,16 @@ def _agentsh_domains_for(ctx: TaskProcessingContext) -> list[str] | None:
return None if (ctx.use_modal_network_allowlist and not ctx.use_modal_vm_sandbox) else ctx.allowed_domains
+def _include_personal_mcp_for_task(task: Task) -> bool:
+ """Whether a run may pull the task creator's *personal* MCP installations.
+
+ Internal/autonomous runs (support reply, signals) must never pull a
+ resolved member's personal creds — they get shared team connections only.
+ User-initiated Code runs get shared + the creator's personal installs.
+ """
+ return not task.internal
+
+
def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes) -> _LaunchParams:
try:
task = Task.objects.select_related("created_by", "team").get(id=ctx.task_id)
@@ -214,15 +224,16 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes) -> _La
interaction_origin=ctx.interaction_origin,
task_id=str(ctx.task_id),
)
- if actor_user and actor_user.id:
- user_mcp_configs = get_user_mcp_server_configs(
- token=access_token,
- team_id=ctx.team_id,
- user_id=actor_user.id,
- interaction_origin=ctx.interaction_origin,
- )
- if user_mcp_configs:
- mcp_configs = mcp_configs + user_mcp_configs
+ include_personal = _include_personal_mcp_for_task(task)
+ user_mcp_configs = get_user_mcp_server_configs(
+ token=access_token,
+ team_id=ctx.team_id,
+ user_id=actor_user.id if actor_user else None,
+ include_personal=include_personal,
+ interaction_origin=ctx.interaction_origin,
+ )
+ if user_mcp_configs:
+ mcp_configs = mcp_configs + user_mcp_configs
if mcp_configs:
emit_agent_log(
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index 8f05c4e4ff48..bd70bb153c1b 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -6,6 +6,7 @@ from products.tasks.backend.temporal.process_task.activities.get_task_processing
from products.tasks.backend.temporal.process_task.activities.start_agent_server import (
StartAgentServerInput,
_ensure_repository_on_disk,
+ _include_personal_mcp_for_task,
_resolve_protected_base_branch,
start_agent_server,
)
@@ -49,6 +50,21 @@ def _mock_github_integration(mocker, pr_base: str | None):
return integration
+ "internal,expected",
+ [
+ # Internal/autonomous runs (support reply, signals) get shared team
+ # connections only — never a resolved member's personal MCP creds.
+ (True, False),
+ # User-initiated Code runs get shared + the creator's personal installs.
+ (False, True),
+ ],
+)
+def test_include_personal_mcp_for_task(mocker, internal, expected) -> None:
+ task = mocker.Mock(internal=internal)
+ assert _include_personal_mcp_for_task(task) is expected
+
+
@pytest.mark.parametrize(
"pr_base,branch,expected",
[
@@ -119,6 +135,7 @@ def test_ensure_repository_on_disk_skips_repo_less_runs(mocker) -> None:
sandbox.execute.assert_not_called()
async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mocker) -> None:
context = _context(sandbox_event_ingest_enabled=True)
sandbox = mocker.Mock()
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index 98ac448c9e80..be7772f28000 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -324,7 +324,7 @@ class TestFetchUserMcpServerConfigs(TestCase):
USER_ID = 7
API_BASE = "https://us.posthog.com"
- MOCK_FACADE = "products.tasks.backend.temporal.process_task.utils.get_active_installations"
+ MOCK_FACADE = "products.tasks.backend.temporal.process_task.utils.get_installations_for_sandbox"
MOCK_API_URL = "products.tasks.backend.temporal.process_task.utils.get_sandbox_api_url"
def _make_installation(self, **kwargs) -> ActiveInstallationInfo:
@@ -351,7 +351,7 @@ class TestFetchUserMcpServerConfigs(TestCase):
configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID)
- mock_facade.assert_called_once_with(self.TEAM_ID, self.USER_ID)
+ mock_facade.assert_called_once_with(self.TEAM_ID, user_id=self.USER_ID, include_personal=True)
assert configs == [
McpServerConfig(
type="http",
@@ -383,6 +383,17 @@ class TestFetchUserMcpServerConfigs(TestCase):
assert configs[0].headers == self._expected_user_headers(consumer=expected_consumer)
+ @parameterized.expand([(True,), (False,)])
+ @patch(MOCK_API_URL)
+ @patch(MOCK_FACADE)
+ def test_include_personal_is_forwarded_to_facade(self, include_personal: bool, mock_facade, mock_api_url) -> None:
+ mock_api_url.return_value = self.API_BASE
+ mock_facade.return_value = []
+
+ get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID, include_personal=include_personal)
+
+ mock_facade.assert_called_once_with(self.TEAM_ID, user_id=self.USER_ID, include_personal=include_personal)
+
@patch(MOCK_API_URL)
@patch(MOCK_FACADE)
def test_returns_empty_when_no_installations(self, mock_facade, mock_api_url) -> None:
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index b3cc35943dc9..7afb34a37886 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -15,7 +15,7 @@ from posthog.models.user import User
from posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegration
from posthog.temporal.oauth import TOKEN_EXPIRATION_SECONDS, PosthogMcpScopes, has_write_scopes
-from products.mcp_store.backend.facade.api import get_active_installations
+from products.mcp_store.backend.facade.api import get_installations_for_sandbox
from products.tasks.backend.constants import (
ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS,
DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,
@@ -399,14 +399,16 @@ def get_sandbox_api_url() -> str:
def get_user_mcp_server_configs(
token: str,
team_id: int,
- user_id: int,
+ user_id: int | None = None,
*,
+ include_personal: bool = True,
interaction_origin: str | None = None,
) -> list[McpServerConfig]:
- """Fetch the user's MCP Store installations and return sandbox configs.
+ """Fetch MCP Store installations for sandbox use and return configs.
- Uses the mcp_store facade to get active installations, then builds
- McpServerConfig entries with full proxy URLs and auth headers.
+ Always includes shared (team-wide) installations. When
+ ``include_personal`` is True and a ``user_id`` is provided, the user's
+ personal installations are included too.
The `x-posthog-mcp-consumer` header is set on every config so the agent's
identity propagates through the MCP Store proxy to whichever upstream MCP
@@ -416,7 +418,11 @@ def get_user_mcp_server_configs(
Returns an empty list on errors (non-fatal).
"""
- installations = get_active_installations(team_id, user_id)
+ installations = get_installations_for_sandbox(
+ team_id,
+ user_id=user_id,
+ include_personal=include_personal,
+ )
api_base = get_sandbox_api_url().rstrip("/")
consumer = _resolve_mcp_consumer(interaction_origin)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 45f10a3baa99..6943945f1f33 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -29507,6 +29507,18 @@ export namespace Schemas {
PosthogCode: 'posthog-code',
} as const;
+ /**
+ * * `personal` - personal
+ * * `shared` - shared
+ */
+ export type MCPInstallationScopeEnum = typeof MCPInstallationScopeEnum[keyof typeof MCPInstallationScopeEnum];
+
+
+ export const MCPInstallationScopeEnum = {
+ Personal: 'personal',
+ Shared: 'shared',
+ } as const;
+
export interface InstallCustom {
/** @maxLength 200 */
name: string;
@@ -29519,6 +29531,11 @@ export namespace Schemas {
client_secret?: string;
install_source?: InstallSourceEnum;
posthog_code_callback_url?: string;
+ /** 'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).
+ *
+ * * `personal` - personal
+ * * `shared` - shared */
+ scope?: MCPInstallationScopeEnum;
}
export interface InstallTemplate {
@@ -29526,6 +29543,11 @@ export namespace Schemas {
api_key?: string;
install_source?: InstallSourceEnum;
posthog_code_callback_url?: string;
+ /** 'personal' is per-user; 'shared' is team-wide (visible to all project members and sandbox agents).
+ *
+ * * `personal` - personal
+ * * `shared` - shared */
+ scope?: MCPInstallationScopeEnum;
}
/**
@@ -31587,6 +31609,18 @@ export namespace Schemas {
blocked?: boolean;
}
+ /**
+ * * `personal` - Personal
+ * * `shared` - Shared
+ */
+ export type MCPServerInstallationScopeEnum = typeof MCPServerInstallationScopeEnum[keyof typeof MCPServerInstallationScopeEnum];
+
+
+ export const MCPServerInstallationScopeEnum = {
+ Personal: 'personal',
+ Shared: 'shared',
+ } as const;
+
export interface MCPServerInstallation {
readonly id: string;
/** @nullable */
@@ -31601,6 +31635,9 @@ export namespace Schemas {
description?: string;
auth_type?: MCPAuthTypeEnum;
is_enabled?: boolean;
+ readonly scope: MCPServerInstallationScopeEnum;
+ /** True when the requesting user owns this installation. Lets clients gate owner-only controls instead of surfacing 403s. */
+ readonly is_owner: boolean;
readonly needs_reauth: boolean;
readonly pending_oauth: boolean;
readonly proxy_url: string;