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-registry): ranked MCP server registry built on MCP Analytics signal (#85710)

Daniel Viscaa0b6303580d1
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index f63d47e1cd96..387637da3b8e 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -298,6 +298,10 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"CommunitySkillFile", # bundled files of a CommunitySkill (scoped via the catalog row)
"HogFunctionTemplate",
"MCPServer",
+ "MCPRegistryServer", # instance-global MCP registry index, crawled from the official registry
+ "MCPRegistryTool", # tools of an MCPRegistryServer (scoped via the catalog row)
+ "MCPRankingRun", # one scoring pass over the global registry index
+ "MCPRankingScore", # per-server score of an MCPRankingRun (scoped via the run/catalog rows)
# --- Special (has source_team + destination_team, not a plain team) ---
"ResourceTransfer",
# --- Organization-scoped (correctly above team level) ---
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index b2c325147fef..7e031356720b 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -269,6 +269,7 @@ rules:
|MCPGatewayServer
|MCPIntentClusterSnapshot
|MCPIntentEmbeddingCache
+ |MCPMeasuredStats
|MCPMemberServerRevocation
|MCPOrgRule
|MCPServiceAccount
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6e03463c35c8..6aaa77d5f1b4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3869,6 +3869,8 @@ importers:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ products/mcp_registry: {}
+
products/mcp_store:
dependencies:
'@posthog/icons':
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index e505ff46b9c7..c5350c53c883 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -88,6 +88,7 @@ PRODUCTS_APPS = [
"products.dashboards.backend.apps.DashboardsConfig",
"products.messaging.backend.apps.MessagingConfig",
"products.mcp_analytics.backend.apps.McpAnalyticsConfig",
+ "products.mcp_registry.backend.apps.McpRegistryConfig",
"products.platform_features.backend.apps.PlatformFeaturesConfig",
"products.streamlit_apps.backend.apps.StreamlitAppsConfig",
"products.legal_documents.backend.apps.LegalDocumentsConfig",
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 790967576e07..ea6134cb92ef 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -99,6 +99,7 @@ from products.feature_flags.backend.tasks import (
)
from products.legal_documents.backend.facade.tasks import reconcile_pending_legal_documents
from products.logs.backend.facade.tasks import logs_alert_events_cleanup_task
+from products.mcp_registry.backend.facade.tasks import MCP_REGISTRY_SYNC_CRONTAB, run_mcp_registry_sync
from products.pulse.backend.tasks import mark_stale_pulse_briefs_failed
from products.reminders.backend.tasks import process_due_reminders
from products.signals.backend.tasks import (
@@ -1005,3 +1006,11 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
send_daily_digests.s(),
name="stamphog daily merged-pr digests",
)
+
+ # MCP registry daily sync: crawl the official registry, aggregate measured servers,
+ # probe stale servers, recompute rankings. Flag-gated inside the task.
+ sender.add_periodic_task(
+ MCP_REGISTRY_SYNC_CRONTAB,
+ run_mcp_registry_sync.s(),
+ name="mcp registry daily sync",
+ )
diff --git a/products/data_catalog/frontend/dataCatalogAgentSyncLogic.ts b/products/data_catalog/frontend/dataCatalogAgentSyncLogic.ts
index 1f7667888988..421afa4466a0 100644
--- a/products/data_catalog/frontend/dataCatalogAgentSyncLogic.ts
+++ b/products/data_catalog/frontend/dataCatalogAgentSyncLogic.ts
@@ -14,6 +14,7 @@ export const METRIC_TOOLS = [
'data-catalog-metric-update',
'data-catalog-metric-delete-execute',
'data-catalog-metric-approve-execute',
+ 'data-catalog-metric-delete-execute',
'data-catalog-metrics-refresh-from-insight-create',
]
export const RELATIONSHIP_TOOLS = [
diff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.py
index 94abbf36908e..9b74a06299e7 100644
--- a/products/mcp_analytics/backend/facade/api.py
+++ b/products/mcp_analytics/backend/facade/api.py
@@ -3,11 +3,19 @@ from datetime import datetime
from django.db import transaction
from django.utils import timezone
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_expr
+
from posthog.api.capture import capture_internal
from posthog.models.team.team import Team
from posthog.models.user import User
from products.mcp_analytics.backend import logic
+from products.mcp_analytics.backend.hogql_queries.base import (
+ EFFECTIVE_DESCRIPTION_SQL,
+ EFFECTIVE_TOOL_SQL,
+ NEW_SDK_SOURCE,
+)
from products.mcp_analytics.backend.models import MCPAnalyticsSubmission
from . import contracts
@@ -236,3 +244,97 @@ def trigger_intent_cluster_recompute(team: Team, user: User | None) -> None:
updated_at=timezone.now(),
)
raise
+
+
+# ---------------------------------------------------------------------------
+# Measured-server aggregation surface (consumed by mcp_registry).
+#
+# mcp_registry's measured-server pipeline aggregates one project's new-SDK
+# $mcp_tool_call events into per-server and per-tool stats. It needs the same
+# exec-coalescing rules this product's own query runners use, so single-exec
+# servers don't collapse into one `exec` bucket. Those rules live in
+# hogql_queries/base; these helpers return them as parsed HogQL placeholders
+# (and a HogQL fragment for the one cross-team discovery question) so the
+# consumer never handles raw SQL text.
+# ---------------------------------------------------------------------------
+
+_SERVER_STATS_SELECT = """
+ SELECT
+ toString(properties.$mcp_server_name) AS server_name,
+ count() AS calls,
+ uniq(toString(properties.$mcp_session_id)) AS sessions,
+ countIf(toString(properties.$mcp_is_error) IN ('true', '1')) AS errors,
+ countIf(notEmpty(toString(properties.$mcp_intent))) AS calls_with_intent,
+ uniq({effective_tool}) AS distinct_tools,
+ uniq(toString(properties.$mcp_client_name)) AS client_names
+ FROM events
+ WHERE event = '$mcp_tool_call'
+ AND timestamp >= {date_from}
+ AND properties.$mcp_source = {source}
+ AND notEmpty(toString(properties.$mcp_server_name))
+ GROUP BY server_name
+ ORDER BY calls DESC
+"""
+
+_TOOL_STATS_SELECT = """
+ SELECT
+ {effective_tool} AS tool_name,
+ any({effective_description}) AS description,
+ count() AS calls,
+ countIf(toString(properties.$mcp_is_error) IN ('true', '1')) AS errors
+ FROM events
+ WHERE event = '$mcp_tool_call'
+ AND timestamp >= {date_from}
+ AND properties.$mcp_source = {source}
+ AND toString(properties.$mcp_server_name) = {server_name}
+ AND notEmpty({effective_tool})
+ GROUP BY tool_name
+ ORDER BY calls DESC
+ LIMIT {tool_limit}
+"""
+
+# Only the deploy-configured database name is interpolated, never caller input.
+_DISCOVERY_SQL = """
+ SELECT DISTINCT team_id
+ FROM {database}.events
+ WHERE event = '$mcp_tool_call'
+ AND timestamp >= now() - INTERVAL %(window_days)s DAY
+ AND JSONExtractString(properties, '$mcp_source') = %(source)s
+ ORDER BY team_id
+ LIMIT %(limit)s
+"""
+
+
+def measured_server_stats_select() -> str:
+ """HogQL select for per-server measured aggregates. Placeholders: date_from, source."""
+ return _SERVER_STATS_SELECT
+
+
+def measured_tool_stats_select() -> str:
+ """HogQL select for per-tool measured aggregates. Placeholders: date_from, source, server_name, tool_limit."""
+ return _TOOL_STATS_SELECT
+
+
+def measured_discovery_sql(database: str) -> str:
+ """ClickHouse SQL listing teams with recent new-SDK $mcp_tool_call traffic.
+
+ Raw ClickHouse rather than HogQL because HogQL execution is scoped to one team and
+ this is the one cross-team question the pipeline asks. Only the deploy-configured
+ database name is interpolated; the rest is parameterised by the caller.
+ """
+ return _DISCOVERY_SQL.format(database=database)
+
+
+def measured_query_placeholders(date_from: datetime) -> dict[str, ast.Expr]:
+ """The placeholder values the measured-server selects share."""
+ return {
+ "effective_tool": parse_expr(EFFECTIVE_TOOL_SQL),
+ "effective_description": parse_expr(EFFECTIVE_DESCRIPTION_SQL),
+ "date_from": ast.Constant(value=date_from),
+ "source": ast.Constant(value=NEW_SDK_SOURCE),
+ }
+
+
+def measured_source() -> str:
+ """The source marker new-SDK $mcp_tool_call events carry."""
+ return NEW_SDK_SOURCE
diff --git a/products/mcp_analytics/backend/facade/contracts.py b/products/mcp_analytics/backend/facade/contracts.py
index ce5aaae6af30..7771b8994115 100644
--- a/products/mcp_analytics/backend/facade/contracts.py
+++ b/products/mcp_analytics/backend/facade/contracts.py
@@ -282,6 +282,29 @@ class ActivityClientRow:
calls: int
+@dataclass(frozen=True)
+class MeasuredServerStatsRow:
+ """One server's aggregate over a window of new-SDK $mcp_tool_call events."""
+
+ server_name: str
+ calls: int
+ sessions: int
+ errors: int
+ calls_with_intent: int
+ distinct_tools: int
+ client_names: int
+
+
+@dataclass(frozen=True)
+class MeasuredToolStatsRow:
+ """One tool's aggregate for a server over the same window."""
+
+ tool_name: str
+ description: str
+ calls: int
+ errors: int
+
+
@dataclass(frozen=True)
class ActivityRecentCall:
timestamp: datetime
diff --git a/products/mcp_registry/README.md b/products/mcp_registry/README.md
new file mode 100644
index 000000000000..6d4484e0a9ef
--- /dev/null
+++ b/products/mcp_registry/README.md
@@ -0,0 +1,93 @@
+# MCP registry
+
+A ranked, searchable index of MCP servers: every server in the official MCP registry, fused with
+behavioral signal from MCP Analytics for the servers our customers measure. The bet: any registry
+can list MCP servers; only PostHog can rank them by what agents actually did.
+
+Backend-only for now, gated behind the `mcp-registry` feature flag.
+
+## How the index is built
+
+Four pipeline stages, run daily by `run_mcp_registry_sync` (flag-gated) or manually via
+`python manage.py sync_mcp_registry`:
+
+1. **Crawl** (`crawl.py`): pages through the official MCP registry API and upserts
+ `MCPRegistryServer` rows. The crawl owns content fields (name, description, remotes, packages)
+ and never touches operational state (probe results, measured flags).
+2. **Aggregate** (`aggregation.py`): finds projects with recent `$mcp_tool_call` traffic, and per
+ (project, advertised server) rolls up calls, sessions, errors, intent coverage, and per-tool
+ usage into `MCPMeasuredStats`. Tool grouping uses the mcp_analytics facade's
+ `EFFECTIVE_TOOL_SQL` so single-exec servers don't collapse into one `exec` bucket.
+3. **Probe** (`probe.py`): a shallow, repeatable liveness probe (initialize handshake, auth
+ classification from the 401 challenge, `tools/list` for open servers). Deliberately weaker than
+ mcp_store's activation probe, which performs a real DCR registration and therefore can't be
+ re-run; this one is side-effect-free so it can sweep the index on a schedule, stalest first.
+4. **Rank** (`ranking.py`): scores every server under every registered ranking version and
+ persists a run per version.
+
+**Linking** (`linking.py`) attaches measured signal to registry entries. It is deliberately
+conservative: a name like "posthog" also matches third-party repackages, so anything ambiguous
+becomes a standalone row with the candidates recorded, and curated overrides
+(`KNOWN_MEASURED_LINKS`) pin the known cases.
+
+## The agent-facing entry point
+
+`GET .../mcp_registry/servers/discover/?intent=<task>` is the one call an agent needs: it
+returns ranked candidates, each with its score rationale, real usage signal where we measure
+it, and connection instructions. Ranking is `fit x authority`: `relevance` (how well the
+server's own text answers the query) multiplied by the run's static score (liveness x trust).
+Neither can dominate, so a dead exact match loses and so does a high-traffic server that does
+not do the thing.
+
+Relevance is lexical today, which is the biggest known gap: it cannot match a paraphrase
+("watch user sessions" against "session replay"). Embedding-based capability search replaces
+`_relevance_annotation` in `presentation/views.py`; keeping relevance separate from the static
+score is what makes that swap local.
+
+## Iterating on ranking
+
+Ranking versions are pure functions in `ranking.py`'s `RANKING_VERSIONS`, and they are never
+edited in place. To trial a change: add a new version key, let the daily sync (or
+`compute_ranking_run`) score it, then compare orderings against the incumbent via
+`GET .../mcp_registry/servers/compare/?versions=a,b` before promoting `DEFAULT_RANKING_VERSION`.
+Scores persist per run with a component breakdown, so every ranking change stays explainable.
+
+The current versions are the core A/B of the product thesis:
+
+- `v1_metadata_prior`: liveness x public-metadata trust. The control arm any registry could build.
+- `v2_measured_trust`: v1 plus behavioral trust (reliability weighted by volume confidence) for
+ measured servers.
+
+## Connection instructions
+
+`connect.py` turns probe results into agent-executable connection instructions: methods ordered by
+how hands-off they are for the human (`agent_provisioning` > `remote_open` > `cli_auth` >
+`remote_oauth` > `remote_api_key` > `local_package`), each a list of steps typed by actor. An
+agent runs `agent` steps itself and narrates `human` steps ("Create an API key here, then paste
+it") to the user. Per-server knowledge probing can't discover lives in `connect_overrides` on the
+row, seeded by `KNOWN_CONNECT_OVERRIDES`.
+
+For [Stripe Projects](https://docs.stripe.com/stripe-projects) partner providers (Vercel,
+Supabase, Neon, Clerk, PostHog, and others), `agent_provisioning` is concrete today: the agent
+runs `stripe projects service add <provider>`, the service is provisioned into the user's own
+provider account, and agent-readable credentials land in the project's secret store. The human's
+only step is the one-time Stripe prompt. `STRIPE_PROJECTS_PROVIDERS` holds the curated partner
+map.
+
+## Data boundaries
+
+- Registry rows and tools are instance-global (public data plus our probes); there is no team FK.
+- `MCPMeasuredStats.team_id` is provenance (which MCP Analytics project produced the aggregate),
+ not access scoping.
+- `measured_public` on a server defaults to False: measured stats are the server owner's analytics
+ data, and showing them outside PostHog requires their opt-in. Until that flow exists the whole
+ product stays internal behind the feature flag.
+
+## Not built yet
+
+- Embedding-based capability search (tool-level retrieval, arXiv:2511.01854) behind the existing
+ `?search=` parameter.
+- `discover` as an actual MCP tool in `services/mcp`. The HTTP endpoint exists; exposing it over
+ the MCP protocol is what makes the registry itself the one server an agent connects to.
+- `report_outcome` feedback ingestion (needs anti-gaming design).
+- A web UI; mcp_store's marketplace is the likely surface.
diff --git a/products/mcp_registry/__init__.py b/products/mcp_registry/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/mcp_registry/backend/__init__.py b/products/mcp_registry/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/mcp_registry/backend/aggregation.py b/products/mcp_registry/backend/aggregation.py
new file mode 100644
index 000000000000..cf776f1aefa2
--- /dev/null
+++ b/products/mcp_registry/backend/aggregation.py
@@ -0,0 +1,147 @@
+"""Cross-team aggregation of MCP Analytics signal into the registry index.
+
+For every project with recent $mcp_tool_call traffic, roll each advertised server up
+to one stats row (volume, reliability, intent coverage) plus per-tool usage, then
+attach it to a registry server row via linking. Tool grouping goes through the
+mcp_analytics facade so single-exec servers don't collapse into one `exec` bucket.
+"""
+
+from datetime import datetime, timedelta
+from typing import Any
+
+from django.conf import settings
+from django.utils import timezone
+
+import structlog
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.team.team import Team
+
+from products.mcp_analytics.backend.facade import api as mcp_analytics_api
+from products.mcp_registry.backend.constants import MEASURED_TEAM_LIMIT, MEASURED_TOOL_LIMIT, MEASURED_WINDOW_DAYS
+from products.mcp_registry.backend.linking import resolve_measured_server
+from products.mcp_registry.backend.models import MCPMeasuredStats, MCPRegistryServer, MCPRegistryTool
+
+logger = structlog.get_logger(__name__)
+
+
+def discover_measured_teams(window_days: int = MEASURED_WINDOW_DAYS, limit: int = MEASURED_TEAM_LIMIT) -> list[int]:
+ """Projects with recent MCP Analytics traffic: the measured-server universe.
+
+ Raw ClickHouse rather than HogQL because HogQL execution is scoped to one team and
+ this is the one cross-team question the pipeline asks. The table is qualified
+ because the connection's default database is not the posthog database in every
+ environment.
+ """
+ sql = mcp_analytics_api.measured_discovery_sql(settings.CLICKHOUSE_DATABASE)
+ rows = sync_execute(
+ sql,
+ {"window_days": window_days, "source": mcp_analytics_api.measured_source(), "limit": limit},
+ )
+ return [row[0] for row in rows or []]
+
+
+def aggregate_team(team: Team, window_days: int = MEASURED_WINDOW_DAYS) -> int:
+ """Upsert measured stats + tool rows for every server seen in one team. Returns server count."""
+ date_from = timezone.now() - timedelta(days=window_days)
+ placeholders = mcp_analytics_api.measured_query_placeholders(date_from)
+ with tags_context(product=Product.MCP, feature=Feature.QUERY, team_id=team.id):
+ stats_response = execute_hogql_query(
+ query=parse_select(mcp_analytics_api.measured_server_stats_select(), placeholders=placeholders),
+ team=team,
+ query_type="mcp_registry_server_stats",
+ )
+
+ computed_at = timezone.now()
+ processed = 0
+ for server_name, calls, sessions, errors, calls_with_intent, distinct_tools, client_names in (
+ stats_response.results or []
+ ):
+ tool_placeholders = {**mcp_analytics_api.measured_query_placeholders(date_from)}
+ tool_placeholders["server_name"] = ast.Constant(value=server_name)
+ tool_placeholders["tool_limit"] = ast.Constant(value=MEASURED_TOOL_LIMIT)
+ with tags_context(product=Product.MCP, feature=Feature.QUERY, team_id=team.id):
+ tools_response = execute_hogql_query(
+ query=parse_select(mcp_analytics_api.measured_tool_stats_select(), placeholders=tool_placeholders),
+ team=team,
+ query_type="mcp_registry_tool_stats",
+ )
+ tool_rows = tools_response.results or []
+
+ resolution = resolve_measured_server(server_name)
+ MCPMeasuredStats.objects.for_team(team.id).update_or_create(
+ team_id=team.id,
+ server_name=server_name,
+ defaults={
+ "server": resolution.server,
+ "window_days": window_days,
+ "calls": calls,
+ "sessions": sessions,
+ "errors": errors,
+ "error_rate_pct": round(100 * errors / calls, 2) if calls else 0.0,
+ "intent_coverage_pct": round(100 * calls_with_intent / calls, 2) if calls else 0.0,
+ "distinct_tools": distinct_tools,
+ "harness_count": client_names,
+ "tool_stats": [
+ {
+ "name": tool_name,
+ "calls": tool_calls,
+ "errors": tool_errors,
+ "error_rate_pct": round(100 * tool_errors / tool_calls, 2) if tool_calls else 0.0,
+ }
+ for tool_name, _description, tool_calls, tool_errors in tool_rows
+ ],
+ "link_method": resolution.link_method,
+ "link_candidates": resolution.link_candidates,
+ "computed_at": computed_at,
+ },
+ )
+ _upsert_analytics_tools(resolution.server, tool_rows, computed_at)
+ processed += 1
+
+ logger.info("mcp_registry.aggregate.team_done", team_id=team.id, servers=processed)
+ return processed
+
+
+def _upsert_analytics_tools(server: MCPRegistryServer, tool_rows: list[Any], seen_at: datetime) -> None:
+ """Record usage-observed tools. A probed tools/list row is authoritative for
+ schema/description, so analytics only refreshes last_seen_at on those."""
+ existing = {tool.name: tool for tool in server.tools.all()}
+ for tool_name, description, _calls, _errors in tool_rows:
+ tool = existing.get(tool_name)
+ if tool is None:
+ MCPRegistryTool.objects.create(
+ server=server,
+ name=tool_name,
+ description=description or "",
+ source="analytics",
+ last_seen_at=seen_at,
+ )
+ elif tool.source == "analytics":
+ tool.description = description or tool.description
+ tool.last_seen_at = seen_at
+ tool.save(update_fields=["description", "last_seen_at", "updated_at"])
+ else:
+ tool.last_seen_at = seen_at
+ tool.save(update_fields=["last_seen_at", "updated_at"])
+
+
+def aggregate_measured_servers(window_days: int = MEASURED_WINDOW_DAYS) -> int:
+ """Aggregate every discovered team. Returns total measured (team, server) pairs."""
+ total = 0
+ for team_id in discover_measured_teams(window_days):
+ try:
+ team = Team.objects.get(pk=team_id)
+ except Team.DoesNotExist:
+ continue
+ try:
+ total += aggregate_team(team, window_days)
+ except Exception:
+ # One bad team must not sink the sweep; the next run retries it.
+ logger.exception("mcp_registry.aggregate.team_failed", team_id=team_id)
+ return total
diff --git a/products/mcp_registry/backend/apps.py b/products/mcp_registry/backend/apps.py
new file mode 100644
index 000000000000..ad2dbe388185
--- /dev/null
+++ b/products/mcp_registry/backend/apps.py
@@ -0,0 +1,8 @@
+from django.apps import AppConfig
+
+
+class McpRegistryConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.mcp_registry.backend"
+ label = "mcp_registry"
+ verbose_name = "MCP REGISTRY"
diff --git a/products/mcp_registry/backend/connect.py b/products/mcp_registry/backend/connect.py
new file mode 100644
index 000000000000..4c2effeff6d8
--- /dev/null
+++ b/products/mcp_registry/backend/connect.py
@@ -0,0 +1,319 @@
+"""Connection instructions: how an agent gets from "found a server" to "using it".
+
+The instruction set is a list of methods ordered by how hands-off they are for the
+human, each made of actor-typed steps (``agent`` executes autonomously, ``human`` is
+a step only a person can do). Agents should attempt the first method and read a
+human step as "narrate this to the user, then wait", e.g. "Create an account at X
+and paste the API key", which is exactly the walk-through UX the instructions exist
+to drive.
+
+Method taxonomy, most to least automated:
+
+- ``agent_provisioning``: an agent can provision an account/credential itself,
+ either through a vendor-specific API the server declares support for, or through
+ Stripe Projects (https://docs.stripe.com/stripe-projects) for its partner
+ providers: the Stripe CLI provisions the service in the user's own provider
+ account and delivers agent-readable credentials to a secret store. Always
+ preferred when available.
+- ``remote_open``: hosted server, no auth. Agent connects instantly.
+- ``cli_auth``: the vendor's own CLI can mint local credentials (``<vendor> login``)
+ that the MCP server or agent then reuses; often one browser tap, sometimes zero if
+ the user already logged in for other work.
+- ``remote_oauth``: standard MCP OAuth (discovery + DCR); the human's only step is
+ the consent click in the browser. An agent with browser control can even drive the
+ consent page itself, subject to the user's approval.
+- ``remote_api_key``: the human must mint a key on the vendor's site; the agent
+ tells them exactly where and takes over from paste onward.
+- ``local_package``: no hosted remote; the agent runs the published package locally.
+
+Values that a registry publisher controls (a remote URL, a package identifier) are
+shell-quoted before they reach a ``command`` string. An agent is told to run these
+verbatim, so a URL carrying shell syntax would otherwise run whatever it appended.
+
+Defaults are derived from probe results (auth_method, remotes, packages). Per-server
+knowledge that probing can't discover (signup URLs, key locations, CLI commands,
+agent-provisioning endpoints) lives in ``connect_overrides`` on the row, with a
+small curated seed in KNOWN_CONNECT_OVERRIDES.
+"""
+
+import re
+import shlex
+from typing import Any
+from urllib.parse import urlparse
+
+from products.mcp_registry.backend.models import MCPRegistryServer
+
+# Stripe Projects partner providers (developer preview), keyed by the vendor's
+# verified domain and valued with the provider slug `stripe projects service add`
+# expects. Domain, not name: the official registry validates reverse-DNS namespace
+# ownership (com.vercel/* requires owning vercel.com) while display names are
+# freely squattable, and the live index does contain third-party repackages named
+# exactly "vercel". Partner list: https://docs.stripe.com/stripe-projects
+STRIPE_PROJECTS_PROVIDERS: dict[str, str] = {
+ "clerk.com": "clerk",
+ "klaviyo.com": "klaviyo",
+ "neon.tech": "neon",
+ "onkernel.com": "kernel",
+ "planetscale.com": "planetscale",
+ "posthog.com": "posthog",
+ "railway.app": "railway",
+ "railway.com": "railway",
+ "runloop.ai": "runloop",
+ "supabase.com": "supabase",
+ "trychroma.com": "chroma",
+ "turso.tech": "turso",
+ "vercel.com": "vercel",
+}
+
+
+def _domain_matches(host: str, domain: str) -> bool:
+ return host == domain or host.endswith(f".{domain}")
+
+
+def _stripe_projects_provider(server: MCPRegistryServer) -> str | None:
+ """Resolve a server to a Stripe Projects provider via vendor-owned signals only:
+ the reverse-DNS registry namespace and the hosted remote's domain."""
+ hosts: list[str] = []
+ if server.registry_name and "/" in server.registry_name:
+ namespace = server.registry_name.split("/", 1)[0]
+ hosts.append(".".join(reversed(namespace.lower().split("."))))
+ if server.canonical_url:
+ parsed_host = urlparse(server.canonical_url).hostname
+ if parsed_host:
+ hosts.append(parsed_host.lower())
+ for domain, provider in STRIPE_PROJECTS_PROVIDERS.items():
+ if any(_domain_matches(host, domain) for host in hosts):
+ return provider
+ return None
+
+
+# Curated per-server overrides, keyed by registry name. Same shape as the
+# connect_overrides JSON field: {"methods": [...]} replaces the derived methods,
+# {"extra_methods": [...]} prepends. Row-level overrides win over this seed.
+KNOWN_CONNECT_OVERRIDES: dict[str, dict[str, Any]] = {
+ "io.github.PostHog/mcp": {
+ "extra_methods": [
+ {
+ "method": "remote_api_key",
+ "automation": "human_required",
+ "summary": "Fallback when OAuth is unavailable: connect with a personal API key.",
+ "steps": [
+ {
+ "actor": "human",
+ "description": (
+ "Create a personal API key in PostHog under Settings -> Personal API keys, "
+ "with the scopes the agent asks for."
+ ),
+ "command": None,
+ },
+ {
+ "actor": "agent",
+ "description": "Add the server with the provided key as a Bearer token.",
+ "command": 'claude mcp add posthog --transport http https://mcp.posthog.com/mcp --header "Authorization: Bearer ${POSTHOG_API_KEY}"',
+ },
+ ],
+ }
+ ],
+ },
+}
+
+
+def _slug(server: MCPRegistryServer) -> str:
+ base = server.registry_name.rsplit("/", 1)[-1] if server.registry_name else server.display_name
+ return re.sub(r"[^a-z0-9-]+", "-", base.lower()).strip("-") or "server"
+
+
+def _remote_url(server: MCPRegistryServer) -> str:
+ return server.canonical_url
+
+
+def _derived_methods(server: MCPRegistryServer) -> list[dict[str, Any]]:
+ methods: list[dict[str, Any]] = []
+ slug = _slug(server)
+ url = _remote_url(server)
+
+ stripe_provider = _stripe_projects_provider(server)
+ if stripe_provider:
+ methods.append(
+ {
+ "method": "agent_provisioning",
+ "automation": "one_click",
+ "summary": "Stripe Projects partner: the agent provisions the account and credentials via the "
+ "Stripe CLI; the human only approves the one-time Stripe prompt (and any paid plan).",
+ "steps": [
+ {
+ "actor": "agent",
+ "description": "Provision the service into the user's own provider account; credentials "
+ "land in the project's secret store, agent-readable.",
+ "command": f"stripe projects service add {stripe_provider}",
+ },
+ {
+ "actor": "human",
+ "description": "Approve the Stripe prompt if this is the first provisioned service or a "
+ "paid plan is selected.",
+ "command": None,
+ },
+ {
+ "actor": "agent",
+ "description": "Connect the MCP server using the provisioned credential from the secret "
+ "store, then verify with a test call.",
+ "command": None,
+ },
+ ],
+ }
+ )
+
+ if server.supports_agent_provisioning and url:
+ methods.append(
+ {
+ "method": "agent_provisioning",
+ "automation": "full",
+ "summary": "The vendor lets agents provision an account/credential via API, with no human steps.",
+ "steps": [
+ {
+ "actor": "agent",
+ "description": "Provision a credential through the vendor's agent-signup API, then connect.",
+ "command": None,
+ }
+ ],
+ }
+ )
+
+ if url and server.liveness == "alive_open":
+ methods.append(
+ {
+ "method": "remote_open",
+ "automation": "full",
+ "summary": "Hosted server with no auth; connects instantly.",
+ "steps": [
+ {
+ "actor": "agent",
+ "description": "Add the server and start calling tools.",
+ "command": f"claude mcp add {slug} --transport http {shlex.quote(url)}",
+ }
+ ],
+ }
+ )
+ elif url and server.auth_method == "oauth":
+ methods.append(
+ {
+ "method": "remote_oauth",
+ "automation": "one_click",
+ "summary": "OAuth server; the only human step is the consent click in the browser.",
+ "steps": [
+ {
+ "actor": "agent",
+ "description": "Add the server; the client runs OAuth discovery and registration.",
+ "command": f"claude mcp add {slug} --transport http {shlex.quote(url)}",
+ },
+ {
+ "actor": "human",
+ "description": "Approve the consent screen that opens in the browser.",
+ "command": None,
+ },
+ ],
+ }
+ )
+ elif url and server.auth_method == "api_key":
+ methods.append(
+ {
+ "method": "remote_api_key",
+ "automation": "human_required",
+ "summary": "Requires an API key minted by the user on the vendor's site.",
+ "steps": [
+ {
+ "actor": "human",
+ "description": (
+ f"Create an account / API key with the vendor"
+ + (f" (docs: {server.website_url})" if server.website_url else "")
+ + ", then hand the key to the agent."
+ ),
+ "command": None,
+ },
+ {
+ "actor": "agent",
+ "description": "Add the server with the provided key and verify the connection.",
+ "command": f'claude mcp add {slug} --transport http {shlex.quote(url)} --header "Authorization: Bearer ${{API_KEY}}"',
+ },
+ ],
+ }
+ )
+ elif url:
+ methods.append(
+ {
+ "method": "remote_oauth",
+ "automation": "one_click",
+ "summary": "Hosted server behind auth (method unverified); attempt the standard OAuth flow first.",
+ "steps": [
+ {
+ "actor": "agent",
+ "description": "Add the server and attempt OAuth; fall back to asking the user for a key.",
+ "command": f"claude mcp add {slug} --transport http {shlex.quote(url)}",
+ },
+ {
+ "actor": "human",
+ "description": "Approve the consent screen if one opens; otherwise provide a key when asked.",
+ "command": None,
+ },
+ ],
+ }
+ )
+
+ package = next((p for p in server.packages if p.get("registry_type") in (None, "npm")), None)
+ if package:
+ version = str(package.get("version") or "")
+ spec = f"{package['identifier']}@{version}" if version else str(package["identifier"])
+ steps: list[dict[str, Any]] = [
+ {
+ "actor": "agent",
+ "description": "Add the server as a local process.",
+ "command": f"claude mcp add {slug} -- npx -y {shlex.quote(spec)}",
+ }
+ ]
+ if not version:
+ # An unpinned spec resolves whatever is latest when the agent runs it, so a
+ # publisher can list something benign and replace it later. Nobody should run
+ # that unattended.
+ steps.insert(
+ 0,
+ {
+ "actor": "human",
+ "description": "Approve the package first: the registry published no version, so this "
+ "resolves whatever the publisher has made latest.",
+ "command": None,
+ },
+ )
+ methods.append(
+ {
+ "method": "local_package",
+ "automation": "full" if version else "human_required",
+ "summary": (
+ "Run the published package locally, pinned to the listed version (auth requirements may "
+ "still apply at runtime)."
+ if version
+ else "Run the published package locally. The registry listed no version, so a human "
+ "approves before it runs."
+ ),
+ "steps": steps,
+ }
+ )
+ return methods
+
+
+def build_connect_instructions(server: MCPRegistryServer) -> dict[str, Any]:
+ """Full connection profile for one server, overrides applied."""
+ overrides = server.connect_overrides or KNOWN_CONNECT_OVERRIDES.get(server.registry_name, {})
+ if overrides.get("methods"):
+ methods = list(overrides["methods"])
+ else:
+ methods = _derived_methods(server)
+ if overrides.get("extra_methods"):
+ methods = methods + list(overrides["extra_methods"])
+
+ return {
+ "recommended": methods[0]["method"] if methods else None,
+ "methods": methods,
+ "auth_method": server.auth_method,
+ "liveness": server.liveness,
+ "notes": overrides.get("notes", ""),
+ }
diff --git a/products/mcp_registry/backend/constants.py b/products/mcp_registry/backend/constants.py
new file mode 100644
index 000000000000..0c2e2110e06b
--- /dev/null
+++ b/products/mcp_registry/backend/constants.py
@@ -0,0 +1,28 @@
+# Deployment-level kill switch for the sync/ranking pipeline (crawl, aggregate, probe, rank)
+# and gate for the DRF endpoints. Evaluated with a constant distinct_id for the pipeline
+# (whole-deployment toggle, like mcp-analytics-clustering-schedule) and per-user for the API.
+MCP_REGISTRY_FEATURE_FLAG = "mcp-registry"
+MCP_REGISTRY_PIPELINE_DISTINCT_ID = "internal_mcp_registry_pipeline"
+
+OFFICIAL_REGISTRY_BASE_URL = "https://registry.modelcontextprotocol.io/v0/servers"
+# The registry has ~22k active servers at ~100/page; this cap only guards against a
+# pagination bug or a runaway registry, not normal growth.
+OFFICIAL_REGISTRY_MAX_PAGES = 1_000
+
+# How far back the measured-signal aggregation looks, and the window stamped on stats rows.
+MEASURED_WINDOW_DAYS = 30
+# A stats row stops counting toward trust once it is this old. Aggregation only upserts
+# servers that appeared in the window, so a server that stopped being called keeps its
+# last row forever; without this it would keep the trust it earned when it was busy.
+MEASURED_STALE_AFTER_DAYS = 60
+# Per-server cap on tool rows kept from analytics aggregation (ordered by call volume).
+MEASURED_TOOL_LIMIT = 200
+# Cap on teams pulled into one aggregation run; revisit before wide rollout.
+MEASURED_TEAM_LIMIT = 500
+
+# Shallow-probe batch size per scheduled run: stalest servers first, so the whole index
+# converges over successive days without one giant sweep.
+PROBE_BATCH_SIZE = 500
+PROBE_TIMEOUT_SECONDS = 10
+PROBE_TOOL_LIMIT = 100
+PROBE_TOOL_DESCRIPTION_MAX_CHARS = 500
diff --git a/products/mcp_registry/backend/crawl.py b/products/mcp_registry/backend/crawl.py
new file mode 100644
index 000000000000..251b108b6e13
--- /dev/null
+++ b/products/mcp_registry/backend/crawl.py
@@ -0,0 +1,168 @@
+"""Crawler for the official MCP registry (registry.modelcontextprotocol.io).
+
+The registry exposes a paginated list API; `version=latest` collapses each server to
+its newest published version. We keep active entries only and upsert on the registry's
+reverse-DNS name, refreshing content fields while never touching operational state
+(probe results, measured flags, links), because the crawl owns metadata, nothing else.
+"""
+
+from typing import Any
+
+from django.utils import timezone
+
+import requests
+import structlog
+
+from posthog.dataclasses import frozen
+
+from products.mcp_registry.backend.constants import OFFICIAL_REGISTRY_BASE_URL, OFFICIAL_REGISTRY_MAX_PAGES
+from products.mcp_registry.backend.models import MCPRegistryServer
+
+logger = structlog.get_logger(__name__)
+
+REQUEST_TIMEOUT_SECONDS = 30
+PAGE_LIMIT = 100
+# Column widths for publisher-supplied values. The registry accepts whatever a publisher
+# writes, so one over-wide value would otherwise fail the whole batch on a DataError and
+# stall the daily crawl for every server.
+_MAX_NAME_CHARS = 400
+_MAX_URL_CHARS = 2048
+
+
+@frozen
+class CrawlOutcome:
+ created: int
+ updated: int
+
+
+def fetch_registry_entries() -> list[dict[str, Any]]:
+ """Page through the official registry and return raw active `server` payloads."""
+ entries: list[dict[str, Any]] = []
+ cursor: str | None = None
+ for _ in range(OFFICIAL_REGISTRY_MAX_PAGES):
+ params: dict[str, str] = {"limit": str(PAGE_LIMIT), "version": "latest"}
+ if cursor:
+ params["cursor"] = cursor
+ response = requests.get(OFFICIAL_REGISTRY_BASE_URL, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+ response.raise_for_status()
+ body = response.json()
+ for wrapper in body.get("servers", []):
+ meta = (wrapper.get("_meta") or {}).get("io.modelcontextprotocol.registry/official") or {}
+ if meta.get("status", "active") != "active":
+ continue
+ server = wrapper.get("server") or {}
+ server["_registry_meta"] = meta
+ entries.append(server)
+ cursor = (body.get("metadata") or {}).get("nextCursor")
+ if not cursor:
+ return entries
+ raise RuntimeError(f"registry pagination did not terminate within {OFFICIAL_REGISTRY_MAX_PAGES} pages")
+
+
+def _url_within_limit(url: str) -> str:
+ """Drop an over-long URL rather than truncate it.
+
+ A shortened URL is a different URL, and storing one would send an agent somewhere the
+ publisher never listed. Dropping it only makes the server look package-only.
+ """
+ return url if len(url) <= _MAX_URL_CHARS else ""
+
+
+def _canonical_remote_url(remotes: list[dict[str, Any]]) -> str:
+ for remote in remotes:
+ if remote.get("type") == "streamable-http" and remote.get("url"):
+ return str(remote["url"])
+ for remote in remotes:
+ if remote.get("url"):
+ return str(remote["url"])
+ return ""
+
+
+def normalize_entry(server: dict[str, Any]) -> dict[str, Any] | None:
+ """Map a raw registry payload onto MCPRegistryServer content fields."""
+ name = server.get("name")
+ if not name or len(name) > _MAX_NAME_CHARS:
+ # registry_name is the upsert key, so a truncated one could collide with a
+ # different server. Skipping the entry is the safe outcome.
+ return None
+ remotes = [{"type": r.get("type"), "url": r.get("url")} for r in (server.get("remotes") or []) if r.get("url")]
+ packages = [
+ {
+ "registry_type": p.get("registryType") or p.get("registry_type"),
+ "identifier": p.get("identifier"),
+ # Kept so a connect command can pin it. Without a version, npx resolves
+ # whatever is latest when the agent runs it, which the publisher can change
+ # after listing something benign.
+ "version": str(p.get("version") or p.get("packageVersion") or ""),
+ }
+ for p in (server.get("packages") or [])
+ if p.get("identifier")
+ ]
+ meta = server.get("_registry_meta") or {}
+ return {
+ "registry_name": name,
+ "display_name": (server.get("title") or name.rsplit("/", 1)[-1])[:_MAX_NAME_CHARS],
+ "description": server.get("description") or "",
+ "canonical_url": _url_within_limit(_canonical_remote_url(remotes)),
+ "remotes": remotes,
+ "packages": packages,
+ "repository_url": _url_within_limit((server.get("repository") or {}).get("url") or ""),
+ "website_url": _url_within_limit(server.get("websiteUrl") or ""),
+ "registry_meta": {
+ "version": server.get("version"),
+ "published_at": meta.get("publishedAt"),
+ "updated_at": meta.get("updatedAt"),
+ },
+ }
+
+
+def upsert_registry_entries(entries: list[dict[str, Any]]) -> CrawlOutcome:
+ """Create/update server rows from raw registry payloads.
+
+ Rows keep the newest payload per registry name. Servers that disappear from the
+ registry are kept (their liveness signal degrades on its own via the probe).
+ """
+ normalized: dict[str, dict[str, Any]] = {}
+ for raw in entries:
+ fields = normalize_entry(raw)
+ if fields is None:
+ continue
+ existing = normalized.get(fields["registry_name"])
+ if existing is None or (fields["registry_meta"].get("published_at") or "") > (
+ existing["registry_meta"].get("published_at") or ""
+ ):
+ normalized[fields["registry_name"]] = fields
+
+ created = 0
+ updated = 0
+ known = {
+ server.registry_name: server
+ for server in MCPRegistryServer.objects.filter(registry_name__in=list(normalized.keys()))
+ }
+ for registry_name, fields in normalized.items():
+ server = known.get(registry_name)
+ if server is None:
+ liveness = "unprobed" if fields["canonical_url"] else "package_only"
+ MCPRegistryServer.objects.create(listed_in_registry=True, liveness=liveness, **fields)
+ created += 1
+ continue
+ for attr, value in fields.items():
+ setattr(server, attr, value)
+ server.listed_in_registry = True
+ if not fields["canonical_url"] and server.liveness == "unprobed":
+ server.liveness = "package_only"
+ server.save()
+ updated += 1
+
+ logger.info(
+ "mcp_registry.crawl.upserted",
+ created=created,
+ updated=updated,
+ fetched=len(entries),
+ at=timezone.now().isoformat(),
+ )
+ return CrawlOutcome(created=created, updated=updated)
+
+
+def crawl_official_registry() -> CrawlOutcome:
+ return upsert_registry_entries(fetch_registry_entries())
diff --git a/products/mcp_registry/backend/facade/__init__.py b/products/mcp_registry/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/mcp_registry/backend/facade/api.py b/products/mcp_registry/backend/facade/api.py
new file mode 100644
index 000000000000..0dbed6446f13
--- /dev/null
+++ b/products/mcp_registry/backend/facade/api.py
@@ -0,0 +1,226 @@
+"""Cross-boundary surface of the MCP registry product.
+
+Presentation (and, later, other products) reach registry capabilities through here rather
+than importing internals. Each entrypoint takes primitive/caller context, drives the
+`logic` layer, and maps ORM rows to `contracts` dataclasses before returning — Django
+models never cross this boundary. The Celery/beat surface lives in `facade/tasks.py`
+rather than here so its heavy imports stay off the request path.
+"""
+
+from typing import Any
+
+from products.mcp_registry.backend import logic
+from products.mcp_registry.backend.connect import build_connect_instructions
+from products.mcp_registry.backend.constants import MCP_REGISTRY_FEATURE_FLAG as MCP_REGISTRY_FEATURE_FLAG
+from products.mcp_registry.backend.models import MCPRegistryServer
+from products.mcp_registry.backend.ranking import DEFAULT_RANKING_VERSION, RANKING_VERSIONS, latest_completed_run
+
+from . import contracts
+
+_DISCOVER_TOOLS_PER_CANDIDATE = 5
+
+
+def known_ranking_versions() -> list[str]:
+ return sorted(RANKING_VERSIONS)
+
+
+def is_valid_version(version: str) -> bool:
+ return version in RANKING_VERSIONS
+
+
+def default_ranking_version() -> str:
+ return DEFAULT_RANKING_VERSION
+
+
+def _to_tool(tool: Any) -> contracts.RegistryTool:
+ return contracts.RegistryTool(
+ name=tool.name,
+ description=tool.description,
+ input_schema=tool.input_schema,
+ source=tool.source,
+ last_seen_at=tool.last_seen_at,
+ )
+
+
+def _to_measured_stats(row: Any) -> contracts.MeasuredStats:
+ return contracts.MeasuredStats(
+ window_days=row.window_days,
+ calls=row.calls,
+ sessions=row.sessions,
+ errors=row.errors,
+ error_rate_pct=row.error_rate_pct,
+ intent_coverage_pct=row.intent_coverage_pct,
+ distinct_tools=row.distinct_tools,
+ harness_count=row.harness_count,
+ tool_stats=row.tool_stats,
+ link_method=row.link_method,
+ link_candidates=row.link_candidates,
+ computed_at=row.computed_at,
+ )
+
+
+def _summary(server: MCPRegistryServer) -> contracts.RegistryServerSummary:
+ return contracts.RegistryServerSummary(
+ id=server.id,
+ registry_name=server.registry_name,
+ display_name=server.display_name,
+ description=server.description,
+ canonical_url=server.canonical_url,
+ liveness=server.liveness,
+ auth_method=server.auth_method,
+ listed_in_registry=server.listed_in_registry,
+ is_measured=server.is_measured,
+ rank_score=getattr(server, "rank_score", None),
+ )
+
+
+def list_servers(
+ *, version: str, search: str, measured_only: bool, team_id: int, caller_is_staff: bool
+) -> list[contracts.RegistryServerSummary]:
+ """Ranked summaries for the caller's visible index."""
+ queryset = logic.ranked_queryset(
+ version=version, search=search, measured_only=measured_only, team_id=team_id, caller_is_staff=caller_is_staff
+ )
+ return [_summary(server) for server in queryset]
+
+
+def get_server_detail(*, pk: str, team_id: int, caller_is_staff: bool) -> contracts.RegistryServerDetail | None:
+ """Full server record, or None when the caller may not see this server."""
+ try:
+ server = logic.get_server_for_caller(pk, team_id=team_id, caller_is_staff=caller_is_staff)
+ except (MCPRegistryServer.DoesNotExist, ValueError):
+ return None
+
+ visibility = logic.measured_visibility(server, team_id, caller_is_staff)
+ can_see_measured = bool(visibility.rows)
+ latest_scores: list[contracts.ScoreInfo] = []
+ for version in known_ranking_versions():
+ run = latest_completed_run(version)
+ if run is None:
+ continue
+ score = logic.score_for_run(run, server)
+ if score is not None:
+ latest_scores.append(
+ contracts.ScoreInfo(
+ version=version,
+ score=score.score,
+ components=logic.visible_components(score.components, visibility.sees_every_row),
+ computed_at=run.computed_at,
+ )
+ )
+
+ return contracts.RegistryServerDetail(
+ **_summary(server).__dict__,
+ remotes=server.remotes,
+ packages=server.packages,
+ repository_url=server.repository_url,
+ website_url=server.website_url,
+ last_probed_at=server.last_probed_at,
+ tools=[_to_tool(tool) for tool in logic.visible_tools(server, can_see_measured)],
+ measured_stats=[_to_measured_stats(row) for row in visibility.rows],
+ scores=latest_scores,
+ connect_instructions=build_connect_instructions(server),
+ )
+
+
+def discover_servers(
+ *, intent: str, version: str, limit: int, team_id: int, caller_is_staff: bool
+) -> list[contracts.DiscoverCandidate]:
+ """Ranked candidates for a natural-language intent, each with its rationale."""
+ tokens = logic.content_tokens(intent)
+ servers = list(
+ logic.ranked_queryset(
+ version=version, search=intent, measured_only=False, team_id=team_id, caller_is_staff=caller_is_staff
+ ).prefetch_related("tools", "measured_stats")[:limit]
+ )
+ run = latest_completed_run(version)
+
+ candidates = []
+ for index, server in enumerate(servers):
+ score = logic.score_for_run(run, server)
+ visibility = logic.measured_visibility(server, team_id, caller_is_staff)
+ can_see_measured = bool(visibility.rows)
+ matched_tools: list[dict[str, contracts.JSONScalar]] = [
+ {
+ "name": tool.name,
+ "description": tool.description[:160],
+ "source": tool.source,
+ }
+ for tool in logic.visible_tools(server, can_see_measured)
+ if any(token in tool.name.lower() for token in tokens)
+ ]
+ matched_tools = matched_tools[:_DISCOVER_TOOLS_PER_CANDIDATE]
+ candidates.append(
+ contracts.DiscoverCandidate(
+ rank=index + 1,
+ id=server.id,
+ registry_name=server.registry_name,
+ title=server.display_name,
+ description=server.description,
+ score=getattr(server, "rank_score", None) or 0.0,
+ why=logic.visible_components(score.components, visibility.sees_every_row) if score else {},
+ liveness=server.liveness,
+ auth_method=server.auth_method,
+ measured=logic.measured_summary(visibility.rows),
+ matched_tools=matched_tools,
+ connect=build_connect_instructions(server),
+ )
+ )
+ return candidates
+
+
+def measured_projects() -> list[contracts.MeasuredProject]:
+ """Which projects feed the measured layer, and how much each contributes. Staff only."""
+ return [
+ contracts.MeasuredProject(team_id=row["team_id"], servers=row["servers"], calls=row["total_calls"])
+ for row in logic.measured_project_rollup()
+ ]
+
+
+def ranking_versions() -> list[contracts.RankingVersionInfo]:
+ """Registered ranking versions and their latest completed runs."""
+ payload = []
+ for version in known_ranking_versions():
+ run = latest_completed_run(version)
+ payload.append(
+ contracts.RankingVersionInfo(
+ version=version,
+ description=(RANKING_VERSIONS[version].__doc__ or "").strip().split("\n")[0],
+ is_default=version == DEFAULT_RANKING_VERSION,
+ latest_run=(
+ contracts.RankingRunInfo(id=run.id, server_count=run.server_count, computed_at=run.computed_at)
+ if run
+ else None
+ ),
+ )
+ )
+ return payload
+
+
+def compare_rankings(
+ *, versions: list[str], search: str, limit: int, team_id: int, caller_is_staff: bool
+) -> dict[str, list[contracts.CompareRow]]:
+ """Rank the same index under several versions side by side."""
+ arms: dict[str, list[contracts.CompareRow]] = {}
+ for version in versions:
+ rows = logic.ranked_queryset(
+ version=version, search=search, measured_only=False, team_id=team_id, caller_is_staff=caller_is_staff
+ )[:limit]
+ arms[version] = [
+ contracts.CompareRow(
+ rank=index + 1,
+ id=server.id,
+ registry_name=server.registry_name,
+ display_name=server.display_name,
+ score=getattr(server, "rank_score", None) or 0.0,
+ is_measured=server.is_measured,
+ )
+ for index, server in enumerate(rows)
+ ]
+ return arms
+
+
+def rank_deltas(arms: dict[str, list[contracts.CompareRow]], first: str, second: str) -> dict[str, int]:
+ """Per-server rank movement between two arms (the review surface for promoting a version)."""
+ second_ranks = {row.id: row.rank for row in arms[second]}
+ return {str(row.id): second_ranks[row.id] - row.rank for row in arms[first] if row.id in second_ranks}
diff --git a/products/mcp_registry/backend/facade/contracts.py b/products/mcp_registry/backend/facade/contracts.py
new file mode 100644
index 000000000000..bcb03ef3f6c6
--- /dev/null
+++ b/products/mcp_registry/backend/facade/contracts.py
@@ -0,0 +1,121 @@
+"""Contract types for the MCP registry product.
+
+Stable, framework-free frozen dataclasses that define what this product exposes to
+the rest of the codebase, and what its own presentation layer serializes. No Django,
+no DRF imports — a `components`/`why` payload is a plain dict of JSON scalars, not an
+ORM JSONField instance.
+"""
+
+from dataclasses import dataclass, field
+from datetime import datetime
+from uuid import UUID
+
+JSONScalar = str | int | float | bool | None
+
+
+@dataclass(frozen=True)
+class RegistryTool:
+ name: str
+ description: str
+ input_schema: dict[str, JSONScalar]
+ source: str
+ last_seen_at: datetime
+
+
+@dataclass(frozen=True)
+class MeasuredStats:
+ window_days: int
+ calls: int
+ sessions: int
+ errors: int
+ error_rate_pct: float
+ intent_coverage_pct: float
+ distinct_tools: int
+ harness_count: int
+ tool_stats: list[dict[str, JSONScalar]]
+ link_method: str
+ link_candidates: list[str]
+ computed_at: datetime
+
+
+@dataclass(frozen=True)
+class ScoreInfo:
+ version: str
+ score: float
+ components: dict[str, JSONScalar]
+ computed_at: datetime | None
+
+
+@dataclass(frozen=True)
+class RankingRunInfo:
+ id: UUID
+ server_count: int
+ computed_at: datetime | None
+
+
+@dataclass(frozen=True)
+class RegistryServerSummary:
+ id: UUID
+ registry_name: str
+ display_name: str
+ description: str
+ canonical_url: str
+ liveness: str
+ auth_method: str
+ listed_in_registry: bool
+ is_measured: bool
+ rank_score: float | None
+
+
+@dataclass(frozen=True)
+class RegistryServerDetail(RegistryServerSummary):
+ remotes: list[dict[str, JSONScalar]] = field(default_factory=list)
+ packages: list[dict[str, JSONScalar]] = field(default_factory=list)
+ repository_url: str = ""
+ website_url: str = ""
+ last_probed_at: datetime | None = None
+ tools: list[RegistryTool] = field(default_factory=list)
+ measured_stats: list[MeasuredStats] = field(default_factory=list)
+ scores: list[ScoreInfo] = field(default_factory=list)
+ connect_instructions: dict[str, JSONScalar] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class DiscoverCandidate:
+ rank: int
+ id: UUID
+ registry_name: str
+ title: str
+ description: str
+ score: float
+ why: dict[str, JSONScalar]
+ liveness: str
+ auth_method: str
+ measured: dict[str, JSONScalar] | None
+ matched_tools: list[dict[str, JSONScalar]]
+ connect: dict[str, JSONScalar]
+
+
+@dataclass(frozen=True)
+class MeasuredProject:
+ team_id: int
+ servers: int
+ calls: int
+
+
+@dataclass(frozen=True)
+class RankingVersionInfo:
+ version: str
+ description: str
+ is_default: bool
+ latest_run: RankingRunInfo | None
+
+
+@dataclass(frozen=True)
+class CompareRow:
+ rank: int
+ id: UUID
+ registry_name: str
+ display_name: str
+ score: float
+ is_measured: bool
diff --git a/products/mcp_registry/backend/facade/tasks.py b/products/mcp_registry/backend/facade/tasks.py
new file mode 100644
index 000000000000..551627dd9a2f
--- /dev/null
+++ b/products/mcp_registry/backend/facade/tasks.py
@@ -0,0 +1,22 @@
+"""Facade re-export for the MCP registry Celery surface.
+
+Core's central beat wiring (``posthog/tasks/scheduled.py``) registers the sync sweep from
+here rather than reaching into the product's internals, and the management command runs the
+same pipeline through this boundary. Lives apart from ``api.py`` so the task modules' heavy
+imports (celery, posthoganalytics) stay off that module, which presentation imports on every
+request.
+"""
+
+from products.mcp_registry.backend.tasks.tasks import (
+ MCP_REGISTRY_SYNC_CRONTAB,
+ is_pipeline_enabled,
+ run_mcp_registry_sync,
+ run_sync_pipeline,
+)
+
+__all__ = [
+ "MCP_REGISTRY_SYNC_CRONTAB",
+ "is_pipeline_enabled",
+ "run_mcp_registry_sync",
+ "run_sync_pipeline",
+]
diff --git a/products/mcp_registry/backend/linking.py b/products/mcp_registry/backend/linking.py
new file mode 100644
index 000000000000..0feed4c75a78
--- /dev/null
+++ b/products/mcp_registry/backend/linking.py
@@ -0,0 +1,97 @@
+"""Entity resolution between measured servers and official-registry entries.
+
+A measured signal arrives as (team_id, $mcp_server_name) with no URL, so linking is
+name-based and deliberately conservative: an advertised name like "posthog" also
+matches third-party repackages of the same product, and attaching real usage stats to
+the wrong entry is worse than attaching them to none. Anything ambiguous becomes a
+standalone measured row with the candidates recorded for human review.
+"""
+
+import re
+from dataclasses import field
+
+from django.db.models import Q
+
+from posthog.dataclasses import frozen
+
+from products.mcp_registry.backend.models import MCPRegistryServer
+
+# Curated (measured server name -> registry name) links that skip matching entirely.
+# The first entry is the motivating example: name-matching "PostHog" alone is ambiguous
+# between the official server and third-party repackages of it.
+KNOWN_MEASURED_LINKS: dict[str, str] = {
+ "PostHog": "io.github.PostHog/mcp",
+}
+
+
+def normalize_name(name: str) -> str:
+ return re.sub(r"[^a-z0-9]+", "", name.lower())
+
+
+@frozen
+class LinkResult:
+ server: MCPRegistryServer | None
+ method: str # a LINK_METHOD_CHOICES key, or "" when unresolved/ambiguous
+ candidates: list[str] = field(default_factory=list)
+
+
+def find_registry_match(server_name: str) -> LinkResult:
+ """Resolve a measured server name against registry entries, refusing ambiguity."""
+ override = KNOWN_MEASURED_LINKS.get(server_name)
+ if override:
+ server = MCPRegistryServer.objects.filter(registry_name=override).first()
+ if server is not None:
+ return LinkResult(server=server, method="override")
+
+ normalized = normalize_name(server_name)
+ if not normalized:
+ return LinkResult(server=None, method="")
+
+ # Candidate pool: registry entries whose title or name segment could plausibly be
+ # this server. The SQL filter over-fetches; exactness is decided in Python.
+ pool = MCPRegistryServer.objects.filter(listed_in_registry=True).filter(
+ Q(display_name__icontains=server_name) | Q(registry_name__icontains=server_name)
+ )[:50]
+ exact: list[MCPRegistryServer] = []
+ for candidate in pool:
+ segment = candidate.registry_name.rsplit("/", 1)[-1]
+ if normalized in (normalize_name(candidate.display_name), normalize_name(segment)):
+ exact.append(candidate)
+
+ if len(exact) == 1:
+ return LinkResult(server=exact[0], method="exact_name")
+ if len(exact) > 1:
+ return LinkResult(server=None, method="", candidates=[c.registry_name for c in exact])
+ return LinkResult(server=None, method="")
+
+
+@frozen
+class MeasuredServerResolution:
+ server: MCPRegistryServer
+ link_method: str
+ link_candidates: list[str] = field(default_factory=list)
+
+
+def resolve_measured_server(server_name: str) -> MeasuredServerResolution:
+ """Resolve a measured server name to its registry server row.
+
+ Falls back to a standalone (non-registry) row when no unambiguous match exists,
+ reusing a previous standalone row for the same name if one was already created.
+ """
+ result = find_registry_match(server_name)
+ if result.server is not None:
+ if not result.server.is_measured:
+ result.server.is_measured = True
+ result.server.save(update_fields=["is_measured", "updated_at"])
+ return MeasuredServerResolution(server=result.server, link_method=result.method)
+
+ standalone = MCPRegistryServer.objects.filter(
+ listed_in_registry=False, is_measured=True, display_name=server_name
+ ).first()
+ if standalone is None:
+ standalone = MCPRegistryServer.objects.create(
+ display_name=server_name,
+ description="Measured via MCP Analytics; not listed in the official registry.",
+ is_measured=True,
+ )
+ return MeasuredServerResolution(server=standalone, link_method="standalone", link_candidates=result.candidates)
diff --git a/products/mcp_registry/backend/logic.py b/products/mcp_registry/backend/logic.py
new file mode 100644
index 000000000000..eaa5a1d9289b
--- /dev/null
+++ b/products/mcp_registry/backend/logic.py
@@ -0,0 +1,275 @@
+"""Business rules and ORM access for the MCP registry.
+
+Owns every `.objects` query, the visibility policy that decides what a caller may see,
+and the queryset construction behind list/discover/compare. The facade is a thin
+orchestration layer over this; presentation never reaches past the facade. The versioned
+scoring functions stay in `ranking` (they are the versioning contract), and the crawl /
+probe / aggregation pipelines keep their own modules — this module is the read-side and
+task-facing business layer.
+"""
+
+import re
+from dataclasses import dataclass
+from typing import Any
+from uuid import UUID
+
+from django.db.models import (
+ Case,
+ Count,
+ Exists,
+ Expression,
+ F,
+ FloatField,
+ OuterRef,
+ Q,
+ QuerySet,
+ Subquery,
+ Sum,
+ Value,
+ When,
+)
+from django.db.models.functions import Coalesce, Power
+
+from products.mcp_registry.backend.models import (
+ MCPMeasuredStats,
+ MCPRankingRun,
+ MCPRankingScore,
+ MCPRegistryServer,
+ MCPRegistryTool,
+)
+from products.mcp_registry.backend.ranking import latest_completed_run
+
+_MAX_SEARCH_TOKENS = 5
+_MAX_TOKEN_WEIGHT = 4.0
+# Fit outweighs authority: a server has to plausibly do the thing before its track
+# record matters. Tuning these is a ranking-version decision, not a per-query one.
+_FIT_EXPONENT = 0.6
+_AUTHORITY_EXPONENT = 0.4
+# Components computed from measured rows, so they carry the same disclosure risk.
+_DERIVED_COMPONENT_KEYS = frozenset(
+ {"trust", "measured_reliability", "measured_volume_confidence", "measured_intent_coverage"}
+)
+# Words that match nearly every server, so they only dilute relevance.
+_STOPWORDS = frozenset(
+ {"and", "any", "can", "for", "from", "get", "how", "into", "its", "make", "me", "my", "our", "the", "with", "you"}
+)
+
+
+@dataclass(frozen=True)
+class MeasuredVisibility:
+ rows: list[MCPMeasuredStats]
+ sees_every_row: bool
+
+
+def content_tokens(search: str) -> list[str]:
+ """Query tokens worth matching on: stopwords carry no signal but match everything."""
+ return [token for token in search.lower().split() if token not in _STOPWORDS and len(token) > 2][
+ :_MAX_SEARCH_TOKENS
+ ]
+
+
+def visible_components(components: dict[str, Any], sees_every_row: bool) -> dict[str, Any]:
+ """Score inputs, minus the ones computed from measurements this caller cannot see.
+
+ A measured server's components are derived from every contributing project's rows, so
+ handing them over whole would disclose by arithmetic what the tiering on the stats
+ withholds directly. The rank itself stays: a caller may learn that a server ranks well
+ and that real usage backs it, without the numbers behind it.
+ """
+ if sees_every_row or not components.get("measured"):
+ return components
+ return {key: value for key, value in components.items() if key not in _DERIVED_COMPONENT_KEYS}
+
+
+def visible_tools(server: MCPRegistryServer, can_see_measured: bool) -> list[MCPRegistryTool]:
+ """Tools known only from another project's traffic stay hidden.
+
+ A probed tools/list is ours, because we asked the server for it. A tool learned from
+ analytics is evidence of somebody's calls, so it follows the same tier as the stats.
+ """
+ tools = list(server.tools.all())
+ if can_see_measured:
+ return tools
+ return [tool for tool in tools if tool.source != "analytics"]
+
+
+def measured_visibility(server: MCPRegistryServer, team_id: int | None, is_staff: bool) -> MeasuredVisibility:
+ """The measured rows this caller may see, and whether they are all of them.
+
+ The second value gates the derived score components, which blend every contributing
+ project's rows. Seeing one row is not licence to see a number computed from somebody
+ else's, so a project sharing a server with other measurers gets its own figures and a
+ redacted breakdown.
+
+ Registry rows are global, but each stats row aggregates one project's own
+ $mcp_tool_call events, so visibility is tiered. PostHog staff see every row, which is
+ how we tell whether ranking behaves across the whole fleet instead of one project. A
+ project sees its own rows. Anyone else sees none, because another customer's call
+ volumes, error rates, and per-tool breakdowns are not ours to hand out.
+
+ `measured_public` is deliberately not consulted. It is one boolean on a server that
+ several projects contribute rows to, so it cannot record which contributor agreed to
+ publish; a public surface needs a rule that can.
+ """
+ rows = list(server.measured_stats.all())
+ if is_staff:
+ return MeasuredVisibility(rows=rows, sees_every_row=True)
+ # No row carries a null team_id, so a caller without a project matches nothing.
+ visible = [row for row in rows if row.team_id == team_id]
+ return MeasuredVisibility(rows=visible, sees_every_row=len(visible) == len(rows))
+
+
+def measured_summary(stats: list[MCPMeasuredStats]) -> dict[str, Any] | None:
+ """Combine a server's measured sources into one agent-readable trust summary."""
+ total_calls = sum(row.calls for row in stats)
+ if total_calls <= 0:
+ return None
+ return {
+ "calls": total_calls,
+ "sessions": sum(row.sessions for row in stats),
+ "error_rate_pct": round(sum(row.error_rate_pct * row.calls for row in stats) / total_calls, 2),
+ "intent_coverage_pct": round(sum(row.intent_coverage_pct * row.calls for row in stats) / total_calls, 2),
+ "harness_count": max(row.harness_count for row in stats),
+ "window_days": max(row.window_days for row in stats),
+ "sources": len(stats),
+ }
+
+
+def base_queryset(team_id: int, caller_is_staff: bool) -> QuerySet:
+ """Servers this caller may see at all.
+
+ Registry rows are global, so there is normally no team column to scope by. The
+ exception is a row absent from the official registry: it exists only because some
+ project's events named a server we could not match, so the row and its name are
+ that project's data rather than a public listing. The name is also unvalidated
+ text from whoever captured the event, which is another reason not to show it to
+ other customers. Those rows stay with the project that produced them, and staff.
+ """
+ queryset = MCPRegistryServer.objects.all()
+ if caller_is_staff:
+ return queryset
+ measured_by_caller = Exists(MCPMeasuredStats.objects.for_team(team_id).filter(server=OuterRef("pk")))
+ return queryset.filter(Q(listed_in_registry=True) | Q(measured_by_caller))
+
+
+def _namespace_match(token: str) -> Q:
+ """Whether the token appears in the server's reverse-DNS namespace.
+
+ Worth more than any other match: the official registry validates namespace
+ ownership, so `com.vercel/*` requires proving control of vercel.com, while a display
+ name is free text anyone can set. Without this, third-party clones with the vendor's
+ name in their title outrank the vendor's own server.
+
+ The token is regex-escaped, so the pattern stays a literal bounded to the segment
+ before the first slash.
+ """
+ return Q(registry_name__iregex=rf"^[^/]*{re.escape(token)}[^/]*/")
+
+
+def _tool_match(token: str) -> Exists:
+ """Whether any of the server's tools is named for the token.
+
+ An Exists subquery rather than a join on `tools`: joining multiplies a server's row
+ once per matching tool, which both duplicates it in the results and makes a
+ row-wise relevance expression score the same server differently per copy.
+ """
+ return Exists(MCPRegistryTool.objects.filter(server=OuterRef("pk"), name__icontains=token))
+
+
+def _search_filter(tokens: list[str]) -> Q:
+ query = Q()
+ for token in tokens:
+ query |= (
+ Q(display_name__icontains=token)
+ | Q(registry_name__icontains=token)
+ | Q(description__icontains=token)
+ | Q(_tool_match(token))
+ )
+ return query
+
+
+def _relevance_annotation(tokens: list[str]) -> Expression:
+ """How well each server's own text answers the query.
+
+ Counts distinct query tokens matched, weighting where the match landed: a server
+ named for the thing beats one that mentions it in passing, and both beat a match
+ that only appears in a tool name. Tool-name matches are worth least because a
+ server exposing `list_data_products` is not thereby about product analytics, which
+ is how the unweighted OR match used to rank an airtime vendor first.
+
+ Lexical, so it cannot match a paraphrase ("watch user sessions" against "session
+ replay"). Embedding-based capability search replaces this function; keeping
+ relevance separate from the static score is what makes that swap local.
+ """
+ if not tokens:
+ return Value(0.0, output_field=FloatField())
+ expression: Expression = Value(0.0, output_field=FloatField())
+ for token in tokens:
+ expression = expression + Case(
+ When(_namespace_match(token), then=Value(_MAX_TOKEN_WEIGHT)),
+ When(display_name__icontains=token, then=Value(3.0)),
+ When(registry_name__icontains=token, then=Value(3.0)),
+ When(description__icontains=token, then=Value(2.0)),
+ When(_tool_match(token), then=Value(0.5)),
+ default=Value(0.0),
+ output_field=FloatField(),
+ )
+ return expression
+
+
+def ranked_queryset(*, version: str, search: str, measured_only: bool, team_id: int, caller_is_staff: bool) -> QuerySet:
+ """Rank by fit x authority, the product this whole thing exists to compute.
+
+ `relevance` is how well the server's text answers the query; `rank_score` is
+ liveness x trust from the ranking run, where trust is real usage signal for
+ measured servers. They multiply rather than tie-break so neither can dominate:
+ a strong match on a dead server loses, and so does a live measured server that
+ does not do the thing. Exponents weight fit over authority.
+ """
+ queryset = base_queryset(team_id, caller_is_staff)
+ tokens = content_tokens(search)
+ if measured_only:
+ queryset = queryset.filter(is_measured=True)
+ run = latest_completed_run(version)
+ if run is not None:
+ score_subquery = MCPRankingScore.objects.filter(run=run, server=OuterRef("pk")).values("score")[:1]
+ queryset = queryset.annotate(rank_score=Subquery(score_subquery))
+
+ if not tokens:
+ ordering = [F("rank_score").desc(nulls_last=True)] if run is not None else []
+ return queryset.order_by(*ordering, "-is_measured", "display_name").distinct()
+
+ queryset = queryset.filter(_search_filter(tokens)).annotate(
+ relevance=_relevance_annotation(tokens) / (_MAX_TOKEN_WEIGHT * len(tokens))
+ )
+ if run is None:
+ return queryset.order_by("-relevance", "-is_measured", "display_name").distinct()
+ return (
+ queryset.annotate(
+ combined_score=Power(F("relevance"), _FIT_EXPONENT)
+ * Power(Coalesce(F("rank_score"), Value(0.0)), _AUTHORITY_EXPONENT)
+ )
+ .order_by(F("combined_score").desc(nulls_last=True), "-is_measured", "display_name")
+ .distinct()
+ )
+
+
+def get_server_for_caller(pk: str | UUID, *, team_id: int, caller_is_staff: bool) -> MCPRegistryServer:
+ """One visible server by id, 404ing for a caller who may not see it."""
+ return base_queryset(team_id, caller_is_staff).get(pk=pk)
+
+
+def score_for_run(run: MCPRankingRun | None, server: MCPRegistryServer) -> MCPRankingScore | None:
+ if run is None:
+ return None
+ return MCPRankingScore.objects.filter(run=run, server=server).first()
+
+
+def measured_project_rollup() -> list[dict[str, Any]]:
+ """Per-project contribution to the measured layer (staff fleet view)."""
+ return list(
+ MCPMeasuredStats.objects.unscoped()
+ .values("team_id")
+ .annotate(servers=Count("server", distinct=True), total_calls=Sum("calls"))
+ .order_by("-total_calls")
+ )
diff --git a/products/mcp_registry/backend/management/__init__.py b/products/mcp_registry/backend/management/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/mcp_registry/backend/management/commands/__init__.py b/products/mcp_registry/backend/management/commands/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/mcp_registry/backend/management/commands/sync_mcp_registry.py b/products/mcp_registry/backend/management/commands/sync_mcp_registry.py
new file mode 100644
index 000000000000..553497a2a7bc
--- /dev/null
+++ b/products/mcp_registry/backend/management/commands/sync_mcp_registry.py
@@ -0,0 +1,21 @@
+from typing import Any
+
+from django.core.management.base import BaseCommand
+
+from products.mcp_registry.backend.facade.tasks import run_sync_pipeline
+
+
+class Command(BaseCommand):
+ help = (
+ "Run the MCP registry sync pipeline synchronously: crawl the official registry, "
+ "aggregate measured servers from MCP Analytics, probe stale servers, compute rankings. "
+ "Bypasses the feature-flag gate because this command is an explicit human action."
+ )
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--skip-crawl", action="store_true", help="Skip the official-registry crawl.")
+ parser.add_argument("--skip-probe", action="store_true", help="Skip the liveness probe batch.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ outcome = run_sync_pipeline(skip_crawl=options["skip_crawl"], skip_probe=options["skip_probe"])
+ self.stdout.write(self.style.SUCCESS(f"mcp registry sync: {outcome}"))
diff --git a/products/mcp_registry/backend/migrations/0001_initial.py b/products/mcp_registry/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..ef51371c56ea
--- /dev/null
+++ b/products/mcp_registry/backend/migrations/0001_initial.py
@@ -0,0 +1,289 @@
+# Generated by Django 5.2.17 on 2026-08-19 14:48
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = []
+
+ operations = [
+ migrations.CreateModel(
+ name="MCPRankingRun",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("version", models.CharField(max_length=100)),
+ ("params", models.JSONField(blank=True, default=dict)),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("running", "Running"),
+ ("completed", "Completed"),
+ ("failed", "Failed"),
+ ],
+ default="running",
+ max_length=20,
+ ),
+ ),
+ ("error", models.TextField(blank=True, default="")),
+ ("server_count", models.IntegerField(default=0)),
+ ("computed_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ],
+ options={
+ "db_table": "mcp_registry_ranking_run",
+ "indexes": [
+ models.Index(
+ fields=["version", "-created_at"],
+ name="mcp_registr_version_f53ab8_idx",
+ )
+ ],
+ },
+ ),
+ migrations.CreateModel(
+ name="MCPRegistryServer",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "registry_name",
+ models.CharField(blank=True, default="", max_length=400),
+ ),
+ ("display_name", models.CharField(max_length=400)),
+ ("description", models.TextField(blank=True, default="")),
+ (
+ "canonical_url",
+ models.URLField(blank=True, default="", max_length=2048),
+ ),
+ ("remotes", models.JSONField(blank=True, default=list)),
+ ("packages", models.JSONField(blank=True, default=list)),
+ (
+ "repository_url",
+ models.URLField(blank=True, default="", max_length=2048),
+ ),
+ (
+ "website_url",
+ models.URLField(blank=True, default="", max_length=2048),
+ ),
+ ("listed_in_registry", models.BooleanField(default=False)),
+ ("registry_meta", models.JSONField(blank=True, default=dict)),
+ ("is_measured", models.BooleanField(default=False)),
+ ("measured_public", models.BooleanField(default=False)),
+ (
+ "liveness",
+ models.CharField(
+ choices=[
+ ("alive_open", "Alive, no auth required"),
+ ("alive_auth", "Alive, behind auth"),
+ ("alive_protocol", "Alive, protocol-level error"),
+ ("dead", "Dead"),
+ ("not_mcp", "Responds, but not an MCP server"),
+ ("package_only", "No hosted remote, package install only"),
+ ("unprobed", "Not probed yet"),
+ ],
+ default="unprobed",
+ max_length=20,
+ ),
+ ),
+ (
+ "auth_method",
+ models.CharField(
+ choices=[
+ ("none", "No auth"),
+ ("oauth", "OAuth"),
+ ("api_key", "API key"),
+ ("unknown", "Unknown"),
+ ],
+ default="unknown",
+ max_length=20,
+ ),
+ ),
+ ("last_probed_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "probe_detail",
+ models.CharField(blank=True, default="", max_length=200),
+ ),
+ ("mcp_store_template_id", models.UUIDField(blank=True, null=True)),
+ ("connect_overrides", models.JSONField(blank=True, default=dict)),
+ ("supports_agent_provisioning", models.BooleanField(default=False)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ],
+ options={
+ "db_table": "mcp_registry_server",
+ "indexes": [
+ models.Index(
+ fields=["listed_in_registry"],
+ name="mcp_registr_listed__c8e64b_idx",
+ ),
+ models.Index(fields=["is_measured"], name="mcp_registr_is_meas_b12741_idx"),
+ models.Index(fields=["liveness"], name="mcp_registr_livenes_3dac66_idx"),
+ models.Index(fields=["last_probed_at"], name="mcp_registr_last_pr_0a386c_idx"),
+ models.Index(fields=["canonical_url"], name="mcp_registr_canonic_63116d_idx"),
+ ],
+ "constraints": [
+ models.UniqueConstraint(
+ condition=models.Q(("registry_name", ""), _negated=True),
+ fields=("registry_name",),
+ name="unique_registry_name_when_set",
+ )
+ ],
+ },
+ ),
+ migrations.CreateModel(
+ name="MCPRankingScore",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("score", models.FloatField()),
+ ("components", models.JSONField(blank=True, default=dict)),
+ (
+ "run",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="scores",
+ to="mcp_registry.mcprankingrun",
+ ),
+ ),
+ (
+ "server",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="scores",
+ to="mcp_registry.mcpregistryserver",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "mcp_registry_ranking_score",
+ "indexes": [models.Index(fields=["run", "-score"], name="mcp_registr_run_id_abf0dc_idx")],
+ "constraints": [models.UniqueConstraint(fields=("run", "server"), name="unique_score_per_run_server")],
+ },
+ ),
+ migrations.CreateModel(
+ name="MCPMeasuredStats",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.IntegerField()),
+ ("server_name", models.CharField(max_length=400)),
+ ("window_days", models.IntegerField()),
+ ("calls", models.BigIntegerField(default=0)),
+ ("sessions", models.BigIntegerField(default=0)),
+ ("errors", models.BigIntegerField(default=0)),
+ ("error_rate_pct", models.FloatField(default=0.0)),
+ ("intent_coverage_pct", models.FloatField(default=0.0)),
+ ("distinct_tools", models.IntegerField(default=0)),
+ ("harness_count", models.IntegerField(default=0)),
+ ("tool_stats", models.JSONField(blank=True, default=list)),
+ (
+ "link_method",
+ models.CharField(
+ choices=[
+ ("override", "Known-link override"),
+ ("url", "Remote URL match"),
+ ("exact_name", "Exact name match"),
+ ("standalone", "No registry match, standalone row"),
+ ],
+ max_length=20,
+ ),
+ ),
+ ("link_candidates", models.JSONField(blank=True, default=list)),
+ ("computed_at", models.DateTimeField()),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "server",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="measured_stats",
+ to="mcp_registry.mcpregistryserver",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name_plural": "MCP measured stats",
+ "db_table": "mcp_registry_measured_stats",
+ "indexes": [models.Index(fields=["server"], name="mcp_registr_server__35565b_idx")],
+ "constraints": [
+ models.UniqueConstraint(fields=("team_id", "server_name"), name="unique_measured_source")
+ ],
+ },
+ ),
+ migrations.CreateModel(
+ name="MCPRegistryTool",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(max_length=400)),
+ ("description", models.TextField(blank=True, default="")),
+ ("input_schema", models.JSONField(blank=True, default=dict)),
+ (
+ "source",
+ models.CharField(
+ choices=[
+ ("tools_list", "Probed tools/list"),
+ ("analytics", "MCP Analytics usage"),
+ ],
+ max_length=20,
+ ),
+ ),
+ ("last_seen_at", models.DateTimeField()),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "server",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="tools",
+ to="mcp_registry.mcpregistryserver",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "mcp_registry_tool",
+ "constraints": [models.UniqueConstraint(fields=("server", "name"), name="unique_tool_per_server")],
+ },
+ ),
+ ]
diff --git a/products/mcp_registry/backend/migrations/0002_alter_mcpmeasuredstats_options_and_more.py b/products/mcp_registry/backend/migrations/0002_alter_mcpmeasuredstats_options_and_more.py
new file mode 100644
index 000000000000..1a55e76c1572
--- /dev/null
+++ b/products/mcp_registry/backend/migrations/0002_alter_mcpmeasuredstats_options_and_more.py
@@ -0,0 +1,23 @@
+# Generated by Django 5.2.17 on 2026-09-03 21:24
+
+import django.db.models.manager
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mcp_registry", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name="mcpmeasuredstats",
+ options={"default_manager_name": "all_teams", "verbose_name_plural": "MCP measured stats"},
+ ),
+ migrations.AlterModelManagers(
+ name="mcpmeasuredstats",
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ ]
diff --git a/products/mcp_registry/backend/migrations/__init__.py b/products/mcp_registry/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/mcp_registry/backend/migrations/max_migration.txt b/products/mcp_registry/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..c28eca79b89c
--- /dev/null
+++ b/products/mcp_registry/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0002_alter_mcpmeasuredstats_options_and_more
diff --git a/products/mcp_registry/backend/models.py b/products/mcp_registry/backend/models.py
new file mode 100644
index 000000000000..53554819729c
--- /dev/null
+++ b/products/mcp_registry/backend/models.py
@@ -0,0 +1,252 @@
+from django.db import models
+from django.db.models import Q
+
+from posthog.models.scoping.manager import TeamScopedManager
+from posthog.models.utils import UUIDModel
+
+# Liveness as classified by the shallow probe. `package_only` and `unprobed` are
+# pre-probe states derived from the registry entry itself.
+LIVENESS_CHOICES = [
+ ("alive_open", "Alive, no auth required"),
+ ("alive_auth", "Alive, behind auth"),
+ ("alive_protocol", "Alive, protocol-level error"),
+ ("dead", "Dead"),
+ ("not_mcp", "Responds, but not an MCP server"),
+ ("package_only", "No hosted remote, package install only"),
+ ("unprobed", "Not probed yet"),
+]
+
+# How the server authenticates, as far as we can tell without credentials.
+# `oauth` comes from a Bearer WWW-Authenticate challenge, `api_key` from an
+# explicit api-key hint in the 401/403 body or headers.
+AUTH_METHOD_CHOICES = [
+ ("none", "No auth"),
+ ("oauth", "OAuth"),
+ ("api_key", "API key"),
+ ("unknown", "Unknown"),
+]
+
+TOOL_SOURCE_CHOICES = [
+ ("tools_list", "Probed tools/list"),
+ ("analytics", "MCP Analytics usage"),
+]
+
+# How a measured (team, server_name) signal got attached to its registry server row.
+LINK_METHOD_CHOICES = [
+ ("override", "Known-link override"),
+ ("url", "Remote URL match"),
+ ("exact_name", "Exact name match"),
+ ("standalone", "No registry match, standalone row"),
+]
+
+RANKING_RUN_STATUS_CHOICES = [
+ ("running", "Running"),
+ ("completed", "Completed"),
+ ("failed", "Failed"),
+]
+
+
+class MCPRegistryServer(UUIDModel):
+ """One MCP server known to the registry index.
+
+ Global rows (no team FK): the index fuses public data (the official MCP registry
+ crawl, probes) with cross-team aggregates from MCP Analytics. A row can come from
+ either side alone or both; `listed_in_registry` / `is_measured` record provenance.
+ """
+
+ # Reverse-DNS name from the official registry (e.g. "io.github.PostHog/mcp").
+ # Empty for measured-only servers that never appeared in the registry.
+ registry_name = models.CharField(max_length=400, blank=True, default="")
+ display_name = models.CharField(max_length=400)
+ description = models.TextField(blank=True, default="")
+ # Primary streamable-http remote, when the server is hosted.
+ canonical_url = models.URLField(max_length=2048, blank=True, default="")
+ remotes = models.JSONField(default=list, blank=True)
+ packages = models.JSONField(default=list, blank=True)
+ repository_url = models.URLField(max_length=2048, blank=True, default="")
+ website_url = models.URLField(max_length=2048, blank=True, default="")
+
+ listed_in_registry = models.BooleanField(default=False)
+ # Raw official-registry metadata (version, publishedAt, updatedAt, status).
+ registry_meta = models.JSONField(default=dict, blank=True)
+ is_measured = models.BooleanField(default=False)
+ # Whether measured stats may be shown outside PostHog. Stays False until the
+ # server owner opts in, because it is their analytics data.
+ measured_public = models.BooleanField(default=False)
+
+ liveness = models.CharField(max_length=20, choices=LIVENESS_CHOICES, default="unprobed")
+ auth_method = models.CharField(max_length=20, choices=AUTH_METHOD_CHOICES, default="unknown")
+ last_probed_at = models.DateTimeField(null=True, blank=True)
+ probe_detail = models.CharField(max_length=200, blank=True, default="")
+
+ # Soft link to a curated mcp_store MCPServerTemplate (UUID, no FK: mcp_store is a
+ # separate product boundary and the link is advisory).
+ mcp_store_template_id = models.UUIDField(null=True, blank=True)
+
+ # Per-server overrides for connection instructions (see connect.py for the shape).
+ connect_overrides = models.JSONField(default=dict, blank=True)
+ # The vendor exposes an API through which an agent can provision an account/key
+ # without a human. When True, connect instructions always prefer that path.
+ supports_agent_provisioning = models.BooleanField(default=False)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "mcp_registry_server"
+ constraints = [
+ models.UniqueConstraint(
+ fields=["registry_name"],
+ condition=~Q(registry_name=""),
+ name="unique_registry_name_when_set",
+ ),
+ ]
+ indexes = [
+ models.Index(fields=["listed_in_registry"]),
+ models.Index(fields=["is_measured"]),
+ models.Index(fields=["liveness"]),
+ models.Index(fields=["last_probed_at"]),
+ models.Index(fields=["canonical_url"]),
+ ]
+
+ def __str__(self) -> str:
+ return self.registry_name or self.display_name
+
+
+class MCPRegistryTool(UUIDModel):
+ """One tool a server exposes, from a probed tools/list or from analytics usage.
+
+ A tools/list row is authoritative for schema; an analytics row proves real usage
+ (and is the only source for auth-walled servers). The same tool name upgrades in
+ place when a better source arrives.
+ """
+
+ server = models.ForeignKey(MCPRegistryServer, on_delete=models.CASCADE, related_name="tools")
+ name = models.CharField(max_length=400)
+ description = models.TextField(blank=True, default="")
+ input_schema = models.JSONField(default=dict, blank=True)
+ source = models.CharField(max_length=20, choices=TOOL_SOURCE_CHOICES)
+ last_seen_at = models.DateTimeField()
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "mcp_registry_tool"
+ constraints = [
+ models.UniqueConstraint(fields=["server", "name"], name="unique_tool_per_server"),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.server}:{self.name}"
+
+
+class MCPMeasuredStats(UUIDModel):
+ """Behavioral aggregate for one measured server, from one MCP Analytics project.
+
+ Keyed on (team_id, server_name): the same advertised server name can appear in
+ more than one customer project, and each is its own signal source. `team_id` is a
+ raw int on purpose, because this is a global table and must not FK the hot team table.
+
+ `objects` is the fail-closed TeamScopedManager: a bare `.objects` query without team
+ context raises rather than leaking another project's measurements, so the IDOR
+ coverage check needs no exemption for this model. Reads that intentionally span the
+ fleet (the staff rollup, ranking) opt out with `.unscoped()`; reads for one project's
+ own measurements go through `.for_team(...)` or the request's ambient team scope.
+ """
+
+ objects = TeamScopedManager()
+ # Django framework internals (related-object access, prefetch_related, admin) use
+ # `_default_manager` and expect an unfiltered manager; pointing that at `all_teams`
+ # keeps `server.measured_stats.all()` working while `.objects` stays fail-closed.
+ all_teams = models.Manager() # noqa: DJ012
+
+ server = models.ForeignKey(MCPRegistryServer, on_delete=models.CASCADE, related_name="measured_stats")
+ team_id = models.IntegerField()
+ server_name = models.CharField(max_length=400)
+ window_days = models.IntegerField()
+
+ calls = models.BigIntegerField(default=0)
+ sessions = models.BigIntegerField(default=0)
+ errors = models.BigIntegerField(default=0)
+ error_rate_pct = models.FloatField(default=0.0)
+ intent_coverage_pct = models.FloatField(default=0.0)
+ distinct_tools = models.IntegerField(default=0)
+ harness_count = models.IntegerField(default=0)
+ # Top tools by call volume: [{"name", "calls", "errors", "error_rate_pct"}].
+ tool_stats = models.JSONField(default=list, blank=True)
+
+ link_method = models.CharField(max_length=20, choices=LINK_METHOD_CHOICES)
+ # Registry names that also matched when linking was ambiguous, kept for review.
+ link_candidates = models.JSONField(default=list, blank=True)
+
+ computed_at = models.DateTimeField()
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "mcp_registry_measured_stats"
+ verbose_name_plural = "MCP measured stats"
+ # Related-object access (server.measured_stats.all(), prefetch_related) resolves
+ # through `_default_manager`; point it at the unscoped sibling so those reads keep
+ # working without team context while `.objects` stays fail-closed.
+ default_manager_name = "all_teams"
+ constraints = [
+ models.UniqueConstraint(fields=["team_id", "server_name"], name="unique_measured_source"),
+ ]
+ indexes = [
+ models.Index(fields=["server"]),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.server_name} (team {self.team_id})"
+
+
+class MCPRankingRun(UUIDModel):
+ """One execution of one ranking version over the whole index.
+
+ Scores are persisted per run rather than overwritten in place so ranking versions
+ can be iterated on and compared side by side: run v1 and v2 against the same index
+ state, then diff their orderings before promoting either.
+ """
+
+ version = models.CharField(max_length=100)
+ params = models.JSONField(default=dict, blank=True)
+ status = models.CharField(max_length=20, choices=RANKING_RUN_STATUS_CHOICES, default="running")
+ error = models.TextField(blank=True, default="")
+ server_count = models.IntegerField(default=0)
+ computed_at = models.DateTimeField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ db_table = "mcp_registry_ranking_run"
+ indexes = [
+ models.Index(fields=["version", "-created_at"]),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.version} @ {self.created_at:%Y-%m-%d %H:%M}"
+
+
+class MCPRankingScore(UUIDModel):
+ """The static (query-independent) score one run assigned one server.
+
+ Search combines this with query-time relevance; this row is the "authority" half,
+ with `components` recording every input so ranking changes stay explainable.
+ """
+
+ run = models.ForeignKey(MCPRankingRun, on_delete=models.CASCADE, related_name="scores")
+ server = models.ForeignKey(MCPRegistryServer, on_delete=models.CASCADE, related_name="scores")
+ score = models.FloatField()
+ components = models.JSONField(default=dict, blank=True)
+
+ class Meta:
+ db_table = "mcp_registry_ranking_score"
+ constraints = [
+ models.UniqueConstraint(fields=["run", "server"], name="unique_score_per_run_server"),
+ ]
+ indexes = [
+ models.Index(fields=["run", "-score"]),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.server} = {self.score:.4f}"
diff --git a/products/mcp_registry/backend/presentation/__init__.py b/products/mcp_registry/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/mcp_registry/backend/presentation/serializers.py b/products/mcp_registry/backend/presentation/serializers.py
new file mode 100644
index 000000000000..5eb6eed72ff7
--- /dev/null
+++ b/products/mcp_registry/backend/presentation/serializers.py
@@ -0,0 +1,277 @@
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+
+
+@extend_schema_field(OpenApiTypes.OBJECT)
+class JSONDictField(serializers.JSONField):
+ pass
+
+
+@extend_schema_field({"type": "array", "items": {"type": "object"}})
+class JSONListField(serializers.JSONField):
+ pass
+
+
+@extend_schema_field({"type": "array", "items": {"type": "string"}})
+class JSONStringListField(serializers.JSONField):
+ pass
+
+
+@extend_schema_field(
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "calls": {"type": "integer"},
+ "errors": {"type": "integer"},
+ "error_rate_pct": {"type": "number"},
+ },
+ },
+ }
+)
+class ToolStatsListField(serializers.JSONField):
+ """Per-tool usage rows: [{name, calls, errors, error_rate_pct}]."""
+
+ pass
+
+
+@extend_schema_field(
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string"},
+ "url": {"type": "string"},
+ },
+ },
+ }
+)
+class RemotesListField(serializers.JSONField):
+ """Hosted remotes: [{type, url}]."""
+
+ pass
+
+
+@extend_schema_field(
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "registry_type": {"type": "string"},
+ "identifier": {"type": "string"},
+ },
+ },
+ }
+)
+class PackagesListField(serializers.JSONField):
+ """Published packages: [{registry_type, identifier}]."""
+
+ pass
+
+
+@extend_schema_field(
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "description": {"type": "string"},
+ "source": {"type": "string"},
+ },
+ },
+ }
+)
+class MatchedToolsListField(serializers.JSONField):
+ """Tools matched in a discover intent: [{name, description, source}]."""
+
+ pass
+
+
+class MCPRegistryToolSerializer(serializers.Serializer):
+ name = serializers.CharField(
+ help_text="Tool name as advertised by the server (exec-resolved for measured servers)."
+ )
+ description = serializers.CharField(help_text="Tool description, from tools/list or from observed calls.")
+ input_schema = JSONDictField(
+ help_text="JSON Schema for the tool's input. Only populated for probed (tools_list) tools."
+ )
+ source = serializers.CharField( # type: ignore[assignment] # field named `source` shadows DRF Field.source
+ help_text="Where we learned about this tool: a probed tools/list (authoritative schema) "
+ "or MCP Analytics usage (proof of real calls, no schema)."
+ )
+ last_seen_at = serializers.DateTimeField(help_text="Last time this tool was observed by either source.")
+
+
+class MCPMeasuredStatsSerializer(serializers.Serializer):
+ window_days = serializers.IntegerField(help_text="Aggregation window in days.")
+ calls = serializers.IntegerField(help_text="Tool calls observed in the window.")
+ sessions = serializers.IntegerField(help_text="Distinct MCP sessions observed in the window.")
+ # Field named `errors` shadows Serializer.errors; fine for a read-only output field.
+ errors = serializers.IntegerField(help_text="Errored tool calls in the window.") # type: ignore[assignment]
+ error_rate_pct = serializers.FloatField(help_text="Errors as a percentage of calls.")
+ intent_coverage_pct = serializers.FloatField(
+ help_text="Percentage of calls carrying an agent-written intent ($mcp_intent)."
+ )
+ distinct_tools = serializers.IntegerField(help_text="Distinct effective tools called in the window.")
+ harness_count = serializers.IntegerField(help_text="Distinct MCP client names observed in the window.")
+ tool_stats = ToolStatsListField(
+ help_text="Per-tool usage, ordered by call volume: [{name, calls, errors, error_rate_pct}]."
+ )
+ link_method = serializers.CharField(
+ help_text="How this measured source was attached to its registry entry "
+ "(override | url | exact_name | standalone)."
+ )
+ link_candidates = JSONStringListField(
+ help_text="Registry names that also matched when linking was ambiguous (kept for review)."
+ )
+ computed_at = serializers.DateTimeField(help_text="When this aggregate was computed.")
+
+
+class MCPRankingScoreInfoSerializer(serializers.Serializer):
+ """One ranking version's latest score for a server."""
+
+ version = serializers.CharField(help_text="Ranking version key (see the versions endpoint).")
+ score = serializers.FloatField(help_text="Static score in [0, 1]; higher ranks first.")
+ components = JSONDictField(help_text="Score inputs (liveness, trust, measured signals) for explainability.")
+ computed_at = serializers.DateTimeField(allow_null=True, help_text="When the run producing this score completed.")
+
+
+class MCPRegistryServerListSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="Registry server id.")
+ registry_name = serializers.CharField(
+ help_text="Reverse-DNS name in the official MCP registry; empty for measured-only servers."
+ )
+ display_name = serializers.CharField(help_text="Human-readable server name.")
+ description = serializers.CharField(help_text="Server description.")
+ canonical_url = serializers.CharField(help_text="Primary hosted remote URL; empty for package-only servers.")
+ liveness = serializers.CharField(help_text="Probed liveness state (alive_open, alive_auth, dead, ...).")
+ auth_method = serializers.CharField(help_text="Detected auth method (none, oauth, api_key, unknown).")
+ listed_in_registry = serializers.BooleanField(help_text="Whether the server appears in the official MCP registry.")
+ is_measured = serializers.BooleanField(help_text="Whether real usage signal exists via MCP Analytics.")
+ rank_score = serializers.FloatField(
+ allow_null=True,
+ help_text="Static score under the requested ranking version; null when the version has no completed run.",
+ )
+
+
+class MCPRegistryServerDetailSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="Registry server id.")
+ registry_name = serializers.CharField(
+ help_text="Reverse-DNS name in the official MCP registry; empty for measured-only servers."
+ )
+ display_name = serializers.CharField(help_text="Human-readable server name.")
+ description = serializers.CharField(help_text="Server description.")
+ canonical_url = serializers.CharField(help_text="Primary hosted remote URL; empty for package-only servers.")
+ liveness = serializers.CharField(help_text="Probed liveness state (alive_open, alive_auth, dead, ...).")
+ auth_method = serializers.CharField(help_text="Detected auth method (none, oauth, api_key, unknown).")
+ listed_in_registry = serializers.BooleanField(help_text="Whether the server appears in the official MCP registry.")
+ is_measured = serializers.BooleanField(help_text="Whether real usage signal exists via MCP Analytics.")
+ rank_score = serializers.FloatField(
+ allow_null=True,
+ help_text="Static score under the requested ranking version; null when the version has no completed run.",
+ )
+ remotes = RemotesListField(help_text="All hosted remotes: [{type, url}].")
+ packages = PackagesListField(help_text="Published packages: [{registry_type, identifier}].")
+ repository_url = serializers.CharField(help_text="Source repository URL, when published.")
+ website_url = serializers.CharField(help_text="Vendor website URL, when published.")
+ last_probed_at = serializers.DateTimeField(allow_null=True, help_text="When the shallow probe last ran.")
+ tools = serializers.ListField(
+ child=serializers.DictField(),
+ help_text="Known tools, fused from probes and analytics. A tool known only from another "
+ "project's traffic is limited to callers who may see that project's measurements.",
+ )
+ measured_stats = serializers.ListField(
+ child=serializers.DictField(),
+ help_text="Behavioral aggregates, one per measured MCP Analytics project. Limited to this "
+ "project's own measurements unless the server is marked measured_public.",
+ )
+ scores = serializers.ListField(
+ child=serializers.DictField(), help_text="Latest score under every ranking version with a completed run."
+ )
+ connect = JSONDictField(
+ help_text="Connection instructions: methods ordered most-automated first, steps typed by actor "
+ "(agent executes; human steps are narrated to the user)."
+ )
+
+
+class MCPRankingRunSerializer(serializers.Serializer):
+ """A completed ranking run."""
+
+ id = serializers.UUIDField(help_text="Run id.")
+ server_count = serializers.IntegerField(help_text="Servers scored in the run.")
+ computed_at = serializers.DateTimeField(allow_null=True, help_text="When the run completed.")
+
+
+class MCPRankingVersionSerializer(serializers.Serializer):
+ """A registered ranking version and its latest completed run."""
+
+ version = serializers.CharField(help_text="Ranking version key, passed as ?version= to the list endpoint.")
+ description = serializers.CharField(help_text="What this version scores on.")
+ is_default = serializers.BooleanField(help_text="Whether this is the version used when ?version= is omitted.")
+ latest_run = MCPRankingRunSerializer(
+ allow_null=True,
+ help_text="Latest completed run; null when the version never ran.",
+ )
+
+
+class MCPDiscoverCandidateSerializer(serializers.Serializer):
+ """One ranked candidate in a discover response, with everything an agent needs to act."""
+
+ rank = serializers.IntegerField(help_text="1-based position under the ranking version used.")
+ id = serializers.UUIDField(help_text="Registry server id, for the detail endpoint.")
+ registry_name = serializers.CharField(help_text="Official registry name, empty for measured-only servers.")
+ title = serializers.CharField(help_text="Human-readable server name.")
+ description = serializers.CharField(help_text="What the server does.")
+ score = serializers.FloatField(help_text="Rank score in [0, 1] under the ranking version used.")
+ why = JSONDictField(
+ help_text="Score breakdown so an agent can explain its choice: fit, liveness, trust, and whether "
+ "real usage signal contributed."
+ )
+ liveness = serializers.CharField(help_text="Probed liveness state (alive_open, alive_auth, dead, ...).")
+ auth_method = serializers.CharField(help_text="Detected auth method (none, oauth, api_key, unknown).")
+ measured = JSONDictField(
+ allow_null=True,
+ help_text="Real MCP Analytics aggregates when the server is measured, otherwise null: calls, "
+ "sessions, error_rate_pct, intent_coverage_pct, harness_count.",
+ )
+ matched_tools = MatchedToolsListField(
+ help_text="Tools that matched the intent: [{name, description, source}]. Empty when only the server "
+ "description matched."
+ )
+ connect = JSONDictField(
+ help_text="Connection instructions, most-automated method first, steps typed by actor so the agent "
+ "runs its own steps and narrates the human ones."
+ )
+
+
+class MCPDiscoverResponseSerializer(serializers.Serializer):
+ """Everything an agent gets back from one discover call."""
+
+ intent = serializers.CharField(help_text="The intent the candidates were ranked against, echoed back.")
+ ranking_version = serializers.CharField(help_text="Ranking version the candidates were ordered by.")
+ candidates = MCPDiscoverCandidateSerializer(many=True, help_text="Servers most likely to do the thing, best first.")
+
+
+class MCPMeasuredProjectSerializer(serializers.Serializer):
+ """One project's contribution to the measured layer, for the staff fleet view."""
+
+ team_id = serializers.IntegerField(help_text="Project supplying the MCP Analytics signal.")
+ servers = serializers.IntegerField(help_text="Distinct servers this project has measured.")
+ calls = serializers.IntegerField(help_text="Tool calls this project contributes across those servers.")
+
+
+class MCPRegistryCompareRowSerializer(serializers.Serializer):
+ """One server's position under one ranking version."""
+
+ rank = serializers.IntegerField(help_text="1-based position under this version.")
+ id = serializers.UUIDField(help_text="Registry server id.")
+ registry_name = serializers.CharField(help_text="Official registry name, empty for measured-only rows.")
+ display_name = serializers.CharField(help_text="Human-readable server name.")
+ score = serializers.FloatField(help_text="Static score under this version.")
+ is_measured = serializers.BooleanField(help_text="Whether the server carries MCP Analytics signal.")
diff --git a/products/mcp_registry/backend/presentation/views.py b/products/mcp_registry/backend/presentation/views.py
new file mode 100644
index 000000000000..e22c3d1e6cc1
--- /dev/null
+++ b/products/mcp_registry/backend/presentation/views.py
@@ -0,0 +1,234 @@
+from typing import Any
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, extend_schema
+from rest_framework import viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
+from rest_framework.pagination import LimitOffsetPagination
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.permissions import PostHogFeatureFlagPermission
+
+from products.mcp_registry.backend.facade import api as registry_api
+from products.mcp_registry.backend.facade.api import MCP_REGISTRY_FEATURE_FLAG
+from products.mcp_registry.backend.presentation.serializers import (
+ MCPDiscoverResponseSerializer,
+ MCPMeasuredProjectSerializer,
+ MCPMeasuredStatsSerializer,
+ MCPRankingScoreInfoSerializer,
+ MCPRankingVersionSerializer,
+ MCPRegistryCompareRowSerializer,
+ MCPRegistryServerDetailSerializer,
+ MCPRegistryServerListSerializer,
+ MCPRegistryToolSerializer,
+)
+
+_COMPARE_DEFAULT_LIMIT = 20
+_COMPARE_MAX_LIMIT = 100
+_DISCOVER_DEFAULT_LIMIT = 5
+_DISCOVER_MAX_LIMIT = 20
+
+
+class MCPRegistryPagination(LimitOffsetPagination):
+ default_limit = 50
+ max_limit = 200
+
+
+class MCPRegistryServerViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """Search and inspect the MCP registry index.
+
+ The index is global (the same servers exist for every project); the endpoint is
+ project-scoped only for auth and flag gating. Every read goes through the facade:
+ this viewset parses the request and serializes the contract it gets back.
+ """
+
+ serializer_class = MCPRegistryServerListSerializer
+ scope_object = "INTERNAL"
+ posthog_feature_flag = MCP_REGISTRY_FEATURE_FLAG
+ permission_classes = [PostHogFeatureFlagPermission]
+ pagination_class = MCPRegistryPagination
+
+ def _caller_is_staff(self) -> bool:
+ return bool(getattr(self.request.user, "is_staff", False))
+
+ def _caller_context(self) -> dict[str, Any]:
+ return {"team_id": self.team.id, "caller_is_staff": self._caller_is_staff()}
+
+ def _resolve_version(self, request: Request) -> str:
+ version = request.query_params.get("version") or registry_api.default_ranking_version()
+ if not registry_api.is_valid_version(version):
+ raise ValidationError(
+ {"version": f"unknown ranking version; one of: {registry_api.known_ranking_versions()}"}
+ )
+ return version
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "search",
+ OpenApiTypes.STR,
+ description="Free-text query matched against server names, descriptions, and tool names.",
+ ),
+ OpenApiParameter(
+ "version",
+ OpenApiTypes.STR,
+ description="Ranking version ordering the results; defaults to the current default version.",
+ ),
+ OpenApiParameter(
+ "measured_only",
+ OpenApiTypes.BOOL,
+ description="Only servers with real MCP Analytics signal.",
+ ),
+ ],
+ responses={200: MCPRegistryServerListSerializer(many=True)},
+ description="List registry servers ordered by static rank under the chosen ranking version.",
+ )
+ def list(self, request: Request, **kwargs) -> Response:
+ version = self._resolve_version(request)
+ summaries = registry_api.list_servers(
+ version=version,
+ search=(request.query_params.get("search") or "").strip(),
+ measured_only=request.query_params.get("measured_only") in ("true", "1"),
+ **self._caller_context(),
+ )
+ page = self.paginate_queryset(summaries)
+ serializer = MCPRegistryServerListSerializer(page, many=True)
+ return self.get_paginated_response(serializer.data)
+
+ @extend_schema(
+ responses={200: MCPRegistryServerDetailSerializer},
+ description="Full server record: tools, measured stats, per-version scores, connection instructions.",
+ )
+ def retrieve(self, request: Request, pk: str | None = None, **kwargs) -> Response:
+ if pk is None:
+ raise NotFound()
+ detail = registry_api.get_server_detail(pk=pk, **self._caller_context())
+ if detail is None:
+ raise NotFound()
+ summary_fields = [
+ "id",
+ "registry_name",
+ "display_name",
+ "description",
+ "canonical_url",
+ "liveness",
+ "auth_method",
+ "listed_in_registry",
+ "is_measured",
+ "rank_score",
+ ]
+ serializer = MCPRegistryServerDetailSerializer(
+ {
+ **{field: getattr(detail, field) for field in summary_fields},
+ "remotes": detail.remotes,
+ "packages": detail.packages,
+ "repository_url": detail.repository_url,
+ "website_url": detail.website_url,
+ "last_probed_at": detail.last_probed_at,
+ "tools": MCPRegistryToolSerializer(detail.tools, many=True).data,
+ "measured_stats": MCPMeasuredStatsSerializer(detail.measured_stats, many=True).data,
+ "scores": MCPRankingScoreInfoSerializer(detail.scores, many=True).data,
+ "connect": detail.connect_instructions,
+ }
+ )
+ return Response(serializer.data)
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "intent",
+ OpenApiTypes.STR,
+ required=True,
+ description="What the agent is trying to do, in natural language.",
+ ),
+ OpenApiParameter("version", OpenApiTypes.STR, description="Ranking version to rank candidates by."),
+ OpenApiParameter("limit", OpenApiTypes.INT, description="Candidates to return (default 5, max 20)."),
+ ],
+ responses={200: MCPDiscoverResponseSerializer},
+ description="Given a task, return the MCP servers most likely to do it, each with its rank rationale, "
+ "real usage signal where we measure it, and ready-to-run connection instructions. One call is "
+ "everything an agent needs to go from a task to a connected server.",
+ )
+ @action(detail=False, methods=["GET"], pagination_class=None)
+ def discover(self, request: Request, **kwargs) -> Response:
+ intent = (request.query_params.get("intent") or "").strip()
+ if not intent:
+ raise ValidationError({"intent": "describe what you are trying to do"})
+ version = self._resolve_version(request)
+ try:
+ limit = min(int(request.query_params.get("limit", _DISCOVER_DEFAULT_LIMIT)), _DISCOVER_MAX_LIMIT)
+ except ValueError:
+ raise ValidationError({"limit": "must be an integer"})
+
+ candidates = registry_api.discover_servers(
+ intent=intent, version=version, limit=limit, **self._caller_context()
+ )
+ return Response(
+ MCPDiscoverResponseSerializer({"intent": intent, "ranking_version": version, "candidates": candidates}).data
+ )
+
+ @extend_schema(
+ responses={200: MCPMeasuredProjectSerializer(many=True)},
+ description="Which projects feed MCP Analytics signal into the index, and how much each "
+ "contributes. Staff only, because it reports across every project rather than the one in "
+ "the route: it answers whether the measured layer has enough coverage to rank on.",
+ )
+ @action(detail=False, methods=["GET"], pagination_class=None)
+ def measured_projects(self, request: Request, **kwargs) -> Response:
+ if not self._caller_is_staff():
+ raise PermissionDenied("Reporting across projects is limited to PostHog staff.")
+ rows = registry_api.measured_projects()
+ return Response(MCPMeasuredProjectSerializer(rows, many=True).data)
+
+ @extend_schema(
+ responses={200: MCPRankingVersionSerializer(many=True)},
+ description="Registered ranking versions and their latest completed runs.",
+ )
+ @action(detail=False, methods=["GET"], pagination_class=None)
+ def versions(self, request: Request, **kwargs) -> Response:
+ payload = registry_api.ranking_versions()
+ return Response(MCPRankingVersionSerializer(payload, many=True).data)
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "versions",
+ OpenApiTypes.STR,
+ description="Comma-separated ranking versions to compare (2+).",
+ required=True,
+ ),
+ OpenApiParameter("search", OpenApiTypes.STR, description="Optional text filter applied to every arm."),
+ OpenApiParameter("limit", OpenApiTypes.INT, description="Rows per arm (default 20, max 100)."),
+ ],
+ responses={200: OpenApiTypes.OBJECT},
+ description="Rank the same index under several ranking versions side by side. With exactly two "
+ "versions the response includes per-server rank deltas, the review surface for promoting a "
+ "new ranking version.",
+ )
+ @action(detail=False, methods=["GET"], pagination_class=None)
+ def compare(self, request: Request, **kwargs) -> Response:
+ raw_versions = [v.strip() for v in (request.query_params.get("versions") or "").split(",") if v.strip()]
+ if len(raw_versions) < 2:
+ raise ValidationError({"versions": "pass at least two comma-separated ranking versions"})
+ unknown = [v for v in raw_versions if not registry_api.is_valid_version(v)]
+ if unknown:
+ raise ValidationError({"versions": f"unknown ranking versions: {unknown}"})
+ try:
+ limit = min(int(request.query_params.get("limit", _COMPARE_DEFAULT_LIMIT)), _COMPARE_MAX_LIMIT)
+ except ValueError:
+ raise ValidationError({"limit": "must be an integer"})
+ search = (request.query_params.get("search") or "").strip()
+
+ arms = registry_api.compare_rankings(
+ versions=raw_versions, search=search, limit=limit, **self._caller_context()
+ )
+ arms_data = {version: MCPRegistryCompareRowSerializer(rows, many=True).data for version, rows in arms.items()}
+
+ response: dict = {"versions": arms_data}
+ if len(raw_versions) == 2:
+ first, second = raw_versions
+ response["rank_deltas"] = registry_api.rank_deltas(arms, first, second)
+ return Response(response)
diff --git a/products/mcp_registry/backend/probe.py b/products/mcp_registry/backend/probe.py
new file mode 100644
index 000000000000..648fcf912367
--- /dev/null
+++ b/products/mcp_registry/backend/probe.py
@@ -0,0 +1,182 @@
+"""Shallow, repeatable liveness probe for registry servers.
+
+Deliberately less thorough than mcp_store's activation probe: that one performs a
+real RFC 7591 DCR registration, which mints an OAuth client on the vendor's system
+and therefore can only run once per server. This probe is side-effect-free (one
+`initialize` handshake to classify liveness + auth, plus `tools/list` when the
+server answers without credentials), so it can sweep the whole index on a schedule
+and keep liveness a living signal.
+"""
+
+import json
+from dataclasses import field
+from typing import Any
+
+from django.utils import timezone
+
+import requests
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.security.pinned_requests import SSRFBlockedError, pinned_request
+
+from products.mcp_registry.backend.constants import (
+ PROBE_BATCH_SIZE,
+ PROBE_TIMEOUT_SECONDS,
+ PROBE_TOOL_DESCRIPTION_MAX_CHARS,
+ PROBE_TOOL_LIMIT,
+)
+from products.mcp_registry.backend.models import MCPRegistryServer, MCPRegistryTool
+
+logger = structlog.get_logger(__name__)
+
+_PROTOCOL_VERSION = "2025-06-18"
+_HEADERS = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+}
+_INITIALIZE_PAYLOAD = {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": _PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {"name": "posthog-mcp-registry-probe", "version": "0.1"},
+ },
+}
+
+
+@frozen
+class ProbeOutcome:
+ liveness: str = "dead" # a LIVENESS_CHOICES key
+ auth_method: str = "unknown" # an AUTH_METHOD_CHOICES key
+ detail: str = ""
+ tools: list[dict[str, Any]] = field(default_factory=list)
+
+
+def _parse_jsonrpc_body(text: str) -> dict[str, Any] | None:
+ """Streamable-HTTP responses arrive as raw JSON or as an SSE frame."""
+ stripped = text.strip()
+ if stripped.startswith("{"):
+ try:
+ return json.loads(stripped)
+ except ValueError:
+ return None
+ for line in stripped.splitlines():
+ if line.startswith("data:"):
+ try:
+ return json.loads(line[len("data:") :].strip())
+ except ValueError:
+ continue
+ return None
+
+
+def _classify_auth(response: requests.Response) -> str:
+ www_authenticate = response.headers.get("WWW-Authenticate", "")
+ if "bearer" in www_authenticate.lower():
+ return "oauth"
+ hint = (www_authenticate + response.text[:400]).lower()
+ if "api key" in hint or "api-key" in hint or "api_key" in hint:
+ return "api_key"
+ return "unknown"
+
+
+def _rpc(url: str, payload: dict[str, Any], session_id: str | None = None) -> requests.Response:
+ headers = dict(_HEADERS)
+ if session_id:
+ headers["mcp-session-id"] = session_id
+ return pinned_request("POST", url, json=payload, headers=headers, timeout=PROBE_TIMEOUT_SECONDS)
+
+
+def _fetch_tools(url: str, session_id: str | None) -> list[dict[str, Any]]:
+ _rpc(url, {"jsonrpc": "2.0", "method": "notifications/initialized"}, session_id)
+ response = _rpc(url, {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}, session_id)
+ body = _parse_jsonrpc_body(response.text) or {}
+ tools = (body.get("result") or {}).get("tools")
+ if not isinstance(tools, list):
+ return []
+ return [
+ {
+ "name": tool.get("name") or "",
+ "description": (tool.get("description") or "")[:PROBE_TOOL_DESCRIPTION_MAX_CHARS],
+ "input_schema": tool.get("inputSchema") or {},
+ }
+ for tool in tools[:PROBE_TOOL_LIMIT]
+ if tool.get("name")
+ ]
+
+
+def shallow_probe(url: str) -> ProbeOutcome:
+ """Classify one server URL. Never raises."""
+ try:
+ response = _rpc(url, _INITIALIZE_PAYLOAD)
+ except SSRFBlockedError as exc:
+ return ProbeOutcome(detail=f"ssrf_blocked: {exc}"[:200])
+ except requests.RequestException as exc:
+ return ProbeOutcome(detail=str(exc)[:200])
+
+ if 300 <= response.status_code < 400:
+ # A redirect target never went through SSRF validation, so refuse to follow.
+ return ProbeOutcome(liveness="not_mcp", detail=f"redirect http {response.status_code}")
+
+ body = _parse_jsonrpc_body(response.text)
+ result = (body or {}).get("result") or {}
+ if result.get("serverInfo") or result.get("capabilities"):
+ tools: list[dict[str, Any]] = []
+ detail = ""
+ try:
+ tools = _fetch_tools(url, response.headers.get("mcp-session-id"))
+ except (requests.RequestException, SSRFBlockedError) as exc:
+ detail = f"tools/list failed: {exc}"[:200]
+ return ProbeOutcome(liveness="alive_open", auth_method="none", detail=detail, tools=tools)
+
+ if response.status_code in (401, 403):
+ return ProbeOutcome(liveness="alive_auth", auth_method=_classify_auth(response))
+ if response.status_code == 200 and (body or {}).get("error"):
+ return ProbeOutcome(liveness="alive_protocol", detail=f"rpc error {(body or {})['error'].get('code')}")
+ if 200 <= response.status_code < 300:
+ return ProbeOutcome(liveness="not_mcp", detail=f"http {response.status_code}")
+ return ProbeOutcome(detail=f"http {response.status_code}")
+
+
+def apply_probe_outcome(server: MCPRegistryServer, outcome: ProbeOutcome) -> None:
+ server.liveness = outcome.liveness
+ if outcome.auth_method != "unknown" or server.auth_method == "unknown":
+ server.auth_method = outcome.auth_method
+ server.probe_detail = outcome.detail
+ server.last_probed_at = timezone.now()
+ server.save(update_fields=["liveness", "auth_method", "probe_detail", "last_probed_at", "updated_at"])
+
+ seen_at = server.last_probed_at
+ for tool in outcome.tools:
+ MCPRegistryTool.objects.update_or_create(
+ server=server,
+ name=tool["name"],
+ defaults={
+ "description": tool["description"],
+ "input_schema": tool["input_schema"],
+ "source": "tools_list",
+ "last_seen_at": seen_at,
+ },
+ )
+
+
+def probe_stalest_servers(batch_size: int = PROBE_BATCH_SIZE) -> int:
+ """Probe the servers with the oldest (or missing) probe results. Returns count probed.
+
+ Measured servers first, because their liveness backs real rankings, then the long tail,
+ so the whole index converges over successive scheduled runs.
+ """
+ queryset = (
+ MCPRegistryServer.objects.exclude(canonical_url="")
+ .order_by("-is_measured", "last_probed_at")
+ .values_list("id", flat=True)[:batch_size]
+ )
+ probed = 0
+ for server_id in list(queryset):
+ server = MCPRegistryServer.objects.get(pk=server_id)
+ apply_probe_outcome(server, shallow_probe(server.canonical_url))
+ probed += 1
+ logger.info("mcp_registry.probe.batch_done", probed=probed)
+ return probed
diff --git a/products/mcp_registry/backend/ranking.py b/products/mcp_registry/backend/ranking.py
new file mode 100644
index 000000000000..4d2f3df546f0
--- /dev/null
+++ b/products/mcp_registry/backend/ranking.py
@@ -0,0 +1,156 @@
+"""Versioned static ranking over the registry index.
+
+Every version is a pure function from a server's signals to a score with an
+explainable component breakdown. Versions are never edited in place: iterate by
+adding a new key, running it, and comparing its ordering against the incumbent via
+the API before promoting DEFAULT_RANKING_VERSION. Query-time relevance (does this
+server match the search?) is layered on top by the API; these scores are the
+query-independent "is this server any good?" half.
+"""
+
+import math
+from collections.abc import Callable
+from datetime import timedelta
+
+from django.utils import timezone
+
+import structlog
+
+from posthog.dataclasses import frozen
+
+from products.mcp_registry.backend.constants import MEASURED_STALE_AFTER_DAYS
+from products.mcp_registry.backend.models import MCPMeasuredStats, MCPRankingRun, MCPRankingScore, MCPRegistryServer
+
+logger = structlog.get_logger(__name__)
+
+# How much each probed liveness state is worth. Dead servers stay in the index (the
+# listing is still real) but rank under everything alive.
+LIVENESS_WEIGHTS: dict[str, float] = {
+ "alive_open": 1.0,
+ "alive_auth": 0.95,
+ "alive_protocol": 0.8,
+ "package_only": 0.55,
+ "unprobed": 0.4,
+ "not_mcp": 0.25,
+ "dead": 0.1,
+}
+
+# Calls at which measured volume confidence saturates (log scale).
+_VOLUME_SATURATION_CALLS = 100_000
+
+
+@frozen
+class ScoreResult:
+ score: float
+ components: dict[str, float | str | bool]
+
+
+def _metadata_prior(server: MCPRegistryServer) -> float:
+ """Weak trust prior from public metadata alone, which any registry could compute."""
+ prior = 0.45
+ if server.repository_url:
+ prior += 0.1
+ if server.tools.exists():
+ prior += 0.1
+ return min(prior, 1.0)
+
+
+def _measured_trust(stats: list[MCPMeasuredStats]) -> tuple[float, dict[str, float]]:
+ """Behavioral trust from MCP Analytics: reliability weighted by volume confidence.
+
+ Multiple stats rows (same server measured in several projects) combine by call
+ volume, so a high-traffic deployment dominates a toy one.
+
+ Rows past MEASURED_STALE_AFTER_DAYS are dropped. Aggregation only upserts servers
+ that appeared in the window, so a server that stopped being called keeps its last
+ row; counting it would let a server coast forever on trust it earned while busy.
+ A server whose rows have all gone stale falls back to its metadata prior.
+ """
+ cutoff = timezone.now() - timedelta(days=MEASURED_STALE_AFTER_DAYS)
+ stats = [row for row in stats if row.computed_at and row.computed_at >= cutoff]
+ total_calls = sum(row.calls for row in stats)
+ if total_calls <= 0:
+ return 0.0, {}
+ reliability = sum((1 - row.error_rate_pct / 100) * row.calls for row in stats) / total_calls
+ intent_coverage = sum(row.intent_coverage_pct * row.calls for row in stats) / total_calls / 100
+ volume_confidence = min(math.log10(total_calls + 1) / math.log10(_VOLUME_SATURATION_CALLS), 1.0)
+ trust = 0.65 + 0.35 * (reliability * volume_confidence)
+ return min(trust, 1.0), {
+ "measured_reliability": round(reliability, 4),
+ "measured_volume_confidence": round(volume_confidence, 4),
+ "measured_intent_coverage": round(intent_coverage, 4),
+ }
+
+
+def _score_v1_metadata_prior(server: MCPRegistryServer, stats: list[MCPMeasuredStats]) -> ScoreResult:
+ """Baseline: liveness x public-metadata trust. Ignores measured signal on purpose because
+ this is the control arm any registry could replicate."""
+ liveness = LIVENESS_WEIGHTS.get(server.liveness, 0.4)
+ trust = _metadata_prior(server)
+ score = (liveness**0.5) * (trust**0.5)
+ return ScoreResult(
+ score=round(score, 6),
+ components={"liveness": liveness, "trust": round(trust, 4), "measured": False},
+ )
+
+
+def _score_v2_measured_trust(server: MCPRegistryServer, stats: list[MCPMeasuredStats]) -> ScoreResult:
+ """v1 plus behavioral trust for measured servers, the arm that uses our signal."""
+ liveness = LIVENESS_WEIGHTS.get(server.liveness, 0.4)
+ components: dict[str, float | str | bool] = {"liveness": liveness, "measured": False}
+ trust = _metadata_prior(server)
+ if stats:
+ measured_trust, measured_components = _measured_trust(stats)
+ if measured_trust > 0:
+ trust = measured_trust
+ components["measured"] = True
+ components.update(measured_components)
+ components["trust"] = round(trust, 4)
+ score = (liveness**0.5) * (trust**0.5)
+ return ScoreResult(score=round(score, 6), components=components)
+
+
+RANKING_VERSIONS: dict[str, Callable[[MCPRegistryServer, list[MCPMeasuredStats]], ScoreResult]] = {
+ "v1_metadata_prior": _score_v1_metadata_prior,
+ "v2_measured_trust": _score_v2_measured_trust,
+}
+
+DEFAULT_RANKING_VERSION = "v2_measured_trust"
+
+_BULK_BATCH_SIZE = 1_000
+
+
+def compute_ranking_run(version: str) -> MCPRankingRun:
+ """Score every server under one version, persisting a new run + its scores."""
+ scorer = RANKING_VERSIONS.get(version)
+ if scorer is None:
+ raise ValueError(f"unknown ranking version: {version}")
+
+ run = MCPRankingRun.objects.create(version=version)
+ try:
+ batch: list[MCPRankingScore] = []
+ count = 0
+ for server in MCPRegistryServer.objects.prefetch_related("measured_stats", "tools").iterator(chunk_size=500):
+ result = scorer(server, list(server.measured_stats.all()))
+ batch.append(MCPRankingScore(run=run, server=server, score=result.score, components=result.components))
+ count += 1
+ if len(batch) >= _BULK_BATCH_SIZE:
+ MCPRankingScore.objects.bulk_create(batch)
+ batch = []
+ if batch:
+ MCPRankingScore.objects.bulk_create(batch)
+ run.status = "completed"
+ run.server_count = count
+ run.computed_at = timezone.now()
+ run.save(update_fields=["status", "server_count", "computed_at"])
+ logger.info("mcp_registry.ranking.completed", version=version, servers=count, run_id=str(run.id))
+ except Exception as exc:
+ run.status = "failed"
+ run.error = str(exc)[:2000]
+ run.save(update_fields=["status", "error"])
+ raise
+ return run
+
+
+def latest_completed_run(version: str) -> MCPRankingRun | None:
+ return MCPRankingRun.objects.filter(version=version, status="completed").order_by("-created_at").first()
diff --git a/products/mcp_registry/backend/routes.py b/products/mcp_registry/backend/routes.py
new file mode 100644
index 000000000000..9141b657700b
--- /dev/null
+++ b/products/mcp_registry/backend/routes.py
@@ -0,0 +1,12 @@
+from posthog.api.routing import RouterRegistry
+
+import products.mcp_registry.backend.presentation.views as mcp_registry
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(
+ r"mcp_registry/servers",
+ mcp_registry.MCPRegistryServerViewSet,
+ "project_mcp_registry_servers",
+ ["team_id"],
+ )
diff --git a/products/mcp_registry/backend/tasks/__init__.py b/products/mcp_registry/backend/tasks/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/mcp_registry/backend/tasks/tasks.py b/products/mcp_registry/backend/tasks/tasks.py
new file mode 100644
index 000000000000..6076bac430cf
--- /dev/null
+++ b/products/mcp_registry/backend/tasks/tasks.py
@@ -0,0 +1,78 @@
+from typing import Any
+
+import structlog
+import posthoganalytics
+from celery import shared_task
+from celery.schedules import crontab
+
+from posthog.celery_queues import CeleryQueue
+from posthog.scoping_audit import skip_team_scope_audit
+
+from products.mcp_registry.backend.aggregation import aggregate_measured_servers
+from products.mcp_registry.backend.constants import MCP_REGISTRY_FEATURE_FLAG, MCP_REGISTRY_PIPELINE_DISTINCT_ID
+from products.mcp_registry.backend.crawl import crawl_official_registry
+from products.mcp_registry.backend.probe import probe_stalest_servers
+from products.mcp_registry.backend.ranking import RANKING_VERSIONS, compute_ranking_run
+
+logger = structlog.get_logger(__name__)
+
+# Registered centrally in posthog/tasks/scheduled.py (crontabs are not auto-collected).
+MCP_REGISTRY_SYNC_CRONTAB = crontab(hour="5", minute="45")
+
+
+def is_pipeline_enabled() -> bool:
+ """Deployment-level kill switch, evaluated with a constant distinct_id. Fails closed."""
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ MCP_REGISTRY_FEATURE_FLAG,
+ MCP_REGISTRY_PIPELINE_DISTINCT_ID,
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.exception("mcp_registry.pipeline_flag_check_failed")
+ return False
+
+
+def run_sync_pipeline(skip_crawl: bool = False, skip_probe: bool = False) -> dict[str, Any]:
+ """Crawl -> aggregate -> probe -> rank, each stage isolated so one failure
+ doesn't starve the rest (yesterday's crawl still deserves today's ranking)."""
+ outcome: dict[str, Any] = {}
+ if not skip_crawl:
+ try:
+ crawl_outcome = crawl_official_registry()
+ outcome["crawl"] = {"created": crawl_outcome.created, "updated": crawl_outcome.updated}
+ except Exception:
+ logger.exception("mcp_registry.sync.crawl_failed")
+ outcome["crawl"] = "failed"
+ try:
+ outcome["measured_sources"] = aggregate_measured_servers()
+ except Exception:
+ logger.exception("mcp_registry.sync.aggregate_failed")
+ outcome["measured_sources"] = "failed"
+ if not skip_probe:
+ try:
+ outcome["probed"] = probe_stalest_servers()
+ except Exception:
+ logger.exception("mcp_registry.sync.probe_failed")
+ outcome["probed"] = "failed"
+ outcome["ranking_runs"] = {}
+ for version in sorted(RANKING_VERSIONS):
+ try:
+ run = compute_ranking_run(version)
+ outcome["ranking_runs"][version] = run.server_count
+ except Exception:
+ logger.exception("mcp_registry.sync.ranking_failed", version=version)
+ outcome["ranking_runs"][version] = "failed"
+ logger.info("mcp_registry.sync.done", **{k: v for k, v in outcome.items() if k != "ranking_runs"})
+ return outcome
+
+
+@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)
+@skip_team_scope_audit
+def run_mcp_registry_sync() -> None:
+ if not is_pipeline_enabled():
+ return
+ run_sync_pipeline()
diff --git a/products/mcp_registry/backend/tests/test_aggregation.py b/products/mcp_registry/backend/tests/test_aggregation.py
new file mode 100644
index 000000000000..4ba2b7d295dc
--- /dev/null
+++ b/products/mcp_registry/backend/tests/test_aggregation.py
@@ -0,0 +1,65 @@
+from typing import Any
+
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event
+
+from products.mcp_registry.backend.aggregation import aggregate_team, discover_measured_teams
+from products.mcp_registry.backend.models import MCPMeasuredStats, MCPRegistryServer, MCPRegistryTool
+
+
+def _tool_call(team: Any, session_id: str, **properties: Any) -> None:
+ _create_event(
+ team=team,
+ event="$mcp_tool_call",
+ distinct_id="agent-user",
+ properties={
+ "$mcp_source": "posthog_mcp_analytics",
+ "$mcp_server_name": "PostHog",
+ "$mcp_session_id": session_id,
+ "$mcp_client_name": "Claude Code",
+ "$mcp_is_error": False,
+ **properties,
+ },
+ )
+
+
+class TestAggregation(ClickhouseTestMixin, BaseTest):
+ def test_aggregate_team_rolls_up_stats_and_resolves_effective_tools(self) -> None:
+ official = MCPRegistryServer.objects.create(
+ registry_name="io.github.PostHog/mcp", display_name="PostHog MCP Server", listed_in_registry=True
+ )
+ _tool_call(self.team, "s1", **{"$mcp_tool_name": "execute-sql", "$mcp_intent": "check error volume"})
+ # Single-exec call: must roll up under the inner tool, not under "exec".
+ _tool_call(
+ self.team,
+ "s1",
+ **{"$mcp_tool_name": "exec", "$mcp_exec_tool_call_name": "execute-sql", "$mcp_is_error": True},
+ )
+ _tool_call(self.team, "s2", **{"$mcp_tool_name": "docs-search", "$mcp_intent": "find docs"})
+ # Different SDK source and missing server name must both be ignored.
+ _tool_call(self.team, "s3", **{"$mcp_tool_name": "noise", "$mcp_source": "other_sdk"})
+ _tool_call(self.team, "s3", **{"$mcp_tool_name": "noise", "$mcp_server_name": ""})
+
+ processed = aggregate_team(self.team)
+
+ assert processed == 1
+ stats = MCPMeasuredStats.objects.unscoped().get(team_id=self.team.id, server_name="PostHog")
+ assert stats.server == official
+ assert stats.link_method == "override"
+ assert (stats.calls, stats.sessions, stats.errors) == (3, 2, 1)
+ assert stats.distinct_tools == 2
+ assert round(stats.intent_coverage_pct) == 67
+ by_name = {row["name"]: row for row in stats.tool_stats}
+ assert by_name["execute-sql"]["calls"] == 2
+ assert by_name["execute-sql"]["errors"] == 1
+ assert by_name["docs-search"]["calls"] == 1
+
+ official.refresh_from_db()
+ assert official.is_measured is True
+ assert set(
+ MCPRegistryTool.objects.filter(server=official, source="analytics").values_list("name", flat=True)
+ ) == {"execute-sql", "docs-search"}
+
+ def test_discover_measured_teams_finds_teams_with_new_sdk_traffic(self) -> None:
+ _tool_call(self.team, "s1", **{"$mcp_tool_name": "execute-sql"})
+
+ assert self.team.id in discover_measured_teams()
diff --git a/products/mcp_registry/backend/tests/test_api.py b/products/mcp_registry/backend/tests/test_api.py
new file mode 100644
index 000000000000..4abdf71705f9
--- /dev/null
+++ b/products/mcp_registry/backend/tests/test_api.py
@@ -0,0 +1,387 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from products.mcp_registry.backend.models import MCPMeasuredStats, MCPRegistryServer, MCPRegistryTool
+from products.mcp_registry.backend.ranking import compute_ranking_run
+
+
+def _only_mcp_registry_flag(flag_key: str, *args: object, **kwargs: object) -> bool:
+ return flag_key == "mcp-registry"
+
+
+class TestMCPRegistryAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ flag_patcher = patch("posthoganalytics.feature_enabled", side_effect=_only_mcp_registry_flag)
+ flag_patcher.start()
+ self.addCleanup(flag_patcher.stop)
+
+ def _url(self, suffix: str = "") -> str:
+ return f"/api/projects/{self.team.id}/mcp_registry/servers/{suffix}"
+
+ def _seed_index(self) -> dict[str, MCPRegistryServer]:
+ measured = MCPRegistryServer.objects.create(
+ registry_name="io.github.PostHog/mcp",
+ display_name="Product analytics server",
+ description="Product analytics, session replay, feature flags, and experiments.",
+ listed_in_registry=True,
+ is_measured=True,
+ liveness="alive_auth",
+ auth_method="oauth",
+ canonical_url="https://mcp.example.com/mcp",
+ )
+ MCPMeasuredStats.objects.unscoped().create(
+ server=measured,
+ team_id=self.team.id,
+ server_name="PostHog",
+ window_days=30,
+ calls=50_000,
+ errors=1_000,
+ error_rate_pct=2.0,
+ intent_coverage_pct=90.0,
+ link_method="override",
+ computed_at=timezone.now(),
+ )
+ unmeasured = MCPRegistryServer.objects.create(
+ registry_name="io.example/analytics-helper",
+ display_name="Product analytics helper",
+ description="Product analytics, session replay, feature flags, and experiments.",
+ listed_in_registry=True,
+ repository_url="https://github.com/example/analytics-helper",
+ liveness="alive_open",
+ auth_method="none",
+ canonical_url="https://helper.example.com/mcp",
+ )
+ MCPRegistryTool.objects.create(
+ server=unmeasured,
+ name="query_analytics",
+ description="Run an analytics query",
+ source="tools_list",
+ last_seen_at=timezone.now(),
+ )
+ compute_ranking_run("v1_metadata_prior")
+ compute_ranking_run("v2_measured_trust")
+ return {"measured": measured, "unmeasured": unmeasured}
+
+ def test_endpoints_require_the_feature_flag(self) -> None:
+ with patch("posthoganalytics.feature_enabled", return_value=False):
+ response = self.client.get(self._url())
+ assert response.status_code == 403
+
+ def test_requires_authentication(self) -> None:
+ self.client.logout()
+ assert self.client.get(self._url()).status_code == 401
+
+ def test_list_orders_by_requested_ranking_version(self) -> None:
+ servers = self._seed_index()
+
+ default = self.client.get(self._url()).json()
+ control = self.client.get(self._url(), {"version": "v1_metadata_prior"}).json()
+
+ # The measured arm puts real usage first; the metadata-only arm inverts that.
+ assert [row["id"] for row in default["results"]][:2] == [
+ str(servers["measured"].id),
+ str(servers["unmeasured"].id),
+ ]
+ assert [row["id"] for row in control["results"]][:2] == [
+ str(servers["unmeasured"].id),
+ str(servers["measured"].id),
+ ]
+ assert default["results"][0]["rank_score"] is not None
+
+ def test_list_rejects_unknown_ranking_version(self) -> None:
+ assert self.client.get(self._url(), {"version": "bogus"}).status_code == 400
+
+ def test_search_matches_tool_names(self) -> None:
+ servers = self._seed_index()
+
+ response = self.client.get(self._url(), {"search": "query_analytics"}).json()
+
+ assert [row["id"] for row in response["results"]] == [str(servers["unmeasured"].id)]
+
+ def test_measured_only_filter(self) -> None:
+ servers = self._seed_index()
+
+ response = self.client.get(self._url(), {"measured_only": "true"}).json()
+
+ assert [row["id"] for row in response["results"]] == [str(servers["measured"].id)]
+
+ def test_retrieve_includes_scores_stats_and_connect_instructions(self) -> None:
+ servers = self._seed_index()
+
+ response = self.client.get(self._url(f"{servers['measured'].id}/"))
+
+ assert response.status_code == 200
+ data: dict[str, Any] = response.json()
+ assert {score["version"] for score in data["scores"]} == {"v1_metadata_prior", "v2_measured_trust"}
+ assert data["measured_stats"][0]["calls"] == 50_000
+ assert data["connect"]["recommended"] == "remote_oauth"
+ assert data["connect"]["methods"][-1]["method"] == "remote_api_key"
+
+ def test_discover_returns_ranked_candidates_with_connect_instructions(self) -> None:
+ servers = self._seed_index()
+
+ payload = self.client.get(self._url("discover/"), {"intent": "query my product analytics"}).json()
+
+ assert payload["ranking_version"] == "v2_measured_trust"
+ top = payload["candidates"][0]
+ assert top["id"] == str(servers["measured"].id)
+ assert top["rank"] == 1
+ # The measured block is what no other registry can return.
+ assert top["measured"]["calls"] == 50_000
+ assert top["why"]["measured"] is True
+ # Connect instructions ship in the same response, so one call is enough to act.
+ assert top["connect"]["recommended"] == "remote_oauth"
+ assert payload["candidates"][1]["measured"] is None
+
+ def test_relevance_outranks_authority_when_the_text_match_is_better(self) -> None:
+ # A live, well-documented server that is plainly about the thing must beat a
+ # measured server that only matches on a tool name, or a high-traffic server
+ # would win every unrelated query.
+ self._seed_index()
+ on_topic = MCPRegistryServer.objects.create(
+ registry_name="io.example/webhook-relay",
+ display_name="Webhook relay",
+ description="Relay webhooks between services.",
+ listed_in_registry=True,
+ liveness="alive_open",
+ auth_method="none",
+ canonical_url="https://relay.example.com/mcp",
+ )
+ compute_ranking_run("v2_measured_trust")
+
+ payload = self.client.get(self._url("discover/"), {"intent": "relay webhooks"}).json()
+
+ assert payload["candidates"][0]["id"] == str(on_topic.id)
+
+ def test_discover_returns_one_row_per_server(self) -> None:
+ # Several tools matching one intent used to duplicate the server in the results.
+ servers = self._seed_index()
+ for name in ("query_analytics_daily", "query_analytics_hourly"):
+ MCPRegistryTool.objects.create(
+ server=servers["unmeasured"],
+ name=name,
+ description="Run an analytics query",
+ source="tools_list",
+ last_seen_at=timezone.now(),
+ )
+
+ payload = self.client.get(self._url("discover/"), {"intent": "query_analytics"}).json()
+
+ ids = [candidate["id"] for candidate in payload["candidates"]]
+ assert len(ids) == len(set(ids))
+
+ def test_verified_namespace_outranks_a_lookalike_display_name(self) -> None:
+ # Anyone can title their server "Vercel"; only the domain owner can publish under
+ # com.vercel/*, so the vendor's own entry has to win its own name.
+ official = MCPRegistryServer.objects.create(
+ registry_name="com.vercel/vercel-mcp",
+ display_name="vercel-mcp",
+ description="Deploy and manage projects.",
+ listed_in_registry=True,
+ liveness="alive_auth",
+ auth_method="oauth",
+ canonical_url="https://mcp.vercel.com/",
+ )
+ MCPRegistryServer.objects.create(
+ registry_name="io.github.someone/vercel-helper",
+ display_name="Vercel deploy helper",
+ description="Deploy and manage Vercel projects.",
+ listed_in_registry=True,
+ liveness="alive_open",
+ auth_method="none",
+ canonical_url="https://helper.example.com/mcp",
+ )
+ compute_ranking_run("v2_measured_trust")
+
+ payload = self.client.get(self._url("discover/"), {"intent": "vercel"}).json()
+
+ assert payload["candidates"][0]["id"] == str(official.id)
+
+ def _seed_another_projects_stats(self, server: MCPRegistryServer) -> None:
+ MCPMeasuredStats.objects.unscoped().create(
+ server=server,
+ team_id=self.team.id + 1,
+ server_name="PostHog",
+ window_days=30,
+ calls=999_999,
+ errors=0,
+ error_rate_pct=0.0,
+ intent_coverage_pct=100.0,
+ link_method="override",
+ computed_at=timezone.now(),
+ )
+
+ def _measured_candidate(self, payload: dict[str, Any], server: MCPRegistryServer) -> dict[str, Any]:
+ return next(row for row in payload["candidates"] if row["id"] == str(server.id))
+
+ def test_another_projects_measured_stats_stay_hidden(self) -> None:
+ # Registry rows are global, so a server measured by several projects carries a stats
+ # row per project. A non-staff caller may only see the project it asked as.
+ servers = self._seed_index()
+ self._seed_another_projects_stats(servers["measured"])
+
+ detail = self.client.get(self._url(f"{servers['measured'].id}/")).json()
+ discovered = self.client.get(self._url("discover/"), {"intent": "product analytics"}).json()
+
+ assert [row["calls"] for row in detail["measured_stats"]] == [50_000]
+ assert self._measured_candidate(discovered, servers["measured"])["measured"]["calls"] == 50_000
+
+ def test_staff_see_every_projects_measured_stats(self) -> None:
+ # The fleet view is the point of the staff tier: ranking is only judgeable across
+ # every contributing project, not the one in the route.
+ servers = self._seed_index()
+ self._seed_another_projects_stats(servers["measured"])
+ self.user.is_staff = True
+ self.user.save()
+
+ detail = self.client.get(self._url(f"{servers['measured'].id}/")).json()
+ discovered = self.client.get(self._url("discover/"), {"intent": "product analytics"}).json()
+
+ assert sorted(row["calls"] for row in detail["measured_stats"]) == [50_000, 999_999]
+ assert self._measured_candidate(discovered, servers["measured"])["measured"]["calls"] == 1_049_999
+
+ def test_measured_projects_reports_the_fleet_to_staff_only(self) -> None:
+ # It aggregates across projects, so a non-staff caller must not reach it at all.
+ servers = self._seed_index()
+ self._seed_another_projects_stats(servers["measured"])
+
+ assert self.client.get(self._url("measured_projects/")).status_code == 403
+
+ self.user.is_staff = True
+ self.user.save()
+ rows = self.client.get(self._url("measured_projects/")).json()
+
+ assert [row["team_id"] for row in rows] == [self.team.id + 1, self.team.id]
+ assert [row["calls"] for row in rows] == [999_999, 50_000]
+
+ def _reassign_measurements_to_another_project(self, server: MCPRegistryServer) -> None:
+ MCPMeasuredStats.objects.unscoped().filter(server=server).update(team_id=self.team.id + 1)
+ compute_ranking_run("v2_measured_trust")
+
+ def _v2_components(self, detail: dict[str, Any]) -> dict[str, Any]:
+ return next(row for row in detail["scores"] if row["version"] == "v2_measured_trust")["components"]
+
+ def test_components_derived_from_hidden_measurements_are_withheld(self) -> None:
+ # Ranking components are computed from every contributing project, so returning
+ # them whole would disclose by arithmetic what hiding the stats withholds.
+ servers = self._seed_index()
+ self._reassign_measurements_to_another_project(servers["measured"])
+
+ detail = self.client.get(self._url(f"{servers['measured'].id}/")).json()
+ components = self._v2_components(detail)
+
+ assert "measured_reliability" not in components
+ assert "trust" not in components
+ # The rank itself still shows: only the numbers behind it are withheld.
+ assert components["measured"] is True
+ assert detail["measured_stats"] == []
+
+ def test_sharing_a_server_withholds_the_blended_breakdown(self) -> None:
+ # This project measured the server too, but the components blend its rows with
+ # another project's, so it gets its own figures and a redacted breakdown.
+ servers = self._seed_index()
+ self._seed_another_projects_stats(servers["measured"])
+ compute_ranking_run("v2_measured_trust")
+
+ detail = self.client.get(self._url(f"{servers['measured'].id}/")).json()
+
+ assert [row["calls"] for row in detail["measured_stats"]] == [50_000]
+ assert "measured_reliability" not in self._v2_components(detail)
+
+ def test_staff_get_the_full_component_breakdown(self) -> None:
+ servers = self._seed_index()
+ self._reassign_measurements_to_another_project(servers["measured"])
+ self.user.is_staff = True
+ self.user.save()
+
+ components = self._v2_components(self.client.get(self._url(f"{servers['measured'].id}/")).json())
+
+ assert "measured_reliability" in components
+
+ def test_analytics_sourced_tools_stay_hidden_from_other_projects(self) -> None:
+ # A probed tool is ours to show; one learned from another project's traffic is not.
+ servers = self._seed_index()
+ for name, source in (("probed_tool", "tools_list"), ("learned_from_traffic", "analytics")):
+ MCPRegistryTool.objects.create(
+ server=servers["measured"],
+ name=name,
+ description="",
+ source=source,
+ last_seen_at=timezone.now(),
+ )
+ self._reassign_measurements_to_another_project(servers["measured"])
+
+ detail = self.client.get(self._url(f"{servers['measured'].id}/")).json()
+
+ assert [tool["name"] for tool in detail["tools"]] == ["probed_tool"]
+
+ def test_measured_only_rows_from_another_project_stay_hidden(self) -> None:
+ # A row absent from the official registry exists only because another project's
+ # events named a server we could not match, and that name is unvalidated text
+ # from whoever captured the event.
+ theirs = MCPRegistryServer.objects.create(
+ display_name="Their Internal Tools",
+ description="Measured via MCP Analytics; not listed in the official registry.",
+ listed_in_registry=False,
+ is_measured=True,
+ )
+ MCPMeasuredStats.objects.unscoped().create(
+ server=theirs,
+ team_id=self.team.id + 1,
+ server_name="Their Internal Tools",
+ window_days=30,
+ calls=1_000,
+ errors=0,
+ error_rate_pct=0.0,
+ intent_coverage_pct=100.0,
+ link_method="standalone",
+ computed_at=timezone.now(),
+ )
+ compute_ranking_run("v2_measured_trust")
+
+ listed = self.client.get(self._url(), {"search": "internal tools"}).json()
+
+ assert [row["id"] for row in listed["results"]] == []
+ assert self.client.get(self._url(f"{theirs.id}/")).status_code == 404
+
+ self.user.is_staff = True
+ self.user.save()
+ assert self.client.get(self._url(f"{theirs.id}/")).status_code == 200
+
+ def test_discover_requires_an_intent(self) -> None:
+ assert self.client.get(self._url("discover/")).status_code == 400
+
+ def test_discover_surfaces_tools_that_matched_the_intent(self) -> None:
+ self._seed_index()
+
+ payload = self.client.get(self._url("discover/"), {"intent": "query_analytics"}).json()
+
+ matched = payload["candidates"][0]["matched_tools"]
+ assert [tool["name"] for tool in matched] == ["query_analytics"]
+
+ def test_versions_endpoint_lists_runs_and_default(self) -> None:
+ self._seed_index()
+
+ payload = self.client.get(self._url("versions/")).json()
+
+ by_version = {row["version"]: row for row in payload}
+ assert by_version["v2_measured_trust"]["is_default"] is True
+ assert by_version["v1_metadata_prior"]["latest_run"]["server_count"] == 2
+
+ def test_compare_requires_two_known_versions(self) -> None:
+ assert self.client.get(self._url("compare/")).status_code == 400
+ assert self.client.get(self._url("compare/"), {"versions": "v1_metadata_prior,bogus"}).status_code == 400
+
+ def test_compare_reports_rank_deltas_between_two_versions(self) -> None:
+ servers = self._seed_index()
+
+ response = self.client.get(self._url("compare/"), {"versions": "v1_metadata_prior,v2_measured_trust"}).json()
+
+ assert set(response["versions"].keys()) == {"v1_metadata_prior", "v2_measured_trust"}
+ # The measured server climbs from rank 2 to rank 1 when the measured arm is applied.
+ assert response["rank_deltas"][str(servers["measured"].id)] == -1
diff --git a/products/mcp_registry/backend/tests/test_connect.py b/products/mcp_registry/backend/tests/test_connect.py
new file mode 100644
index 000000000000..35bbeb7b347b
--- /dev/null
+++ b/products/mcp_registry/backend/tests/test_connect.py
@@ -0,0 +1,163 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.mcp_registry.backend.connect import build_connect_instructions
+from products.mcp_registry.backend.models import MCPRegistryServer
+
+
+def _server(**kwargs: object) -> MCPRegistryServer:
+ defaults: dict[str, object] = {
+ "registry_name": "io.example/demo",
+ "display_name": "Demo",
+ "canonical_url": "https://demo.example.com/mcp",
+ "packages": [],
+ "connect_overrides": {},
+ }
+ defaults.update(kwargs)
+ return MCPRegistryServer(**defaults)
+
+
+class TestConnectInstructions(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("open_server", {"liveness": "alive_open", "auth_method": "none"}, "remote_open", "agent"),
+ ("oauth_server", {"liveness": "alive_auth", "auth_method": "oauth"}, "remote_oauth", "agent"),
+ ("api_key_server", {"liveness": "alive_auth", "auth_method": "api_key"}, "remote_api_key", "human"),
+ (
+ "package_only",
+ {
+ "canonical_url": "",
+ "packages": [{"registry_type": "npm", "identifier": "@example/demo-mcp", "version": "1.0.0"}],
+ },
+ "local_package",
+ "agent",
+ ),
+ ]
+ )
+ def test_recommended_method_matches_probe_results(
+ self, _name: str, fields: dict, expected_method: str, expected_first_actor: str
+ ) -> None:
+ instructions = build_connect_instructions(_server(**fields))
+
+ assert instructions["recommended"] == expected_method
+ first_method = instructions["methods"][0]
+ assert first_method["method"] == expected_method
+ assert first_method["steps"][0]["actor"] == expected_first_actor
+
+ def test_oauth_flow_keeps_the_consent_click_human(self) -> None:
+ instructions = build_connect_instructions(_server(liveness="alive_auth", auth_method="oauth"))
+
+ actors = [step["actor"] for step in instructions["methods"][0]["steps"]]
+ assert actors == ["agent", "human"]
+
+ @parameterized.expand(
+ [
+ ("verified_namespace", {"registry_name": "com.vercel/vercel-mcp", "display_name": "vercel-mcp"}),
+ (
+ "vendor_domain_remote",
+ {
+ "registry_name": "io.example/deploy",
+ "display_name": "Deploy tools",
+ "canonical_url": "https://mcp.vercel.com/",
+ },
+ ),
+ ]
+ )
+ def test_stripe_projects_partner_gets_agent_provisioning_first(self, _name: str, fields: dict) -> None:
+ server = _server(liveness="alive_auth", auth_method="oauth", **fields)
+
+ instructions = build_connect_instructions(server)
+
+ assert instructions["recommended"] == "agent_provisioning"
+ first_step = instructions["methods"][0]["steps"][0]
+ assert first_step["actor"] == "agent"
+ assert first_step["command"] == "stripe projects service add vercel"
+ # The standard OAuth path stays available as the fallback method.
+ assert instructions["methods"][1]["method"] == "remote_oauth"
+
+ def test_name_squatting_does_not_match_stripe_projects_partners(self) -> None:
+ # Real case from the live index: a third-party repackage named exactly "vercel"
+ # under an unverified namespace must not inherit provisioning steps.
+ server = _server(
+ registry_name="com.pulsemcp/vercel",
+ display_name="vercel",
+ liveness="alive_auth",
+ auth_method="oauth",
+ )
+
+ instructions = build_connect_instructions(server)
+
+ assert instructions["recommended"] == "remote_oauth"
+
+ def test_agent_provisioning_is_always_preferred(self) -> None:
+ server = _server(liveness="alive_auth", auth_method="api_key", supports_agent_provisioning=True)
+
+ instructions = build_connect_instructions(server)
+
+ assert instructions["recommended"] == "agent_provisioning"
+ assert all(step["actor"] == "agent" for step in instructions["methods"][0]["steps"])
+
+ def test_known_override_appends_extra_methods(self) -> None:
+ server = _server(
+ registry_name="io.github.PostHog/mcp",
+ liveness="alive_auth",
+ auth_method="oauth",
+ )
+
+ instructions = build_connect_instructions(server)
+
+ assert instructions["methods"][0]["method"] == "remote_oauth"
+ assert instructions["methods"][-1]["method"] == "remote_api_key"
+
+ def test_publisher_controlled_url_is_shell_quoted(self) -> None:
+ # A registry publisher chooses canonical_url, and an agent is told to run the
+ # command verbatim, so shell syntax in the URL must not survive as syntax.
+ server = _server(
+ canonical_url="https://evil.example.com/mcp?x=1;touch /tmp/pwned",
+ liveness="alive_open",
+ auth_method="none",
+ )
+
+ command = build_connect_instructions(server)["methods"][0]["steps"][0]["command"]
+
+ assert "'https://evil.example.com/mcp?x=1;touch /tmp/pwned'" in command
+
+ @parameterized.expand(
+ [
+ ("pinned", "1.2.3", "full", "@example/[email protected]", "agent"),
+ ("unpinned", "", "human_required", "@example/demo-mcp", "human"),
+ ]
+ )
+ def test_npm_package_is_pinned_or_needs_approval(
+ self, _name: str, version: str, automation: str, spec: str, first_actor: str
+ ) -> None:
+ # npx resolves latest when the agent runs it, so an unpinned spec lets a publisher
+ # list something benign and replace it with other code afterwards.
+ server = _server(
+ canonical_url="",
+ packages=[{"registry_type": "npm", "identifier": "@example/demo-mcp", "version": version}],
+ )
+
+ method = build_connect_instructions(server)["methods"][0]
+
+ assert method["method"] == "local_package"
+ assert method["automation"] == automation
+ assert method["steps"][0]["actor"] == first_actor
+ assert spec in method["steps"][-1]["command"]
+
+ def test_row_overrides_replace_derived_methods(self) -> None:
+ override_methods = [
+ {
+ "method": "cli_auth",
+ "automation": "one_click",
+ "summary": "Vendor CLI login mints the credential.",
+ "steps": [{"actor": "agent", "description": "Run the vendor CLI login.", "command": "demo login"}],
+ }
+ ]
+ server = _server(liveness="alive_open", auth_method="none", connect_overrides={"methods": override_methods})
+
+ instructions = build_connect_instructions(server)
+
+ assert instructions["methods"] == override_methods
+ assert instructions["recommended"] == "cli_auth"
diff --git a/products/mcp_registry/backend/tests/test_crawl.py b/products/mcp_registry/backend/tests/test_crawl.py
new file mode 100644
index 000000000000..e5a249c0ccdd
--- /dev/null
+++ b/products/mcp_registry/backend/tests/test_crawl.py
@@ -0,0 +1,105 @@
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import Mock, patch
+
+from products.mcp_registry.backend.crawl import crawl_official_registry, upsert_registry_entries
+from products.mcp_registry.backend.models import MCPRegistryServer
+
+
+def _wrapper(name: str, published_at: str = "2026-01-01T00:00:00Z", **server: Any) -> dict[str, Any]:
+ return {
+ "server": {"name": name, "description": "", **server},
+ "_meta": {"io.modelcontextprotocol.registry/official": {"status": "active", "publishedAt": published_at}},
+ }
+
+
+def _page(servers: list[dict[str, Any]], next_cursor: str | None = None) -> Mock:
+ response = Mock()
+ response.json.return_value = {"servers": servers, "metadata": {"nextCursor": next_cursor}}
+ response.raise_for_status.return_value = None
+ return response
+
+
+def _raw_entry(name: str, published_at: str = "2026-01-01T00:00:00Z", **server: Any) -> dict[str, Any]:
+ entry = _wrapper(name, published_at, **server)["server"]
+ entry["_registry_meta"] = {"status": "active", "publishedAt": published_at}
+ return entry
+
+
+class TestCrawl(BaseTest):
+ def test_over_long_publisher_values_do_not_abort_the_crawl(self) -> None:
+ # The registry stores whatever a publisher writes, and a value wider than its
+ # column used to fail the whole batch, stalling the crawl for every server.
+ long_url = "https://example.com/" + "a" * 3_000
+ entries = [
+ _raw_entry("io.example/long-url", remotes=[{"type": "streamable-http", "url": long_url}]),
+ _raw_entry("io.example/" + "x" * 500),
+ _raw_entry(
+ "io.example/fine",
+ remotes=[{"type": "streamable-http", "url": "https://fine.example.com/mcp"}],
+ ),
+ ]
+
+ outcome = upsert_registry_entries(entries)
+
+ # The unusable name is skipped; the over-long URL is dropped but its server kept.
+ assert outcome.created == 2
+ assert MCPRegistryServer.objects.get(registry_name="io.example/long-url").canonical_url == ""
+ assert MCPRegistryServer.objects.get(registry_name="io.example/fine").canonical_url.endswith("/mcp")
+
+ @patch("products.mcp_registry.backend.crawl.requests.get")
+ def test_crawl_paginates_and_skips_inactive_entries(self, mock_get: Mock) -> None:
+ deleted = _wrapper("io.example/gone")
+ deleted["_meta"]["io.modelcontextprotocol.registry/official"]["status"] = "deleted"
+ mock_get.side_effect = [
+ _page([_wrapper("io.example/one", title="One")], next_cursor="cursor-1"),
+ _page(
+ [
+ _wrapper(
+ "io.example/two", remotes=[{"type": "streamable-http", "url": "https://two.example.com/mcp"}]
+ ),
+ deleted,
+ ]
+ ),
+ ]
+
+ outcome = crawl_official_registry()
+
+ assert (outcome.created, outcome.updated) == (2, 0)
+ assert set(MCPRegistryServer.objects.values_list("registry_name", flat=True)) == {
+ "io.example/one",
+ "io.example/two",
+ }
+ two = MCPRegistryServer.objects.get(registry_name="io.example/two")
+ assert two.canonical_url == "https://two.example.com/mcp"
+ assert two.liveness == "unprobed"
+ assert MCPRegistryServer.objects.get(registry_name="io.example/one").liveness == "package_only"
+
+ def test_upsert_keeps_newest_version_per_name(self) -> None:
+ upsert_registry_entries(
+ [
+ _raw_entry("io.example/dup", published_at="2026-02-01T00:00:00Z", description="newer"),
+ _raw_entry("io.example/dup", published_at="2026-01-01T00:00:00Z", description="older"),
+ ]
+ )
+
+ assert MCPRegistryServer.objects.get(registry_name="io.example/dup").description == "newer"
+
+ def test_recrawl_refreshes_content_but_not_operational_state(self) -> None:
+ server = MCPRegistryServer.objects.create(
+ registry_name="io.example/kept",
+ display_name="Kept",
+ listed_in_registry=True,
+ liveness="alive_open",
+ auth_method="none",
+ is_measured=True,
+ )
+
+ outcome = upsert_registry_entries([_raw_entry("io.example/kept", description="fresh description")])
+
+ server.refresh_from_db()
+ assert (outcome.created, outcome.updated) == (0, 1)
+ assert server.description == "fresh description"
+ assert server.liveness == "alive_open"
+ assert server.is_measured is True
diff --git a/products/mcp_registry/backend/tests/test_linking.py b/products/mcp_registry/backend/tests/test_linking.py
new file mode 100644
index 000000000000..de414f00166c
--- /dev/null
+++ b/products/mcp_registry/backend/tests/test_linking.py
@@ -0,0 +1,53 @@
+from posthog.test.base import BaseTest
+
+from products.mcp_registry.backend.linking import resolve_measured_server
+from products.mcp_registry.backend.models import MCPRegistryServer
+
+
+def _registry_server(registry_name: str, display_name: str) -> MCPRegistryServer:
+ return MCPRegistryServer.objects.create(
+ registry_name=registry_name, display_name=display_name, listed_in_registry=True
+ )
+
+
+class TestLinking(BaseTest):
+ def test_override_beats_name_collision_with_repackage(self) -> None:
+ # "PostHog" name-matches both the official server and a third-party repackage;
+ # the curated override must pick the official one.
+ _registry_server("com.thirdparty/posthog", "posthog")
+ official = _registry_server("io.github.PostHog/mcp", "PostHog MCP Server")
+
+ resolution = resolve_measured_server("PostHog")
+
+ assert resolution.server == official
+ assert resolution.link_method == "override"
+ assert resolution.link_candidates == []
+ official.refresh_from_db()
+ assert official.is_measured is True
+
+ def test_ambiguous_name_becomes_standalone_with_candidates(self) -> None:
+ _registry_server("io.example/acme", "Acme")
+ _registry_server("com.acme/mcp", "acme")
+
+ resolution = resolve_measured_server("Acme")
+
+ assert resolution.server.listed_in_registry is False
+ assert resolution.link_method == "standalone"
+ assert set(resolution.link_candidates) == {"io.example/acme", "com.acme/mcp"}
+
+ def test_single_exact_match_links(self) -> None:
+ match = _registry_server("io.example/linear", "Linear")
+ _registry_server("io.example/linear-docs", "Linear docs helper")
+
+ resolution = resolve_measured_server("Linear")
+
+ assert resolution.server == match
+ assert resolution.link_method == "exact_name"
+ assert resolution.link_candidates == []
+
+ def test_standalone_row_is_reused_across_runs(self) -> None:
+ first = resolve_measured_server("Internal Tools")
+ second = resolve_measured_server("Internal Tools")
+
+ assert first.server == second.server
+ assert MCPRegistryServer.objects.filter(display_name="Internal Tools").count() == 1
diff --git a/products/mcp_registry/backend/tests/test_probe.py b/products/mcp_registry/backend/tests/test_probe.py
new file mode 100644
index 000000000000..e5b7f0ed347a
--- /dev/null
+++ b/products/mcp_registry/backend/tests/test_probe.py
@@ -0,0 +1,121 @@
+import json
+
+from posthog.test.base import BaseTest
+from unittest.mock import Mock, patch
+
+from django.test import SimpleTestCase
+
+import requests
+from parameterized import parameterized
+
+from products.mcp_registry.backend.models import MCPRegistryServer, MCPRegistryTool
+from products.mcp_registry.backend.probe import ProbeOutcome, apply_probe_outcome, shallow_probe
+
+
+def _response(status_code: int, body: dict | None = None, text: str = "", headers: dict | None = None) -> Mock:
+ response = Mock(spec=requests.Response)
+ response.status_code = status_code
+ response.text = json.dumps(body) if body is not None else text
+ response.headers = headers or {}
+ return response
+
+
+_INIT_RESULT = {"jsonrpc": "2.0", "id": 1, "result": {"serverInfo": {"name": "demo"}, "capabilities": {}}}
+
+
+class TestShallowProbe(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "oauth_challenge",
+ _response(401, text="unauthorized", headers={"WWW-Authenticate": 'Bearer realm="mcp"'}),
+ "alive_auth",
+ "oauth",
+ ),
+ ("api_key_hint", _response(401, text="missing api key"), "alive_auth", "api_key"),
+ ("auth_unclassified", _response(403, text="forbidden"), "alive_auth", "unknown"),
+ ("redirect_refused", _response(302, text="", headers={"Location": "https://x"}), "not_mcp", "unknown"),
+ ("html_page", _response(200, text="<html>hello</html>"), "not_mcp", "unknown"),
+ ("server_error", _response(503, text="oops"), "dead", "unknown"),
+ (
+ "protocol_error",
+ _response(200, body={"jsonrpc": "2.0", "id": 1, "error": {"code": -32600}}),
+ "alive_protocol",
+ "unknown",
+ ),
+ ]
+ )
+ @patch("products.mcp_registry.backend.probe.pinned_request")
+ def test_classification(
+ self, _name: str, response: Mock, expected_liveness: str, expected_auth: str, mock_request: Mock
+ ) -> None:
+ mock_request.return_value = response
+
+ outcome = shallow_probe("https://demo.example.com/mcp")
+
+ assert outcome.liveness == expected_liveness
+ assert outcome.auth_method == expected_auth
+
+ @patch("products.mcp_registry.backend.probe.pinned_request")
+ def test_connection_failure_is_dead_not_raised(self, mock_request: Mock) -> None:
+ mock_request.side_effect = requests.ConnectionError("refused")
+
+ outcome = shallow_probe("https://demo.example.com/mcp")
+
+ assert outcome.liveness == "dead"
+ assert "refused" in outcome.detail
+
+ @patch("products.mcp_registry.backend.probe.pinned_request")
+ def test_open_server_captures_tools_over_sse(self, mock_request: Mock) -> None:
+ tools_body = {
+ "jsonrpc": "2.0",
+ "id": 2,
+ "result": {
+ "tools": [
+ {"name": "create_issue", "description": "Create an issue", "inputSchema": {"type": "object"}},
+ {"name": "", "description": "nameless, dropped"},
+ ]
+ },
+ }
+ sse_frame = f"event: message\ndata: {json.dumps(tools_body)}\n\n"
+ mock_request.side_effect = [
+ _response(200, body=_INIT_RESULT, headers={"mcp-session-id": "session-1"}),
+ _response(202),
+ _response(200, text=sse_frame),
+ ]
+
+ outcome = shallow_probe("https://demo.example.com/mcp")
+
+ assert outcome.liveness == "alive_open"
+ assert outcome.auth_method == "none"
+ assert [tool["name"] for tool in outcome.tools] == ["create_issue"]
+ # The session handle from initialize must be echoed on the follow-up calls.
+ assert mock_request.call_args.kwargs["headers"]["mcp-session-id"] == "session-1"
+
+
+class TestApplyProbeOutcome(BaseTest):
+ def test_transient_failure_keeps_previously_detected_auth_method(self) -> None:
+ server = MCPRegistryServer.objects.create(
+ display_name="Demo", canonical_url="https://demo.example.com/mcp", auth_method="oauth"
+ )
+
+ apply_probe_outcome(server, ProbeOutcome(liveness="dead", auth_method="unknown", detail="timeout"))
+
+ server.refresh_from_db()
+ assert server.liveness == "dead"
+ assert server.auth_method == "oauth"
+ assert server.last_probed_at is not None
+
+ def test_probed_tools_upgrade_analytics_rows_to_tools_list(self) -> None:
+ server = MCPRegistryServer.objects.create(display_name="Demo", canonical_url="https://demo.example.com/mcp")
+ outcome = ProbeOutcome(
+ liveness="alive_open",
+ auth_method="none",
+ tools=[{"name": "create_issue", "description": "Create an issue", "input_schema": {"type": "object"}}],
+ )
+
+ apply_probe_outcome(server, outcome)
+
+ tool = MCPRegistryTool.objects.get(server=server, name="create_issue")
+ assert tool.source == "tools_list"
+ assert tool.input_schema == {"type": "object"}
diff --git a/products/mcp_registry/backend/tests/test_ranking.py b/products/mcp_registry/backend/tests/test_ranking.py
new file mode 100644
index 000000000000..1461c63bfa26
--- /dev/null
+++ b/products/mcp_registry/backend/tests/test_ranking.py
@@ -0,0 +1,98 @@
+from datetime import timedelta
+
+from freezegun import freeze_time
+from posthog.test.base import BaseTest
+
+from django.utils import timezone
+
+from products.mcp_registry.backend.constants import MEASURED_STALE_AFTER_DAYS
+from products.mcp_registry.backend.models import MCPMeasuredStats, MCPRankingRun, MCPRegistryServer
+from products.mcp_registry.backend.ranking import compute_ranking_run, latest_completed_run
+
+
+def _measured_server(error_rate_pct: float = 5.0, calls: int = 50_000) -> MCPRegistryServer:
+ server = MCPRegistryServer.objects.create(display_name="Measured", is_measured=True)
+ MCPMeasuredStats.objects.unscoped().create(
+ server=server,
+ team_id=1,
+ server_name="Measured",
+ window_days=30,
+ calls=calls,
+ errors=int(calls * error_rate_pct / 100),
+ error_rate_pct=error_rate_pct,
+ intent_coverage_pct=90.0,
+ link_method="exact_name",
+ computed_at=timezone.now(),
+ )
+ return server
+
+
+@freeze_time("2026-08-19")
+class TestRanking(BaseTest):
+ def test_measured_signal_flips_ordering_only_in_the_measured_arm(self) -> None:
+ measured = _measured_server()
+ unmeasured = MCPRegistryServer.objects.create(
+ display_name="Well documented", repository_url="https://github.com/example/mcp"
+ )
+
+ v1 = {score.server_id: score.score for score in compute_ranking_run("v1_metadata_prior").scores.all()}
+ v2 = {score.server_id: score.score for score in compute_ranking_run("v2_measured_trust").scores.all()}
+
+ # The control arm can't see usage, so the repo-backed server wins on metadata prior.
+ assert v1[unmeasured.id] > v1[measured.id]
+ assert v2[measured.id] > v2[unmeasured.id]
+
+ def test_higher_error_rate_lowers_measured_trust(self) -> None:
+ reliable = _measured_server(error_rate_pct=2.0)
+ unreliable_server = MCPRegistryServer.objects.create(display_name="Flaky", is_measured=True)
+ MCPMeasuredStats.objects.unscoped().create(
+ server=unreliable_server,
+ team_id=2,
+ server_name="Flaky",
+ window_days=30,
+ calls=50_000,
+ errors=15_000,
+ error_rate_pct=30.0,
+ link_method="standalone",
+ computed_at=timezone.now(),
+ )
+
+ scores = {score.server_id: score.score for score in compute_ranking_run("v2_measured_trust").scores.all()}
+
+ assert scores[reliable.id] > scores[unreliable_server.id]
+
+ def test_stale_measurements_stop_earning_trust(self) -> None:
+ # Aggregation only upserts servers seen in the window, so a server that stopped
+ # being called keeps its last row. It must not keep the trust that row earned.
+ server = _measured_server()
+ MCPMeasuredStats.objects.unscoped().filter(server=server).update(
+ computed_at=timezone.now() - timedelta(days=MEASURED_STALE_AFTER_DAYS + 1)
+ )
+
+ score = compute_ranking_run("v2_measured_trust").scores.get(server=server)
+
+ assert score.components["measured"] is False
+
+ def test_run_persists_scores_with_components(self) -> None:
+ server = _measured_server()
+
+ run = compute_ranking_run("v2_measured_trust")
+
+ assert run.status == "completed"
+ assert run.server_count == 1
+ assert run.computed_at is not None
+ score = run.scores.get(server=server)
+ assert score.components["measured"] is True
+ assert 0 < score.score <= 1
+
+ def test_unknown_version_is_rejected(self) -> None:
+ with self.assertRaises(ValueError):
+ compute_ranking_run("v99_does_not_exist")
+
+ def test_latest_completed_run_skips_failed_and_running(self) -> None:
+ completed = compute_ranking_run("v1_metadata_prior")
+ MCPRankingRun.objects.create(version="v1_metadata_prior", status="failed")
+ MCPRankingRun.objects.create(version="v1_metadata_prior", status="running")
+
+ assert latest_completed_run("v1_metadata_prior") == completed
+ assert latest_completed_run("v2_measured_trust") is None
diff --git a/products/mcp_registry/frontend/generated/api.schemas.ts b/products/mcp_registry/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..af685cdacc97
--- /dev/null
+++ b/products/mcp_registry/frontend/generated/api.schemas.ts
@@ -0,0 +1,274 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+export interface MCPRegistryServerListApi {
+ /** Registry server id. */
+ id: string
+ /** Reverse-DNS name in the official MCP registry; empty for measured-only servers. */
+ registry_name: string
+ /** Human-readable server name. */
+ display_name: string
+ /** Server description. */
+ description: string
+ /** Primary hosted remote URL; empty for package-only servers. */
+ canonical_url: string
+ /** Probed liveness state (alive_open, alive_auth, dead, ...). */
+ liveness: string
+ /** Detected auth method (none, oauth, api_key, unknown). */
+ auth_method: string
+ /** Whether the server appears in the official MCP registry. */
+ listed_in_registry: boolean
+ /** Whether real usage signal exists via MCP Analytics. */
+ is_measured: boolean
+ /**
+ * Static score under the requested ranking version; null when the version has no completed run.
+ * @nullable
+ */
+ rank_score: number | null
+}
+
+export interface PaginatedMCPRegistryServerListListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: MCPRegistryServerListApi[]
+}
+
+export type MCPRegistryServerDetailApiRemotesItem = {
+ type?: string
+ url?: string
+}
+
+export type MCPRegistryServerDetailApiPackagesItem = {
+ registry_type?: string
+ identifier?: string
+}
+
+export type MCPRegistryServerDetailApiToolsItem = { [key: string]: unknown }
+
+export type MCPRegistryServerDetailApiMeasuredStatsItem = { [key: string]: unknown }
+
+export type MCPRegistryServerDetailApiScoresItem = { [key: string]: unknown }
+
+/**
+ * Connection instructions: methods ordered most-automated first, steps typed by actor (agent executes; human steps are narrated to the user).
+ */
+export type MCPRegistryServerDetailApiConnect = { [key: string]: unknown }
+
+export interface MCPRegistryServerDetailApi {
+ /** Registry server id. */
+ id: string
+ /** Reverse-DNS name in the official MCP registry; empty for measured-only servers. */
+ registry_name: string
+ /** Human-readable server name. */
+ display_name: string
+ /** Server description. */
+ description: string
+ /** Primary hosted remote URL; empty for package-only servers. */
+ canonical_url: string
+ /** Probed liveness state (alive_open, alive_auth, dead, ...). */
+ liveness: string
+ /** Detected auth method (none, oauth, api_key, unknown). */
+ auth_method: string
+ /** Whether the server appears in the official MCP registry. */
+ listed_in_registry: boolean
+ /** Whether real usage signal exists via MCP Analytics. */
+ is_measured: boolean
+ /**
+ * Static score under the requested ranking version; null when the version has no completed run.
+ * @nullable
+ */
+ rank_score: number | null
+ /** All hosted remotes: [{type, url}]. */
+ remotes: MCPRegistryServerDetailApiRemotesItem[]
+ /** Published packages: [{registry_type, identifier}]. */
+ packages: MCPRegistryServerDetailApiPackagesItem[]
+ /** Source repository URL, when published. */
+ repository_url: string
+ /** Vendor website URL, when published. */
+ website_url: string
+ /**
+ * When the shallow probe last ran.
+ * @nullable
+ */
+ last_probed_at: string | null
+ /** Known tools, fused from probes and analytics. A tool known only from another project's traffic is limited to callers who may see that project's measurements. */
+ tools: MCPRegistryServerDetailApiToolsItem[]
+ /** Behavioral aggregates, one per measured MCP Analytics project. Limited to this project's own measurements unless the server is marked measured_public. */
+ measured_stats: MCPRegistryServerDetailApiMeasuredStatsItem[]
+ /** Latest score under every ranking version with a completed run. */
+ scores: MCPRegistryServerDetailApiScoresItem[]
+ /** Connection instructions: methods ordered most-automated first, steps typed by actor (agent executes; human steps are narrated to the user). */
+ connect: MCPRegistryServerDetailApiConnect
+}
+
+/**
+ * Score breakdown so an agent can explain its choice: fit, liveness, trust, and whether real usage signal contributed.
+ */
+export type MCPDiscoverCandidateApiWhy = { [key: string]: unknown }
+
+/**
+ * Real MCP Analytics aggregates when the server is measured, otherwise null: calls, sessions, error_rate_pct, intent_coverage_pct, harness_count.
+ * @nullable
+ */
+export type MCPDiscoverCandidateApiMeasured = { [key: string]: unknown } | null
+
+export type MCPDiscoverCandidateApiMatchedToolsItem = {
+ name?: string
+ description?: string
+ source?: string
+}
+
+/**
+ * Connection instructions, most-automated method first, steps typed by actor so the agent runs its own steps and narrates the human ones.
+ */
+export type MCPDiscoverCandidateApiConnect = { [key: string]: unknown }
+
+/**
+ * One ranked candidate in a discover response, with everything an agent needs to act.
+ */
+export interface MCPDiscoverCandidateApi {
+ /** 1-based position under the ranking version used. */
+ rank: number
+ /** Registry server id, for the detail endpoint. */
+ id: string
+ /** Official registry name, empty for measured-only servers. */
+ registry_name: string
+ /** Human-readable server name. */
+ title: string
+ /** What the server does. */
+ description: string
+ /** Rank score in [0, 1] under the ranking version used. */
+ score: number
+ /** Score breakdown so an agent can explain its choice: fit, liveness, trust, and whether real usage signal contributed. */
+ why: MCPDiscoverCandidateApiWhy
+ /** Probed liveness state (alive_open, alive_auth, dead, ...). */
+ liveness: string
+ /** Detected auth method (none, oauth, api_key, unknown). */
+ auth_method: string
+ /**
+ * Real MCP Analytics aggregates when the server is measured, otherwise null: calls, sessions, error_rate_pct, intent_coverage_pct, harness_count.
+ * @nullable
+ */
+ measured: MCPDiscoverCandidateApiMeasured
+ /** Tools that matched the intent: [{name, description, source}]. Empty when only the server description matched. */
+ matched_tools: MCPDiscoverCandidateApiMatchedToolsItem[]
+ /** Connection instructions, most-automated method first, steps typed by actor so the agent runs its own steps and narrates the human ones. */
+ connect: MCPDiscoverCandidateApiConnect
+}
+
+/**
+ * Everything an agent gets back from one discover call.
+ */
+export interface MCPDiscoverResponseApi {
+ /** The intent the candidates were ranked against, echoed back. */
+ intent: string
+ /** Ranking version the candidates were ordered by. */
+ ranking_version: string
+ /** Servers most likely to do the thing, best first. */
+ candidates: MCPDiscoverCandidateApi[]
+}
+
+/**
+ * One project's contribution to the measured layer, for the staff fleet view.
+ */
+export interface MCPMeasuredProjectApi {
+ /** Project supplying the MCP Analytics signal. */
+ team_id: number
+ /** Distinct servers this project has measured. */
+ servers: number
+ /** Tool calls this project contributes across those servers. */
+ calls: number
+}
+
+/**
+ * A completed ranking run.
+ */
+export interface MCPRankingRunApi {
+ /** Run id. */
+ id: string
+ /** Servers scored in the run. */
+ server_count: number
+ /**
+ * When the run completed.
+ * @nullable
+ */
+ computed_at: string | null
+}
+
+/**
+ * A registered ranking version and its latest completed run.
+ */
+export interface MCPRankingVersionApi {
+ /** Ranking version key, passed as ?version= to the list endpoint. */
+ version: string
+ /** What this version scores on. */
+ description: string
+ /** Whether this is the version used when ?version= is omitted. */
+ is_default: boolean
+ /** Latest completed run; null when the version never ran. */
+ latest_run: MCPRankingRunApi | null
+}
+
+export type McpRegistryServersListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * Only servers with real MCP Analytics signal.
+ */
+ measured_only?: boolean
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Free-text query matched against server names, descriptions, and tool names.
+ */
+ search?: string
+ /**
+ * Ranking version ordering the results; defaults to the current default version.
+ */
+ version?: string
+}
+
+export type McpRegistryServersCompareRetrieveParams = {
+ /**
+ * Rows per arm (default 20, max 100).
+ */
+ limit?: number
+ /**
+ * Optional text filter applied to every arm.
+ */
+ search?: string
+ /**
+ * Comma-separated ranking versions to compare (2+).
+ */
+ versions: string
+}
+
+export type McpRegistryServersCompareRetrieve200 = { [key: string]: unknown }
+
+export type McpRegistryServersDiscoverRetrieveParams = {
+ /**
+ * What the agent is trying to do, in natural language.
+ */
+ intent: string
+ /**
+ * Candidates to return (default 5, max 20).
+ */
+ limit?: number
+ /**
+ * Ranking version to rank candidates by.
+ */
+ version?: string
+}
diff --git a/products/mcp_registry/frontend/generated/api.ts b/products/mcp_registry/frontend/generated/api.ts
new file mode 100644
index 000000000000..334b79ab29c0
--- /dev/null
+++ b/products/mcp_registry/frontend/generated/api.ts
@@ -0,0 +1,172 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type {
+ MCPDiscoverResponseApi,
+ MCPMeasuredProjectApi,
+ MCPRankingVersionApi,
+ MCPRegistryServerDetailApi,
+ McpRegistryServersCompareRetrieve200,
+ McpRegistryServersCompareRetrieveParams,
+ McpRegistryServersDiscoverRetrieveParams,
+ McpRegistryServersListParams,
+ PaginatedMCPRegistryServerListListApi,
+} from './api.schemas'
+
+export const getMcpRegistryServersListUrl = (projectId: string, params?: McpRegistryServersListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/mcp_registry/servers/?${stringifiedParams}`
+ : `/api/projects/${projectId}/mcp_registry/servers/`
+}
+
+/**
+ * List registry servers ordered by static rank under the chosen ranking version.
+ */
+export const mcpRegistryServersList = async (
+ projectId: string,
+ params?: McpRegistryServersListParams,
+ options?: RequestInit
+): Promise<PaginatedMCPRegistryServerListListApi> => {
+ return apiMutator<PaginatedMCPRegistryServerListListApi>(getMcpRegistryServersListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMcpRegistryServersRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/mcp_registry/servers/${id}/`
+}
+
+/**
+ * Full server record: tools, measured stats, per-version scores, connection instructions.
+ */
+export const mcpRegistryServersRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<MCPRegistryServerDetailApi> => {
+ return apiMutator<MCPRegistryServerDetailApi>(getMcpRegistryServersRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMcpRegistryServersCompareRetrieveUrl = (
+ projectId: string,
+ params: McpRegistryServersCompareRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/mcp_registry/servers/compare/?${stringifiedParams}`
+ : `/api/projects/${projectId}/mcp_registry/servers/compare/`
+}
+
+/**
+ * Rank the same index under several ranking versions side by side. With exactly two versions the response includes per-server rank deltas, the review surface for promoting a new ranking version.
+ */
+export const mcpRegistryServersCompareRetrieve = async (
+ projectId: string,
+ params: McpRegistryServersCompareRetrieveParams,
+ options?: RequestInit
+): Promise<McpRegistryServersCompareRetrieve200> => {
+ return apiMutator<McpRegistryServersCompareRetrieve200>(
+ getMcpRegistryServersCompareRetrieveUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getMcpRegistryServersDiscoverRetrieveUrl = (
+ projectId: string,
+ params: McpRegistryServersDiscoverRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/mcp_registry/servers/discover/?${stringifiedParams}`
+ : `/api/projects/${projectId}/mcp_registry/servers/discover/`
+}
+
+/**
+ * Given a task, return the MCP servers most likely to do it, each with its rank rationale, real usage signal where we measure it, and ready-to-run connection instructions. One call is everything an agent needs to go from a task to a connected server.
+ */
+export const mcpRegistryServersDiscoverRetrieve = async (
+ projectId: string,
+ params: McpRegistryServersDiscoverRetrieveParams,
+ options?: RequestInit
+): Promise<MCPDiscoverResponseApi> => {
+ return apiMutator<MCPDiscoverResponseApi>(getMcpRegistryServersDiscoverRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMcpRegistryServersMeasuredProjectsListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/mcp_registry/servers/measured_projects/`
+}
+
+/**
+ * Which projects feed MCP Analytics signal into the index, and how much each contributes. Staff only, because it reports across every project rather than the one in the route: it answers whether the measured layer has enough coverage to rank on.
+ */
+export const mcpRegistryServersMeasuredProjectsList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<MCPMeasuredProjectApi[]> => {
+ return apiMutator<MCPMeasuredProjectApi[]>(getMcpRegistryServersMeasuredProjectsListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMcpRegistryServersVersionsListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/mcp_registry/servers/versions/`
+}
+
+/**
+ * Registered ranking versions and their latest completed runs.
+ */
+export const mcpRegistryServersVersionsList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<MCPRankingVersionApi[]> => {
+ return apiMutator<MCPRankingVersionApi[]>(getMcpRegistryServersVersionsListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/mcp_registry/frontend/generated/api.zod.schemas.ts b/products/mcp_registry/frontend/generated/api.zod.schemas.ts
new file mode 100644
index 000000000000..f0c898839c4b
--- /dev/null
+++ b/products/mcp_registry/frontend/generated/api.zod.schemas.ts
@@ -0,0 +1,262 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import { z as zod } from 'zod'
+
+export const MCPRegistryServerListApi = zod.object({
+ id: zod.uuid().describe('Registry server id.'),
+ registry_name: zod
+ .string()
+ .describe('Reverse-DNS name in the official MCP registry; empty for measured-only servers.'),
+ display_name: zod.string().describe('Human-readable server name.'),
+ description: zod.string().describe('Server description.'),
+ canonical_url: zod.string().describe('Primary hosted remote URL; empty for package-only servers.'),
+ liveness: zod.string().describe('Probed liveness state (alive_open, alive_auth, dead, ...).'),
+ auth_method: zod.string().describe('Detected auth method (none, oauth, api_key, unknown).'),
+ listed_in_registry: zod.boolean().describe('Whether the server appears in the official MCP registry.'),
+ is_measured: zod.boolean().describe('Whether real usage signal exists via MCP Analytics.'),
+ rank_score: zod
+ .number()
+ .nullable()
+ .describe('Static score under the requested ranking version; null when the version has no completed run.'),
+})
+
+export type MCPRegistryServerListApi = zod.input<typeof MCPRegistryServerListApi>
+export type MCPRegistryServerListApiOutput = zod.output<typeof MCPRegistryServerListApi>
+
+export const PaginatedMCPRegistryServerListListApi = zod.object({
+ count: zod.number(),
+ next: zod.url().nullish(),
+ previous: zod.url().nullish(),
+ results: zod.array(
+ zod.object({
+ id: zod.uuid().describe('Registry server id.'),
+ registry_name: zod
+ .string()
+ .describe('Reverse-DNS name in the official MCP registry; empty for measured-only servers.'),
+ display_name: zod.string().describe('Human-readable server name.'),
+ description: zod.string().describe('Server description.'),
+ canonical_url: zod.string().describe('Primary hosted remote URL; empty for package-only servers.'),
+ liveness: zod.string().describe('Probed liveness state (alive_open, alive_auth, dead, ...).'),
+ auth_method: zod.string().describe('Detected auth method (none, oauth, api_key, unknown).'),
+ listed_in_registry: zod.boolean().describe('Whether the server appears in the official MCP registry.'),
+ is_measured: zod.boolean().describe('Whether real usage signal exists via MCP Analytics.'),
+ rank_score: zod
+ .number()
+ .nullable()
+ .describe(
+ 'Static score under the requested ranking version; null when the version has no completed run.'
+ ),
+ })
+ ),
+})
+
+export type PaginatedMCPRegistryServerListListApi = zod.input<typeof PaginatedMCPRegistryServerListListApi>
+export type PaginatedMCPRegistryServerListListApiOutput = zod.output<typeof PaginatedMCPRegistryServerListListApi>
+
+export const MCPRegistryServerDetailApi = zod.object({
+ id: zod.uuid().describe('Registry server id.'),
+ registry_name: zod
+ .string()
+ .describe('Reverse-DNS name in the official MCP registry; empty for measured-only servers.'),
+ display_name: zod.string().describe('Human-readable server name.'),
+ description: zod.string().describe('Server description.'),
+ canonical_url: zod.string().describe('Primary hosted remote URL; empty for package-only servers.'),
+ liveness: zod.string().describe('Probed liveness state (alive_open, alive_auth, dead, ...).'),
+ auth_method: zod.string().describe('Detected auth method (none, oauth, api_key, unknown).'),
+ listed_in_registry: zod.boolean().describe('Whether the server appears in the official MCP registry.'),
+ is_measured: zod.boolean().describe('Whether real usage signal exists via MCP Analytics.'),
+ rank_score: zod
+ .number()
+ .nullable()
+ .describe('Static score under the requested ranking version; null when the version has no completed run.'),
+ remotes: zod
+ .array(
+ zod.object({
+ type: zod.string().optional(),
+ url: zod.string().optional(),
+ })
+ )
+ .describe('All hosted remotes: [{type, url}].'),
+ packages: zod
+ .array(
+ zod.object({
+ registry_type: zod.string().optional(),
+ identifier: zod.string().optional(),
+ })
+ )
+ .describe('Published packages: [{registry_type, identifier}].'),
+ repository_url: zod.string().describe('Source repository URL, when published.'),
+ website_url: zod.string().describe('Vendor website URL, when published.'),
+ last_probed_at: zod.iso.datetime({ offset: true }).nullable().describe('When the shallow probe last ran.'),
+ tools: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .describe(
+ "Known tools, fused from probes and analytics. A tool known only from another project's traffic is limited to callers who may see that project's measurements."
+ ),
+ measured_stats: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .describe(
+ "Behavioral aggregates, one per measured MCP Analytics project. Limited to this project's own measurements unless the server is marked measured_public."
+ ),
+ scores: zod
+ .array(zod.record(zod.string(), zod.unknown()))
+ .describe('Latest score under every ranking version with a completed run.'),
+ connect: zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ 'Connection instructions: methods ordered most-automated first, steps typed by actor (agent executes; human steps are narrated to the user).'
+ ),
+})
+
+export type MCPRegistryServerDetailApi = zod.input<typeof MCPRegistryServerDetailApi>
+export type MCPRegistryServerDetailApiOutput = zod.output<typeof MCPRegistryServerDetailApi>
+
+export const MCPDiscoverCandidateApi = zod
+ .object({
+ rank: zod.number().describe('1-based position under the ranking version used.'),
+ id: zod.uuid().describe('Registry server id, for the detail endpoint.'),
+ registry_name: zod.string().describe('Official registry name, empty for measured-only servers.'),
+ title: zod.string().describe('Human-readable server name.'),
+ description: zod.string().describe('What the server does.'),
+ score: zod.number().describe('Rank score in [0, 1] under the ranking version used.'),
+ why: zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ 'Score breakdown so an agent can explain its choice: fit, liveness, trust, and whether real usage signal contributed.'
+ ),
+ liveness: zod.string().describe('Probed liveness state (alive_open, alive_auth, dead, ...).'),
+ auth_method: zod.string().describe('Detected auth method (none, oauth, api_key, unknown).'),
+ measured: zod
+ .record(zod.string(), zod.unknown())
+ .nullable()
+ .describe(
+ 'Real MCP Analytics aggregates when the server is measured, otherwise null: calls, sessions, error_rate_pct, intent_coverage_pct, harness_count.'
+ ),
+ matched_tools: zod
+ .array(
+ zod.object({
+ name: zod.string().optional(),
+ description: zod.string().optional(),
+ source: zod.string().optional(),
+ })
+ )
+ .describe(
+ 'Tools that matched the intent: [{name, description, source}]. Empty when only the server description matched.'
+ ),
+ connect: zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ 'Connection instructions, most-automated method first, steps typed by actor so the agent runs its own steps and narrates the human ones.'
+ ),
+ })
+ .describe('One ranked candidate in a discover response, with everything an agent needs to act.')
+
+export type MCPDiscoverCandidateApi = zod.input<typeof MCPDiscoverCandidateApi>
+export type MCPDiscoverCandidateApiOutput = zod.output<typeof MCPDiscoverCandidateApi>
+
+export const MCPDiscoverResponseApi = zod
+ .object({
+ intent: zod.string().describe('The intent the candidates were ranked against, echoed back.'),
+ ranking_version: zod.string().describe('Ranking version the candidates were ordered by.'),
+ candidates: zod
+ .array(
+ zod
+ .object({
+ rank: zod.number().describe('1-based position under the ranking version used.'),
+ id: zod.uuid().describe('Registry server id, for the detail endpoint.'),
+ registry_name: zod
+ .string()
+ .describe('Official registry name, empty for measured-only servers.'),
+ title: zod.string().describe('Human-readable server name.'),
+ description: zod.string().describe('What the server does.'),
+ score: zod.number().describe('Rank score in [0, 1] under the ranking version used.'),
+ why: zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ 'Score breakdown so an agent can explain its choice: fit, liveness, trust, and whether real usage signal contributed.'
+ ),
+ liveness: zod.string().describe('Probed liveness state (alive_open, alive_auth, dead, ...).'),
+ auth_method: zod.string().describe('Detected auth method (none, oauth, api_key, unknown).'),
+ measured: zod
+ .record(zod.string(), zod.unknown())
+ .nullable()
+ .describe(
+ 'Real MCP Analytics aggregates when the server is measured, otherwise null: calls, sessions, error_rate_pct, intent_coverage_pct, harness_count.'
+ ),
+ matched_tools: zod
+ .array(
+ zod.object({
+ name: zod.string().optional(),
+ description: zod.string().optional(),
+ source: zod.string().optional(),
+ })
+ )
+ .describe(
+ 'Tools that matched the intent: [{name, description, source}]. Empty when only the server description matched.'
+ ),
+ connect: zod
+ .record(zod.string(), zod.unknown())
+ .describe(
+ 'Connection instructions, most-automated method first, steps typed by actor so the agent runs its own steps and narrates the human ones.'
+ ),
+ })
+ .describe('One ranked candidate in a discover response, with everything an agent needs to act.')
+ )
+ .describe('Servers most likely to do the thing, best first.'),
+ })
+ .describe('Everything an agent gets back from one discover call.')
+
+export type MCPDiscoverResponseApi = zod.input<typeof MCPDiscoverResponseApi>
+export type MCPDiscoverResponseApiOutput = zod.output<typeof MCPDiscoverResponseApi>
+
+export const MCPMeasuredProjectApi = zod
+ .object({
+ team_id: zod.number().describe('Project supplying the MCP Analytics signal.'),
+ servers: zod.number().describe('Distinct servers this project has measured.'),
+ calls: zod.number().describe('Tool calls this project contributes across those servers.'),
+ })
+ .describe("One project's contribution to the measured layer, for the staff fleet view.")
+
+export type MCPMeasuredProjectApi = zod.input<typeof MCPMeasuredProjectApi>
+export type MCPMeasuredProjectApiOutput = zod.output<typeof MCPMeasuredProjectApi>
+
+export const MCPRankingRunApi = zod
+ .object({
+ id: zod.uuid().describe('Run id.'),
+ server_count: zod.number().describe('Servers scored in the run.'),
+ computed_at: zod.iso.datetime({ offset: true }).nullable().describe('When the run completed.'),
+ })
+ .describe('A completed ranking run.')
+
+export type MCPRankingRunApi = zod.input<typeof MCPRankingRunApi>
+export type MCPRankingRunApiOutput = zod.output<typeof MCPRankingRunApi>
+
+export const MCPRankingVersionApi = zod
+ .object({
+ version: zod.string().describe('Ranking version key, passed as ?version= to the list endpoint.'),
+ description: zod.string().describe('What this version scores on.'),
+ is_default: zod.boolean().describe('Whether this is the version used when ?version= is omitted.'),
+ latest_run: zod
+ .union([
+ zod
+ .object({
+ id: zod.uuid().describe('Run id.'),
+ server_count: zod.number().describe('Servers scored in the run.'),
+ computed_at: zod.iso.datetime({ offset: true }).nullable().describe('When the run completed.'),
+ })
+ .describe('A completed ranking run.'),
+ zod.null(),
+ ])
+ .describe('Latest completed run; null when the version never ran.'),
+ })
+ .describe('A registered ranking version and its latest completed run.')
+
+export type MCPRankingVersionApi = zod.input<typeof MCPRankingVersionApi>
+export type MCPRankingVersionApiOutput = zod.output<typeof MCPRankingVersionApi>
diff --git a/products/mcp_registry/frontend/generated/api.zod.ts b/products/mcp_registry/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..e8a15d4e1b52
--- /dev/null
+++ b/products/mcp_registry/frontend/generated/api.zod.ts
@@ -0,0 +1,9 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
diff --git a/products/mcp_registry/manifest.tsx b/products/mcp_registry/manifest.tsx
new file mode 100644
index 000000000000..360db4fdb81b
--- /dev/null
+++ b/products/mcp_registry/manifest.tsx
@@ -0,0 +1,7 @@
+import { ProductManifest } from '~/types'
+
+export const manifest: ProductManifest = {
+ name: 'MCP registry',
+ treeItemsNew: [],
+ treeItemsProducts: [],
+}
diff --git a/products/mcp_registry/package.json b/products/mcp_registry/package.json
new file mode 100644
index 000000000000..a09e1971ec25
--- /dev/null
+++ b/products/mcp_registry/package.json
@@ -0,0 +1,8 @@
+{
+ "name": "@posthog/products-mcp-registry",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
+ "backend:lint": "ruff check --config ../../pyproject.toml backend && ruff format --config ../../pyproject.toml --check backend",
+ "backend:contract-check": "echo 'Contract files unchanged'"
+ }
+}
diff --git a/products/mcp_registry/product.yaml b/products/mcp_registry/product.yaml
new file mode 100644
index 000000000000..0c044ead62a9
--- /dev/null
+++ b/products/mcp_registry/product.yaml
@@ -0,0 +1,3 @@
+name: MCP registry
+owners:
+ - mcp-analytics
diff --git a/products/mcp_registry/tsconfig.json b/products/mcp_registry/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/mcp_registry/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/products/mcp_registry/turbo.json b/products/mcp_registry/turbo.json
new file mode 100644
index 000000000000..a765b03ee90e
--- /dev/null
+++ b/products/mcp_registry/turbo.json
@@ -0,0 +1,17 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": [
+ "backend/facade/**",
+ "backend/presentation/**",
+ "backend/routes.py",
+ "backend/tasks/**",
+ "backend/models.py",
+ "backend/migrations/**"
+ ],
+ "outputs": [],
+ "cache": true
+ }
+ }
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 578b10293f8d..904982e73e3c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -49924,6 +49924,73 @@ export namespace Schemas {
readonly count: number;
}
+ /**
+ * Score breakdown so an agent can explain its choice: fit, liveness, trust, and whether real usage signal contributed.
+ */
+ export type MCPDiscoverCandidateWhy = { [key: string]: unknown };
+
+ /**
+ * Real MCP Analytics aggregates when the server is measured, otherwise null: calls, sessions, error_rate_pct, intent_coverage_pct, harness_count.
+ * @nullable
+ */
+ export type MCPDiscoverCandidateMeasured = { [key: string]: unknown } | null;
+
+ export type MCPDiscoverCandidateMatchedToolsItem = {
+ name?: string;
+ description?: string;
+ source?: string;
+ };
+
+ /**
+ * Connection instructions, most-automated method first, steps typed by actor so the agent runs its own steps and narrates the human ones.
+ */
+ export type MCPDiscoverCandidateConnect = { [key: string]: unknown };
+
+ /**
+ * One ranked candidate in a discover response, with everything an agent needs to act.
+ */
+ export interface MCPDiscoverCandidate {
+ /** 1-based position under the ranking version used. */
+ rank: number;
+ /** Registry server id, for the detail endpoint. */
+ id: string;
+ /** Official registry name, empty for measured-only servers. */
+ registry_name: string;
+ /** Human-readable server name. */
+ title: string;
+ /** What the server does. */
+ description: string;
+ /** Rank score in [0, 1] under the ranking version used. */
+ score: number;
+ /** Score breakdown so an agent can explain its choice: fit, liveness, trust, and whether real usage signal contributed. */
+ why: MCPDiscoverCandidateWhy;
+ /** Probed liveness state (alive_open, alive_auth, dead, ...). */
+ liveness: string;
+ /** Detected auth method (none, oauth, api_key, unknown). */
+ auth_method: string;
+ /**
+ * Real MCP Analytics aggregates when the server is measured, otherwise null: calls, sessions, error_rate_pct, intent_coverage_pct, harness_count.
+ * @nullable
+ */
+ measured: MCPDiscoverCandidateMeasured;
+ /** Tools that matched the intent: [{name, description, source}]. Empty when only the server description matched. */
+ matched_tools: MCPDiscoverCandidateMatchedToolsItem[];
+ /** Connection instructions, most-automated method first, steps typed by actor so the agent runs its own steps and narrates the human ones. */
+ connect: MCPDiscoverCandidateConnect;
+ }
+
+ /**
+ * Everything an agent gets back from one discover call.
+ */
+ export interface MCPDiscoverResponse {
+ /** The intent the candidates were ranked against, echoed back. */
+ intent: string;
+ /** Ranking version the candidates were ordered by. */
+ ranking_version: string;
+ /** Servers most likely to do the thing, best first. */
+ candidates: MCPDiscoverCandidate[];
+ }
+
export interface MCPFeedbackCreate {
/**
* The tool the user tried before leaving feedback, if known.
@@ -50357,6 +50424,18 @@ export namespace Schemas {
readonly themes: readonly MCPIntentTheme[];
}
+ /**
+ * One project's contribution to the measured layer, for the staff fleet view.
+ */
+ export interface MCPMeasuredProject {
+ /** Project supplying the MCP Analytics signal. */
+ team_id: number;
+ /** Distinct servers this project has measured. */
+ servers: number;
+ /** Tool calls this project contributes across those servers. */
+ calls: number;
+ }
+
export interface MCPMissingCapabilityCreate {
/**
* The tool the user tried before leaving feedback, if known.
@@ -50438,6 +50517,129 @@ export namespace Schemas {
readonly updated_at: string;
}
+ /**
+ * A completed ranking run.
+ */
+ export interface MCPRankingRun {
+ /** Run id. */
+ id: string;
+ /** Servers scored in the run. */
+ server_count: number;
+ /**
+ * When the run completed.
+ * @nullable
+ */
+ computed_at: string | null;
+ }
+
+ /**
+ * A registered ranking version and its latest completed run.
+ */
+ export interface MCPRankingVersion {
+ /** Ranking version key, passed as ?version= to the list endpoint. */
+ version: string;
+ /** What this version scores on. */
+ description: string;
+ /** Whether this is the version used when ?version= is omitted. */
+ is_default: boolean;
+ /** Latest completed run; null when the version never ran. */
+ latest_run: MCPRankingRun | null;
+ }
+
+ export type MCPRegistryServerDetailRemotesItem = {
+ type?: string;
+ url?: string;
+ };
+
+ export type MCPRegistryServerDetailPackagesItem = {
+ registry_type?: string;
+ identifier?: string;
+ };
+
+ export type MCPRegistryServerDetailToolsItem = { [key: string]: unknown };
+
+ export type MCPRegistryServerDetailMeasuredStatsItem = { [key: string]: unknown };
+
+ export type MCPRegistryServerDetailScoresItem = { [key: string]: unknown };
+
+ /**
+ * Connection instructions: methods ordered most-automated first, steps typed by actor (agent executes; human steps are narrated to the user).
+ */
+ export type MCPRegistryServerDetailConnect = { [key: string]: unknown };
+
+ export interface MCPRegistryServerDetail {
+ /** Registry server id. */
+ id: string;
+ /** Reverse-DNS name in the official MCP registry; empty for measured-only servers. */
+ registry_name: string;
+ /** Human-readable server name. */
+ display_name: string;
+ /** Server description. */
+ description: string;
+ /** Primary hosted remote URL; empty for package-only servers. */
+ canonical_url: string;
+ /** Probed liveness state (alive_open, alive_auth, dead, ...). */
+ liveness: string;
+ /** Detected auth method (none, oauth, api_key, unknown). */
+ auth_method: string;
+ /** Whether the server appears in the official MCP registry. */
+ listed_in_registry: boolean;
+ /** Whether real usage signal exists via MCP Analytics. */
+ is_measured: boolean;
+ /**
+ * Static score under the requested ranking version; null when the version has no completed run.
+ * @nullable
+ */
+ rank_score: number | null;
+ /** All hosted remotes: [{type, url}]. */
+ remotes: MCPRegistryServerDetailRemotesItem[];
+ /** Published packages: [{registry_type, identifier}]. */
+ packages: MCPRegistryServerDetailPackagesItem[];
+ /** Source repository URL, when published. */
+ repository_url: string;
+ /** Vendor website URL, when published. */
+ website_url: string;
+ /**
+ * When the shallow probe last ran.
+ * @nullable
+ */
+ last_probed_at: string | null;
+ /** Known tools, fused from probes and analytics. A tool known only from another project's traffic is limited to callers who may see that project's measurements. */
+ tools: MCPRegistryServerDetailToolsItem[];
+ /** Behavioral aggregates, one per measured MCP Analytics project. Limited to this project's own measurements unless the server is marked measured_public. */
+ measured_stats: MCPRegistryServerDetailMeasuredStatsItem[];
+ /** Latest score under every ranking version with a completed run. */
+ scores: MCPRegistryServerDetailScoresItem[];
+ /** Connection instructions: methods ordered most-automated first, steps typed by actor (agent executes; human steps are narrated to the user). */
+ connect: MCPRegistryServerDetailConnect;
+ }
+
+ export interface MCPRegistryServerList {
+ /** Registry server id. */
+ id: string;
+ /** Reverse-DNS name in the official MCP registry; empty for measured-only servers. */
+ registry_name: string;
+ /** Human-readable server name. */
+ display_name: string;
+ /** Server description. */
+ description: string;
+ /** Primary hosted remote URL; empty for package-only servers. */
+ canonical_url: string;
+ /** Probed liveness state (alive_open, alive_auth, dead, ...). */
+ liveness: string;
+ /** Detected auth method (none, oauth, api_key, unknown). */
+ auth_method: string;
+ /** Whether the server appears in the official MCP registry. */
+ listed_in_registry: boolean;
+ /** Whether real usage signal exists via MCP Analytics. */
+ is_measured: boolean;
+ /**
+ * Static score under the requested ranking version; null when the version has no completed run.
+ * @nullable
+ */
+ rank_score: number | null;
+ }
+
/**
* * `personal` - Personal
* * `shared` - Shared
@@ -55037,6 +55239,15 @@ export namespace Schemas {
results: MCPOrgRule[];
}
+ export interface PaginatedMCPRegistryServerListList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: MCPRegistryServerList[];
+ }
+
export interface PaginatedMCPServerInstallationList {
count: number;
/** @nullable */
@@ -97827,6 +98038,61 @@ export namespace Schemas {
offset?: number;
};
+ export type McpRegistryServersListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * Only servers with real MCP Analytics signal.
+ */
+ measured_only?: boolean;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Free-text query matched against server names, descriptions, and tool names.
+ */
+ search?: string;
+ /**
+ * Ranking version ordering the results; defaults to the current default version.
+ */
+ version?: string;
+ };
+
+ export type McpRegistryServersCompareRetrieveParams = {
+ /**
+ * Rows per arm (default 20, max 100).
+ */
+ limit?: number;
+ /**
+ * Optional text filter applied to every arm.
+ */
+ search?: string;
+ /**
+ * Comma-separated ranking versions to compare (2+).
+ */
+ versions: string;
+ };
+
+ export type McpRegistryServersCompareRetrieve200 = { [key: string]: unknown };
+
+ export type McpRegistryServersDiscoverRetrieveParams = {
+ /**
+ * What the agent is trying to do, in natural language.
+ */
+ intent: string;
+ /**
+ * Candidates to return (default 5, max 20).
+ */
+ limit?: number;
+ /**
+ * Ranking version to rank candidates by.
+ */
+ version?: string;
+ };
+
export type McpServerInstallationsListParams = {
/**
* Number of results to return per page.
diff --git a/tach.toml b/tach.toml
index 27c1972a621a..7f247697b680 100644
--- a/tach.toml
+++ b/tach.toml
@@ -135,6 +135,7 @@ depends_on = [
"products.tracing",
"products.user_interviews",
"products.mcp_analytics",
+ "products.mcp_registry",
"products.web_analytics",
"products.workflows",
"products.actions",
@@ -542,6 +543,26 @@ depends_on = [
]
layer = "modules"
+[[modules]]
+path = "products.mcp_registry"
+depends_on = [
+ "posthog",
+ # Facade-only (enforced by mcp_registry's [[interfaces]] block): the measured-server
+ # aggregation reads new-SDK $mcp_tool_call grouping rules through mcp_analytics' facade.
+ "products.mcp_analytics",
+]
+layer = "modules"
+
+[[interfaces]]
+expose = [
+ "backend\\.facade.*",
+ "backend\\.presentation\\.views.*",
+ "backend\\.routes.*",
+]
+from = [
+ "products.mcp_registry",
+]
+
[[modules]]
path = "products.mcp_store"
depends_on = [