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): restrict slack dev connections to selected projects (#102653)

Dylan Martin1056c194553c
diff --git a/docs/internal/slack-local-setup-guide.md b/docs/internal/slack-local-setup-guide.md
index 9a09199a7ad1..75143b7da546 100644
--- a/docs/internal/slack-local-setup-guide.md
+++ b/docs/internal/slack-local-setup-guide.md
@@ -258,6 +258,43 @@ when the repo-discovery agent has to choose among repos (a no-repo prompt skips
Follow-ups — reply in-thread with another `@mention` — are forwarded to the running sandbox and
should react 👀 → 🦔 (or ❌ if the sandbox is gone). Expected from the code; not verified in our run.
+## Use a development Slack app from production Desktop
+
+This setup lets selected projects connect to Slack through the MCP store with a development Slack app.
+It does not move bot events to production or change the production Slack app's credentials.
+
+1. Add `https://us.posthog.com/api/mcp_store/oauth_redirect/` to the development app's OAuth redirect URLs for US production.
+ Keep its existing dev redirect URLs and event callbacks.
+ For another region, use that region's PostHog origin instead.
+2. Provision the existing development app's client ID and client secret as the `SLACK_DEV_APP_CLIENT_ID` and `SLACK_DEV_APP_CLIENT_SECRET` instance settings in the target region.
+ Do not replace `SLACK_APP_CLIENT_ID`, `SLACK_APP_CLIENT_SECRET`, or `SLACK_APP_SIGNING_SECRET`.
+3. Set `MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS` to a comma-separated list of permitted project IDs in that region's server configuration.
+ The default is empty, which blocks access.
+ Apply the same configuration to the web processes and workers.
+ Production deployments must also add these variables to `posthog/charts` and provision their values through `posthog/secrets`.
+ Adding the settings in this repository does not configure production.
+4. Enable the `mcp-slack-dev` feature flag for PostHog users.
+ Target users whose email ends with `@posthog.com`.
+ Use that email condition, not a cohort or an early access list.
+ The check evaluates the flag locally and treats targeting it cannot resolve as off.
+ For local testing, add `mcp-slack-dev` to `POSTHOG_FEATURE_FLAGS_FORCE_ENABLED` and restart Django.
+5. Run `python manage.py sync_mcp_server_templates` in that environment.
+ The existing Slack MCP entry becomes **Slack via PostHog (dev)** and uses the separate credentials.
+ It activates only after the shared-client probe passes.
+ Existing Slack MCP installations block a change of OAuth app; do not disconnect them without their owners' approval.
+6. In an allowed project, connect **Slack via PostHog (dev)** from the MCP store, finish Slack authorization, and confirm that a channel search returns results.
+ Confirm that another project cannot list or authorize this entry.
+
+The connection keeps the catalog's reviewed MCP scopes; it does not request all scopes available to the bot.
+The project restriction applies to authorization, token exchange, token refresh, and upstream requests.
+Removing a project from the allowlist blocks its existing connection, even before catalog sync runs.
+
+To retire this setup, empty the allowlist and run catalog sync to deactivate the entry.
+Disconnect the development-app MCP installations, then run catalog sync again to restore the `slack_app` credential source.
+Remove the separate development credentials and the added production redirect URL if nothing else uses them.
+After the production catalog suspension is removed, run catalog sync and reconnect through the production app.
+Tokens from the development app cannot be transferred to the production app.
+
## Debugging
- **ngrok request inspector** (`http://127.0.0.1:4040`) — confirms Slack's webhook actually reached
diff --git a/posthog/egress/slack/README.md b/posthog/egress/slack/README.md
index 26a565f3c834..985c2c4baae9 100644
--- a/posthog/egress/slack/README.md
+++ b/posthog/egress/slack/README.md
@@ -18,7 +18,7 @@ No lanes, because nothing is gated.
- Slack SDK calls use `SlackWebClient` or `SlackAsyncWebClient` from `client.py` and `async_client.py`. A retry handler records every HTTP attempt, including each retry.
- Direct HTTP calls, such as file downloads in `posthog/temporal/ai/slack_app/attachments.py`, use `slack_request`.
-- The OAuth code exchange in `posthog/models/integration/oauth.py` records its response with `record_slack_api_response`.
+- OAuth code exchanges in `posthog/models/integration/oauth.py` and MCP Store token exchanges and refreshes record their responses with `record_slack_api_response`.
The `slack-api-calls-go-through-egress` semgrep rule fails CI on a bare `WebClient` or a raw `requests` call to `slack.com/api`.
diff --git a/posthog/permissions.py b/posthog/permissions.py
index 639b3cf63ceb..d95cf3e3a8ae 100644
--- a/posthog/permissions.py
+++ b/posthog/permissions.py
@@ -1,7 +1,7 @@
import os
import time
import uuid
-from typing import Optional, cast
+from typing import Any, Optional, cast
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
@@ -1186,6 +1186,7 @@ def posthog_feature_flag_value(
*,
organization_id: str | uuid.UUID,
team_id: int | None = None,
+ person_properties: dict[str, Any] | None = None,
only_evaluate_locally: bool = False,
) -> bool | None:
"""Server-side check of a PostHog-internal gating flag with org/project group context.
@@ -1211,6 +1212,7 @@ def posthog_feature_flag_value(
distinct_id,
groups=groups,
group_properties=group_properties,
+ person_properties=person_properties,
only_evaluate_locally=only_evaluate_locally,
send_feature_flag_events=False,
)
@@ -1222,6 +1224,7 @@ def posthog_feature_flag_enabled(
*,
organization_id: str | uuid.UUID,
team_id: int | None = None,
+ person_properties: dict[str, Any] | None = None,
only_evaluate_locally: bool = False,
) -> bool:
return bool(
@@ -1230,6 +1233,7 @@ def posthog_feature_flag_enabled(
distinct_id,
organization_id=organization_id,
team_id=team_id,
+ person_properties=person_properties,
only_evaluate_locally=only_evaluate_locally,
)
)
diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.py
index af801e10d39d..c6fb4d6e7db9 100644
--- a/posthog/settings/dynamic_settings.py
+++ b/posthog/settings/dynamic_settings.py
@@ -197,6 +197,16 @@ CONSTANCE_CONFIG = {
"Used to validate Slack events for example when unfurling links",
str,
),
+ "SLACK_DEV_APP_CLIENT_ID": (
+ get_from_env("SLACK_DEV_APP_CLIENT_ID", default=""),
+ "OAuth client ID for the project-restricted Slack MCP connection",
+ str,
+ ),
+ "SLACK_DEV_APP_CLIENT_SECRET": (
+ get_from_env("SLACK_DEV_APP_CLIENT_SECRET", default=""),
+ "OAuth client secret for the project-restricted Slack MCP connection",
+ str,
+ ),
"SUPPORT_SLACK_APP_CLIENT_ID": (
get_from_env("SUPPORT_SLACK_APP_CLIENT_ID", default=""),
"Used to enable the 'Add to Slack' button for the SupportHog Slack app.",
@@ -429,6 +439,8 @@ SETTINGS_ALLOWING_API_OVERRIDE = (
"SLACK_APP_CLIENT_ID",
"SLACK_APP_CLIENT_SECRET",
"SLACK_APP_SIGNING_SECRET",
+ "SLACK_DEV_APP_CLIENT_ID",
+ "SLACK_DEV_APP_CLIENT_SECRET",
"SUPPORT_SLACK_APP_CLIENT_ID",
"SUPPORT_SLACK_APP_CLIENT_SECRET",
"SUPPORT_SLACK_SIGNING_SECRET",
@@ -465,6 +477,7 @@ SETTINGS_ALLOWING_API_OVERRIDE = (
SECRET_SETTINGS = [
"EMAIL_HOST_PASSWORD",
"SLACK_APP_CLIENT_SECRET",
+ "SLACK_DEV_APP_CLIENT_SECRET",
"SLACK_APP_SIGNING_SECRET",
"SUPPORT_SLACK_SIGNING_SECRET",
"SUPPORT_SLACK_APP_CLIENT_SECRET",
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 6bb59f8f8486..1c58455c29e5 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1330,6 +1330,8 @@ try:
except ValueError:
MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM = {}
+MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS = get_list(get_from_env("MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS", ""))
+
# AEO citation-tracking POC (products/aeo). The scheduled runner only covers
# teams in this allowlist AND with the `aeo-citation-tracking` flag enabled.
AEO_CITATION_TEAM_IDS = get_list(get_from_env("AEO_CITATION_TEAM_IDS", ""))
diff --git a/products/mcp_store/README.md b/products/mcp_store/README.md
index f61f2a1aab28..619e8cc32a0a 100644
--- a/products/mcp_store/README.md
+++ b/products/mcp_store/README.md
@@ -165,6 +165,9 @@ OAuth catalog entries can set `oauth_scope_allowlist` to limit registration and
Slack uses the existing `SLACK_APP_CLIENT_ID` and `SLACK_APP_CLIENT_SECRET` instance settings. Its catalog entry remains suspended until the production Slack app supports MCP and its regional callbacks are live. After the suspension is removed, catalog sync activates Slack only when both settings exist and the shared-client probe passes. Each Desktop user still completes a separate OAuth grant for the catalog's reviewed MCP scopes.
+For a project-restricted connection through a separate Slack app, see [Slack MCP development app setup](../../docs/internal/slack-local-setup-guide.md#use-a-development-slack-app-from-production-desktop).
+This uses separate OAuth credentials and does not change the Slack bot or its webhook settings.
+
## Operator runbook: activating a manually provisioned shared-creds server
1. Register these redirect URIs in the vendor's developer console:
diff --git a/products/mcp_store/backend/catalog_sync.py b/products/mcp_store/backend/catalog_sync.py
index f81c98884dc4..1c4adab144d9 100644
--- a/products/mcp_store/backend/catalog_sync.py
+++ b/products/mcp_store/backend/catalog_sync.py
@@ -30,8 +30,9 @@ Semantics, chosen so the sync can run unattended at every app startup:
not by anything in this module.
"""
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
+from django.conf import settings
from django.db import IntegrityError
import structlog
@@ -201,12 +202,31 @@ def _update_template(template: MCPServerTemplate, entry: CatalogEntry, skip_prob
counts.updated += 1
+def _entry_for_environment(entry: CatalogEntry, template: MCPServerTemplate | None) -> CatalogEntry:
+ if entry.oauth_credentials_source != "slack_app" or entry.url != "https://mcp.slack.com/mcp":
+ return entry
+ dev_enabled = bool(settings.MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS)
+ dev_template = template is not None and template.oauth_credentials_source == "slack_dev_app"
+ if not dev_enabled and (not dev_template or (template is not None and not template.installations.exists())):
+ return entry
+ if template is not None and not dev_template and template.installations.exists():
+ raise ValueError("Disconnect existing Slack MCP installations before changing OAuth apps")
+ return replace(
+ entry,
+ name="Slack via PostHog (dev)",
+ description="Search public Slack channels with the internal PostHog development app.",
+ oauth_credentials_source="slack_dev_app",
+ disabled=not dev_enabled,
+ )
+
+
def sync_mcp_catalog(entries: list[CatalogEntry] | None = None, skip_probe: bool = False) -> SyncCounts:
counts = SyncCounts()
catalog = entries if entries is not None else MCP_SERVER_CATALOG
for entry in catalog:
try:
template = MCPServerTemplate.objects.filter(url=entry.url).first()
+ entry = _entry_for_environment(entry, template)
if template is None:
try:
_create_template(entry, skip_probe, counts)
diff --git a/products/mcp_store/backend/models.py b/products/mcp_store/backend/models.py
index 8f4ac8ccc389..f7093d52e608 100644
--- a/products/mcp_store/backend/models.py
+++ b/products/mcp_store/backend/models.py
@@ -8,6 +8,8 @@ from posthog.helpers.encrypted_fields import EncryptedJSONField
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+from .oauth_credentials import oauth_credentials_source_is_allowed
+
class MCPAuthType(models.TextChoices):
API_KEY = "api_key", "API Key"
@@ -174,6 +176,16 @@ class MCPServerTemplate(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
oauth_credentials = EncryptedJSONField(default=dict, blank=True)
is_active = models.BooleanField(default=False)
+ @classmethod
+ def available_for_team(cls, team_id: int) -> models.QuerySet["MCPServerTemplate"]:
+ templates = cls.objects.filter(is_active=True)
+ if not oauth_credentials_source_is_allowed("slack_dev_app", team_id):
+ templates = templates.exclude(oauth_credentials_source="slack_dev_app")
+ return templates
+
+ def oauth_credentials_source_is_allowed_for_team(self, team_id: int) -> bool:
+ return oauth_credentials_source_is_allowed(self.oauth_credentials_source, team_id)
+
def save(self, *args, **kwargs) -> None:
update_fields = kwargs.get("update_fields")
if update_fields is None or "icon_key" in update_fields:
diff --git a/products/mcp_store/backend/oauth.py b/products/mcp_store/backend/oauth.py
index 19a9b10bd9d7..97b13d470b45 100644
--- a/products/mcp_store/backend/oauth.py
+++ b/products/mcp_store/backend/oauth.py
@@ -14,10 +14,16 @@ import structlog
import tldextract
from posthog.dataclasses import frozen
+from posthog.egress.slack.observability import record_slack_api_response, slack_endpoint_from_url
from posthog.security.url_validation import is_url_allowed
from .models import MCPServerInstallation, MCPServerTemplate, TemplateOAuthCredentials
-from .oauth_credentials import resolve_oauth_credentials_source, validate_oauth_credentials_source_metadata
+from .oauth_credentials import (
+ SUPPORTED_OAUTH_CREDENTIAL_SOURCES,
+ oauth_credentials_source_is_allowed,
+ resolve_oauth_credentials_source,
+ validate_oauth_credentials_source_metadata,
+)
logger = structlog.get_logger(__name__)
@@ -501,6 +507,8 @@ def resolve_installation_oauth_context(installation: MCPServerInstallation) -> I
template = installation.template
if template is not None:
+ if not oauth_credentials_source_is_allowed(template.oauth_credentials_source, installation.team_id):
+ raise ValueError("OAuth app is not available for this project")
credentials = resolve_template_oauth_credentials(template)
shared_client_id = credentials.get("client_id", "")
if shared_client_id:
@@ -592,6 +600,7 @@ def refresh_oauth_token(
client_secret: str | None = None,
token_endpoint_auth_method: str | None = None,
resource: str = "",
+ oauth_credentials_source: str = "",
) -> dict:
data: dict[str, str] = {
"grant_type": "refresh_token",
@@ -614,6 +623,15 @@ def refresh_oauth_token(
try:
_validate_url(token_url)
resp = requests.post(token_url, data=data, auth=auth, timeout=TIMEOUT, allow_redirects=False)
+ if oauth_credentials_source in SUPPORTED_OAUTH_CREDENTIAL_SOURCES:
+ record_slack_api_response(
+ resp,
+ source="mcp_store_oauth",
+ workspace_id=None,
+ app_id=oauth_credentials_source,
+ method="POST",
+ endpoint=slack_endpoint_from_url(token_url),
+ )
if 300 <= resp.status_code < 400:
raise TokenRefreshError("Token refresh endpoint redirected")
resp.raise_for_status()
@@ -701,6 +719,7 @@ def refresh_installation_token(installation: MCPServerInstallation) -> dict:
client_secret=ctx.client_secret,
token_endpoint_auth_method=ctx.token_endpoint_auth_method,
resource=oauth_resource(ctx.metadata),
+ oauth_credentials_source=installation.template.oauth_credentials_source if installation.template else "",
)
except TokenRefreshRejectedError:
_flag_needs_reauth(installation, rejected_refresh_token=refresh_token_value)
@@ -776,6 +795,16 @@ def exchange_oauth_token(
raise OAuthTokenExchangeError(str(exc))
token_response = requests.post(token_endpoint, data=form, auth=auth, timeout=TIMEOUT, allow_redirects=False)
+ oauth_credentials_source = installation.template.oauth_credentials_source if installation.template else ""
+ if oauth_credentials_source in SUPPORTED_OAUTH_CREDENTIAL_SOURCES:
+ record_slack_api_response(
+ token_response,
+ source="mcp_store_oauth",
+ workspace_id=None,
+ app_id=oauth_credentials_source,
+ method="POST",
+ endpoint=slack_endpoint_from_url(token_endpoint),
+ )
# RFC 6749 specifies 200, but some providers (e.g. Supabase) return 201.
if 300 <= token_response.status_code < 400:
diff --git a/products/mcp_store/backend/oauth_credentials.py b/products/mcp_store/backend/oauth_credentials.py
index 37769cb20d6a..80aae7ace3ea 100644
--- a/products/mcp_store/backend/oauth_credentials.py
+++ b/products/mcp_store/backend/oauth_credentials.py
@@ -1,21 +1,32 @@
from collections.abc import Mapping
from typing import Literal
+from django.conf import settings
+
from posthog.models.instance_setting import get_instance_settings
-OAuthCredentialsSource = Literal["slack_app"]
+OAuthCredentialsSource = Literal["slack_app", "slack_dev_app"]
_TRUSTED_OAUTH_METADATA_BY_SOURCE: dict[str, dict[str, str]] = {
"slack_app": {
"issuer": "https://mcp.slack.com",
"authorization_endpoint": "https://slack.com/oauth/v2_user/authorize",
"token_endpoint": "https://slack.com/api/oauth.v2.user.access",
- }
+ },
+ "slack_dev_app": {
+ "issuer": "https://mcp.slack.com",
+ "authorization_endpoint": "https://slack.com/oauth/v2_user/authorize",
+ "token_endpoint": "https://slack.com/api/oauth.v2.user.access",
+ },
}
SUPPORTED_OAUTH_CREDENTIAL_SOURCES = frozenset(_TRUSTED_OAUTH_METADATA_BY_SOURCE)
+def oauth_credentials_source_is_allowed(source: str, team_id: int) -> bool:
+ return source != "slack_dev_app" or str(team_id) in settings.MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS
+
+
def validate_oauth_credentials_source_metadata(source: str, metadata: Mapping[str, object]) -> None:
trusted_metadata = _TRUSTED_OAUTH_METADATA_BY_SOURCE.get(source)
if trusted_metadata is None:
@@ -25,12 +36,13 @@ def validate_oauth_credentials_source_metadata(source: str, metadata: Mapping[st
def resolve_oauth_credentials_source(source: str) -> dict[str, str]:
- if source != "slack_app":
+ if source not in SUPPORTED_OAUTH_CREDENTIAL_SOURCES:
raise ValueError(f"Unknown OAuth credential source: {source}")
- settings = get_instance_settings(["SLACK_APP_CLIENT_ID", "SLACK_APP_CLIENT_SECRET"])
- client_id = settings.get("SLACK_APP_CLIENT_ID")
- client_secret = settings.get("SLACK_APP_CLIENT_SECRET")
+ prefix = "SLACK_DEV_APP" if source == "slack_dev_app" else "SLACK_APP"
+ instance_settings = get_instance_settings([f"{prefix}_CLIENT_ID", f"{prefix}_CLIENT_SECRET"])
+ client_id = instance_settings.get(f"{prefix}_CLIENT_ID")
+ client_secret = instance_settings.get(f"{prefix}_CLIENT_SECRET")
return {
"client_id": client_id if isinstance(client_id, str) else "",
"client_secret": client_secret if isinstance(client_secret, str) else "",
diff --git a/products/mcp_store/backend/presentation/gateway_views.py b/products/mcp_store/backend/presentation/gateway_views.py
index 1545c711c46d..9ec42e8cf3c1 100644
--- a/products/mcp_store/backend/presentation/gateway_views.py
+++ b/products/mcp_store/backend/presentation/gateway_views.py
@@ -66,6 +66,7 @@ from ..models import (
TeamMCPGatewayConfig,
)
from ..policy import GatewayCaller, PolicyContext, is_destructive_tool, is_policy_state_allowed
+from .visibility import slack_dev_mcp_ui_enabled
logger = structlog.get_logger(__name__)
@@ -303,6 +304,9 @@ class MCPGatewayServerSerializer(serializers.ModelSerializer):
is_revoked_for_you = serializers.SerializerMethodField(
help_text="True when an admin has turned this server off for the requesting user."
)
+ is_team_enabled = serializers.SerializerMethodField(
+ help_text="True when this server is enabled and available to the project."
+ )
class Meta:
model = MCPGatewayServer
@@ -346,6 +350,12 @@ class MCPGatewayServerSerializer(serializers.ModelSerializer):
return obj.template.auth_type
return obj.auth_type or None
+ @extend_schema_field(serializers.BooleanField())
+ def get_is_team_enabled(self, obj: MCPGatewayServer) -> bool:
+ if obj.template is not None and not obj.template.oauth_credentials_source_is_allowed_for_team(obj.team_id):
+ return False
+ return obj.is_team_enabled
+
@extend_schema_field(serializers.IntegerField())
def get_tool_count(self, obj: MCPGatewayServer) -> int:
annotated = getattr(obj, "tool_count_annotated", None)
@@ -714,9 +724,16 @@ class MCPServiceAccountSerializer(serializers.ModelSerializer):
"icon_key": server.template.icon_key if server.template else "",
"icon_domain": server.template.icon_domain if server.template else "",
"connection_state": connection_state,
- # Mirrors the run-path predicate (reachable_agent_grants plus the
- # is_team_enabled filter), so pickers can hide grants a run cannot mount.
- "reachable": server.is_team_enabled and not getattr(access, "grant_owner_revoked", False),
+ # Mirrors the run path's grant, server, and credential-source checks so
+ # pickers can hide grants a run cannot mount.
+ "reachable": (
+ server.is_team_enabled
+ and (
+ server.template is None
+ or server.template.oauth_credentials_source_is_allowed_for_team(server.team_id)
+ )
+ and not getattr(access, "grant_owner_revoked", False)
+ ),
}
)
return servers
@@ -937,6 +954,10 @@ class MCPGatewayServerViewSet(
def safely_get_queryset(self, queryset: QuerySet[MCPGatewayServer]) -> QuerySet[MCPGatewayServer]:
servers = MCPGatewayServer.objects.for_team(self.team_id)
+ if servers.filter(template__oauth_credentials_source="slack_dev_app").exists() and not slack_dev_mcp_ui_enabled(
+ user=cast(User, self.request.user), team=self.team
+ ):
+ servers = servers.exclude(template__oauth_credentials_source="slack_dev_app")
if not self._is_project_admin():
user_id = cast(int, self.request.user.id)
servers = servers.filter(is_team_enabled=True).exclude(member_revocations__user_id=user_id)
@@ -1136,7 +1157,7 @@ class MCPGatewayServerViewSet(
self._require_project_admin()
data = request.validated_data
try:
- template = MCPServerTemplate.objects.get(id=data["template_id"], is_active=True)
+ template = MCPServerTemplate.available_for_team(self.team_id).get(id=data["template_id"])
except MCPServerTemplate.DoesNotExist:
raise NotFound("Template not found.")
diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.py
index f715a67b5517..5957bd059333 100644
--- a/products/mcp_store/backend/presentation/views.py
+++ b/products/mcp_store/backend/presentation/views.py
@@ -82,6 +82,7 @@ from ..policy import GatewayCaller, PolicyContext, ResolvedPolicy, is_policy_sta
from ..proxy import proxy_mcp_request, record_tool_call_audit, resolve_call_decision, validate_installation_auth
from ..tasks import sync_installation_tools_task
from ..tools import ToolCallError, ToolsFetchError, call_upstream_tool, sync_installation_tools
+from .visibility import slack_dev_mcp_ui_enabled
class MCPProxyRenderer(renderers.BaseRenderer):
@@ -256,7 +257,11 @@ class MCPServerViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, viewsets.G
responses={200: OpenApiResponse(response=MCPServerTemplateSerializer(many=True))},
)
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- queryset = MCPServerTemplate.objects.filter(is_active=True).order_by("name")
+ queryset = MCPServerTemplate.available_for_team(self.team_id).order_by("name")
+ if queryset.filter(oauth_credentials_source="slack_dev_app").exists() and not slack_dev_mcp_ui_enabled(
+ user=cast(User, request.user), team=self.team
+ ):
+ queryset = queryset.exclude(oauth_credentials_source="slack_dev_app")
serializer = MCPServerTemplateSerializer(queryset, many=True)
return Response({"results": serializer.data})
@@ -1382,7 +1387,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
self._validate_gateway_options(data)
try:
- template = MCPServerTemplate.objects.get(id=template_id, is_active=True)
+ template = MCPServerTemplate.available_for_team(self.team_id).get(id=template_id)
except MCPServerTemplate.DoesNotExist:
return Response({"detail": "Template not found"}, status=status.HTTP_404_NOT_FOUND)
self._require_server_enabled_for_team(template.url)
@@ -1883,7 +1888,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
web_return_path: str = "",
) -> HttpResponse:
try:
- template = MCPServerTemplate.objects.get(id=template_id, is_active=True)
+ template = MCPServerTemplate.available_for_team(self.team_id).get(id=template_id)
except MCPServerTemplate.DoesNotExist:
return Response({"detail": "Template not found"}, status=status.HTTP_404_NOT_FOUND)
self._require_server_enabled_for_team(template.url)
diff --git a/products/mcp_store/backend/presentation/visibility.py b/products/mcp_store/backend/presentation/visibility.py
new file mode 100644
index 000000000000..fef71d34f62c
--- /dev/null
+++ b/products/mcp_store/backend/presentation/visibility.py
@@ -0,0 +1,26 @@
+import structlog
+
+from posthog.models import Team, User
+from posthog.permissions import posthog_feature_flag_enabled
+
+logger = structlog.get_logger(__name__)
+
+SLACK_DEV_MCP_UI_FLAG = "mcp-slack-dev"
+
+
+def slack_dev_mcp_ui_enabled(*, user: User, team: Team) -> bool:
+ try:
+ return posthog_feature_flag_enabled(
+ SLACK_DEV_MCP_UI_FLAG,
+ str(user.distinct_id),
+ organization_id=team.organization_id,
+ team_id=team.id,
+ person_properties={"email": user.email} if user.email else {},
+ # Local evaluation only: both call sites sit in a request path, and the SDK's remote
+ # fallback blocks for up to its request timeout. The email-suffix rollout still
+ # resolves locally because `person_properties` supplies the address.
+ only_evaluate_locally=True,
+ )
+ except Exception:
+ logger.warning("mcp_store.slack_dev_flag_check_failed", exc_info=True)
+ return False
diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.py
index 14de2816a4e1..90ef6352c453 100644
--- a/products/mcp_store/backend/proxy.py
+++ b/products/mcp_store/backend/proxy.py
@@ -20,6 +20,7 @@ from ee.hogai.utils.asgi import SyncIterableToAsync
from .models import MCPAuditEvent, MCPGatewayServer, MCPServerInstallation, MCPServerInstallationTool
from .oauth import TokenRefreshError, TokenRefreshRejectedError, is_token_expiring, refresh_installation_token
+from .oauth_credentials import oauth_credentials_source_is_allowed
from .policy import GatewayCaller, PolicyContext
from .url_policy import resolve_mcp_url_policy, trust_environment_proxy
@@ -117,6 +118,10 @@ def send_mcp_request_with_same_origin_redirect(
def build_upstream_auth_headers(installation: MCPServerInstallation) -> dict[str, str]:
+ if installation.template and not oauth_credentials_source_is_allowed(
+ installation.template.oauth_credentials_source, installation.team_id
+ ):
+ raise TokenRefreshRejectedError("OAuth app is not available for this project")
sensitive = installation.sensitive_configuration or {}
if installation.auth_type == "api_key":
@@ -147,7 +152,12 @@ def validate_installation_auth(
Returns (True, None) if auth is valid, or (False, error_response) if not.
"""
- if not installation.is_enabled:
+ if not installation.is_enabled or (
+ installation.template
+ and not oauth_credentials_source_is_allowed(
+ installation.template.oauth_credentials_source, installation.team_id
+ )
+ ):
logger.warning(
"Proxy auth failed: server is disabled",
installation_id=str(installation.id),
diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.py
index 18678f2f397a..efff869700e7 100644
--- a/products/mcp_store/backend/test/test_api.py
+++ b/products/mcp_store/backend/test/test_api.py
@@ -25,6 +25,8 @@ from posthog.models.organization import OrganizationMembership
from posthog.security.url_validation import PinnedUrlVerdict
from products.mcp_store.backend.agents import create_gateway_agent_token, sync_built_in_agents
+from products.mcp_store.backend.catalog import MCP_SERVER_CATALOG
+from products.mcp_store.backend.catalog_sync import sync_mcp_catalog
from products.mcp_store.backend.models import (
MCPAuditEvent,
MCPGatewayServer,
@@ -197,6 +199,32 @@ class TestMCPServerAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
inactive_names = set(MCPServerTemplate.objects.filter(is_active=False).values_list("name", flat=True))
assert inactive_names.isdisjoint(names)
+ @parameterized.expand(
+ [
+ ("allowed_and_flagged", True, True, True),
+ ("allowed_without_flag", True, False, False),
+ ("flagged_outside_allowed_project", False, True, False),
+ ]
+ )
+ def test_slack_dev_template_visibility(self, _name: str, allowed: bool, flag_enabled: bool, expected: bool) -> None:
+ template = self._create_active_template(oauth_credentials_source="slack_dev_app")
+ with (
+ self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[str(self.team.id)] if allowed else []),
+ patch("posthog.permissions.posthoganalytics.feature_enabled", return_value=flag_enabled) as feature_enabled,
+ ):
+ response = self.client.get(f"/api/environments/{self.team.id}/mcp_servers/")
+ assert response.status_code == status.HTTP_200_OK
+ assert (str(template.id) in {entry["id"] for entry in response.json()["results"]}) is expected
+ if allowed:
+ assert feature_enabled.call_args.kwargs["person_properties"] == {"email": self.user.email}
+ assert feature_enabled.call_args.kwargs["only_evaluate_locally"] is True
+ assert feature_enabled.call_args.kwargs["groups"] == {
+ "organization": str(self.organization.id),
+ "project": str(self.team.id),
+ }
+ else:
+ feature_enabled.assert_not_called()
+
def test_list_servers_entries_match_serializer_schema(self):
self._create_active_template()
response = self.client.get(f"/api/environments/{self.team.id}/mcp_servers/")
@@ -363,6 +391,41 @@ class TestMCPGatewayServerAPI(APIBaseTest):
assert [result["id"] for result in response.json()["results"]] == [str(registered.id)]
assert not MCPGatewayServer.objects.for_team(self.team.id).filter(url=untouched.url).exists()
+ def test_slack_dev_registered_server_follows_ui_flag(self) -> None:
+ self._make_admin()
+ template = self._template("Slack dev")
+ template.oauth_credentials_source = "slack_dev_app"
+ template.save(update_fields=["oauth_credentials_source", "updated_at"])
+ server = MCPGatewayServer.objects.for_team(self.team.id).create(
+ team=self.team,
+ name="Slack via PostHog (dev)",
+ url=template.url,
+ template=template,
+ created_by=self.user,
+ )
+
+ with (
+ self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[str(self.team.id)]),
+ patch("posthog.permissions.posthoganalytics.feature_enabled", return_value=False),
+ ):
+ hidden_response = self.client.get(self._api_url())
+ with (
+ self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[str(self.team.id)]),
+ patch("posthog.permissions.posthoganalytics.feature_enabled", return_value=True),
+ ):
+ visible_response = self.client.get(self._api_url())
+ with (
+ self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[]),
+ patch("posthog.permissions.posthoganalytics.feature_enabled", return_value=True),
+ ):
+ blocked_response = self.client.get(self._api_url())
+
+ assert hidden_response.status_code == status.HTTP_200_OK
+ assert str(server.id) not in {result["id"] for result in hidden_response.json()["results"]}
+ assert str(server.id) in {result["id"] for result in visible_response.json()["results"]}
+ blocked_server = next(result for result in blocked_response.json()["results"] if result["id"] == str(server.id))
+ assert blocked_server["is_team_enabled"] is False
+
def test_list_exposes_the_auth_type_members_connect_with(self) -> None:
self._make_admin()
template = self._template("API key", auth_type="api_key")
@@ -2348,6 +2411,41 @@ class TestMCPServiceAccountAPI(APIBaseTest):
reachable_by_owner = {row["shared_by"]["id"]: row["reachable"] for row in scout["servers"]}
assert reachable_by_owner == {self.user.id: True, revoked_member.id: False}
+ def test_removed_slack_dev_project_serializes_agent_grant_unreachable(self) -> None:
+ account = self._active_scout_account()
+ template = MCPServerTemplate.objects.create(
+ name="Slack via PostHog (dev)",
+ url="https://mcp.slack.com/mcp",
+ oauth_credentials_source="slack_dev_app",
+ is_active=True,
+ )
+ server = MCPGatewayServer.objects.for_team(self.team.id).create(
+ team=self.team,
+ template=template,
+ name=template.name,
+ url=template.url,
+ )
+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(
+ team=self.team,
+ user=self.user,
+ service_account=account,
+ gateway_server=server,
+ scope="team",
+ granted_by=self.user,
+ )
+
+ with self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[str(self.team.id)]):
+ allowed_response = self.client.get(self._api_url())
+ with self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[]):
+ removed_response = self.client.get(self._api_url())
+
+ assert allowed_response.status_code == status.HTTP_200_OK
+ assert removed_response.status_code == status.HTTP_200_OK
+ allowed_scout = next(row for row in allowed_response.json()["results"] if row["agent_key"] == "scout")
+ removed_scout = next(row for row in removed_response.json()["results"] if row["agent_key"] == "scout")
+ assert allowed_scout["servers"][0]["reachable"] is True
+ assert removed_scout["servers"][0]["reachable"] is False
+
def test_agent_catalog_query_count_does_not_grow_with_accessible_servers(self) -> None:
account = self._active_scout_account()
client = self._agent_client(account)
@@ -3858,6 +3956,38 @@ class TestMCPAuthorizePosthogCodeResponse(APIBaseTest):
class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
+ @parameterized.expand(["slack_app", "slack_dev_app"])
+ def test_catalog_preserves_oauth_app_for_existing_installations(self, source: str) -> None:
+ entry = next(entry for entry in MCP_SERVER_CATALOG if entry.oauth_credentials_source == "slack_app")
+ template = self._template(url=entry.url, oauth_credentials_source=source)
+ installation = MCPServerInstallation.objects.create(
+ team=self.team,
+ user=self.user,
+ template=template,
+ url=template.url,
+ auth_type="oauth",
+ sensitive_configuration={"access_token": "existing-token"},
+ )
+ allowed_teams = [str(self.team.id)] if source == "slack_app" else []
+ with self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=allowed_teams):
+ counts = sync_mcp_catalog(entries=[entry])
+ template.refresh_from_db()
+ installation.refresh_from_db()
+ assert template.oauth_credentials_source == source
+ assert installation.sensitive_configuration == {"access_token": "existing-token"}
+ if source == "slack_app":
+ assert counts.failed == 1
+ assert template.is_active
+ else:
+ assert counts.failed == 0
+ assert not template.is_active
+ installation.delete()
+ with self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[]):
+ sync_mcp_catalog(entries=[entry])
+ template.refresh_from_db()
+ assert template.oauth_credentials_source == "slack_app"
+ assert not template.is_active
+
def _template(self, **overrides) -> MCPServerTemplate:
import uuid as _uuid
@@ -3901,9 +4031,10 @@ class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest
installation = MCPServerInstallation.objects.get(url=template.url, user=self.user)
assert installation.template_id == template.id
- def test_install_template_oauth_uses_instance_credential_source(self):
+ @parameterized.expand([("slack_app", "SLACK_APP"), ("slack_dev_app", "SLACK_DEV_APP")])
+ def test_install_template_oauth_uses_instance_credential_source(self, source: str, prefix: str) -> None:
template = self._template(
- oauth_credentials_source="slack_app",
+ oauth_credentials_source=source,
oauth_credentials={},
oauth_metadata={
"issuer": "https://mcp.slack.com",
@@ -3914,8 +4045,9 @@ class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest
)
with (
- override_instance_config("SLACK_APP_CLIENT_ID", "slack-client"),
- override_instance_config("SLACK_APP_CLIENT_SECRET", "slack-secret"),
+ self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[str(self.team.id)]),
+ override_instance_config(f"{prefix}_CLIENT_ID", "slack-client"),
+ override_instance_config(f"{prefix}_CLIENT_SECRET", "slack-secret"),
):
response = self.client.post(
f"/api/environments/{self.team.id}/mcp_server_installations/install_template/",
@@ -3928,6 +4060,30 @@ class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest
assert params["client_id"] == ["slack-client"]
assert MCPServerInstallation.objects.filter(url=template.url, user=self.user).exists()
+ @parameterized.expand(["install", "authorize", "gateway"])
+ def test_slack_dev_template_cannot_be_used_by_another_project(self, action: str) -> None:
+ template = self._template(oauth_credentials_source="slack_dev_app")
+ with self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[str(self.team.id + 1)]):
+ if action == "install":
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/mcp_server_installations/install_template/",
+ data={"template_id": str(template.id)},
+ format="json",
+ )
+ elif action == "authorize":
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/mcp_server_installations/authorize/",
+ data={"template_id": str(template.id)},
+ )
+ else:
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/mcp_gateway_servers/set_template_enabled/",
+ data={"template_id": str(template.id), "enabled": True},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND, response.content
+ assert not MCPServerInstallation.objects.filter(template=template).exists()
+
def test_install_template_oauth_fails_closed_when_instance_credentials_are_missing(self):
template = self._template(
oauth_credentials_source="slack_app",
diff --git a/products/mcp_store/backend/test/test_catalog_sync.py b/products/mcp_store/backend/test/test_catalog_sync.py
index e420465cd71e..9379026d992e 100644
--- a/products/mcp_store/backend/test/test_catalog_sync.py
+++ b/products/mcp_store/backend/test/test_catalog_sync.py
@@ -83,6 +83,46 @@ class TestCatalogEntries(SimpleTestCase):
class TestSyncMCPCatalog(TestCase):
+ @patch("products.mcp_store.backend.oauth_credentials.get_instance_settings")
+ @patch("products.mcp_store.backend.catalog_sync.probe_mcp_server")
+ def test_slack_dev_uses_separate_credentials_and_resets_after_disable(self, probe, instance_settings):
+ entry = next(entry for entry in MCP_SERVER_CATALOG if entry.oauth_credentials_source == "slack_app")
+ instance_settings.return_value = {
+ "SLACK_DEV_APP_CLIENT_ID": "dev-client",
+ "SLACK_DEV_APP_CLIENT_SECRET": "dev-secret",
+ }
+ probe.return_value = ProbeResult(
+ reachable=True,
+ speaks_mcp=True,
+ auth_flavor="oauth_shared",
+ oauth_metadata={"issuer": "https://mcp.slack.com"},
+ authorize_endpoint_ok=True,
+ )
+
+ with self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=["42"]):
+ counts = sync_mcp_catalog(entries=[entry])
+ template = MCPServerTemplate.objects.get(url=entry.url)
+ assert template.name == "Slack via PostHog (dev)"
+ assert template.description == "Search public Slack channels with the internal PostHog development app."
+ assert template.oauth_credentials_source == "slack_dev_app"
+ assert template.oauth_credentials == {}
+ assert entry.oauth_scope_allowlist is not None
+ assert template.oauth_scope_allowlist == list(entry.oauth_scope_allowlist)
+ assert counts.activated == 1
+ assert MCPServerTemplate.available_for_team(42).filter(id=template.id).exists()
+ assert not MCPServerTemplate.available_for_team(43).filter(id=template.id).exists()
+
+ instance_settings.assert_called_with(["SLACK_DEV_APP_CLIENT_ID", "SLACK_DEV_APP_CLIENT_SECRET"])
+ probe.assert_called_once_with(
+ entry.url, scope_allowlist=entry.oauth_scope_allowlist, shared_client_id="dev-client"
+ )
+
+ with self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[]):
+ sync_mcp_catalog(entries=[entry])
+ template.refresh_from_db()
+ assert not template.is_active
+ assert template.oauth_credentials_source == "slack_app"
+
@parameterized.expand(
[
("oauth_dcr_pass", _entry(), _dcr_pass_probe(), True),
diff --git a/products/mcp_store/backend/test/test_oauth.py b/products/mcp_store/backend/test/test_oauth.py
index f132b4437b0e..22ff227a061d 100644
--- a/products/mcp_store/backend/test/test_oauth.py
+++ b/products/mcp_store/backend/test/test_oauth.py
@@ -1180,7 +1180,8 @@ class TestResolveInstallationOauthContext(BaseTest):
assert ctx.client_secret == "template-secret"
assert ctx.token_endpoint_auth_method == expected_auth_method
- def test_template_backed_install_uses_instance_credential_source(self):
+ @parameterized.expand([("slack_app", "SLACK_APP"), ("slack_dev_app", "SLACK_DEV_APP")])
+ def test_template_backed_install_uses_instance_credential_source(self, source: str, prefix: str) -> None:
template = MCPServerTemplate.objects.create(
name="Slack",
url="https://mcp.slack.test.example/mcp",
@@ -1191,7 +1192,7 @@ class TestResolveInstallationOauthContext(BaseTest):
"token_endpoint": "https://slack.com/api/oauth.v2.user.access",
"token_endpoint_auth_methods_supported": ["client_secret_post"],
},
- oauth_credentials_source="slack_app",
+ oauth_credentials_source=source,
oauth_credentials={},
created_by=self.user,
)
@@ -1205,8 +1206,9 @@ class TestResolveInstallationOauthContext(BaseTest):
)
with (
- override_instance_config("SLACK_APP_CLIENT_ID", "slack-client"),
- override_instance_config("SLACK_APP_CLIENT_SECRET", "slack-secret"),
+ self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[str(self.team.id)]),
+ override_instance_config(f"{prefix}_CLIENT_ID", "slack-client"),
+ override_instance_config(f"{prefix}_CLIENT_SECRET", "slack-secret"),
):
ctx = resolve_installation_oauth_context(installation)
@@ -1214,6 +1216,11 @@ class TestResolveInstallationOauthContext(BaseTest):
assert ctx.client_secret == "slack-secret"
assert ctx.token_endpoint_auth_method == "client_secret_post"
+ if source == "slack_dev_app":
+ with self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[]):
+ with self.assertRaisesRegex(ValueError, "not available for this project"):
+ resolve_installation_oauth_context(installation)
+
def test_dcr_template_backed_install_returns_per_installation_metadata_and_creds(self):
# DCR templates carry no shared client_id AND no trusted metadata —
# both were discovered + minted at install time and cached on the
@@ -1285,7 +1292,12 @@ class TestResolveInstallationOauthContext(BaseTest):
class TestSourceBackedOauthMetadataBinding(BaseTest):
- def _installation(self) -> MCPServerInstallation:
+ def _installation(
+ self,
+ *,
+ token_endpoint: str = "https://attacker.example.com/token",
+ oauth_credentials_source: str = "slack_app",
+ ) -> MCPServerInstallation:
template = MCPServerTemplate.objects.create(
name="Slack",
url="https://mcp.slack.test.example/mcp",
@@ -1293,10 +1305,10 @@ class TestSourceBackedOauthMetadataBinding(BaseTest):
oauth_metadata={
"issuer": "https://mcp.slack.com",
"authorization_endpoint": "https://slack.com/oauth/v2_user/authorize",
- "token_endpoint": "https://attacker.example.com/token",
+ "token_endpoint": token_endpoint,
"token_endpoint_auth_methods_supported": ["client_secret_post"],
},
- oauth_credentials_source="slack_app",
+ oauth_credentials_source=oauth_credentials_source,
created_by=self.user,
)
return MCPServerInstallation.objects.create(
@@ -1328,6 +1340,47 @@ class TestSourceBackedOauthMetadataBinding(BaseTest):
mock_post.assert_not_called()
+ @parameterized.expand(["exchange", "refresh"])
+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.oauth.record_slack_api_response")
+ @patch("products.mcp_store.backend.oauth.requests.post")
+ def test_slack_dev_token_requests_are_recorded(self, operation, mock_post, record_response, _allow):
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.headers = {}
+ response.json.return_value = {"access_token": "access-token", "refresh_token": "refresh-token"}
+ mock_post.return_value = response
+ installation = self._installation(
+ token_endpoint="https://slack.com/api/oauth.v2.user.access",
+ oauth_credentials_source="slack_dev_app",
+ )
+
+ with (
+ override_instance_config("SLACK_DEV_APP_CLIENT_ID", "slack-client"),
+ override_instance_config("SLACK_DEV_APP_CLIENT_SECRET", "slack-secret"),
+ self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[str(self.team.id)]),
+ ):
+ if operation == "exchange":
+ exchange_oauth_token(
+ installation=installation,
+ code="auth-code",
+ pkce_verifier="pkce-verifier",
+ redirect_uri="https://app.posthog.com/callback",
+ is_https=lambda url: url.startswith("https://"),
+ )
+ else:
+ refresh_installation_token(installation)
+
+ record_response.assert_called_once_with(
+ response,
+ source="mcp_store_oauth",
+ workspace_id=None,
+ app_id="slack_dev_app",
+ method="POST",
+ endpoint="oauth.v2.user.access",
+ )
+
@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.oauth.requests.post")
def test_refresh_rejects_modified_token_endpoint_before_sending_secret(self, mock_post, _allow):
diff --git a/products/mcp_store/backend/test/test_proxy.py b/products/mcp_store/backend/test/test_proxy.py
index ebe2befc97f7..3cc9821fe0f6 100644
--- a/products/mcp_store/backend/test/test_proxy.py
+++ b/products/mcp_store/backend/test/test_proxy.py
@@ -23,15 +23,39 @@ from products.mcp_store.backend.models import (
MCPGatewayServer,
MCPServerInstallation,
MCPServerInstallationTool,
+ MCPServerTemplate,
MCPToolPolicy,
)
from products.mcp_store.backend.oauth import TokenRefreshRejectedError
-from products.mcp_store.backend.proxy import _build_sse_response
+from products.mcp_store.backend.proxy import (
+ _build_sse_response,
+ build_upstream_auth_headers,
+ validate_installation_auth,
+)
ALLOWED_VERDICT = PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set())
class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
+ @parameterized.expand([True, False])
+ def test_slack_dev_token_use_requires_project_access(self, allowed: bool) -> None:
+ template = MCPServerTemplate(oauth_credentials_source="slack_dev_app")
+ installation = MCPServerInstallation(
+ team_id=self.team.id,
+ template=template,
+ auth_type="oauth",
+ sensitive_configuration={"access_token": "dev-user-token"},
+ )
+ with self.settings(MCP_STORE_SLACK_DEV_ALLOWED_TEAM_IDS=[str(self.team.id)] if allowed else []):
+ valid, response = validate_installation_auth(installation)
+ assert valid is allowed
+ if allowed:
+ assert build_upstream_auth_headers(installation) == {"Authorization": "Bearer dev-user-token"}
+ else:
+ assert response is not None and response.status_code == 403
+ with self.assertRaises(TokenRefreshRejectedError):
+ build_upstream_auth_headers(installation)
+
def setUp(self):
super().setUp()
# Policy checks flow through url_policy (resolve_mcp_url_policy);
diff --git a/products/mcp_store/backend/tools.py b/products/mcp_store/backend/tools.py
index 201258a01a58..414e50db90b5 100644
--- a/products/mcp_store/backend/tools.py
+++ b/products/mcp_store/backend/tools.py
@@ -18,6 +18,7 @@ from posthog.security.pinned_requests import SSRFBlockedError
from .models import MCPServerInstallation, MCPServerInstallationTool
from .oauth import TokenRefreshError, is_token_expiring, refresh_installation_token
+from .oauth_credentials import oauth_credentials_source_is_allowed
from .policy import SYNC_DEFAULT_APPROVAL_STATE
from .proxy import build_upstream_auth_headers, validated_same_origin_redirect_url
from .url_policy import resolve_mcp_url_policy, trust_environment_proxy
@@ -58,6 +59,10 @@ class ToolCallError(Exception):
def _ensure_valid_token_for_fetch(installation: MCPServerInstallation) -> None:
+ if installation.template and not oauth_credentials_source_is_allowed(
+ installation.template.oauth_credentials_source, installation.team_id
+ ):
+ raise ToolsFetchError("OAuth app is not available for this project. Contact your project admin.")
if installation.auth_type != "oauth":
return
sensitive = installation.sensitive_configuration or {}
diff --git a/products/mcp_store/frontend/generated/api.schemas.ts b/products/mcp_store/frontend/generated/api.schemas.ts
index 166126d9d5e4..6dc494f22fdc 100644
--- a/products/mcp_store/frontend/generated/api.schemas.ts
+++ b/products/mcp_store/frontend/generated/api.schemas.ts
@@ -501,6 +501,7 @@ export interface MCPGatewayServerApi {
readonly template_auth_type: MCPAuthTypeEnumApi | null
/** How members connect to this server: the template's type for catalog servers, or the type the custom server was added with. Null only for custom servers registered before the type was recorded; members then choose. */
readonly auth_type: MCPAuthTypeEnumApi | null
+ /** True when this server is enabled and available to the project. */
readonly is_team_enabled: boolean
/** Deprecated brand icon key from the linked template. Empty for custom servers. */
readonly icon_key: string
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 662fdfacdcec..8a5c1ae03256 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -56490,6 +56490,7 @@ export namespace Schemas {
readonly template_auth_type: MCPAuthTypeEnum | null;
/** How members connect to this server: the template's type for catalog servers, or the type the custom server was added with. Null only for custom servers registered before the type was recorded; members then choose. */
readonly auth_type: MCPAuthTypeEnum | null;
+ /** True when this server is enabled and available to the project. */
readonly is_team_enabled: boolean;
/** Deprecated brand icon key from the linked template. Empty for custom servers. */
readonly icon_key: string;