Skip to content

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

feat(mcp-store): add MCP server probe module and management command (#70926)

Chris Volzer82b963768458
diff --git a/posthog/security/pinned_requests.py b/posthog/security/pinned_requests.py
new file mode 100644
index 000000000000..12e1cbef81b1
--- /dev/null
+++ b/posthog/security/pinned_requests.py
@@ -0,0 +1,156 @@
+"""SSRF-hardened HTTP requests with DNS pinning.
+
+``validate_url_and_pin_ips`` alone leaves a TOCTOU window: the hostname is
+resolved once for validation and again when ``requests`` opens the connection,
+so a rebinding DNS record can pass validation and still connect internally.
+``PinnedIPAdapter`` closes that window by connecting to the exact IPs that were
+validated, and ``pinned_request`` packages the validate → pin → send sequence
+for callers that make one-shot requests to externally controlled URLs.
+
+Redirects are never followed automatically — a redirect target has not been
+validated. Callers that need to follow one must re-enter ``pinned_request``
+with the new URL so every hop is validated and pinned.
+"""
+
+import ipaddress
+import urllib.parse as urlparse
+
+import idna
+import requests
+from requests.adapters import HTTPAdapter
+
+from posthog.security.url_validation import validate_url_and_pin_ips
+
+
+class SSRFBlockedError(Exception):
+ """URL failed SSRF validation. The message is the block reason."""
+
+
+def _canonical_host(hostname: str) -> str:
+ """Return the host in the same ASCII form ``requests`` connects to.
+
+ ``requests`` IDNA-encodes non-ASCII hosts before opening the connection
+ (``éxample.com`` -> ``xn--xample-9ua.com``), so a pin stored under the raw
+ Unicode host would never match the host seen in ``send()`` and the request
+ would silently fall back to a fresh DNS lookup — reopening the rebinding
+ window. Encoding both the stored pin and the lookup identically keeps the
+ match, and the SSRF guarantee, intact.
+ """
+ host = hostname.lower()
+ if host.isascii():
+ return host
+ try:
+ return idna.encode(host, uts46=True).decode("ascii")
+ except idna.IDNAError:
+ # requests rejects such a host during URL prep and never reaches send();
+ # keep the raw value so the map stays consistent if it somehow does.
+ return host
+
+
+class PinnedIPAdapter(HTTPAdapter):
+ """
+ Requests adapter that rewrites URLs to connect to pre-validated IPs,
+ preventing DNS rebinding between validation and connection.
+
+ For HTTPS, sets ``assert_hostname`` and ``server_hostname`` on the
+ connection pool so TLS SNI and certificate verification use the
+ original hostname (not the IP).
+
+ NOT thread-safe — mount on a single-use ``requests.Session``.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._pin_map: dict[str, str] = {}
+ self._current_original_host: str | None = None
+
+ def pin(self, hostname: str, ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> None:
+ self._pin_map[_canonical_host(hostname)] = str(ip)
+
+ def send( # type: ignore[override]
+ self,
+ request: requests.PreparedRequest,
+ stream: bool = False,
+ timeout: None | float | tuple[float, float] = None,
+ verify: bool | str = True,
+ cert: None | str | tuple[str, str] = None,
+ proxies: dict[str, str] | None = None,
+ ) -> requests.Response:
+ parsed = urlparse.urlparse(request.url or "")
+ host = _canonical_host(parsed.hostname or "")
+ ip_str = self._pin_map.get(host)
+
+ if ip_str is None:
+ # Fail closed: an adapter that pinned at least one host must refuse a
+ # request it can't match rather than let requests re-resolve DNS —
+ # that re-resolution is the rebinding window pinning exists to close.
+ # An empty map means pinning was intentionally skipped (e.g. the dev
+ # SSRF bypass), so pass the request through untouched.
+ if self._pin_map:
+ raise SSRFBlockedError(f"No validated pin for host {host!r}; refusing to connect")
+ self._current_original_host = None
+ return super().send(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
+
+ self._current_original_host = host
+
+ ip_netloc = f"[{ip_str}]" if ":" in ip_str else ip_str
+ if parsed.port:
+ ip_netloc = f"{ip_netloc}:{parsed.port}"
+
+ request.url = urlparse.urlunparse((parsed.scheme, ip_netloc, parsed.path, parsed.params, parsed.query, ""))
+
+ original_netloc = host
+ if parsed.port:
+ original_netloc = f"{host}:{parsed.port}"
+ if request.headers is not None:
+ request.headers["Host"] = original_netloc
+
+ return super().send(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
+
+ def cert_verify(self, conn: object, url: str, verify: bool | str, cert: None | str | tuple[str, str]) -> None:
+ super().cert_verify(conn, url, verify, cert)
+ original = getattr(self, "_current_original_host", None)
+ if original:
+ # We mutate urllib3 pool internals intentionally — these attributes
+ # exist at runtime (verified against urllib3 2.6.3) but aren't
+ # visible to static type checkers.
+ if hasattr(conn, "assert_hostname"):
+ conn.assert_hostname = original # ty: ignore[invalid-assignment]
+ # Inject server_hostname into conn_kw so newly created connections
+ # use the original hostname for TLS SNI (not the rewritten IP).
+ # urllib3 passes **conn_kw to ConnectionCls.__init__, and
+ # HTTPSConnection.connect() reads self.server_hostname for SNI.
+ if hasattr(conn, "conn_kw") and isinstance(getattr(conn, "conn_kw", None), dict):
+ conn.conn_kw["server_hostname"] = original # ty: ignore[invalid-assignment]
+
+
+def pinned_request(
+ method: str,
+ url: str,
+ *,
+ timeout: float | tuple[float, float],
+ headers: dict[str, str] | None = None,
+ json: object | None = None,
+) -> requests.Response:
+ """Send one SSRF-validated HTTP request over a connection pinned to the validated IPs.
+
+ Never follows redirects. Raises ``SSRFBlockedError`` when the URL fails
+ validation and lets ``requests.RequestException`` propagate on transport
+ failures.
+ """
+ allowed, reason, pinned_ips = validate_url_and_pin_ips(url)
+ if not allowed:
+ raise SSRFBlockedError(reason or "URL blocked by SSRF protection")
+
+ adapter = PinnedIPAdapter()
+ hostname = (urlparse.urlparse(url).hostname or "").lower()
+ if pinned_ips:
+ adapter.pin(hostname, next(iter(pinned_ips)))
+
+ session = requests.Session()
+ session.mount("http://", adapter) # nosemgrep: request-session-with-http
+ session.mount("https://", adapter)
+ try:
+ return session.request(method, url, headers=headers, json=json, timeout=timeout, allow_redirects=False)
+ finally:
+ session.close()
diff --git a/posthog/security/test/test_pinned_requests.py b/posthog/security/test/test_pinned_requests.py
new file mode 100644
index 000000000000..b716fdcebee7
--- /dev/null
+++ b/posthog/security/test/test_pinned_requests.py
@@ -0,0 +1,79 @@
+import ipaddress
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from requests.adapters import HTTPAdapter
+
+from posthog.security import pinned_requests as pr
+
+
+class TestPinnedRequest:
+ def test_blocked_url_raises_before_any_connection(self):
+ with (
+ patch.object(pr, "validate_url_and_pin_ips", return_value=(False, "Loopback host", set())),
+ patch.object(pr.requests, "Session") as session_cls,
+ ):
+ with pytest.raises(pr.SSRFBlockedError, match="Loopback host"):
+ pr.pinned_request("GET", "http://127.0.0.1/admin", timeout=5)
+ session_cls.assert_not_called()
+
+
+class TestPinnedIPAdapter:
+ @pytest.mark.parametrize(
+ "ip,expected_netloc",
+ [
+ ("93.184.216.34", "93.184.216.34:8443"),
+ ("2001:db8::1", "[2001:db8::1]:8443"),
+ ],
+ )
+ def test_rewrites_url_to_pinned_ip_and_preserves_host_header(self, ip, expected_netloc):
+ adapter = pr.PinnedIPAdapter()
+ adapter.pin("Example.COM", ipaddress.ip_address(ip))
+ request = requests.Request("GET", "https://example.com:8443/path?q=1").prepare()
+
+ with patch.object(HTTPAdapter, "send", return_value=MagicMock()):
+ adapter.send(request)
+
+ assert request.url == f"https://{expected_netloc}/path?q=1"
+ assert request.headers["Host"] == "example.com:8443"
+
+ def test_idn_host_still_matches_its_pin(self):
+ # requests IDNA-encodes the host before send(), so the pin must be stored
+ # under the same encoded form or the request silently re-resolves DNS —
+ # the rebinding bypass this adapter exists to prevent.
+ adapter = pr.PinnedIPAdapter()
+ adapter.pin("éxample.com", ipaddress.ip_address("93.184.216.34"))
+ request = requests.Request("GET", "https://éxample.com/path").prepare()
+ assert "xn--xample-9ua.com" in (request.url or "") # requests already punycoded it
+
+ with patch.object(HTTPAdapter, "send", return_value=MagicMock()):
+ adapter.send(request)
+
+ assert request.url == "https://93.184.216.34/path"
+ assert request.headers["Host"] == "xn--xample-9ua.com"
+
+ def test_unmatched_host_is_refused(self):
+ # A pinned adapter that can't match the outgoing host must fail closed
+ # rather than let requests re-resolve DNS to an unvalidated address.
+ adapter = pr.PinnedIPAdapter()
+ adapter.pin("example.com", ipaddress.ip_address("93.184.216.34"))
+ request = requests.Request("GET", "https://other.example.org/path").prepare()
+
+ with patch.object(HTTPAdapter, "send", return_value=MagicMock()) as inner_send:
+ with pytest.raises(pr.SSRFBlockedError):
+ adapter.send(request)
+ inner_send.assert_not_called()
+
+ def test_no_pins_passes_through(self):
+ # Empty map means pinning was intentionally skipped (dev SSRF bypass);
+ # fail-closed must not fire there or local requests break.
+ adapter = pr.PinnedIPAdapter()
+ request = requests.Request("GET", "https://other.example.org/path").prepare()
+
+ with patch.object(HTTPAdapter, "send", return_value=MagicMock()):
+ adapter.send(request)
+
+ assert request.url == "https://other.example.org/path"
+ assert "Host" not in request.headers
diff --git a/products/business_knowledge/backend/url_fetch.py b/products/business_knowledge/backend/url_fetch.py
index 2ed366583d7d..078cadea136b 100644
--- a/products/business_knowledge/backend/url_fetch.py
+++ b/products/business_knowledge/backend/url_fetch.py
@@ -16,14 +16,13 @@ Responsibilities:
from __future__ import annotations
import hashlib
-import ipaddress
import urllib.parse as urlparse
from dataclasses import dataclass
import requests
import structlog
-from requests.adapters import HTTPAdapter
+from posthog.security.pinned_requests import PinnedIPAdapter
from posthog.security.url_validation import validate_url_and_pin_ips
from .constants import URL_CONNECT_TIMEOUT, URL_MAX_BYTES, URL_MAX_REDIRECTS, URL_READ_TIMEOUT, URL_USER_AGENT
@@ -100,78 +99,6 @@ def prefetch_key(url: str) -> str:
return url
-# --- DNS-pinning adapter — eliminates TOCTOU rebinding window ----------------
-
-
-class _PinnedIPAdapter(HTTPAdapter):
- """
- Requests adapter that rewrites URLs to connect to pre-validated IPs,
- preventing DNS rebinding between validation and connection.
-
- For HTTPS, sets ``assert_hostname`` and ``server_hostname`` on the
- connection pool so TLS SNI and certificate verification use the
- original hostname (not the IP).
-
- NOT thread-safe — designed for single-use sessions in ``_ssrf_safe_get``.
- """
-
- def __init__(self) -> None:
- super().__init__()
- self._pin_map: dict[str, str] = {}
- self._current_original_host: str | None = None
-
- def pin(self, hostname: str, ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> None:
- self._pin_map[hostname.lower()] = str(ip)
-
- def send( # type: ignore[override]
- self,
- request: requests.PreparedRequest,
- stream: bool = False,
- timeout: None | float | tuple[float, float] = None,
- verify: bool | str = True,
- cert: None | str | tuple[str, str] = None,
- proxies: dict[str, str] | None = None,
- ) -> requests.Response:
- parsed = urlparse.urlparse(request.url or "")
- host = (parsed.hostname or "").lower()
- ip_str = self._pin_map.get(host)
-
- if ip_str is not None:
- self._current_original_host = host
-
- ip_netloc = f"[{ip_str}]" if ":" in ip_str else ip_str
- if parsed.port:
- ip_netloc = f"{ip_netloc}:{parsed.port}"
-
- request.url = urlparse.urlunparse((parsed.scheme, ip_netloc, parsed.path, parsed.params, parsed.query, ""))
-
- original_netloc = host
- if parsed.port:
- original_netloc = f"{host}:{parsed.port}"
- if request.headers is not None:
- request.headers["Host"] = original_netloc
- else:
- self._current_original_host = None
-
- return super().send(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
-
- def cert_verify(self, conn: object, url: str, verify: bool | str, cert: None | str | tuple[str, str]) -> None:
- super().cert_verify(conn, url, verify, cert)
- original = getattr(self, "_current_original_host", None)
- if original:
- # We mutate urllib3 pool internals intentionally — these attributes
- # exist at runtime (verified against urllib3 2.6.3) but aren't
- # visible to static type checkers.
- if hasattr(conn, "assert_hostname"):
- conn.assert_hostname = original # ty: ignore[invalid-assignment]
- # Inject server_hostname into conn_kw so newly created connections
- # use the original hostname for TLS SNI (not the rewritten IP).
- # urllib3 passes **conn_kw to ConnectionCls.__init__, and
- # HTTPSConnection.connect() reads self.server_hostname for SNI.
- if hasattr(conn, "conn_kw") and isinstance(getattr(conn, "conn_kw", None), dict):
- conn.conn_kw["server_hostname"] = original # ty: ignore[invalid-assignment]
-
-
# --- Shared SSRF-safe fetch core ---------------------------------------------
@@ -209,7 +136,7 @@ def _ssrf_safe_get(
"""
current = strip_userinfo(normalize_url(url))
- adapter = _PinnedIPAdapter()
+ adapter = PinnedIPAdapter()
session = requests.Session()
session.mount("http://", adapter) # nosemgrep: request-session-with-http
session.mount("https://", adapter)
diff --git a/products/mcp_store/backend/management/commands/probe_mcp_server.py b/products/mcp_store/backend/management/commands/probe_mcp_server.py
new file mode 100644
index 000000000000..cc37eca7ef5d
--- /dev/null
+++ b/products/mcp_store/backend/management/commands/probe_mcp_server.py
@@ -0,0 +1,21 @@
+import json
+from dataclasses import asdict
+from typing import cast
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+
+from products.mcp_store.backend.probe import probe_mcp_server
+
+
+class Command(BaseCommand):
+ help = "Probe a remote MCP server end-to-end, up to the OAuth consent screen."
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("url", help="URL of the MCP server to probe.")
+
+ def handle(self, *args: object, **options: object) -> None:
+ result = probe_mcp_server(cast(str, options["url"]))
+ payload = {**asdict(result), "passed_activation_gate": result.passed_activation_gate}
+ self.stdout.write(json.dumps(payload, indent=2))
+ if not result.speaks_mcp:
+ raise CommandError("Server did not respond like an MCP server")
diff --git a/products/mcp_store/backend/probe.py b/products/mcp_store/backend/probe.py
new file mode 100644
index 000000000000..bbc904ddf8e6
--- /dev/null
+++ b/products/mcp_store/backend/probe.py
@@ -0,0 +1,297 @@
+"""Probe a remote MCP server end-to-end, up to (but not through) the OAuth consent screen.
+
+Verifies that a catalog entry actually works before it gets activated: speaks the
+MCP initialize handshake, classifies the server's auth model, mints a real DCR
+client when the provider supports one, and checks that the authorization endpoint
+serves a plausible login page.
+
+Deliberately dependency-light (pure HTTP plus the helpers in ``oauth.py`` — no
+Django models, no database access) so it can run from management commands and
+catalog sync jobs alike.
+"""
+
+import json
+import secrets
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+from typing import Literal
+from urllib.parse import urlencode, urljoin
+
+from django.conf import settings
+
+import requests
+import structlog
+
+from posthog.security.pinned_requests import SSRFBlockedError, pinned_request
+
+from .oauth import (
+ TIMEOUT,
+ discover_oauth_metadata,
+ generate_pkce,
+ oauth_resource,
+ register_dcr_client,
+ requested_oauth_scopes,
+)
+
+logger = structlog.get_logger(__name__)
+
+MCP_PROTOCOL_VERSION = "2025-06-18"
+MAX_AUTHORIZE_REDIRECTS = 3
+
+_AUTH_REQUIRED_STATUSES = (401, 403)
+# A rendered login/consent page, or an immediate redirect into a hosted login flow.
+_AUTHORIZE_ALIVE_STATUSES = (200, 302, 303)
+_AUTHORIZE_FOLLOWABLE_STATUSES = (301, 307, 308)
+
+AuthFlavor = Literal["open", "oauth_dcr", "oauth_shared", "api_key_or_unknown"]
+_InitializeOutcome = Literal["open", "auth_required", "failed"]
+
+
+@dataclass
+class ProbeResult:
+ reachable: bool = False
+ speaks_mcp: bool = False
+ server_info: dict | None = None
+ auth_flavor: AuthFlavor = "api_key_or_unknown"
+ oauth_metadata: dict | None = None
+ dcr_registered: bool = False
+ authorize_endpoint_ok: bool = False
+ errors: list[str] = field(default_factory=list)
+
+ @property
+ def passed_activation_gate(self) -> bool:
+ """Whether the probe outcome is strong enough to auto-activate a catalog entry."""
+ if not (self.reachable and self.speaks_mcp):
+ return False
+ if self.auth_flavor == "oauth_dcr":
+ return self.dcr_registered and self.authorize_endpoint_ok
+ # oauth_shared needs manually provisioned shared client credentials, and
+ # api_key_or_unknown carries no MCP evidence (a bare 401/403 could be any
+ # protected endpoint) — neither may auto-activate.
+ return self.auth_flavor == "open"
+
+
+def probe_mcp_server(url: str) -> ProbeResult:
+ """Probe ``url`` and return a :class:`ProbeResult`. Never raises."""
+ result = ProbeResult()
+ try:
+ _run_probe(url, result)
+ except Exception as exc:
+ logger.exception("MCP server probe failed unexpectedly", server_url=url)
+ result.errors.append(f"Probe aborted unexpectedly: {exc}")
+ return result
+
+
+def _run_probe(url: str, result: ProbeResult) -> None:
+ outcome = _probe_initialize(url, result)
+ if outcome == "failed":
+ return
+
+ metadata = _discover_metadata(url, result, auth_required=outcome == "auth_required")
+ if metadata is None:
+ if outcome == "open":
+ result.auth_flavor = "open"
+ return
+ # A bare 401/403 is indistinguishable from any auth-walled endpoint, so
+ # without OAuth metadata there is no evidence the server speaks MCP.
+ result.auth_flavor = "api_key_or_unknown"
+ result.errors.append(
+ "Initialize was rejected and no OAuth metadata was discovered; cannot verify the server speaks MCP"
+ )
+ return
+
+ # OAuth protected-resource metadata (RFC 9728) served for this URL is the
+ # strongest MCP evidence available without credentials.
+ result.speaks_mcp = True
+ result.oauth_metadata = metadata
+ client_id = _register_probe_client(metadata, result)
+ if client_id is None:
+ result.auth_flavor = "oauth_shared"
+ return
+
+ result.auth_flavor = "oauth_dcr"
+ result.dcr_registered = True
+ result.authorize_endpoint_ok = _check_authorize_endpoint(metadata, client_id, result)
+
+
+def _probe_redirect_uri() -> str:
+ # Mirrors the redirect URI the install flow registers (views._get_oauth_redirect_uri).
+ return f"{settings.SITE_URL}/api/mcp_store/oauth_redirect/"
+
+
+def _probe_initialize(url: str, result: ProbeResult) -> _InitializeOutcome:
+ """Run the MCP initialize handshake.
+
+ "open" means the server completed the handshake without auth (MCP verified);
+ "auth_required" means it rejected the call with 401/403, which proves nothing
+ about MCP until OAuth discovery corroborates it; "failed" means it did not
+ respond like an MCP server.
+ """
+ payload = {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": MCP_PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {"name": "posthog-mcp-store-probe", "version": "1.0"},
+ },
+ }
+ headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ }
+ try:
+ response = pinned_request("POST", url, json=payload, headers=headers, timeout=TIMEOUT)
+ except SSRFBlockedError as exc:
+ result.errors.append(f"MCP server URL blocked by SSRF protection: {exc}")
+ return "failed"
+ except requests.RequestException as exc:
+ result.errors.append(f"MCP initialize request failed: {exc}")
+ return "failed"
+
+ result.reachable = True
+ if 300 <= response.status_code < 400:
+ # A redirect target never went through SSRF validation, and a catalog URL
+ # should point at the MCP endpoint itself — refuse rather than follow.
+ result.errors.append(f"MCP initialize returned a redirect (HTTP {response.status_code}); not following it")
+ return "failed"
+ if response.status_code in _AUTH_REQUIRED_STATUSES:
+ return "auth_required"
+ if response.status_code != 200:
+ result.errors.append(f"MCP initialize returned HTTP {response.status_code}")
+ return "failed"
+
+ rpc_result = _jsonrpc_result(response)
+ if rpc_result is None:
+ content_type = response.headers.get("Content-Type", "")
+ result.errors.append(
+ f"MCP initialize returned HTTP 200 without a JSON-RPC result (content-type: {content_type})"
+ )
+ return "failed"
+
+ result.speaks_mcp = True
+ server_info = rpc_result.get("serverInfo")
+ if isinstance(server_info, dict):
+ result.server_info = server_info
+ return "open"
+
+
+def _iter_sse_data(body: str) -> Iterator[str]:
+ """Yield the ``data:`` payload of each SSE event, joining multi-line data frames."""
+ data_lines: list[str] = []
+ for line in body.splitlines():
+ if line.startswith("data:"):
+ data_lines.append(line[len("data:") :].lstrip())
+ elif not line.strip() and data_lines:
+ yield "\n".join(data_lines)
+ data_lines = []
+ if data_lines:
+ yield "\n".join(data_lines)
+
+
+def _jsonrpc_result(response: requests.Response) -> dict | None:
+ """Extract the JSON-RPC ``result`` object from a JSON or SSE-wrapped initialize response.
+
+ MCP streamable HTTP servers may answer directly with JSON or over a
+ ``text/event-stream`` frame; sniff the body as a fallback because some
+ proxies mislabel the stream (same approach as ``tools._parse_jsonrpc_response``).
+ """
+ content_type = response.headers.get("Content-Type", "").lower()
+ body = response.text
+ candidates: Iterator[str]
+ if "text/event-stream" in content_type or body.lstrip().startswith(("event:", "data:", ":")):
+ candidates = _iter_sse_data(body)
+ else:
+ candidates = iter([body])
+
+ for candidate in candidates:
+ try:
+ message = json.loads(candidate)
+ except ValueError:
+ continue
+ if not isinstance(message, dict) or message.get("jsonrpc") != "2.0":
+ continue
+ rpc_result = message.get("result")
+ if isinstance(rpc_result, dict):
+ return rpc_result
+ return None
+
+
+def _discover_metadata(url: str, result: ProbeResult, *, auth_required: bool) -> dict | None:
+ try:
+ return discover_oauth_metadata(url)
+ except Exception as exc:
+ # Open servers legitimately have no discoverable OAuth metadata; only note
+ # the failure when the server demanded auth we now can't classify.
+ if auth_required:
+ result.errors.append(f"OAuth discovery failed: {exc}")
+ return None
+
+
+def _register_probe_client(metadata: dict, result: ProbeResult) -> str | None:
+ """Mint a real DCR client. Returns its client_id, or None when DCR is unavailable."""
+ if not metadata.get("registration_endpoint"):
+ return None
+ try:
+ client_id, _client_secret, _auth_method = register_dcr_client(metadata, _probe_redirect_uri())
+ except ValueError as exc:
+ # Mirrors views._register_dcr_client_or_raise: ValueError means DCR isn't supported.
+ result.errors.append(f"Dynamic Client Registration not supported: {exc}")
+ return None
+ except Exception as exc:
+ result.errors.append(f"Dynamic Client Registration failed: {exc}")
+ return None
+ return client_id
+
+
+def _build_authorize_url(metadata: dict, client_id: str) -> str | None:
+ authorization_endpoint = metadata.get("authorization_endpoint")
+ if not isinstance(authorization_endpoint, str) or not authorization_endpoint:
+ return None
+
+ _code_verifier, code_challenge = generate_pkce()
+ query_params = {
+ "client_id": client_id,
+ "redirect_uri": _probe_redirect_uri(),
+ "response_type": "code",
+ "state": secrets.token_urlsafe(16),
+ "code_challenge": code_challenge,
+ "code_challenge_method": "S256",
+ }
+ if scopes := requested_oauth_scopes(metadata):
+ query_params["scope"] = " ".join(scopes)
+ if resource := oauth_resource(metadata):
+ query_params["resource"] = resource
+ return f"{authorization_endpoint}?{urlencode(query_params)}"
+
+
+def _check_authorize_endpoint(metadata: dict, client_id: str, result: ProbeResult) -> bool:
+ """GET the authorization URL and report whether it serves a plausible login/consent page."""
+ authorize_url = _build_authorize_url(metadata, client_id)
+ if authorize_url is None:
+ result.errors.append("OAuth metadata is missing authorization_endpoint")
+ return False
+
+ current_url = authorize_url
+ for _hop in range(MAX_AUTHORIZE_REDIRECTS + 1):
+ try:
+ response = pinned_request("GET", current_url, timeout=TIMEOUT)
+ except SSRFBlockedError as exc:
+ result.errors.append(f"Authorization endpoint blocked by SSRF protection: {exc}")
+ return False
+ except requests.RequestException as exc:
+ result.errors.append(f"Authorization endpoint request failed: {exc}")
+ return False
+
+ if response.status_code in _AUTHORIZE_ALIVE_STATUSES:
+ return True
+ location = response.headers.get("Location", "")
+ if response.status_code in _AUTHORIZE_FOLLOWABLE_STATUSES and location:
+ current_url = urljoin(current_url, location)
+ continue
+ result.errors.append(f"Authorization endpoint returned HTTP {response.status_code}")
+ return False
+
+ result.errors.append(f"Authorization endpoint redirected more than {MAX_AUTHORIZE_REDIRECTS} times")
+ return False
diff --git a/products/mcp_store/backend/test/test_probe.py b/products/mcp_store/backend/test/test_probe.py
new file mode 100644
index 000000000000..f5eac8cedad6
--- /dev/null
+++ b/products/mcp_store/backend/test/test_probe.py
@@ -0,0 +1,298 @@
+import json
+from urllib.parse import parse_qs, urlparse
+
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+import requests
+from parameterized import parameterized
+
+from posthog.security.pinned_requests import SSRFBlockedError
+
+from products.mcp_store.backend.probe import ProbeResult, probe_mcp_server
+
+SERVER_URL = "https://mcp.example.com/mcp"
+ORIGIN = "https://mcp.example.com"
+
+INITIALIZE_MESSAGE = {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "result": {
+ "protocolVersion": "2025-06-18",
+ "capabilities": {},
+ "serverInfo": {"name": "test-server", "version": "1.0"},
+ },
+}
+
+PROTECTED_RESOURCE_URL = f"{ORIGIN}/.well-known/oauth-protected-resource/mcp"
+AUTH_SERVER_METADATA_URL = f"{ORIGIN}/.well-known/oauth-authorization-server"
+REGISTRATION_URL = f"{ORIGIN}/register"
+AUTHORIZE_URL = f"{ORIGIN}/authorize"
+
+PROTECTED_RESOURCE_BODY = {"resource": SERVER_URL, "authorization_servers": [ORIGIN]}
+AUTH_SERVER_METADATA_BODY = {
+ "issuer": ORIGIN,
+ "authorization_endpoint": AUTHORIZE_URL,
+ "token_endpoint": f"{ORIGIN}/token",
+ "registration_endpoint": REGISTRATION_URL,
+}
+
+
+def _mock_response(status_code=200, *, json_body=None, text="", content_type="application/json", headers=None):
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.headers = {"Content-Type": content_type, **(headers or {})}
+ if json_body is not None:
+ response.text = json.dumps(json_body)
+ response.json.return_value = json_body
+ else:
+ response.text = text
+ response.json.side_effect = ValueError("not json")
+ if status_code >= 400:
+ response.raise_for_status.side_effect = requests.HTTPError(f"HTTP {status_code}", response=response)
+ else:
+ response.raise_for_status.return_value = None
+ return response
+
+
+def _url_router(routes):
+ def handle(url, *args, **kwargs):
+ handler = routes.get(url.split("?")[0])
+ if handler is None:
+ return _mock_response(404, text="not found", content_type="text/plain")
+ if isinstance(handler, Exception):
+ raise handler
+ return handler
+
+ return handle
+
+
+class TestProbeMCPServer(SimpleTestCase):
+ def _probe(self, *, post_routes, get_routes=None):
+ post_router = _url_router(post_routes)
+ get_router = _url_router(get_routes or {})
+
+ # The probe's own requests go through pinned_request; oauth.py's discovery
+ # and DCR requests still use the plain requests module. Both sides share
+ # the same route tables so a URL behaves identically on either path.
+ def pinned_router(method, url, **kwargs):
+ return post_router(url) if method == "POST" else get_router(url)
+
+ with (
+ patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None)),
+ patch("products.mcp_store.backend.probe.pinned_request", side_effect=pinned_router) as pinned,
+ patch("products.mcp_store.backend.oauth.requests.post", side_effect=post_router) as post,
+ patch("products.mcp_store.backend.oauth.requests.get", side_effect=get_router) as get,
+ ):
+ result = probe_mcp_server(SERVER_URL)
+ return result, post, get, pinned
+
+ @parameterized.expand(
+ [
+ ("json_response", "application/json", json.dumps(INITIALIZE_MESSAGE)),
+ ("sse_response", "text/event-stream", f"event: message\ndata: {json.dumps(INITIALIZE_MESSAGE)}\n\n"),
+ ]
+ )
+ def test_open_server_happy_path(self, _name, content_type, body):
+ result, _post, _get, _pinned = self._probe(
+ post_routes={SERVER_URL: _mock_response(200, text=body, content_type=content_type)},
+ )
+
+ self.assertTrue(result.reachable)
+ self.assertTrue(result.speaks_mcp)
+ self.assertEqual(result.server_info, {"name": "test-server", "version": "1.0"})
+ self.assertEqual(result.auth_flavor, "open")
+ self.assertIsNone(result.oauth_metadata)
+ self.assertEqual(result.errors, [])
+ self.assertTrue(result.passed_activation_gate)
+
+ def test_oauth_dcr_full_pass(self):
+ result, _post, _get, pinned = self._probe(
+ post_routes={
+ SERVER_URL: _mock_response(401, text="unauthorized", content_type="text/plain"),
+ REGISTRATION_URL: _mock_response(
+ 201, json_body={"client_id": "minted-client-id", "token_endpoint_auth_method": "none"}
+ ),
+ },
+ get_routes={
+ PROTECTED_RESOURCE_URL: _mock_response(200, json_body=PROTECTED_RESOURCE_BODY),
+ AUTH_SERVER_METADATA_URL: _mock_response(200, json_body=AUTH_SERVER_METADATA_BODY),
+ AUTHORIZE_URL: _mock_response(200, text="<html>log in</html>", content_type="text/html"),
+ },
+ )
+
+ self.assertTrue(result.reachable)
+ self.assertTrue(result.speaks_mcp)
+ self.assertEqual(result.auth_flavor, "oauth_dcr")
+ self.assertTrue(result.dcr_registered)
+ self.assertTrue(result.authorize_endpoint_ok)
+ self.assertEqual(result.oauth_metadata["registration_endpoint"], REGISTRATION_URL)
+ self.assertTrue(result.passed_activation_gate)
+
+ authorize_calls = [c for c in pinned.call_args_list if c.args[1].startswith(f"{AUTHORIZE_URL}?")]
+ self.assertEqual(len(authorize_calls), 1)
+ query = parse_qs(urlparse(authorize_calls[0].args[1]).query)
+ self.assertEqual(query["client_id"], ["minted-client-id"])
+ self.assertEqual(query["response_type"], ["code"])
+ self.assertEqual(query["code_challenge_method"], ["S256"])
+ self.assertIn("code_challenge", query)
+ self.assertTrue(query["redirect_uri"][0].endswith("/api/mcp_store/oauth_redirect/"))
+
+ def test_oauth_without_registration_endpoint_is_oauth_shared(self):
+ metadata = {k: v for k, v in AUTH_SERVER_METADATA_BODY.items() if k != "registration_endpoint"}
+ result, _post, _get, _pinned = self._probe(
+ post_routes={SERVER_URL: _mock_response(401, text="unauthorized", content_type="text/plain")},
+ get_routes={
+ PROTECTED_RESOURCE_URL: _mock_response(200, json_body=PROTECTED_RESOURCE_BODY),
+ AUTH_SERVER_METADATA_URL: _mock_response(200, json_body=metadata),
+ },
+ )
+
+ self.assertTrue(result.speaks_mcp)
+ self.assertEqual(result.auth_flavor, "oauth_shared")
+ self.assertFalse(result.dcr_registered)
+ self.assertFalse(result.authorize_endpoint_ok)
+ self.assertEqual(result.oauth_metadata["token_endpoint"], f"{ORIGIN}/token")
+ self.assertFalse(result.passed_activation_gate)
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
+ def test_auth_required_without_metadata_is_unverified_and_fails_gate(self, _name, status_code):
+ result, _post, _get, _pinned = self._probe(
+ post_routes={SERVER_URL: _mock_response(status_code, text="denied", content_type="text/plain")},
+ )
+
+ self.assertTrue(result.reachable)
+ self.assertFalse(result.speaks_mcp)
+ self.assertEqual(result.auth_flavor, "api_key_or_unknown")
+ self.assertIsNone(result.oauth_metadata)
+ self.assertFalse(result.dcr_registered)
+ self.assertTrue(any(error.startswith("OAuth discovery failed") for error in result.errors))
+ self.assertTrue(any("cannot verify the server speaks MCP" in error for error in result.errors))
+ self.assertFalse(result.passed_activation_gate)
+
+ @parameterized.expand(
+ [
+ ("html_200", lambda: _mock_response(200, text="<html>a docs page</html>", content_type="text/html"), True),
+ ("not_found", lambda: _mock_response(404, text="not found", content_type="text/plain"), True),
+ ("connection_error", lambda: requests.ConnectionError("connection refused"), False),
+ ]
+ )
+ def test_non_mcp_endpoint(self, _name, response_factory, expected_reachable):
+ result, _post, _get, _pinned = self._probe(post_routes={SERVER_URL: response_factory()})
+
+ self.assertIs(result.reachable, expected_reachable)
+ self.assertFalse(result.speaks_mcp)
+ self.assertIsNone(result.server_info)
+ self.assertEqual(len(result.errors), 1)
+ self.assertFalse(result.passed_activation_gate)
+
+ def test_initialize_url_blocked_by_ssrf(self):
+ result, _post, _get, _pinned = self._probe(
+ post_routes={SERVER_URL: SSRFBlockedError("Disallowed target IP: 10.0.0.5")},
+ )
+
+ self.assertFalse(result.reachable)
+ self.assertFalse(result.speaks_mcp)
+ self.assertTrue(any(error.startswith("MCP server URL blocked by SSRF protection") for error in result.errors))
+ self.assertFalse(result.passed_activation_gate)
+
+ def test_initialize_redirect_is_not_followed(self):
+ result, _post, _get, pinned = self._probe(
+ post_routes={
+ SERVER_URL: _mock_response(
+ 302, text="", content_type="text/plain", headers={"Location": "http://169.254.169.254/latest/"}
+ )
+ },
+ )
+
+ self.assertTrue(result.reachable)
+ self.assertFalse(result.speaks_mcp)
+ self.assertTrue(any("redirect" in error for error in result.errors))
+ self.assertFalse(result.passed_activation_gate)
+ # The redirect target must never be requested.
+ self.assertEqual(pinned.call_count, 1)
+
+ def test_authorize_redirect_to_blocked_target_fails_gate(self):
+ blocked_url = "http://169.254.169.254/latest/"
+ result, _post, _get, _pinned = self._probe(
+ post_routes={
+ SERVER_URL: _mock_response(401, text="unauthorized", content_type="text/plain"),
+ REGISTRATION_URL: _mock_response(
+ 201, json_body={"client_id": "minted-client-id", "token_endpoint_auth_method": "none"}
+ ),
+ },
+ get_routes={
+ PROTECTED_RESOURCE_URL: _mock_response(200, json_body=PROTECTED_RESOURCE_BODY),
+ AUTH_SERVER_METADATA_URL: _mock_response(200, json_body=AUTH_SERVER_METADATA_BODY),
+ AUTHORIZE_URL: _mock_response(
+ 307, text="", content_type="text/plain", headers={"Location": blocked_url}
+ ),
+ blocked_url: SSRFBlockedError("Local/metadata host"),
+ },
+ )
+
+ self.assertEqual(result.auth_flavor, "oauth_dcr")
+ self.assertTrue(result.dcr_registered)
+ self.assertFalse(result.authorize_endpoint_ok)
+ self.assertTrue(
+ any(error.startswith("Authorization endpoint blocked by SSRF protection") for error in result.errors)
+ )
+ self.assertFalse(result.passed_activation_gate)
+
+ @parameterized.expand(
+ [
+ ("registration_http_500", lambda: _mock_response(500, text="boom", content_type="text/plain")),
+ ("registration_missing_client_id", lambda: _mock_response(201, json_body={"scope": "read"})),
+ ]
+ )
+ def test_dcr_registration_failure_falls_back_to_oauth_shared(self, _name, registration_response_factory):
+ result, _post, _get, _pinned = self._probe(
+ post_routes={
+ SERVER_URL: _mock_response(401, text="unauthorized", content_type="text/plain"),
+ REGISTRATION_URL: registration_response_factory(),
+ },
+ get_routes={
+ PROTECTED_RESOURCE_URL: _mock_response(200, json_body=PROTECTED_RESOURCE_BODY),
+ AUTH_SERVER_METADATA_URL: _mock_response(200, json_body=AUTH_SERVER_METADATA_BODY),
+ },
+ )
+
+ self.assertEqual(result.auth_flavor, "oauth_shared")
+ self.assertFalse(result.dcr_registered)
+ self.assertFalse(result.authorize_endpoint_ok)
+ self.assertTrue(any("Dynamic Client Registration" in error for error in result.errors))
+ self.assertFalse(result.passed_activation_gate)
+
+ def test_probe_never_raises_on_unexpected_error(self):
+ result, _post, _get, _pinned = self._probe(post_routes={SERVER_URL: RuntimeError("boom")})
+
+ self.assertFalse(result.reachable)
+ self.assertFalse(result.speaks_mcp)
+ self.assertTrue(any(error.startswith("Probe aborted unexpectedly") for error in result.errors))
+ self.assertFalse(result.passed_activation_gate)
+
+
+class TestPassedActivationGate(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("open_reachable_mcp", "open", True, True, False, False, True),
+ ("open_not_mcp", "open", True, False, False, False, False),
+ ("open_unreachable", "open", False, False, False, False, False),
+ ("api_key_never_auto_activates", "api_key_or_unknown", True, True, False, False, False),
+ ("oauth_dcr_full_pass", "oauth_dcr", True, True, True, True, True),
+ ("oauth_dcr_authorize_down", "oauth_dcr", True, True, True, False, False),
+ ("oauth_dcr_not_registered", "oauth_dcr", True, True, False, True, False),
+ ("oauth_shared", "oauth_shared", True, True, False, False, False),
+ ]
+ )
+ def test_gate(self, _name, auth_flavor, reachable, speaks_mcp, dcr_registered, authorize_endpoint_ok, expected):
+ result = ProbeResult(
+ reachable=reachable,
+ speaks_mcp=speaks_mcp,
+ auth_flavor=auth_flavor,
+ dcr_registered=dcr_registered,
+ authorize_endpoint_ok=authorize_endpoint_ok,
+ )
+ self.assertIs(result.passed_activation_gate, expected)