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): connect slack with existing app credentials (#91177)

Dylan Martinb3c46d6dfa9e
diff --git a/.agents/skills/adding-mcp-store-servers/SKILL.md b/.agents/skills/adding-mcp-store-servers/SKILL.md
index 48b72e0ae0c9..45f5ebd47d26 100644
--- a/.agents/skills/adding-mcp-store-servers/SKILL.md
+++ b/.agents/skills/adding-mcp-store-servers/SKILL.md
@@ -31,7 +31,7 @@ Adding a server is a small PR to that file.
The JSON verdict tells you everything the entry needs:
- `speaks_mcp: false` → the probe could not verify MCP. Stop and re-research — with one exception: `reachable: true` plus the error "Initialize was rejected and no OAuth metadata was discovered" is the auth-walled API-key case (last bullet below).
- `auth_flavor: "oauth_dcr"` with `passed_activation_gate: true` → OAuth with Dynamic Client Registration. The entry is `auth_type="oauth"` and will **activate automatically on merge**.
- - `auth_flavor: "oauth_shared"` → OAuth without DCR. The entry is `auth_type="oauth"` but ships **inactive**; an operator must register an OAuth app with the vendor and paste credentials in Django admin (see the operator checklist below — include it in your PR description).
+ - `auth_flavor: "oauth_shared"` → OAuth without DCR. The entry is `auth_type="oauth"` but normally ships **inactive**; an operator must register an OAuth app with the vendor and paste credentials in Django admin (see the operator checklist below — include it in your PR description). If PostHog already provisions that exact OAuth app through an instance credential source, declare the reviewed source instead; catalog sync verifies and activates it without copying secrets.
- `auth_flavor: "open"` → the handshake completed without credentials. `auth_type="api_key"`; activates automatically on merge.
- `auth_flavor: "api_key_or_unknown"` with `reachable: true` → an auth-walled API-key server; a bare 401/403 gives the probe no MCP evidence. `auth_type="api_key"`, but the entry ships **inactive** — verify it with a real install (Gate B) before adding it, and note in the PR that an operator flips it active in Django admin per environment (users bring their own key; nothing to provision).
@@ -59,7 +59,7 @@ Adding a server is a small PR to that file.
6. **Open the PR** — one server per PR, on an `mcp-store/`-prefixed branch (e.g. `mcp-store/add-pagerduty`), with a `feat(mcp-store)` title: `feat(mcp-store): add <name> to the MCP server catalog`.
State the probe verdict and verification tier in the description.
- For `oauth_shared` servers, include the operator checklist so activation isn't forgotten.
+ For `oauth_shared` servers without an existing instance credential source, include the operator checklist so activation isn't forgotten.
## Operator checklist for oauth_shared servers (paste into the PR)
@@ -77,5 +77,6 @@ This server does not support Dynamic Client Registration, so it ships inactive.
- Don't add entries with unprobed URLs — a dead catalog entry is user-visible breakage.
- Don't edit `is_active`, `oauth_credentials`, or `oauth_metadata` expectations into the catalog — those are operational state owned by the row, not by code.
+- Don't add an instance credential source for a newly registered vendor app. Sources are only for an existing client already provisioned across every target environment, with exact trusted issuer, authorization, and token endpoints enforced before any secret is used.
- Don't add icon assets or `icon_key` values — icons resolve from `icon_domain` via logo.dev at render time.
- Don't batch unrelated servers into one PR unless explicitly doing a scaffold sweep; per-server PRs keep review and reverts clean.
diff --git a/products/mcp_store/README.md b/products/mcp_store/README.md
index 2f450e4e1b43..2311eb4eb75f 100644
--- a/products/mcp_store/README.md
+++ b/products/mcp_store/README.md
@@ -67,10 +67,11 @@ Settings supplies its own navigation shell so the gateway workflows fit the main
The catalog is **code**: `backend/catalog.py` holds one `CatalogEntry` per server.
At app startup, every environment queues `sync_mcp_server_templates` (see `backend/tasks/tasks.py`, queued from `backend/apps.py`), which upserts entries into `MCPServerTemplate` rows:
-- Rows are keyed on `url`. New entries are created; existing rows get **content fields** updated (name, description, auth_type, category, icon_domain, docs_url). The catalog owns content — edit it in code, not admin.
-- **Operational state is never touched by the sync**: `is_active` after creation, `oauth_credentials`, and `oauth_metadata` once set belong to the row and to operators. Rows absent from the catalog (e.g. admin-added) are left alone.
-- **Activation gate**: a newly created entry is probed live (`backend/probe.py` — MCP initialize handshake, OAuth metadata discovery, a real DCR registration, authorization-endpoint liveness). It is born active only when the probe passes for the auth model the catalog declares. Servers that need shared OAuth credentials (no DCR) are born inactive until an operator provisions them.
-- Probes run **only on creation** — a DCR probe mints a real client on the provider, so re-probing every sync would leak registrations.
+- Rows are keyed on `url`. New entries are created; existing rows get **content fields** updated (name, description, auth type, category, icon, docs URL, OAuth scope allowlist, and credential source). The catalog owns content. Edit it in code, not admin.
+- **Operational state normally stays operator-owned**: the sync preserves `is_active`, `oauth_credentials`, and `oauth_metadata` after creation unless an auth change or suspension must fail closed. A catalog-managed credential source is the exception: sync activates it after a successful shared-client probe and deactivates it when its required settings disappear. Rows absent from the catalog remain untouched.
+- **Activation gate**: a newly created entry is probed live (`backend/probe.py` — MCP initialize handshake, OAuth metadata discovery, a real DCR registration, authorization-endpoint liveness). It is born active only when the probe passes for the auth model the catalog declares. A reviewed instance credential source can satisfy the shared-client gate without copying secrets into the template.
+- **Temporary suspension**: `disabled=True` keeps a catalog entry inactive and deactivates an existing row on the next sync. Removing it lets a configured credential source retry its shared-client probe; other entries still require operator review.
+- Probes run **only on creation**, except when a configured credential source is inactive or first adopted. DCR probes never repeat because they mint real clients.
To add a server, follow the `adding-mcp-store-servers` skill (`.agents/skills/adding-mcp-store-servers/`).
To probe a server by hand:
@@ -87,6 +88,7 @@ Only **hosted (remote) MCP servers** on a public HTTPS endpoint speaking the str
Adds and auto-activates on merge:
- OAuth servers with Dynamic Client Registration — the probe mints a real DCR client and verifies the authorization page.
+- OAuth servers backed by a configured, catalog-reviewed instance credential source — the probe verifies the shared client and authorization page.
- API-key and unauthenticated servers that answer the MCP initialize handshake without credentials.
Adds but ships **inactive** until an operator finishes activation (see the runbook below):
@@ -150,15 +152,26 @@ To show brand icons on a self-hosted instance, create a logo.dev account, genera
## Auth models
- **OAuth with DCR** (most modern remote servers): nothing to provision. Each install discovers OAuth metadata fresh and mints a per-user client via RFC 7591. Template `oauth_credentials`/`oauth_metadata` stay empty.
+- **OAuth with an instance credential source**: a catalog entry can reuse a client already configured for that PostHog environment. The template stores only the source name; installs resolve the current credentials at runtime, so rotation does not create another secret copy. Each source pins its trusted issuer, authorization endpoint, and token endpoint before any secret leaves PostHog.
- **OAuth without DCR** ("shared creds"): an operator registers one OAuth app with the vendor and pastes `client_id`/`client_secret` into Django admin (stored encrypted per template). The sync pre-fills `oauth_metadata` from discovery; installs then share the client while each user gets their own tokens. Redirect URI: `{SITE_URL}/api/mcp_store/oauth_redirect/`.
- **API key**: users supply their own key at install; nothing on the template.
-## Operator runbook: activating a shared-creds server
+OAuth catalog entries can set `oauth_scope_allowlist` to limit registration and authorization to reviewed scopes. Without an allowlist, the client requests every scope advertised by the server. Shared clients derive their token endpoint authentication method from discovered metadata unless `oauth_credentials.token_endpoint_auth_method` overrides it.
-1. Register an OAuth app in the vendor's developer console with redirect URI `https://us.posthog.com/api/mcp_store/oauth_redirect/` (repeat for EU with the EU host).
-2. Django admin → MCP server templates → the server: paste client ID and client secret.
-3. `oauth_metadata` should already be populated by the sync; if empty, run the "Discover metadata" admin action.
-4. Tick "is active". Repeat per environment — templates are per-database rows.
+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.
+
+## Operator runbook: activating a manually provisioned shared-creds server
+
+1. Register these redirect URIs in the vendor's developer console:
+ - `https://us.posthog.com/api/mcp_store/oauth_redirect/`
+ - `https://eu.posthog.com/api/mcp_store/oauth_redirect/`
+2. Request only the scopes in the catalog entry's `oauth_scope_allowlist` and complete any provider review.
+3. Django admin → MCP server templates → the server: paste client ID and client secret.
+4. Confirm the discovered metadata and token endpoint authentication method. Run the "Discover metadata" admin action if metadata is empty.
+5. Complete one internal authorization and tool discovery in each environment.
+6. Tick "is active". Repeat per environment because templates are per-database rows.
+
+If the catalog entry has `disabled=True`, remove the suspension in a follow-up only after these checks pass. Removing the suspension does not reactivate a manually provisioned row.
## Reaching connected servers from an agent
diff --git a/products/mcp_store/backend/admin.py b/products/mcp_store/backend/admin.py
index 4826690b1640..0ed326dc9b05 100644
--- a/products/mcp_store/backend/admin.py
+++ b/products/mcp_store/backend/admin.py
@@ -8,6 +8,7 @@ from django.utils.html import format_html
from products.mcp_store.backend.models import MCPServerTemplate
from products.mcp_store.backend.oauth import discover_oauth_metadata
+from products.mcp_store.backend.oauth_credentials import oauth_credentials_source_is_configured
logger = logging.getLogger(__name__)
@@ -33,6 +34,7 @@ class MCPServerTemplateAdminForm(forms.ModelForm):
"category",
"oauth_issuer_url",
"oauth_metadata",
+ "oauth_scope_allowlist",
"is_active",
)
@@ -47,16 +49,25 @@ class MCPServerTemplateAdminForm(forms.ModelForm):
# data, not the instance, so there's nothing to fall back to.
instance: MCPServerTemplate | None = kwargs.get("instance")
existing_creds = (instance.oauth_credentials or {}) if instance else {}
-
- if existing_creds.get("client_id"):
+ credentials_source = instance.oauth_credentials_source if instance else ""
+
+ if credentials_source:
+ self.fields["client_id"].disabled = True
+ self.fields["client_secret"].disabled = True
+ self.fields["client_id"].help_text = f"Managed by the {credentials_source} instance credential source."
+ self.fields["client_secret"].help_text = f"Managed by the {credentials_source} instance credential source."
+ elif existing_creds.get("client_id"):
self.fields["client_id"].help_text = "(stored — leave blank to keep, or type a new value to replace)"
else:
self.fields["client_id"].help_text = "(not set — template will use per-user DCR on install)"
- if existing_creds.get("client_secret"):
- self.fields["client_secret"].help_text = "(stored — leave blank to keep, or type a new value to replace)"
- else:
- self.fields["client_secret"].help_text = "(not set — fine if the provider uses PKCE-only)"
+ if not credentials_source:
+ if existing_creds.get("client_secret"):
+ self.fields[
+ "client_secret"
+ ].help_text = "(stored — leave blank to keep, or type a new value to replace)"
+ else:
+ self.fields["client_secret"].help_text = "(not set — fine if the provider uses PKCE-only)"
# The token endpoint comes from the server's own (unauthenticated) metadata
# discovery, so show the operator exactly where a pasted secret will be sent
@@ -88,11 +99,13 @@ class MCPServerTemplateAdminForm(forms.ModelForm):
@admin.register(MCPServerTemplate)
class MCPServerTemplateAdmin(admin.ModelAdmin):
form = MCPServerTemplateAdminForm
+ readonly_fields = ("oauth_credentials_source",)
list_display = (
"name",
"url",
"category",
"auth_type",
+ "oauth_credentials_source",
"has_client_id",
"has_metadata",
"is_active",
@@ -104,6 +117,8 @@ class MCPServerTemplateAdmin(admin.ModelAdmin):
@admin.display(boolean=True, description="Has client_id")
def has_client_id(self, obj: MCPServerTemplate) -> bool:
+ if obj.oauth_credentials_source:
+ return oauth_credentials_source_is_configured(obj.oauth_credentials_source)
return bool((obj.oauth_credentials or {}).get("client_id"))
@admin.display(boolean=True, description="Has metadata")
diff --git a/products/mcp_store/backend/catalog.py b/products/mcp_store/backend/catalog.py
index a709b9de30fa..400df64372bb 100644
--- a/products/mcp_store/backend/catalog.py
+++ b/products/mcp_store/backend/catalog.py
@@ -5,9 +5,9 @@ Each entry here becomes (or updates) an ``MCPServerTemplate`` row via the
environment — adding a server to the store is a PR to this file, not a data migration.
The catalog owns a template's *content* (name, description, category, icon_domain,
-docs_url, auth_type). Operational state — ``is_active`` after creation, and the
-``oauth_credentials`` an operator provisions for servers without Dynamic Client
-Registration — lives on the row and is never touched by the sync. See
+docs_url, auth_type, and any existing instance credential source). Operational
+state — ``is_active`` after creation, and the ``oauth_credentials`` an operator
+provisions for other servers without Dynamic Client Registration — lives on the row. See
``catalog_sync.py`` for the exact semantics, including the probe-gated activation
of newly created entries.
@@ -21,10 +21,12 @@ vendor-identity check: confirm the url is the vendor's officially documented MCP
endpoint before approving. This file is CODEOWNERS-gated for that reason.
"""
-from dataclasses import dataclass
+from posthog.dataclasses import frozen
+from .oauth_credentials import OAuthCredentialsSource
-@dataclass(frozen=True)
+
+@frozen
class CatalogEntry:
name: str
url: str
@@ -33,6 +35,9 @@ class CatalogEntry:
category: str # one of CATEGORY_CHOICES on the model
icon_domain: str # the vendor's brand domain, rendered via the logo.dev proxy
docs_url: str = ""
+ oauth_scope_allowlist: tuple[str, ...] | None = None
+ oauth_credentials_source: OAuthCredentialsSource | None = None
+ disabled: bool = False
MCP_SERVER_CATALOG: list[CatalogEntry] = [
@@ -304,10 +309,21 @@ MCP_SERVER_CATALOG: list[CatalogEntry] = [
CatalogEntry(
name="Slack",
url="https://mcp.slack.com/mcp",
- description="Search Slack channels, send messages, and access workspace context.",
+ description="Search public Slack channels and read messages and user profiles.",
auth_type="oauth",
category="productivity",
icon_domain="slack.com",
+ docs_url="https://docs.slack.dev/ai/slack-mcp-server/",
+ oauth_credentials_source="slack_app",
+ disabled=True,
+ # Private-channel, DM, email, and write scopes require separate security approval.
+ oauth_scope_allowlist=(
+ "channels:read",
+ "channels:history",
+ "search:read.public",
+ "users:read",
+ "search:read.users",
+ ),
),
CatalogEntry(
name="Sourcegraph",
diff --git a/products/mcp_store/backend/catalog_sync.py b/products/mcp_store/backend/catalog_sync.py
index 67c21daac379..ff65e21b9f31 100644
--- a/products/mcp_store/backend/catalog_sync.py
+++ b/products/mcp_store/backend/catalog_sync.py
@@ -3,26 +3,26 @@
Semantics, chosen so the sync can run unattended at every app startup:
- Rows are keyed on ``url``. A catalog entry with no row **creates** one; an entry with an
- existing row **updates content fields only** (name, description, auth_type, category,
- icon_domain, docs_url). A changed ``url`` is therefore a new identity: the sync creates a
- fresh row and leaves the old row — and installations pointing at it — untouched. Retire
- the old row by deactivating it in admin; the sync logs a warning for every *active* row
- with no catalog entry so an orphaned row can't linger unnoticed.
-- The sync never touches operational state: ``is_active`` after creation,
+ existing row **updates content fields only**. A changed ``url`` is therefore a new identity:
+ the sync creates a fresh row and leaves the old row — and installations pointing at it —
+ untouched. Retire the old row by deactivating it in admin; the sync logs a warning for every
+ *active* row with no catalog entry so an orphaned row can't linger unnoticed.
+- The sync normally preserves operational state: ``is_active`` after creation,
``oauth_credentials`` (operator-provisioned shared client creds), or ``oauth_metadata``
once set. Rows absent from the catalog (admin-added or removed entries) are left alone.
- One fail-closed exception: an ``auth_type`` flip on an active row deactivates it, since
- the row was vetted and activated under the old auth model — an operator re-vets and
- reactivates in admin.
+ Two fail-closed exceptions deactivate active rows: an ``auth_type`` flip, or a catalog
+ entry marked ``disabled``. Entries with a catalog-managed credential source also follow
+ that source: sync probes and activates them when configured, and deactivates them when
+ their required settings are absent.
- **Activation gate**: a newly created entry is probed live (``probe.probe_mcp_server``)
and born active only when the probe passes for the auth model the catalog declares —
DCR OAuth servers must complete a real client registration and serve an authorization
page; API-key servers must complete the MCP handshake without credentials. An API-key
server that auth-walls the handshake (the common case) yields no MCP evidence, so it
- is born inactive for an operator to vet and activate in admin. Servers needing shared
- OAuth credentials are always born inactive: an operator provisions credentials in
- admin and activates. Probes run only on creation — a DCR probe mints a real client on the
- provider, so re-probing every sync cycle would leak registrations.
+ is born inactive for an operator to vet and activate in admin. Other servers needing
+ shared OAuth credentials remain inactive until an operator provisions them. Probes run
+ only on creation, except while a catalog-managed shared client is inactive or first adopts
+ its credential source. A DCR probe mints a real client, so it never repeats during sync.
The probe is a liveness and protocol check, not a security control: it catches a dead
url or a mis-declared auth model, but a malicious server passes it trivially. Vendor
@@ -38,11 +38,30 @@ import structlog
from .catalog import MCP_SERVER_CATALOG, CatalogEntry
from .models import MCPServerTemplate
+from .oauth_credentials import resolve_oauth_credentials_source
from .probe import ProbeResult, probe_mcp_server
logger = structlog.get_logger(__name__)
-_CONTENT_FIELDS = ("name", "description", "auth_type", "category", "icon_domain", "docs_url")
+_CONTENT_FIELDS = (
+ "name",
+ "description",
+ "auth_type",
+ "category",
+ "icon_domain",
+ "docs_url",
+ "oauth_scope_allowlist",
+ "oauth_credentials_source",
+)
+
+
+def _entry_field_value(entry: CatalogEntry, field: str) -> object:
+ value = getattr(entry, field)
+ if field == "oauth_scope_allowlist" and value is not None:
+ return list(value)
+ if field == "oauth_credentials_source":
+ return value or ""
+ return value
@dataclass
@@ -65,9 +84,49 @@ def _activation_allowed(entry: CatalogEntry, probe: ProbeResult) -> bool:
# gate — a bare 401/403 proves nothing about MCP — so agreement here means the
# handshake completed without credentials.
return probe.auth_flavor == "open"
+ if entry.oauth_credentials_source:
+ return probe.auth_flavor == "oauth_shared"
return probe.auth_flavor == "oauth_dcr"
+def _shared_client_id(entry: CatalogEntry) -> str | None:
+ if not entry.oauth_credentials_source:
+ return None
+ credentials = resolve_oauth_credentials_source(entry.oauth_credentials_source)
+ if not credentials["client_id"] or not credentials["client_secret"]:
+ return None
+ return credentials["client_id"]
+
+
+def _probe_entry(entry: CatalogEntry) -> ProbeResult:
+ return probe_mcp_server(
+ entry.url,
+ scope_allowlist=entry.oauth_scope_allowlist,
+ shared_client_id=_shared_client_id(entry),
+ )
+
+
+def _apply_probe(template: MCPServerTemplate, entry: CatalogEntry, probe: ProbeResult, counts: SyncCounts) -> list[str]:
+ changed: list[str] = []
+ if probe.oauth_metadata:
+ if template.oauth_metadata != probe.oauth_metadata:
+ template.oauth_metadata = probe.oauth_metadata
+ changed.append("oauth_metadata")
+ issuer = probe.oauth_metadata.get("issuer", "")
+ if issuer and template.oauth_issuer_url != issuer:
+ template.oauth_issuer_url = issuer
+ changed.append("oauth_issuer_url")
+ if _activation_allowed(entry, probe):
+ if not template.is_active:
+ template.is_active = True
+ changed.append("is_active")
+ counts.activated += 1
+ elif template.is_active:
+ template.is_active = False
+ changed.append("is_active")
+ return changed
+
+
def _create_template(entry: CatalogEntry, skip_probe: bool, counts: SyncCounts) -> None:
template = MCPServerTemplate.objects.create(
name=entry.name,
@@ -77,27 +136,17 @@ def _create_template(entry: CatalogEntry, skip_probe: bool, counts: SyncCounts)
category=entry.category,
icon_domain=entry.icon_domain,
docs_url=entry.docs_url,
+ oauth_scope_allowlist=_entry_field_value(entry, "oauth_scope_allowlist"),
+ oauth_credentials_source=entry.oauth_credentials_source or "",
is_active=False,
)
counts.created += 1
- if skip_probe:
+ if skip_probe or entry.disabled:
return
- probe = probe_mcp_server(entry.url)
- update_fields = []
- if probe.oauth_metadata and not template.oauth_metadata:
- # Persisting discovered metadata saves the operator the admin "discover metadata"
- # step for shared-creds servers; DCR installs discover fresh per install anyway.
- template.oauth_metadata = probe.oauth_metadata
- issuer = probe.oauth_metadata.get("issuer", "")
- if issuer:
- template.oauth_issuer_url = issuer
- update_fields += ["oauth_metadata", "oauth_issuer_url"]
- if _activation_allowed(entry, probe):
- template.is_active = True
- update_fields.append("is_active")
- counts.activated += 1
- else:
+ probe = _probe_entry(entry)
+ update_fields = _apply_probe(template, entry, probe, counts)
+ if not template.is_active:
logger.warning(
"mcp_catalog_sync.created_inactive",
url=entry.url,
@@ -108,14 +157,15 @@ def _create_template(entry: CatalogEntry, skip_probe: bool, counts: SyncCounts)
template.save(update_fields=[*update_fields, "updated_at"])
-def _update_template(template: MCPServerTemplate, entry: CatalogEntry, counts: SyncCounts) -> None:
- changed = [f for f in _CONTENT_FIELDS if getattr(template, f) != getattr(entry, f)]
- if not changed:
- counts.unchanged += 1
- return
+def _update_template(template: MCPServerTemplate, entry: CatalogEntry, skip_probe: bool, counts: SyncCounts) -> None:
+ changed = [f for f in _CONTENT_FIELDS if getattr(template, f) != _entry_field_value(entry, f)]
for f in changed:
- setattr(template, f, getattr(entry, f))
- if "auth_type" in changed and template.is_active:
+ setattr(template, f, _entry_field_value(entry, f))
+ if entry.disabled and template.is_active:
+ template.is_active = False
+ changed.append("is_active")
+ logger.warning("mcp_catalog_sync.deactivated_disabled_entry", url=entry.url)
+ elif "auth_type" in changed and template.is_active:
# The row was vetted and activated under the old auth model — e.g. an
# oauth→api_key flip would route new installs through the API-key branch
# with no key provisioned. Fail closed; an operator re-vets and reactivates.
@@ -126,6 +176,26 @@ def _update_template(template: MCPServerTemplate, entry: CatalogEntry, counts: S
url=entry.url,
auth_type=entry.auth_type,
)
+ elif entry.oauth_credentials_source:
+ shared_client_id = _shared_client_id(entry)
+ needs_probe = shared_client_id is not None and (
+ not template.is_active or not template.oauth_metadata or "oauth_credentials_source" in changed
+ )
+ if needs_probe and not skip_probe:
+ changed += [
+ field for field in _apply_probe(template, entry, _probe_entry(entry), counts) if field not in changed
+ ]
+ elif shared_client_id is None and template.is_active:
+ template.is_active = False
+ changed.append("is_active")
+ logger.warning(
+ "mcp_catalog_sync.deactivated_missing_credential_source",
+ url=entry.url,
+ oauth_credentials_source=entry.oauth_credentials_source,
+ )
+ if not changed:
+ counts.unchanged += 1
+ return
template.save(update_fields=[*changed, "updated_at"])
counts.updated += 1
@@ -143,7 +213,7 @@ def sync_mcp_catalog(entries: list[CatalogEntry] | None = None, skip_probe: bool
# Lost a create race (unique url) — the winner owns creation+probe.
counts.unchanged += 1
else:
- _update_template(template, entry, counts)
+ _update_template(template, entry, skip_probe, counts)
except Exception:
logger.exception("mcp_catalog_sync.entry_failed", url=entry.url)
counts.failed += 1
diff --git a/products/mcp_store/backend/migrations/0029_add_mcp_template_oauth_scope_allowlist.py b/products/mcp_store/backend/migrations/0029_add_mcp_template_oauth_scope_allowlist.py
new file mode 100644
index 000000000000..cbaf017de085
--- /dev/null
+++ b/products/mcp_store/backend/migrations/0029_add_mcp_template_oauth_scope_allowlist.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.17 on 2026-08-28 23:05
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mcp_store", "0028_backfill_gateway_server_auth_type"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="mcpservertemplate",
+ name="oauth_scope_allowlist",
+ field=models.JSONField(blank=True, default=None, null=True),
+ ),
+ ]
diff --git a/products/mcp_store/backend/migrations/0030_add_mcp_template_oauth_credentials_source.py b/products/mcp_store/backend/migrations/0030_add_mcp_template_oauth_credentials_source.py
new file mode 100644
index 000000000000..2373a9b21fb8
--- /dev/null
+++ b/products/mcp_store/backend/migrations/0030_add_mcp_template_oauth_credentials_source.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.17 on 2026-09-02 15:41
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mcp_store", "0029_add_mcp_template_oauth_scope_allowlist"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="mcpservertemplate",
+ name="oauth_credentials_source",
+ field=models.CharField(blank=True, db_default="", default="", max_length=64),
+ ),
+ ]
diff --git a/products/mcp_store/backend/migrations/max_migration.txt b/products/mcp_store/backend/migrations/max_migration.txt
index e6e31e834994..09dc87fcb15a 100644
--- a/products/mcp_store/backend/migrations/max_migration.txt
+++ b/products/mcp_store/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0028_backfill_gateway_server_auth_type
+0030_add_mcp_template_oauth_credentials_source
diff --git a/products/mcp_store/backend/models.py b/products/mcp_store/backend/models.py
index 94e82dd2fdff..146b37600eb5 100644
--- a/products/mcp_store/backend/models.py
+++ b/products/mcp_store/backend/models.py
@@ -125,6 +125,7 @@ class SensitiveConfig(TypedDict, total=False):
class TemplateOAuthCredentials(TypedDict, total=False):
client_id: str
client_secret: str
+ token_endpoint_auth_method: str
InstallSource = Literal["posthog", "twig", "posthog-code"]
@@ -148,12 +149,12 @@ def normalize_mcp_icon_domain(value: str) -> str:
class MCPServerTemplate(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
- """A curated, pre-registered MCP server. PostHog operators register a real
- OAuth app with the provider ahead of time and paste the client_id /
- client_secret in Django admin. The credentials are shared across every user
- who installs the template — users only get their own per-user access/refresh
- tokens. User-added servers (see MCPServerInstallation without a template
- FK) go through per-user DCR instead."""
+ """A curated, pre-registered MCP server.
+
+ Shared OAuth clients use an existing instance credential source or encrypted
+ credentials provisioned on the template. Each installation still stores its
+ own user tokens. User-added servers use per-user DCR instead.
+ """
name = models.CharField(max_length=200)
url = models.URLField(max_length=2048, unique=True)
@@ -168,6 +169,8 @@ class MCPServerTemplate(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default="dev", db_default="dev")
oauth_issuer_url = models.URLField(max_length=2048, blank=True, default="")
oauth_metadata = models.JSONField(default=dict, blank=True)
+ oauth_scope_allowlist = models.JSONField(null=True, blank=True, default=None)
+ oauth_credentials_source = models.CharField(max_length=64, blank=True, default="", db_default="")
oauth_credentials = EncryptedJSONField(default=dict, blank=True)
is_active = models.BooleanField(default=False)
diff --git a/products/mcp_store/backend/oauth.py b/products/mcp_store/backend/oauth.py
index c1c8736703e4..d5f458d2a304 100644
--- a/products/mcp_store/backend/oauth.py
+++ b/products/mcp_store/backend/oauth.py
@@ -3,7 +3,7 @@ import base64
import hashlib
import secrets
import dataclasses
-from collections.abc import Callable
+from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from urllib.parse import urlparse
@@ -14,7 +14,8 @@ import tldextract
from posthog.dataclasses import frozen
from posthog.security.url_validation import is_url_allowed
-from .models import MCPServerInstallation
+from .models import MCPServerInstallation, MCPServerTemplate, TemplateOAuthCredentials
+from .oauth_credentials import resolve_oauth_credentials_source, validate_oauth_credentials_source_metadata
logger = structlog.get_logger(__name__)
@@ -100,12 +101,24 @@ def _as_string_list(value: object) -> list[str]:
return [item for item in value if isinstance(item, str)]
-def requested_oauth_scopes(metadata: dict) -> list[str]:
+def requested_oauth_scopes(metadata: dict, scope_allowlist: Sequence[str] | None = None) -> list[str]:
"""Return the exact scopes we should request from this provider."""
resource_scopes = _as_string_list(metadata.get("resource_scopes_supported"))
- if resource_scopes:
- return resource_scopes
- return _as_string_list(metadata.get("scopes_supported"))
+ advertised_scopes = resource_scopes or _as_string_list(metadata.get("scopes_supported"))
+ if scope_allowlist is None:
+ return advertised_scopes
+
+ allowed_scopes = list(dict.fromkeys(scope_allowlist))
+ if not allowed_scopes:
+ raise ValueError("OAuth scope allowlist does not contain any scopes")
+ if not advertised_scopes:
+ return allowed_scopes
+
+ advertised = set(advertised_scopes)
+ requested_scopes = [scope for scope in allowed_scopes if scope in advertised]
+ if not requested_scopes:
+ raise ValueError("OAuth scope allowlist does not match any provider-supported scopes")
+ return requested_scopes
def requested_oauth_grant_types(metadata: dict) -> list[str]:
@@ -340,7 +353,9 @@ def _describe_dcr_rejection(resp: requests.Response) -> str:
return f"The server rejected registration (HTTP {resp.status_code})."
-def register_dcr_client(metadata: dict, redirect_uri: str) -> DcrClientRegistration:
+def register_dcr_client(
+ metadata: dict, redirect_uri: str, scope_allowlist: Sequence[str] | None = None
+) -> DcrClientRegistration:
"""Run RFC 7591 Dynamic Client Registration.
Some servers (e.g. Supabase) register a confidential client even when we
@@ -362,7 +377,7 @@ def register_dcr_client(metadata: dict, redirect_uri: str) -> DcrClientRegistrat
"response_types": ["code"],
"token_endpoint_auth_method": token_endpoint_auth_method,
}
- if scopes := requested_oauth_scopes(metadata):
+ if scopes := requested_oauth_scopes(metadata, scope_allowlist):
payload["scope"] = " ".join(scopes)
_validate_url(registration_endpoint)
@@ -432,11 +447,13 @@ class TokenRefreshError(Exception):
pass
-def _credential_auth_method(credentials: dict, auth_method_key: str, client_secret: str | None) -> str:
+def _credential_auth_method(
+ credentials: Mapping[str, object], auth_method_key: str, client_secret: str | None, metadata: dict
+) -> str:
method = credentials.get(auth_method_key)
if isinstance(method, str) and method in SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS:
return method
- return DEFAULT_CONFIDENTIAL_TOKEN_ENDPOINT_AUTH_METHOD if client_secret else "none"
+ return select_token_endpoint_auth_method(metadata, has_client_secret=bool(client_secret))
@frozen
@@ -447,12 +464,25 @@ class InstallationOAuthContext:
token_endpoint_auth_method: str
+def resolve_template_oauth_credentials(template: MCPServerTemplate) -> TemplateOAuthCredentials:
+ if template.oauth_credentials_source:
+ validate_oauth_credentials_source_metadata(template.oauth_credentials_source, template.oauth_metadata or {})
+ credentials = resolve_oauth_credentials_source(template.oauth_credentials_source)
+ if not credentials["client_id"] or not credentials["client_secret"]:
+ raise ValueError(f"OAuth credential source '{template.oauth_credentials_source}' is not configured")
+ return TemplateOAuthCredentials(
+ client_id=credentials["client_id"],
+ client_secret=credentials["client_secret"],
+ )
+ return TemplateOAuthCredentials(**(template.oauth_credentials or {}))
+
+
def resolve_installation_oauth_context(installation: MCPServerInstallation) -> InstallationOAuthContext:
"""Resolve the OAuth metadata + client credentials for an installation.
Returns an ``InstallationOAuthContext``.
- Secrets come from the shared template when set, or from the installation's
- encrypted ``sensitive_configuration`` for user-added servers.
+ Shared client secrets come from a template credential source or the template's
+ encrypted credentials. User-added servers use the installation's encrypted state.
Raises ``ValueError`` if the installation is missing required OAuth state.
"""
@@ -460,17 +490,16 @@ def resolve_installation_oauth_context(installation: MCPServerInstallation) -> I
template = installation.template
if template is not None:
- credentials = template.oauth_credentials or {}
+ credentials = resolve_template_oauth_credentials(template)
shared_client_id = credentials.get("client_id", "")
if shared_client_id:
- # Shared-creds template: every installation of this template
- # authenticates with the same client against the admin-seeded
- # metadata on the template.
+ # Shared-creds template: every installation authenticates with the
+ # same client against the trusted metadata on the template.
metadata = dict(template.oauth_metadata or {})
if not metadata:
raise ValueError("Template missing OAuth metadata")
client_secret = credentials.get("client_secret") or None
- auth_method = _credential_auth_method(credentials, "token_endpoint_auth_method", client_secret)
+ auth_method = _credential_auth_method(credentials, "token_endpoint_auth_method", client_secret, metadata)
return InstallationOAuthContext(
metadata=metadata,
client_id=shared_client_id,
@@ -486,7 +515,7 @@ def resolve_installation_oauth_context(installation: MCPServerInstallation) -> I
client_secret = sensitive.get("dcr_client_secret") or None
if not metadata or not client_id:
raise ValueError("DCR template installation missing OAuth metadata or dcr_client_id")
- auth_method = _credential_auth_method(sensitive, "dcr_token_endpoint_auth_method", client_secret)
+ auth_method = _credential_auth_method(sensitive, "dcr_token_endpoint_auth_method", client_secret, metadata)
return InstallationOAuthContext(
metadata=metadata,
client_id=client_id,
@@ -499,7 +528,7 @@ def resolve_installation_oauth_context(installation: MCPServerInstallation) -> I
client_secret = sensitive.get("dcr_client_secret") or None
if not metadata or not client_id:
raise ValueError("Installation missing OAuth metadata or client_id")
- auth_method = _credential_auth_method(sensitive, "dcr_token_endpoint_auth_method", client_secret)
+ auth_method = _credential_auth_method(sensitive, "dcr_token_endpoint_auth_method", client_secret, metadata)
return InstallationOAuthContext(
metadata=metadata,
client_id=client_id,
@@ -630,9 +659,8 @@ def exchange_oauth_token(
) -> dict:
"""Exchange an authorization code for tokens using the installation's resolved client creds.
- Works for both template-backed installs (shared client creds from
- ``MCPServerTemplate.oauth_credentials``) and user-added installs (per-user
- DCR creds stored in ``sensitive_configuration``).
+ Works for both template-backed installs with a shared client and user-added
+ installs with per-user DCR credentials.
"""
if not pkce_verifier:
raise OAuthTokenExchangeError("Missing PKCE verifier")
diff --git a/products/mcp_store/backend/oauth_credentials.py b/products/mcp_store/backend/oauth_credentials.py
new file mode 100644
index 000000000000..37769cb20d6a
--- /dev/null
+++ b/products/mcp_store/backend/oauth_credentials.py
@@ -0,0 +1,42 @@
+from collections.abc import Mapping
+from typing import Literal
+
+from posthog.models.instance_setting import get_instance_settings
+
+OAuthCredentialsSource = Literal["slack_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",
+ }
+}
+
+SUPPORTED_OAUTH_CREDENTIAL_SOURCES = frozenset(_TRUSTED_OAUTH_METADATA_BY_SOURCE)
+
+
+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:
+ raise ValueError(f"Unknown OAuth credential source: {source}")
+ if any(metadata.get(key) != value for key, value in trusted_metadata.items()):
+ raise ValueError(f"OAuth metadata for credential source '{source}' does not match its trusted endpoints")
+
+
+def resolve_oauth_credentials_source(source: str) -> dict[str, str]:
+ if source != "slack_app":
+ 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")
+ return {
+ "client_id": client_id if isinstance(client_id, str) else "",
+ "client_secret": client_secret if isinstance(client_secret, str) else "",
+ }
+
+
+def oauth_credentials_source_is_configured(source: str) -> bool:
+ credentials = resolve_oauth_credentials_source(source)
+ return bool(credentials["client_id"] and credentials["client_secret"])
diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.py
index 90fe45ded493..f715a67b5517 100644
--- a/products/mcp_store/backend/presentation/views.py
+++ b/products/mcp_store/backend/presentation/views.py
@@ -75,6 +75,7 @@ from ..oauth import (
oauth_resource,
register_dcr_client,
requested_oauth_scopes,
+ resolve_template_oauth_credentials,
select_token_endpoint_auth_method,
)
from ..policy import GatewayCaller, PolicyContext, ResolvedPolicy, is_policy_state_allowed
@@ -198,13 +199,21 @@ def _template_uses_dcr(template: MCPServerTemplate) -> bool:
detects this implicitly — the user-facing ``auth_type`` stays ``"oauth"``
so neither the API nor the UI needs to know about DCR as a concept.
- Operators seed a DCR template by populating (name, url, oauth_metadata,
- icon, category, docs_url) and leaving ``oauth_credentials`` empty.
+ A catalog credential source also identifies a shared client without copying
+ its secret into the template row.
"""
if template.auth_type != "oauth":
return False
credentials = template.oauth_credentials or {}
- return not credentials.get("client_id")
+ return not template.oauth_credentials_source and not credentials.get("client_id")
+
+
+def _template_shared_client_id(template: MCPServerTemplate) -> str:
+ credentials = resolve_template_oauth_credentials(template)
+ client_id = credentials.get("client_id", "")
+ if not client_id:
+ raise ValueError("Template OAuth client is not configured")
+ return client_id
# The domain becomes a path segment of img.logo.dev/{domain} and part of the icon cache key.
@@ -994,11 +1003,16 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
return None
def _register_dcr_client_or_raise(
- self, metadata: dict, redirect_uri: str, *, server_url: str = ""
+ self,
+ metadata: dict,
+ redirect_uri: str,
+ *,
+ server_url: str = "",
+ scope_allowlist: list[str] | tuple[str, ...] | None = None,
) -> DcrClientRegistration:
log_context = {"error": ""} if not server_url else {"server_url": server_url, "error": ""}
try:
- return register_dcr_client(metadata, redirect_uri)
+ return register_dcr_client(metadata, redirect_uri, scope_allowlist)
except ValueError as e:
log_context["error"] = str(e)
logger.warning("DCR not supported", **log_context)
@@ -1020,6 +1034,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
redirect_uri: str,
state_token: str,
code_challenge: str,
+ scope_allowlist: list[str] | tuple[str, ...] | None = None,
) -> str:
query_params = {
"client_id": client_id,
@@ -1029,7 +1044,11 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"code_challenge": code_challenge,
"code_challenge_method": "S256",
}
- if scopes := requested_oauth_scopes(metadata):
+ try:
+ scopes = requested_oauth_scopes(metadata, scope_allowlist)
+ except ValueError as exc:
+ raise OAuthAuthorizeURLError(str(exc)) from exc
+ if scopes:
query_params["scope"] = " ".join(scopes)
if resource := oauth_resource(metadata):
query_params["resource"] = resource
@@ -1450,6 +1469,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
metadata,
redirect_uri,
server_url=template.url,
+ scope_allowlist=template.oauth_scope_allowlist,
)
except DCRNotSupportedError:
if created:
@@ -1485,7 +1505,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
team_id=self.team_id,
)
else:
- # Shared-creds template: admin-seeded metadata + shared client_id.
+ # Shared-creds template: trusted metadata + shared client_id.
if not template.oauth_metadata:
if created:
installation.delete()
@@ -1494,8 +1514,15 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
status=status.HTTP_400_BAD_REQUEST,
)
metadata = template.oauth_metadata
- # _template_uses_dcr guarantees client_id is present here.
- client_id = template.oauth_credentials["client_id"]
+ try:
+ client_id = _template_shared_client_id(template)
+ except ValueError:
+ if created:
+ installation.delete()
+ return Response(
+ {"detail": "Template OAuth client is not configured"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
pkce = generate_pkce()
token = secrets.token_urlsafe(32)
@@ -1517,6 +1544,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
redirect_uri=redirect_uri,
state_token=token,
code_challenge=pkce.code_challenge,
+ scope_allowlist=template.oauth_scope_allowlist,
)
except OAuthAuthorizeURLError as exc:
logger.warning(
@@ -1912,8 +1940,13 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
if not template.oauth_metadata:
return Response({"detail": "Template missing OAuth metadata"}, status=status.HTTP_400_BAD_REQUEST)
metadata = template.oauth_metadata
- # _template_uses_dcr guarantees client_id is present here.
- client_id = template.oauth_credentials["client_id"]
+ try:
+ client_id = _template_shared_client_id(template)
+ except ValueError:
+ return Response(
+ {"detail": "Template OAuth client is not configured"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
redirect_uri = _get_oauth_redirect_uri()
pkce = generate_pkce()
@@ -1935,6 +1968,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
redirect_uri=redirect_uri,
state_token=token,
code_challenge=pkce.code_challenge,
+ scope_allowlist=template.oauth_scope_allowlist,
)
except OAuthAuthorizeURLError as exc:
logger.warning(
diff --git a/products/mcp_store/backend/probe.py b/products/mcp_store/backend/probe.py
index beade6beab73..70911aa7f4bf 100644
--- a/products/mcp_store/backend/probe.py
+++ b/products/mcp_store/backend/probe.py
@@ -12,8 +12,8 @@ catalog sync jobs alike.
import json
import secrets
-from collections.abc import Iterator
-from dataclasses import dataclass, field
+from collections.abc import Iterator, Sequence
+from dataclasses import field
from typing import Literal
from urllib.parse import urlencode, urljoin
@@ -22,6 +22,7 @@ from django.conf import settings
import requests
import structlog
+from posthog.dataclasses import frozen
from posthog.security.pinned_requests import SSRFBlockedError, pinned_request
from .oauth import (
@@ -47,7 +48,7 @@ AuthFlavor = Literal["open", "oauth_dcr", "oauth_shared", "api_key_or_unknown"]
_InitializeOutcome = Literal["open", "auth_required", "failed"]
-@dataclass
+@frozen(frozen=False)
class ProbeResult:
reachable: bool = False
speaks_mcp: bool = False
@@ -65,24 +66,34 @@ class ProbeResult:
return False
if self.auth_flavor == "oauth_dcr":
return self.dcr_registered and self.authorize_endpoint_ok
- # oauth_shared needs manually provisioned shared client credentials, and
+ if self.auth_flavor == "oauth_shared":
+ return self.authorize_endpoint_ok
# api_key_or_unknown carries no MCP evidence (a bare 401/403 could be any
- # protected endpoint) — neither may auto-activate.
+ # protected endpoint), so it may not auto-activate.
return self.auth_flavor == "open"
-def probe_mcp_server(url: str) -> ProbeResult:
+def probe_mcp_server(
+ url: str,
+ scope_allowlist: Sequence[str] | None = None,
+ shared_client_id: str | None = None,
+) -> ProbeResult:
"""Probe ``url`` and return a :class:`ProbeResult`. Never raises."""
result = ProbeResult()
try:
- _run_probe(url, result)
+ _run_probe(url, result, scope_allowlist, shared_client_id)
except Exception as exc:
logger.exception("MCP server probe failed unexpectedly", server_url=url)
result.errors.append(f"Probe aborted unexpectedly: {exc}")
return result
-def _run_probe(url: str, result: ProbeResult) -> None:
+def _run_probe(
+ url: str,
+ result: ProbeResult,
+ scope_allowlist: Sequence[str] | None,
+ shared_client_id: str | None,
+) -> None:
outcome = _probe_initialize(url, result)
if outcome == "failed":
return
@@ -104,14 +115,24 @@ def _run_probe(url: str, result: ProbeResult) -> None:
# strongest MCP evidence available without credentials.
result.speaks_mcp = True
result.oauth_metadata = metadata
- client_id = _register_probe_client(metadata, result)
+ try:
+ requested_oauth_scopes(metadata, scope_allowlist)
+ except ValueError as exc:
+ result.errors.append(str(exc))
+ return
+
+ client_id = _register_probe_client(metadata, result, scope_allowlist)
if client_id is None:
result.auth_flavor = "oauth_shared"
+ if shared_client_id:
+ result.authorize_endpoint_ok = _check_authorize_endpoint(
+ metadata, shared_client_id, result, scope_allowlist
+ )
return
result.auth_flavor = "oauth_dcr"
result.dcr_registered = True
- result.authorize_endpoint_ok = _check_authorize_endpoint(metadata, client_id, result)
+ result.authorize_endpoint_ok = _check_authorize_endpoint(metadata, client_id, result, scope_allowlist)
def _probe_redirect_uri() -> str:
@@ -229,12 +250,12 @@ def _discover_metadata(url: str, result: ProbeResult, *, auth_required: bool) ->
return None
-def _register_probe_client(metadata: dict, result: ProbeResult) -> str | None:
+def _register_probe_client(metadata: dict, result: ProbeResult, scope_allowlist: Sequence[str] | None) -> str | None:
"""Mint a real DCR client. Returns its client_id, or None when DCR is unavailable."""
if not metadata.get("registration_endpoint"):
return None
try:
- registration = register_dcr_client(metadata, _probe_redirect_uri())
+ registration = register_dcr_client(metadata, _probe_redirect_uri(), scope_allowlist)
except ValueError as exc:
# Mirrors views._register_dcr_client_or_raise: ValueError means DCR isn't supported.
result.errors.append(f"Dynamic Client Registration not supported: {exc}")
@@ -245,7 +266,7 @@ def _register_probe_client(metadata: dict, result: ProbeResult) -> str | None:
return registration.client_id
-def _build_authorize_url(metadata: dict, client_id: str) -> str | None:
+def _build_authorize_url(metadata: dict, client_id: str, scope_allowlist: Sequence[str] | None) -> str | None:
authorization_endpoint = metadata.get("authorization_endpoint")
if not isinstance(authorization_endpoint, str) or not authorization_endpoint:
return None
@@ -260,16 +281,21 @@ def _build_authorize_url(metadata: dict, client_id: str) -> str | None:
"code_challenge": code_challenge,
"code_challenge_method": "S256",
}
- if scopes := requested_oauth_scopes(metadata):
+ if scopes := requested_oauth_scopes(metadata, scope_allowlist):
query_params["scope"] = " ".join(scopes)
if resource := oauth_resource(metadata):
query_params["resource"] = resource
return f"{authorization_endpoint}?{urlencode(query_params)}"
-def _check_authorize_endpoint(metadata: dict, client_id: str, result: ProbeResult) -> bool:
+def _check_authorize_endpoint(
+ metadata: dict,
+ client_id: str,
+ result: ProbeResult,
+ scope_allowlist: Sequence[str] | None,
+) -> bool:
"""GET the authorization URL and report whether it serves a plausible login/consent page."""
- authorize_url = _build_authorize_url(metadata, client_id)
+ authorize_url = _build_authorize_url(metadata, client_id, scope_allowlist)
if authorize_url is None:
result.errors.append("OAuth metadata is missing authorization_endpoint")
return False
diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.py
index af5d3c5c4ec8..62cd9149e5f3 100644
--- a/products/mcp_store/backend/test/test_api.py
+++ b/products/mcp_store/backend/test/test_api.py
@@ -19,6 +19,7 @@ from rest_framework import serializers, status
from rest_framework.test import APIClient
from posthog.models import Organization, Team, User
+from posthog.models.instance_setting import override_instance_config
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization import OrganizationMembership
@@ -3867,7 +3868,14 @@ class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest
return MCPServerTemplate.objects.create(**defaults)
def test_install_template_oauth_returns_redirect_url(self):
- template = self._template()
+ template = self._template(
+ oauth_scope_allowlist=["read"],
+ oauth_metadata={
+ "authorization_endpoint": "https://auth.test.example.com/authorize",
+ "token_endpoint": "https://auth.test.example.com/token",
+ "scopes_supported": ["read", "write"],
+ },
+ )
response = self.client.post(
f"/api/environments/{self.team.id}/mcp_server_installations/install_template/",
@@ -3880,10 +3888,78 @@ class TestInstallTemplateAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest
assert urlparse(redirect_url).netloc == "auth.test.example.com"
params = parse_qs(urlparse(redirect_url).query)
assert params["client_id"][0] == "template-client-id"
+ assert params["scope"] == ["read"]
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):
+ template = self._template(
+ oauth_credentials_source="slack_app",
+ oauth_credentials={},
+ oauth_metadata={
+ "issuer": "https://mcp.slack.com",
+ "authorization_endpoint": "https://slack.com/oauth/v2_user/authorize",
+ "token_endpoint": "https://slack.com/api/oauth.v2.user.access",
+ "token_endpoint_auth_methods_supported": ["client_secret_post"],
+ },
+ )
+
+ with (
+ override_instance_config("SLACK_APP_CLIENT_ID", "slack-client"),
+ override_instance_config("SLACK_APP_CLIENT_SECRET", "slack-secret"),
+ ):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/mcp_server_installations/install_template/",
+ data={"template_id": str(template.id)},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ params = parse_qs(urlparse(response.json()["redirect_url"]).query)
+ assert params["client_id"] == ["slack-client"]
+ assert MCPServerInstallation.objects.filter(url=template.url, user=self.user).exists()
+
+ def test_install_template_oauth_fails_closed_when_instance_credentials_are_missing(self):
+ template = self._template(
+ oauth_credentials_source="slack_app",
+ oauth_credentials={"client_id": "stale-template-client"},
+ )
+
+ with (
+ override_instance_config("SLACK_APP_CLIENT_ID", ""),
+ override_instance_config("SLACK_APP_CLIENT_SECRET", ""),
+ ):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/mcp_server_installations/install_template/",
+ data={"template_id": str(template.id)},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["detail"] == "Template OAuth client is not configured"
+ assert not MCPServerInstallation.objects.filter(url=template.url, user=self.user).exists()
+
+ def test_install_template_rejects_nonmatching_oauth_scope_allowlist(self):
+ template = self._template(
+ oauth_scope_allowlist=["read"],
+ oauth_metadata={
+ "authorization_endpoint": "https://auth.test.example.com/authorize",
+ "token_endpoint": "https://auth.test.example.com/token",
+ "scopes_supported": ["write"],
+ },
+ )
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/mcp_server_installations/install_template/",
+ data={"template_id": str(template.id)},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["detail"] == "Could not build OAuth authorize URL"
+ assert not MCPServerInstallation.objects.filter(url=template.url, user=self.user).exists()
+
def test_install_template_api_key_stores_key_and_returns_installation(self):
template = self._template(auth_type="api_key", oauth_credentials={}, oauth_metadata={})
diff --git a/products/mcp_store/backend/test/test_catalog_sync.py b/products/mcp_store/backend/test/test_catalog_sync.py
index a5cc1689ba02..eab14e8cf0ff 100644
--- a/products/mcp_store/backend/test/test_catalog_sync.py
+++ b/products/mcp_store/backend/test/test_catalog_sync.py
@@ -1,3 +1,5 @@
+from collections.abc import Sequence
+
from unittest.mock import patch
from django.test import SimpleTestCase, TestCase
@@ -12,23 +14,38 @@ from products.mcp_store.backend.models import (
MCPServerTemplate,
normalize_mcp_icon_domain,
)
+from products.mcp_store.backend.oauth_credentials import SUPPORTED_OAUTH_CREDENTIAL_SOURCES, OAuthCredentialsSource
from products.mcp_store.backend.probe import ProbeResult
VALID_AUTH_TYPES = {choice for choice, _ in AUTH_TYPE_CHOICES}
VALID_CATEGORIES = {choice for choice, _ in CATEGORY_CHOICES}
-def _entry(**overrides) -> CatalogEntry:
- defaults = {
- "name": "Linear",
- "url": "https://mcp.linear.app/mcp",
- "description": "Manage Linear issues.",
- "auth_type": "oauth",
- "category": "dev",
- "icon_domain": "linear.app",
- }
- defaults.update(overrides)
- return CatalogEntry(**defaults)
+def _entry(
+ *,
+ name: str = "Linear",
+ url: str = "https://mcp.linear.app/mcp",
+ description: str = "Manage Linear issues.",
+ auth_type: str = "oauth",
+ category: str = "dev",
+ icon_domain: str = "linear.app",
+ docs_url: str = "",
+ oauth_scope_allowlist: tuple[str, ...] | None = None,
+ oauth_credentials_source: OAuthCredentialsSource | None = None,
+ disabled: bool = False,
+) -> CatalogEntry:
+ return CatalogEntry(
+ name=name,
+ url=url,
+ description=description,
+ auth_type=auth_type,
+ category=category,
+ icon_domain=icon_domain,
+ docs_url=docs_url,
+ oauth_scope_allowlist=oauth_scope_allowlist,
+ oauth_credentials_source=oauth_credentials_source,
+ disabled=disabled,
+ )
def _dcr_pass_probe() -> ProbeResult:
@@ -56,6 +73,13 @@ class TestCatalogEntries(SimpleTestCase):
assert entry.url.startswith("https://"), entry.url
assert entry.name and entry.description, entry.url
assert entry.icon_domain == normalize_mcp_icon_domain(entry.icon_domain), entry.url
+ if entry.oauth_scope_allowlist is not None:
+ assert entry.auth_type == "oauth", entry.url
+ assert len(entry.oauth_scope_allowlist) == len(set(entry.oauth_scope_allowlist)), entry.url
+ assert all(entry.oauth_scope_allowlist), entry.url
+ if entry.oauth_credentials_source is not None:
+ assert entry.auth_type == "oauth", entry.url
+ assert entry.oauth_credentials_source in SUPPORTED_OAUTH_CREDENTIAL_SOURCES, entry.url
class TestSyncMCPCatalog(TestCase):
@@ -97,16 +121,88 @@ class TestSyncMCPCatalog(TestCase):
with patch("products.mcp_store.backend.catalog_sync.probe_mcp_server", return_value=probe_result) as probe_mock:
counts = sync_mcp_catalog(entries=[entry])
- probe_mock.assert_called_once_with(entry.url)
+ probe_mock.assert_called_once_with(
+ entry.url,
+ scope_allowlist=entry.oauth_scope_allowlist,
+ shared_client_id=None,
+ )
template = MCPServerTemplate.objects.get(url=entry.url)
assert counts.created == 1
assert template.is_active is expect_active
assert template.name == entry.name
assert template.icon_domain == entry.icon_domain
+ assert template.oauth_scope_allowlist == (
+ list(entry.oauth_scope_allowlist) if entry.oauth_scope_allowlist is not None else None
+ )
if probe_result.oauth_metadata:
assert template.oauth_metadata == probe_result.oauth_metadata
assert template.oauth_issuer_url == probe_result.oauth_metadata.get("issuer", "")
+ @patch(
+ "products.mcp_store.backend.oauth_credentials.get_instance_settings",
+ return_value={"SLACK_APP_CLIENT_ID": "slack-client", "SLACK_APP_CLIENT_SECRET": "slack-secret"},
+ )
+ def test_existing_shared_oauth_entry_activates_from_instance_credentials(self, _settings):
+ template = MCPServerTemplate.objects.create(
+ name="Slack",
+ url="https://mcp.slack.test.example/mcp",
+ description="Search Slack.",
+ auth_type="oauth",
+ category="productivity",
+ is_active=False,
+ )
+ probe_result = ProbeResult(
+ reachable=True,
+ speaks_mcp=True,
+ auth_flavor="oauth_shared",
+ oauth_metadata={"issuer": "https://mcp.slack.com"},
+ authorize_endpoint_ok=True,
+ )
+
+ with patch("products.mcp_store.backend.catalog_sync.probe_mcp_server", return_value=probe_result) as probe:
+ counts = sync_mcp_catalog(
+ entries=[
+ _entry(
+ name="Slack",
+ url=template.url,
+ category="productivity",
+ icon_domain="slack.com",
+ oauth_credentials_source="slack_app",
+ )
+ ]
+ )
+
+ template.refresh_from_db()
+ assert template.is_active is True
+ assert template.oauth_credentials_source == "slack_app"
+ assert template.oauth_credentials == {}
+ assert counts.activated == 1
+ probe.assert_called_once_with(template.url, scope_allowlist=None, shared_client_id="slack-client")
+
+ @patch(
+ "products.mcp_store.backend.oauth_credentials.get_instance_settings",
+ return_value={"SLACK_APP_CLIENT_ID": "", "SLACK_APP_CLIENT_SECRET": ""},
+ )
+ def test_instance_credential_source_deactivates_when_settings_are_missing(self, _settings):
+ entry = _entry(oauth_credentials_source="slack_app")
+ template = MCPServerTemplate.objects.create(
+ name=entry.name,
+ url=entry.url,
+ description=entry.description,
+ auth_type=entry.auth_type,
+ category=entry.category,
+ icon_domain=entry.icon_domain,
+ oauth_credentials_source="slack_app",
+ is_active=True,
+ )
+
+ with patch("products.mcp_store.backend.catalog_sync.probe_mcp_server") as probe:
+ sync_mcp_catalog(entries=[entry])
+
+ template.refresh_from_db()
+ assert template.is_active is False
+ probe.assert_not_called()
+
def test_update_touches_content_fields_but_never_operational_state(self):
# Clobbering is_active/credentials/metadata on an operator-configured row would break
# every existing install of that server the moment a catalog PR edits its copy.
@@ -122,13 +218,22 @@ class TestSyncMCPCatalog(TestCase):
)
with patch("products.mcp_store.backend.catalog_sync.probe_mcp_server") as probe_mock:
- counts = sync_mcp_catalog(entries=[_entry(description="New description.", category="dev")])
+ counts = sync_mcp_catalog(
+ entries=[
+ _entry(
+ description="New description.",
+ category="dev",
+ oauth_scope_allowlist=("read",),
+ )
+ ]
+ )
probe_mock.assert_not_called()
template.refresh_from_db()
assert counts.updated == 1
assert template.description == "New description."
assert template.category == "dev"
+ assert template.oauth_scope_allowlist == ["read"]
assert template.is_active is True
assert template.oauth_credentials == {"client_id": "shared-client", "client_secret": "shhh"}
assert template.oauth_metadata == {"authorization_endpoint": "https://auth.linear.app/authorize"}
@@ -177,6 +282,33 @@ class TestSyncMCPCatalog(TestCase):
assert counts.created == 1
assert MCPServerTemplate.objects.get(url=_entry().url).is_active is False
+ def test_disabled_entry_stays_inactive_without_probing(self):
+ with patch("products.mcp_store.backend.catalog_sync.probe_mcp_server") as probe_mock:
+ counts = sync_mcp_catalog(entries=[_entry(disabled=True)])
+
+ probe_mock.assert_not_called()
+ assert counts.created == 1
+ assert MCPServerTemplate.objects.get(url=_entry().url).is_active is False
+
+ def test_disabled_entry_deactivates_existing_template(self):
+ template = MCPServerTemplate.objects.create(
+ name="Linear",
+ url=_entry().url,
+ description="Manage Linear issues.",
+ auth_type="oauth",
+ category="dev",
+ icon_domain="linear.app",
+ is_active=True,
+ )
+
+ with patch("products.mcp_store.backend.catalog_sync.probe_mcp_server") as probe_mock:
+ counts = sync_mcp_catalog(entries=[_entry(disabled=True)])
+
+ probe_mock.assert_not_called()
+ template.refresh_from_db()
+ assert counts.updated == 1
+ assert template.is_active is False
+
def test_warns_on_active_row_missing_from_catalog(self):
# A catalog url edit orphans the old active row silently — the sync warning is the
# only thing that surfaces it, so a refactor dropping it must fail here.
@@ -204,7 +336,11 @@ class TestSyncMCPCatalog(TestCase):
good = _entry()
bad = _entry(url="https://mcp.broken.example/mcp", name="Broken")
- def _probe(url: str) -> ProbeResult:
+ def _probe(
+ url: str,
+ scope_allowlist: Sequence[str] | None = None,
+ shared_client_id: str | None = None,
+ ) -> ProbeResult:
if "broken" in url:
raise RuntimeError("boom")
return _dcr_pass_probe()
diff --git a/products/mcp_store/backend/test/test_oauth.py b/products/mcp_store/backend/test/test_oauth.py
index e4c04d1ec667..2bc7fbfa2a59 100644
--- a/products/mcp_store/backend/test/test_oauth.py
+++ b/products/mcp_store/backend/test/test_oauth.py
@@ -8,6 +8,8 @@ from django.test import SimpleTestCase, TestCase
import requests
from parameterized import parameterized
+from posthog.models.instance_setting import override_instance_config
+
from products.mcp_store.backend.models import MCPServerInstallation, MCPServerTemplate
from products.mcp_store.backend.oauth import (
TIMEOUT,
@@ -21,6 +23,7 @@ from products.mcp_store.backend.oauth import (
discover_oauth_metadata,
exchange_oauth_token,
oauth_resource,
+ refresh_installation_token,
refresh_oauth_token,
register_dcr_client,
requested_oauth_grant_types,
@@ -1021,6 +1024,7 @@ class TestRegisterDCRClient(SimpleTestCase):
"token_endpoint_auth_methods_supported": ["client_secret_post", "client_secret_basic"],
},
"https://app.posthog.com/callback",
+ ("read",),
)
assert result == DcrClientRegistration(
@@ -1029,7 +1033,7 @@ class TestRegisterDCRClient(SimpleTestCase):
payload = mock_post.call_args.kwargs["json"]
assert payload["grant_types"] == ["authorization_code", "refresh_token"]
assert payload["token_endpoint_auth_method"] == "client_secret_post"
- assert payload["scope"] == "read write"
+ assert payload["scope"] == "read"
assert "refresh_token" not in payload["scope"]
assert mock_post.call_args.kwargs["allow_redirects"] is False
@@ -1105,17 +1109,37 @@ class TestRegisterDCRClient(SimpleTestCase):
}
assert requested_oauth_scopes(metadata) == ["read"]
+ assert requested_oauth_scopes(metadata, ("read", "admin", "read")) == ["read"]
+ with self.assertRaisesRegex(ValueError, "does not contain any scopes"):
+ requested_oauth_scopes(metadata, ())
+ with self.assertRaisesRegex(ValueError, "does not match any provider-supported scopes"):
+ requested_oauth_scopes(metadata, ("admin",))
assert requested_oauth_grant_types(metadata) == ["authorization_code", "refresh_token"]
assert oauth_resource(metadata) == "https://mcp.example.com/"
class TestResolveInstallationOauthContext(BaseTest):
- def test_template_backed_install_returns_template_creds(self):
+ @parameterized.expand(
+ [
+ ("metadata_without_methods_defaults_to_basic", {}, "client_secret_basic"),
+ (
+ "metadata_selects_client_secret_post",
+ {"token_endpoint_auth_methods_supported": ["client_secret_post"]},
+ "client_secret_post",
+ ),
+ ]
+ )
+ def test_template_backed_install_returns_template_creds(
+ self, _name: str, metadata_overrides: dict, expected_auth_method: str
+ ) -> None:
template = MCPServerTemplate.objects.create(
name="Template",
url="https://mcp.template.example.com/mcp",
auth_type="oauth",
- oauth_metadata={"token_endpoint": "https://auth.template.example.com/token"},
+ oauth_metadata={
+ "token_endpoint": "https://auth.template.example.com/token",
+ **metadata_overrides,
+ },
oauth_credentials={"client_id": "template-client", "client_secret": "template-secret"},
created_by=self.user,
)
@@ -1135,7 +1159,41 @@ class TestResolveInstallationOauthContext(BaseTest):
assert ctx.metadata["token_endpoint"] == "https://auth.template.example.com/token"
assert ctx.client_id == "template-client"
assert ctx.client_secret == "template-secret"
- assert ctx.token_endpoint_auth_method == "client_secret_basic"
+ assert ctx.token_endpoint_auth_method == expected_auth_method
+
+ def test_template_backed_install_uses_instance_credential_source(self):
+ template = MCPServerTemplate.objects.create(
+ name="Slack",
+ url="https://mcp.slack.test.example/mcp",
+ auth_type="oauth",
+ oauth_metadata={
+ "issuer": "https://mcp.slack.com",
+ "authorization_endpoint": "https://slack.com/oauth/v2_user/authorize",
+ "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={},
+ created_by=self.user,
+ )
+ installation = MCPServerInstallation.objects.create(
+ team=self.team,
+ user=self.user,
+ template=template,
+ url=template.url,
+ auth_type="oauth",
+ sensitive_configuration={"access_token": "tok"},
+ )
+
+ with (
+ override_instance_config("SLACK_APP_CLIENT_ID", "slack-client"),
+ override_instance_config("SLACK_APP_CLIENT_SECRET", "slack-secret"),
+ ):
+ ctx = resolve_installation_oauth_context(installation)
+
+ assert ctx.client_id == "slack-client"
+ assert ctx.client_secret == "slack-secret"
+ assert ctx.token_endpoint_auth_method == "client_secret_post"
def test_dcr_template_backed_install_returns_per_installation_metadata_and_creds(self):
# DCR templates carry no shared client_id AND no trusted metadata —
@@ -1207,6 +1265,65 @@ class TestResolveInstallationOauthContext(BaseTest):
assert ctx.token_endpoint_auth_method == "none"
+class TestSourceBackedOauthMetadataBinding(BaseTest):
+ def _installation(self) -> MCPServerInstallation:
+ template = MCPServerTemplate.objects.create(
+ name="Slack",
+ url="https://mcp.slack.test.example/mcp",
+ auth_type="oauth",
+ 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_auth_methods_supported": ["client_secret_post"],
+ },
+ oauth_credentials_source="slack_app",
+ created_by=self.user,
+ )
+ return MCPServerInstallation.objects.create(
+ team=self.team,
+ user=self.user,
+ template=template,
+ url=template.url,
+ auth_type="oauth",
+ sensitive_configuration={"refresh_token": "refresh-token"},
+ )
+
+ @patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.oauth.requests.post")
+ def test_exchange_rejects_modified_token_endpoint_before_sending_secret(self, mock_post, _allow):
+ installation = self._installation()
+
+ with (
+ override_instance_config("SLACK_APP_CLIENT_ID", "slack-client"),
+ override_instance_config("SLACK_APP_CLIENT_SECRET", "slack-secret"),
+ self.assertRaises(OAuthTokenExchangeError),
+ ):
+ 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://"),
+ )
+
+ mock_post.assert_not_called()
+
+ @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):
+ installation = self._installation()
+
+ with (
+ override_instance_config("SLACK_APP_CLIENT_ID", "slack-client"),
+ override_instance_config("SLACK_APP_CLIENT_SECRET", "slack-secret"),
+ self.assertRaises(TokenRefreshError),
+ ):
+ refresh_installation_token(installation)
+
+ mock_post.assert_not_called()
+
+
class TestExchangeOauthToken(BaseTest):
def _make_installation(self, *, sensitive_configuration: dict) -> MCPServerInstallation:
return MCPServerInstallation.objects.create(
diff --git a/products/mcp_store/backend/test/test_probe.py b/products/mcp_store/backend/test/test_probe.py
index f5eac8cedad6..121f4d192b40 100644
--- a/products/mcp_store/backend/test/test_probe.py
+++ b/products/mcp_store/backend/test/test_probe.py
@@ -70,7 +70,7 @@ def _url_router(routes):
class TestProbeMCPServer(SimpleTestCase):
- def _probe(self, *, post_routes, get_routes=None):
+ def _probe(self, *, post_routes, get_routes=None, scope_allowlist=None, shared_client_id=None):
post_router = _url_router(post_routes)
get_router = _url_router(get_routes or {})
@@ -86,7 +86,7 @@ class TestProbeMCPServer(SimpleTestCase):
patch("products.mcp_store.backend.oauth.requests.post", side_effect=post_router) as post,
patch("products.mcp_store.backend.oauth.requests.get", side_effect=get_router) as get,
):
- result = probe_mcp_server(SERVER_URL)
+ result = probe_mcp_server(SERVER_URL, scope_allowlist, shared_client_id)
return result, post, get, pinned
@parameterized.expand(
@@ -109,7 +109,7 @@ class TestProbeMCPServer(SimpleTestCase):
self.assertTrue(result.passed_activation_gate)
def test_oauth_dcr_full_pass(self):
- result, _post, _get, pinned = self._probe(
+ result, post, _get, pinned = self._probe(
post_routes={
SERVER_URL: _mock_response(401, text="unauthorized", content_type="text/plain"),
REGISTRATION_URL: _mock_response(
@@ -118,9 +118,13 @@ class TestProbeMCPServer(SimpleTestCase):
},
get_routes={
PROTECTED_RESOURCE_URL: _mock_response(200, json_body=PROTECTED_RESOURCE_BODY),
- AUTH_SERVER_METADATA_URL: _mock_response(200, json_body=AUTH_SERVER_METADATA_BODY),
+ AUTH_SERVER_METADATA_URL: _mock_response(
+ 200,
+ json_body={**AUTH_SERVER_METADATA_BODY, "scopes_supported": ["read", "write"]},
+ ),
AUTHORIZE_URL: _mock_response(200, text="<html>log in</html>", content_type="text/html"),
},
+ scope_allowlist=("read",),
)
self.assertTrue(result.reachable)
@@ -139,6 +143,33 @@ class TestProbeMCPServer(SimpleTestCase):
self.assertEqual(query["code_challenge_method"], ["S256"])
self.assertIn("code_challenge", query)
self.assertTrue(query["redirect_uri"][0].endswith("/api/mcp_store/oauth_redirect/"))
+ self.assertEqual(query["scope"], ["read"])
+
+ registration_calls = [c for c in post.call_args_list if c.args[0] == REGISTRATION_URL]
+ self.assertEqual(registration_calls[0].kwargs["json"]["scope"], "read")
+
+ def test_oauth_scope_allowlist_must_match_advertised_scopes(self):
+ result, post, _get, _pinned = self._probe(
+ post_routes={
+ SERVER_URL: _mock_response(401, text="unauthorized", content_type="text/plain"),
+ REGISTRATION_URL: _mock_response(
+ 201, json_body={"client_id": "minted-client-id", "token_endpoint_auth_method": "none"}
+ ),
+ },
+ get_routes={
+ PROTECTED_RESOURCE_URL: _mock_response(200, json_body=PROTECTED_RESOURCE_BODY),
+ AUTH_SERVER_METADATA_URL: _mock_response(
+ 200,
+ json_body={**AUTH_SERVER_METADATA_BODY, "scopes_supported": ["read"]},
+ ),
+ },
+ scope_allowlist=("write",),
+ )
+
+ self.assertFalse(result.passed_activation_gate)
+ self.assertFalse(result.dcr_registered)
+ self.assertTrue(any("does not match" in error for error in result.errors))
+ self.assertFalse(any(call.args[0] == REGISTRATION_URL for call in post.call_args_list))
def test_oauth_without_registration_endpoint_is_oauth_shared(self):
metadata = {k: v for k, v in AUTH_SERVER_METADATA_BODY.items() if k != "registration_endpoint"}
@@ -157,6 +188,24 @@ class TestProbeMCPServer(SimpleTestCase):
self.assertEqual(result.oauth_metadata["token_endpoint"], f"{ORIGIN}/token")
self.assertFalse(result.passed_activation_gate)
+ def test_oauth_shared_client_checks_authorization_endpoint(self):
+ metadata = {k: v for k, v in AUTH_SERVER_METADATA_BODY.items() if k != "registration_endpoint"}
+ result, _post, _get, pinned = self._probe(
+ post_routes={SERVER_URL: _mock_response(401, text="unauthorized", content_type="text/plain")},
+ get_routes={
+ PROTECTED_RESOURCE_URL: _mock_response(200, json_body=PROTECTED_RESOURCE_BODY),
+ AUTH_SERVER_METADATA_URL: _mock_response(200, json_body=metadata),
+ AUTHORIZE_URL: _mock_response(200, text="<html>log in</html>", content_type="text/html"),
+ },
+ shared_client_id="shared-client",
+ )
+
+ self.assertEqual(result.auth_flavor, "oauth_shared")
+ self.assertTrue(result.authorize_endpoint_ok)
+ self.assertTrue(result.passed_activation_gate)
+ authorize_call = next(call for call in pinned.call_args_list if call.args[1].startswith(f"{AUTHORIZE_URL}?"))
+ self.assertEqual(parse_qs(urlparse(authorize_call.args[1]).query)["client_id"], ["shared-client"])
+
@parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
def test_auth_required_without_metadata_is_unverified_and_fails_gate(self, _name, status_code):
result, _post, _get, _pinned = self._probe(
@@ -284,7 +333,8 @@ class TestPassedActivationGate(SimpleTestCase):
("oauth_dcr_full_pass", "oauth_dcr", True, True, True, True, True),
("oauth_dcr_authorize_down", "oauth_dcr", True, True, True, False, False),
("oauth_dcr_not_registered", "oauth_dcr", True, True, False, True, False),
- ("oauth_shared", "oauth_shared", True, True, False, False, False),
+ ("oauth_shared_without_client", "oauth_shared", True, True, False, False, False),
+ ("oauth_shared_with_client", "oauth_shared", True, True, False, True, True),
]
)
def test_gate(self, _name, auth_flavor, reachable, speaks_mcp, dcr_registered, authorize_endpoint_ok, expected):