:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp-store): define the server catalog in code with probe-gated sync (#70162)
Chris Volzere9b7d2f2eae6
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex a93f1d4902a3..ae77ad4aea73 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -64,3 +64,9 @@ posthog/temporal/data_modeling/run_workflow.py @PostHog/team-data-modeling# Dev sandbox provides important protection in local devbin/dev-sandbox* @PostHog/team-security++# The MCP store catalog is a fleet-wide trust decision, not ordinary code: a merged entry+# becomes (probe permitting) an active server template in every environment on the next+# deploy — installable by all tenants and feeding tool results into their LLM agents. The+# probe only verifies liveness, so PR review is the vendor-identity gate.+products/mcp_store/backend/catalog.py @PostHog/team-self-driving @cvolzer3diff --git a/products/mcp_store/backend/admin.py b/products/mcp_store/backend/admin.pyindex 0693ad733984..4826690b1640 100644--- a/products/mcp_store/backend/admin.py+++ b/products/mcp_store/backend/admin.py@@ -4,6 +4,7 @@ from typing import Anyfrom django import formsfrom django.contrib import admin, messagesfrom django.http import HttpRequest+from django.utils.html import format_htmlfrom products.mcp_store.backend.models import MCPServerTemplatefrom products.mcp_store.backend.oauth import discover_oauth_metadata@@ -57,6 +58,18 @@ class MCPServerTemplateAdminForm(forms.ModelForm):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+ # before they commit it — a lying server shouldn't get a secret quietly.+ token_endpoint = (instance.oauth_metadata or {}).get("token_endpoint", "") if instance else ""+ if token_endpoint:+ self.fields["client_secret"].help_text = format_html(+ "{} Token exchange sends this secret to <code>{}</code> (from discovered metadata) — "+ "confirm that endpoint belongs to the vendor before saving.",+ self.fields["client_secret"].help_text,+ token_endpoint,+ )+def save(self, commit: bool = True) -> MCPServerTemplate:instance: MCPServerTemplate = super().save(commit=False)existing_creds = dict(instance.oauth_credentials or {})diff --git a/products/mcp_store/backend/apps.py b/products/mcp_store/backend/apps.pyindex 2098c5e793c9..0b1de9e4a8c3 100644--- a/products/mcp_store/backend/apps.py+++ b/products/mcp_store/backend/apps.py@@ -1,4 +1,5 @@from django.apps import AppConfig+from django.conf import settingsclass McpStoreConfig(AppConfig):@@ -6,3 +7,12 @@ class McpStoreConfig(AppConfig):name = "products.mcp_store.backend"label = "mcp_store"verbose_name = "MCP STORE"++ def ready(self) -> None:+ # Deferred: task modules pull in models, which can't import until the app registry is ready.+ from products.mcp_store.backend.tasks.tasks import queue_sync_mcp_server_templates # noqa: PLC0415++ # Skip during tests (suites sync the catalog explicitly where needed) and during+ # collectstatic (STATIC_COLLECTION=1 in Dockerfile) — no Redis available at build time.+ if not settings.TEST and not settings.STATIC_COLLECTION:+ queue_sync_mcp_server_templates()diff --git a/products/mcp_store/backend/catalog.py b/products/mcp_store/backend/catalog.pynew file mode 100644index 000000000000..735726753a3d--- /dev/null+++ b/products/mcp_store/backend/catalog.py@@ -0,0 +1,343 @@+"""The curated MCP server catalog, as code.++Each entry here becomes (or updates) an ``MCPServerTemplate`` row via the+``sync_mcp_server_templates`` management command, which runs on app startup in every+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+``catalog_sync.py`` for the exact semantics, including the probe-gated activation+of newly created entries.++REVIEWERS: merging an entry here is a vendor-trust decision, not data entry. Once+merged, the sync runs in every environment on the next deploy and — if the probe+passes — activates the server, making it installable by every tenant and reachable+by their LLM agents. The probe only verifies the server is alive, speaks MCP, and+matches the declared auth model; it CANNOT verify that the url belongs to the named+vendor — a malicious endpoint passes it trivially. PR review of this file is the+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+++@dataclass(frozen=True)+class CatalogEntry:+ name: str+ url: str+ description: str+ auth_type: str # "oauth" | "api_key" — must match AUTH_TYPE_CHOICES on the model+ 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 = ""+++MCP_SERVER_CATALOG: list[CatalogEntry] = [+ CatalogEntry(+ name="Atlassian",+ url="https://mcp.atlassian.com/v1/mcp",+ description="Integrate with Atlassian products like Jira and Confluence.",+ auth_type="oauth",+ category="productivity",+ icon_domain="atlassian.com",+ ),+ CatalogEntry(+ name="Box",+ url="https://mcp.box.com",+ description="Search and manage Box content with Box AI-powered Q&A and extraction.",+ auth_type="oauth",+ category="data",+ icon_domain="box.com",+ ),+ CatalogEntry(+ name="Browserbase",+ url="https://mcp.browserbase.com/mcp",+ description="Run cloud browser automation, screenshots, and page extraction.",+ auth_type="api_key",+ category="dev",+ icon_domain="browserbase.com",+ ),+ CatalogEntry(+ name="Circle",+ url="https://api.circle.com/v1/codegen/mcp",+ description="Build on Circle stablecoin, wallet, and payment infrastructure.",+ auth_type="api_key",+ category="dev",+ icon_domain="circle.com",+ ),+ CatalogEntry(+ name="Clerk",+ url="https://mcp.clerk.com/mcp",+ description="Retrieve Clerk authentication setup guides and SDK context.",+ auth_type="api_key",+ category="dev",+ icon_domain="clerk.com",+ ),+ CatalogEntry(+ name="ClickHouse",+ url="https://mcp.clickhouse.cloud/mcp",+ description="Query ClickHouse Cloud databases, schemas, and analytics.",+ auth_type="oauth",+ category="infra",+ icon_domain="clickhouse.com",+ ),+ CatalogEntry(+ name="Cloudflare",+ url="https://mcp.cloudflare.com/mcp",+ description="Manage Cloudflare Workers, Durable Objects, and platform resources.",+ auth_type="oauth",+ category="infra",+ icon_domain="cloudflare.com",+ ),+ CatalogEntry(+ name="Context7",+ url="https://mcp.context7.com/mcp",+ description="Retrieve up-to-date developer documentation for libraries and frameworks.",+ auth_type="api_key",+ category="productivity",+ icon_domain="context7.com",+ ),+ CatalogEntry(+ name="Datadog",+ url="https://mcp.datadoghq.com/api/unstable/mcp-server/mcp",+ description="Query Datadog logs, metrics, traces, and dashboards.",+ auth_type="oauth",+ category="data",+ icon_domain="datadoghq.com",+ ),+ CatalogEntry(+ name="dbt Labs",+ url="https://cloud.getdbt.com/api/ai/v1/mcp/",+ description="Work with dbt data modeling, transformations, and project workflows.",+ auth_type="oauth",+ category="data",+ icon_domain="getdbt.com",+ ),+ CatalogEntry(+ name="Figma",+ url="https://mcp.figma.com/mcp",+ description="Work with Figma design files, dev handoff, and design-to-code context.",+ auth_type="oauth",+ category="design",+ icon_domain="figma.com",+ ),+ CatalogEntry(+ name="Firetiger",+ url="https://api.cloud.firetiger.com/mcp/v1",+ description="Run Firetiger telemetry queries, investigations, and observability automation.",+ auth_type="oauth",+ category="dev",+ icon_domain="firetiger.com",+ ),+ CatalogEntry(+ name="GitLab",+ url="https://gitlab.com/api/v4/mcp",+ description="Manage GitLab issues, merge requests, pipelines, and repos.",+ auth_type="oauth",+ category="dev",+ icon_domain="gitlab.com",+ ),+ CatalogEntry(+ name="Granola",+ url="https://mcp.granola.ai/mcp",+ description="Search Granola meeting notes, transcripts, and meeting insights.",+ auth_type="oauth",+ category="dev",+ icon_domain="granola.ai",+ ),+ CatalogEntry(+ name="Hex",+ url="https://app.hex.tech/mcp",+ description="Search Hex workspaces, notebooks, and data analysis collaboration.",+ auth_type="oauth",+ category="data",+ icon_domain="hex.tech",+ ),+ CatalogEntry(+ name="HubSpot",+ url="https://mcp.hubspot.com",+ description="Manage HubSpot contacts, companies, and deals.",+ auth_type="oauth",+ category="business",+ icon_domain="hubspot.com",+ ),+ CatalogEntry(+ name="LaunchDarkly AI Configs",+ url="https://mcp.launchdarkly.com/mcp/aiconfigs",+ description="Manage LaunchDarkly AI Configs for prompts, models, and runtime AI settings.",+ auth_type="oauth",+ category="dev",+ icon_domain="launchdarkly.com",+ ),+ CatalogEntry(+ name="LaunchDarkly Feature Management",+ url="https://mcp.launchdarkly.com/mcp/fm",+ description="Manage LaunchDarkly feature flags and release controls.",+ auth_type="oauth",+ category="data",+ icon_domain="launchdarkly.com",+ ),+ CatalogEntry(+ name="LaunchDarkly Observability",+ url="https://mcp.launchdarkly.com/mcp/observability",+ description="Explore LaunchDarkly observability errors, sessions, logs, and traces.",+ auth_type="oauth",+ category="dev",+ icon_domain="launchdarkly.com",+ ),+ CatalogEntry(+ name="Linear",+ url="https://mcp.linear.app/mcp",+ description="Manage Linear issues, projects, teams, and workflows.",+ auth_type="oauth",+ category="productivity",+ icon_domain="linear.app",+ ),+ CatalogEntry(+ name="Mem0",+ url="https://mcp.mem0.ai/mcp/",+ description="Save, search, and update AI agent memories with Mem0.",+ auth_type="oauth",+ category="dev",+ icon_domain="mem0.ai",+ ),+ CatalogEntry(+ name="Neon",+ url="https://mcp.neon.tech/mcp",+ description="Manage Neon serverless Postgres projects, branches, and databases.",+ auth_type="oauth",+ category="infra",+ icon_domain="neon.tech",+ ),+ CatalogEntry(+ name="Notion",+ url="https://mcp.notion.com/mcp",+ description="Search and manage Notion pages, databases, and knowledge base content.",+ auth_type="oauth",+ category="productivity",+ icon_domain="notion.com",+ ),+ CatalogEntry(+ name="PagerDuty (EU)",+ url="https://mcp.eu.pagerduty.com/mcp",+ description="Manage PagerDuty incidents, services, schedules, and on-call rotations in the EU region.",+ auth_type="oauth",+ category="productivity",+ icon_domain="pagerduty.com",+ ),+ CatalogEntry(+ name="PagerDuty (US)",+ url="https://mcp.pagerduty.com/mcp",+ description="Manage PagerDuty incidents, services, schedules, and on-call rotations in the US region.",+ auth_type="oauth",+ category="productivity",+ icon_domain="pagerduty.com",+ ),+ CatalogEntry(+ name="PlanetScale",+ url="https://mcp.pscale.dev/mcp/planetscale",+ description="Manage PlanetScale databases, branches, schemas, and insights.",+ auth_type="oauth",+ category="infra",+ icon_domain="planetscale.com",+ ),+ CatalogEntry(+ name="Prisma",+ url="https://mcp.prisma.io/mcp",+ description="Manage Prisma Postgres databases and ORM workflows.",+ auth_type="oauth",+ category="infra",+ icon_domain="prisma.io",+ ),+ CatalogEntry(+ name="Render",+ url="https://mcp.render.com/mcp",+ description="Deploy, debug, and monitor applications on Render.",+ auth_type="api_key",+ category="dev",+ icon_domain="render.com",+ ),+ CatalogEntry(+ name="Sanity",+ url="https://mcp.sanity.io",+ description="Work with Sanity content studio, schemas, and structured content.",+ auth_type="oauth",+ category="dev",+ icon_domain="sanity.io",+ ),+ CatalogEntry(+ name="Semgrep",+ url="https://mcp.semgrep.ai/mcp",+ description="Run Semgrep static analysis and security scans.",+ auth_type="oauth",+ category="dev",+ icon_domain="semgrep.dev",+ ),+ CatalogEntry(+ name="Sentry",+ url="https://mcp.sentry.dev/mcp",+ description="Inspect Sentry errors, traces, issues, and release context.",+ auth_type="oauth",+ category="dev",+ icon_domain="sentry.io",+ ),+ CatalogEntry(+ name="Slack",+ url="https://mcp.slack.com/mcp",+ description="Search Slack channels, send messages, and access workspace context.",+ auth_type="oauth",+ category="productivity",+ icon_domain="slack.com",+ ),+ CatalogEntry(+ name="Sourcegraph",+ url="https://sourcegraph.com/.api/mcp/v1",+ description="Search code and retrieve code intelligence across repos.",+ auth_type="oauth",+ category="dev",+ icon_domain="sourcegraph.com",+ ),+ CatalogEntry(+ name="Stripe",+ url="https://mcp.stripe.com",+ description="Manage Stripe payments, billing, and API integration context.",+ auth_type="oauth",+ category="business",+ icon_domain="stripe.com",+ ),+ CatalogEntry(+ name="Supabase",+ url="https://mcp.supabase.com/mcp",+ description="Manage Supabase projects, databases, and branches.",+ auth_type="oauth",+ category="infra",+ icon_domain="supabase.com",+ ),+ CatalogEntry(+ name="Svelte",+ url="https://mcp.svelte.dev/mcp",+ description="Access Svelte docs and framework development workflows.",+ auth_type="oauth",+ category="dev",+ icon_domain="svelte.dev",+ ),+ CatalogEntry(+ name="ThoughtSpot",+ url="https://agent.thoughtspot.app/mcp",+ description="Search ThoughtSpot developer docs and embedded analytics APIs.",+ auth_type="oauth",+ category="dev",+ icon_domain="thoughtspot.com",+ ),+ CatalogEntry(+ name="Wix",+ url="https://mcp.wix.com/mcp",+ description="Manage Wix sites, apps, and dashboard extensions.",+ auth_type="oauth",+ category="business",+ icon_domain="wix.com",+ ),+]diff --git a/products/mcp_store/backend/catalog_sync.py b/products/mcp_store/backend/catalog_sync.pynew file mode 100644index 000000000000..67c21daac379--- /dev/null+++ b/products/mcp_store/backend/catalog_sync.py@@ -0,0 +1,168 @@+"""Sync the code-defined catalog (``catalog.py``) into ``MCPServerTemplate`` rows.++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,+ ``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.+- **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.++ 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+ identity is established by human review of the ``catalog.py`` PR (CODEOWNERS-gated),+ not by anything in this module.+"""++from dataclasses import dataclass++from django.db import IntegrityError++import structlog++from .catalog import MCP_SERVER_CATALOG, CatalogEntry+from .models import MCPServerTemplate+from .probe import ProbeResult, probe_mcp_server++logger = structlog.get_logger(__name__)++_CONTENT_FIELDS = ("name", "description", "auth_type", "category", "icon_domain", "docs_url")+++@dataclass+class SyncCounts:+ created: int = 0+ activated: int = 0+ updated: int = 0+ unchanged: int = 0+ failed: int = 0+++def _activation_allowed(entry: CatalogEntry, probe: ProbeResult) -> bool:+ """The probe must pass *and* agree with the auth model the catalog declares — a probe+ that classifies an "api_key" entry as OAuth (or vice versa) means the entry is wrong,+ not that the server is ready for users."""+ if not probe.passed_activation_gate:+ return False+ if entry.auth_type == "api_key":+ # A reachable but auth-walled endpoint ("api_key_or_unknown") never passes the+ # gate — a bare 401/403 proves nothing about MCP — so agreement here means the+ # handshake completed without credentials.+ return probe.auth_flavor == "open"+ return probe.auth_flavor == "oauth_dcr"+++def _create_template(entry: CatalogEntry, skip_probe: bool, counts: SyncCounts) -> None:+ 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,+ docs_url=entry.docs_url,+ is_active=False,+ )+ counts.created += 1+ if skip_probe:+ 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:+ logger.warning(+ "mcp_catalog_sync.created_inactive",+ url=entry.url,+ auth_flavor=probe.auth_flavor,+ probe_errors=probe.errors,+ )+ if update_fields:+ 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+ for f in changed:+ setattr(template, f, getattr(entry, f))+ if "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.+ template.is_active = False+ changed.append("is_active")+ logger.warning(+ "mcp_catalog_sync.deactivated_on_auth_type_change",+ url=entry.url,+ auth_type=entry.auth_type,+ )+ template.save(update_fields=[*changed, "updated_at"])+ counts.updated += 1+++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()+ if template is None:+ try:+ _create_template(entry, skip_probe, counts)+ except IntegrityError:+ # Lost a create race (unique url) — the winner owns creation+probe.+ counts.unchanged += 1+ else:+ _update_template(template, entry, counts)+ except Exception:+ logger.exception("mcp_catalog_sync.entry_failed", url=entry.url)+ counts.failed += 1+ orphaned_active = list(+ MCPServerTemplate.objects.filter(is_active=True)+ .exclude(url__in=[e.url for e in catalog])+ .values_list("url", flat=True)+ )+ if orphaned_active:+ # Either an admin-added row (consider folding it into the catalog) or a row+ # orphaned by a catalog url edit — the latter keeps serving installs forever+ # unless an operator notices and retires it.+ logger.warning("mcp_catalog_sync.active_rows_not_in_catalog", urls=orphaned_active)+ logger.info(+ "mcp_catalog_sync.done",+ created=counts.created,+ activated=counts.activated,+ updated=counts.updated,+ unchanged=counts.unchanged,+ failed=counts.failed,+ )+ return countsdiff --git a/products/mcp_store/backend/management/commands/sync_mcp_server_templates.py b/products/mcp_store/backend/management/commands/sync_mcp_server_templates.pynew file mode 100644index 000000000000..e6f841315a01--- /dev/null+++ b/products/mcp_store/backend/management/commands/sync_mcp_server_templates.py@@ -0,0 +1,23 @@+from typing import Any++from django.core.management.base import BaseCommand++from products.mcp_store.backend.catalog_sync import sync_mcp_catalog+++class Command(BaseCommand):+ help = "Sync the code-defined MCP server catalog (catalog.py) into MCPServerTemplate rows"++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument(+ "--skip-probe",+ action="store_true",+ help="Create new entries without probing them (they stay inactive until probed or activated in admin)",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ counts = sync_mcp_catalog(skip_probe=options["skip_probe"])+ self.stdout.write(+ f"created={counts.created} activated={counts.activated} updated={counts.updated} "+ f"unchanged={counts.unchanged} failed={counts.failed}"+ )diff --git a/products/mcp_store/backend/tasks/tasks.py b/products/mcp_store/backend/tasks/tasks.pyindex 5c1353197cdf..16c18fa4c150 100644--- a/products/mcp_store/backend/tasks/tasks.py+++ b/products/mcp_store/backend/tasks/tasks.py@@ -1,14 +1,48 @@import structlogfrom celery import shared_task+from posthog.redis import get_clientfrom posthog.scoping_audit import skip_team_scope_audit+from ..catalog_sync import sync_mcp_catalogfrom ..models import MCPServerInstallationfrom ..tools import ToolsFetchError, sync_installation_toolslogger = structlog.get_logger(__name__)+@shared_task(ignore_result=True)+@skip_team_scope_audit+def sync_mcp_server_templates_task() -> None:+ sync_mcp_catalog()+++def queue_sync_mcp_server_templates() -> None:+ """Queue the catalog sync once per deploy window (Redis lock so only one pod runs it)."""+ lock_key = "posthog_sync_mcp_server_templates_task_lock"+ try:+ r = get_client()+ # nx+ex in one call — a crash between a separate setnx and expire would leave+ # a TTL-less key that permanently skips the sync.+ if not r.set(lock_key, 1, nx=True, ex=60 * 60):+ logger.info("Not queuing sync_mcp_server_templates task: lock already set")+ return+ except Exception:+ logger.exception("Failed to acquire sync_mcp_server_templates lock")+ return+ try:+ logger.info("Queuing sync_mcp_server_templates celery task (redis lock)")+ sync_mcp_server_templates_task.delay()+ except Exception:+ logger.exception("Failed to queue sync_mcp_server_templates celery task")+ try:+ # Give the lock back so the next pod startup retries the enqueue instead+ # of the sync silently dropping for the whole lock window.+ r.delete(lock_key)+ except Exception:+ logger.exception("Failed to release sync_mcp_server_templates lock")++@shared_task(ignore_result=True)@skip_team_scope_auditdef sync_installation_tools_task(installation_id: str) -> None:diff --git a/products/mcp_store/backend/test/test_catalog_sync.py b/products/mcp_store/backend/test/test_catalog_sync.pynew file mode 100644index 000000000000..a5cc1689ba02--- /dev/null+++ b/products/mcp_store/backend/test/test_catalog_sync.py@@ -0,0 +1,217 @@+from unittest.mock import patch++from django.test import SimpleTestCase, TestCase++from parameterized import parameterized++from products.mcp_store.backend.catalog import MCP_SERVER_CATALOG, CatalogEntry+from products.mcp_store.backend.catalog_sync import sync_mcp_catalog+from products.mcp_store.backend.models import (+ AUTH_TYPE_CHOICES,+ CATEGORY_CHOICES,+ MCPServerTemplate,+ normalize_mcp_icon_domain,+)+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 _dcr_pass_probe() -> ProbeResult:+ return ProbeResult(+ reachable=True,+ speaks_mcp=True,+ auth_flavor="oauth_dcr",+ oauth_metadata={"issuer": "https://auth.linear.app", "registration_endpoint": "https://auth.linear.app/reg"},+ dcr_registered=True,+ authorize_endpoint_ok=True,+ )+++class TestCatalogEntries(SimpleTestCase):+ def test_catalog_entries_are_valid(self):+ # A typo'd category/auth_type or duplicate url in a future catalog PR would otherwise+ # only surface as a failed sync in production — this is the pre-merge guard. Format+ # checks only: whether a url actually belongs to the named vendor is established by+ # human review of catalog.py (CODEOWNERS-gated), not by this test.+ urls = [entry.url for entry in MCP_SERVER_CATALOG]+ assert len(urls) == len(set(urls))+ for entry in MCP_SERVER_CATALOG:+ assert entry.auth_type in VALID_AUTH_TYPES, entry.url+ assert entry.category in VALID_CATEGORIES, entry.url+ 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+++class TestSyncMCPCatalog(TestCase):+ @parameterized.expand(+ [+ ("oauth_dcr_pass", _entry(), _dcr_pass_probe(), True),+ (+ "oauth_shared_needs_operator",+ _entry(),+ ProbeResult(+ reachable=True,+ speaks_mcp=True,+ auth_flavor="oauth_shared",+ oauth_metadata={"issuer": "https://auth.linear.app"},+ ),+ False,+ ),+ (+ "api_key_open_handshake_pass",+ _entry(auth_type="api_key"),+ ProbeResult(reachable=True, speaks_mcp=True, auth_flavor="open"),+ True,+ ),+ # A reachable but auth-walled endpoint proves nothing about MCP, so the entry+ # must stay inactive for an operator to vet and activate in admin.+ (+ "api_key_auth_walled_stays_inactive",+ _entry(auth_type="api_key"),+ ProbeResult(reachable=True, speaks_mcp=False, auth_flavor="api_key_or_unknown"),+ False,+ ),+ ("unreachable", _entry(), ProbeResult(reachable=False), False),+ # The probe saying "this is a DCR OAuth server" for a catalog entry declared api_key+ # means the entry is wrong — it must not activate even though the probe passed.+ ("flavor_disagrees_with_catalog", _entry(auth_type="api_key"), _dcr_pass_probe(), False),+ ]+ )+ def test_created_entries_gate_activation_on_probe(self, _name, entry, probe_result, expect_active):+ 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)+ 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+ if probe_result.oauth_metadata:+ assert template.oauth_metadata == probe_result.oauth_metadata+ assert template.oauth_issuer_url == probe_result.oauth_metadata.get("issuer", "")++ 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.+ template = MCPServerTemplate.objects.create(+ name="Linear",+ url="https://mcp.linear.app/mcp",+ description="Old description.",+ auth_type="oauth",+ category="productivity",+ is_active=True,+ oauth_metadata={"authorization_endpoint": "https://auth.linear.app/authorize"},+ oauth_credentials={"client_id": "shared-client", "client_secret": "shhh"},+ )++ 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")])++ probe_mock.assert_not_called()+ template.refresh_from_db()+ assert counts.updated == 1+ assert template.description == "New description."+ assert template.category == "dev"+ 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"}++ def test_auth_type_change_deactivates_active_template(self):+ # An active row was vetted under its old auth model; letting a catalog auth_type+ # flip through while it stays active would route new installs down the wrong+ # auth branch (e.g. the API-key path with no key provisioned).+ template = MCPServerTemplate.objects.create(+ name="Linear",+ url="https://mcp.linear.app/mcp",+ description="Manage Linear issues.",+ auth_type="api_key",+ category="dev",+ is_active=True,+ oauth_credentials={"client_id": "shared-client", "client_secret": "shhh"},+ )++ with patch("products.mcp_store.backend.catalog_sync.probe_mcp_server") as probe_mock:+ counts = sync_mcp_catalog(entries=[_entry(auth_type="oauth")])++ probe_mock.assert_not_called()+ template.refresh_from_db()+ assert counts.updated == 1+ assert template.auth_type == "oauth"+ assert template.is_active is False+ assert template.oauth_credentials == {"client_id": "shared-client", "client_secret": "shhh"}++ def test_identical_entry_is_a_noop_without_probing(self):+ entry = _entry()+ with patch("products.mcp_store.backend.catalog_sync.probe_mcp_server", return_value=_dcr_pass_probe()):+ sync_mcp_catalog(entries=[entry])++ with patch("products.mcp_store.backend.catalog_sync.probe_mcp_server") as probe_mock:+ counts = sync_mcp_catalog(entries=[entry])++ probe_mock.assert_not_called()+ assert counts.unchanged == 1+ assert MCPServerTemplate.objects.filter(url=entry.url).count() == 1++ def test_skip_probe_creates_inactive(self):+ with patch("products.mcp_store.backend.catalog_sync.probe_mcp_server") as probe_mock:+ counts = sync_mcp_catalog(entries=[_entry()], skip_probe=True)++ probe_mock.assert_not_called()+ assert counts.created == 1+ assert MCPServerTemplate.objects.get(url=_entry().url).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.+ MCPServerTemplate.objects.create(name="Linear", url=_entry().url, auth_type="oauth", is_active=True)+ orphan = MCPServerTemplate.objects.create(+ name="Old Linear", url="https://legacy.linear.app/mcp", auth_type="oauth", is_active=True+ )+ MCPServerTemplate.objects.create(+ name="Inactive orphan", url="https://gone.example/mcp", auth_type="oauth", is_active=False+ )++ with patch("products.mcp_store.backend.catalog_sync.logger") as logger_mock:+ sync_mcp_catalog(entries=[_entry()])++ warned_urls = [+ call.kwargs["urls"]+ for call in logger_mock.warning.call_args_list+ if call.args[0] == "mcp_catalog_sync.active_rows_not_in_catalog"+ ]+ assert warned_urls == [[orphan.url]]++ def test_one_bad_entry_does_not_stop_the_sync(self):+ # category outside the model's choices makes .create raise only on full_clean, so use a+ # probe explosion instead — the loop must isolate per-entry failures.+ good = _entry()+ bad = _entry(url="https://mcp.broken.example/mcp", name="Broken")++ def _probe(url: str) -> ProbeResult:+ if "broken" in url:+ raise RuntimeError("boom")+ return _dcr_pass_probe()++ with patch("products.mcp_store.backend.catalog_sync.probe_mcp_server", side_effect=_probe):+ counts = sync_mcp_catalog(entries=[bad, good])++ assert counts.failed == 1+ assert counts.created >= 1+ assert MCPServerTemplate.objects.filter(url=good.url, is_active=True).exists()