:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): enforce connection policies and bound upstream responses (#118401)
Richard Solomou92e39e557445
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex ec3cb692f159..fe254cf7c117 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -427,6 +427,8 @@ Register your new reference in [`products/posthog_ai/skills/querying-posthog-dat## Code generation pipeline+Generated handlers URL-encode path parameters. `ApiClient.request` also rejects empty path segments and paths that URL parsing would normalize. Keep generated calls on this client so the requested resource stays within the handler's endpoint.+The pipeline turns Django serializers into MCP tool handlers via OpenAPI.Run the full pipeline with:diff --git a/ee/hogai/tools/call_mcp_server/installations.py b/ee/hogai/tools/call_mcp_server/installations.pyindex f845afc58657..8f361fce8f84 100644--- a/ee/hogai/tools/call_mcp_server/installations.py+++ b/ee/hogai/tools/call_mcp_server/installations.py@@ -100,7 +100,7 @@ def _get_tool_approval_states(def _get_unlisted_tool_state(- installation_id: str, team_id: int, gateway_server_id: UUID, user: User, tool_name: str+ installation_id: str, team_id: int, gateway_server_id: UUID | None, user: User, tool_name: str) -> str:return resolve_member_unlisted_tool_state(installation_id, team_id, gateway_server_id, user.id, tool_name)@@ -127,14 +127,15 @@ def _build_server_headers(installations: list[dict]) -> dict[str, dict[str, str]headers: dict[str, dict[str, str]] = {}for inst in installations:url = inst["url"]+ headers[url] = {"x-posthog-mcp-mode": "tools", "x-posthog-mcp-store": "true"}auth_type = inst.get("auth_type", "api_key")sensitive = inst.get("sensitive_configuration") or {}if auth_type == "api_key":if api_key := sensitive.get("api_key"):- headers[url] = {"Authorization": f"Bearer {api_key}"}+ headers[url]["Authorization"] = f"Bearer {api_key}"elif auth_type == "oauth":if access_token := sensitive.get("access_token"):- headers[url] = {"Authorization": f"Bearer {access_token}"}+ headers[url]["Authorization"] = f"Bearer {access_token}"return headersdiff --git a/ee/hogai/tools/call_mcp_server/test/test_tool.py b/ee/hogai/tools/call_mcp_server/test/test_tool.pyindex 43aced091b91..dda8f839228b 100644--- a/ee/hogai/tools/call_mcp_server/test/test_tool.py+++ b/ee/hogai/tools/call_mcp_server/test/test_tool.py@@ -53,8 +53,9 @@ class TestCallMCPServerTool(BaseTest):url="https://mcp.example.com/mcp",auth_type="api_key",sensitive_configuration=None,+ tool_names: tuple[str, ...] = (),):- return MCPServerInstallation.objects.create(+ installation = MCPServerInstallation.objects.create(team=self.team,user=self.user,display_name=name,@@ -62,6 +63,15 @@ class TestCallMCPServerTool(BaseTest):auth_type=auth_type,sensitive_configuration=sensitive_configuration or {},)+ MCPServerInstallationTool.objects.bulk_create(+ [+ MCPServerInstallationTool(+ installation=installation, tool_name=name, approval_state="approved", last_seen_at=timezone.now()+ )+ for name in tool_names+ ]+ )+ return installationdef _create_tool(self, installations: list[dict] | None = None, conversation_id: str | None = None):if installations is None:@@ -178,7 +188,14 @@ class TestAuthHeaders(TestCallMCPServerTool):MockClient.assert_called_once()_, kwargs = MockClient.call_args- self.assertEqual(kwargs["headers"], {"Authorization": "Bearer my-oauth-token"})+ self.assertEqual(+ kwargs["headers"],+ {+ "Authorization": "Bearer my-oauth-token",+ "x-posthog-mcp-mode": "tools",+ "x-posthog-mcp-store": "true",+ },+ )async def test_api_key_sent_as_bearer_header(self):inst = {@@ -197,9 +214,12 @@ class TestAuthHeaders(TestCallMCPServerTool):await tool._arun_impl(server_url="https://mcp.example.com", tool_name="__list_tools__")_, kwargs = MockClient.call_args- self.assertEqual(kwargs["headers"], {"Authorization": "Bearer my-api-key"})+ self.assertEqual(+ kwargs["headers"],+ {"Authorization": "Bearer my-api-key", "x-posthog-mcp-mode": "tools", "x-posthog-mcp-store": "true"},+ )- async def test_no_auth_sends_no_headers(self):+ async def test_no_auth_sends_only_store_headers(self):inst = {"id": str(uuid.uuid4()),"display_name": "Server",@@ -216,7 +236,7 @@ class TestAuthHeaders(TestCallMCPServerTool):await tool._arun_impl(server_url="https://mcp.example.com", tool_name="__list_tools__")_, kwargs = MockClient.call_args- self.assertIsNone(kwargs["headers"])+ self.assertEqual(kwargs["headers"], {"x-posthog-mcp-mode": "tools", "x-posthog-mcp-store": "true"})class TestSSRFPrevention(TestCallMCPServerTool):@@ -276,7 +296,12 @@ class TestListTools(TestCallMCPServerTool):class TestCallTool(TestCallMCPServerTool):async def test_call_tool_returns_result(self):- tool = self._create_tool(installations=[{"display_name": "Linear", "url": "https://mcp.linear.app"}])+ installation = await sync_to_async(self._install_server)(+ url="https://mcp.linear.app", tool_names=("create_issue",)+ )+ tool = self._create_tool(+ installations=[{"id": str(installation.id), "display_name": "Linear", "url": installation.url}]+ )with patch("ee.hogai.tools.call_mcp_server.tool.MCPClient") as MockClient:mock_instance = self._make_mock_client()mock_instance.call_tool = AsyncMock(return_value="Issue LIN-123 created successfully")@@ -644,6 +669,8 @@ class TestAuthRefresh(TestCallMCPServerTool):async def test_error_on_authed_server_triggers_refresh_and_retry(self):inst = _make_oauth_installation(server_url=self.SERVER_URL)+ installation = await sync_to_async(self._install_server)(url=self.SERVER_URL, tool_names=("some_tool",))+ inst["id"] = str(installation.id)tool = self._create_tool(installations=[inst])tool._refresh_token_for_server = AsyncMock()@@ -977,6 +1004,26 @@ class TestToolApprovalEnforcement(TestCallMCPServerTool):self.assertIn("disabled by the user", str(ctx.exception))+ @parameterized.expand([("personal", False), ("gateway", True)])+ @patch("products.mcp_store.backend.facade.api.resync_installation_tools", return_value=False)+ async def test_unlisted_call_is_refused(self, _name: str, gateway: bool, _resync) -> None:+ installation = await sync_to_async(self._seed_installation_and_tools)({"create_issue": "approved"})+ inst = self._make_inst_dict(installation)+ if gateway:+ server = await sync_to_async(+ lambda: MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team, name="Example", url=self.SERVER_URL+ )+ )()+ inst["gateway_server_id"] = server.id+ tool = self._create_tool(installations=[inst])+ with patch("ee.hogai.tools.call_mcp_server.tool.MCPClient") as MockClient:+ client = self._make_mock_client()+ MockClient.return_value = client+ with self.assertRaises(MaxToolFatalError):+ await tool._arun_impl(server_url=self.SERVER_URL, tool_name="create_alias", arguments={})+ client.call_tool.assert_not_called()+async def test_call_tool_with_approved_state_passes_through(self):installation = await sync_to_async(self._seed_installation_and_tools)({"create_issue": "approved"})tool = self._create_tool(installations=[self._make_inst_dict(installation)])@@ -1058,10 +1105,11 @@ class TestIsDangerousOperation(TestCallMCPServerTool):tool = self._create_tool(installations=[self._inst_dict(installation)])self.assertFalse(await tool.is_dangerous_operation(server_url=self.SERVER_URL, tool_name="create_issue"))- async def test_unknown_tool_defaults_to_needs_approval(self):+ @patch("products.mcp_store.backend.facade.api.resync_installation_tools", return_value=False)+ async def test_unknown_tool_does_not_offer_member_approval(self, _resync):installation = await sync_to_async(self._seed)({})tool = self._create_tool(installations=[self._inst_dict(installation)])- self.assertTrue(await tool.is_dangerous_operation(server_url=self.SERVER_URL, tool_name="new_tool"))+ self.assertFalse(await tool.is_dangerous_operation(server_url=self.SERVER_URL, tool_name="new_tool"))@parameterized.expand([("listed_tool", True), ("unlisted_tool", False)])@patch("products.mcp_store.backend.facade.api.resync_installation_tools", return_value=False)diff --git a/ee/hogai/tools/call_mcp_server/tool.py b/ee/hogai/tools/call_mcp_server/tool.pyindex 58037e2d68ba..d147aeccdaa3 100644--- a/ee/hogai/tools/call_mcp_server/tool.py+++ b/ee/hogai/tools/call_mcp_server/tool.py@@ -153,9 +153,6 @@ class CallMCPServerTool(MaxTool):return states[tool_name]inst = self._get_installation(server_url)gateway_server_id = inst.get("gateway_server_id")- if gateway_server_id is None:- return _APPROVAL_DEFAULT- # An org rule can match a tool the installation has no row for yet.state = await database_sync_to_async(_get_unlisted_tool_state)(str(inst["id"]), self._team.id, gateway_server_id, self._user, tool_name)@@ -353,7 +350,7 @@ class CallMCPServerTool(MaxTool):inst["sensitive_configuration"] = updatedself._installations_by_url[server_url] = inst- self._server_headers[server_url] = {"Authorization": f"Bearer {updated['access_token']}"}+ self._server_headers.setdefault(server_url, {}).update({"Authorization": f"Bearer {updated['access_token']}"})def _get_installation(self, server_url: str) -> dict:inst = self._installations_by_url.get(server_url)diff --git a/products/mcp_store/README.md b/products/mcp_store/README.mdindex 619e8cc32a0a..0b5ebfcbaa44 100644--- a/products/mcp_store/README.md+++ b/products/mcp_store/README.md@@ -3,6 +3,10 @@A curated marketplace of third-party MCP servers (Linear, Notion, Sentry, ...) that users browse and connect from Settings → MCP servers (behind the `mcp-gateway` feature flag).Connected servers are consumed by agent surfaces via the `backend/facade/` package.+Store connections to PostHog MCP use individual tools so each call receives its own policy check. They cannot invoke the `exec` wrapper or expand nested connections. Direct PostHog MCP clients retain CLI mode and access to their own connected tools.++Tool names missing from the cached registry are re-listed before use and refused if the server still does not advertise them. OAuth responses are limited to 1 MiB. Buffered MCP handshakes and calls allow 8 MiB for full tool schemas and results. Both paths enforce a total response deadline. Upstream servers must honor `Accept-Encoding: identity`.+This is unrelated to `products/*/mcp/tools.yaml`, which exposes PostHog's own endpoints as MCP tools.## Keep the desktop UI in syncdiff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.pyindex fad945305146..a817c0f75171 100644--- a/products/mcp_store/backend/facade/api.py+++ b/products/mcp_store/backend/facade/api.py@@ -41,12 +41,7 @@ from products.mcp_store.backend.models import (MCPServiceAccount,MCPServiceAccountServerAccess,)-from products.mcp_store.backend.policy import (- GatewayCaller,- PolicyContext,- is_policy_state_allowed,- is_read_only_connector_tool,-)+from products.mcp_store.backend.policy import GatewayCaller, PolicyContext, is_read_only_connector_toolfrom products.mcp_store.backend.proxy import record_tool_call_audit, resolve_call_decision, validate_installation_authfrom products.mcp_store.backend.tools import (ToolCallError,@@ -78,9 +73,8 @@ def resolve_member_tool_states(unregistered installations fall back to the cached per-tool approval state.Rows with `removed_at` set surface as `"do_not_use"` so the agent can'tcall them even if the cached approval state was previously `approved` —- if the tool is gone upstream, it's gone. Anything not in the map is- treated as `needs_approval` by the caller (explicit opt-in for freshly- discovered tools).+ if the tool is gone upstream, it's gone. Callers resolve missing names+ through `resolve_member_unlisted_tool_state` before execution.With `block_locked_approvals`, a `needs_approval` state that an org rulelocks surfaces as `"do_not_use"`. Use it for callers that approve calls@@ -113,31 +107,24 @@ def resolve_member_tool_states(def resolve_member_unlisted_tool_state(installation_id: str,team_id: int,- gateway_server_id: uuid.UUID,+ gateway_server_id: uuid.UUID | None,user_id: int,tool_name: str,) -> str:- """Return the effective state of a tool the installation has no row for.-- The installation re-lists its tools once, so a tool the upstream server- added later resolves with its real annotations. Without a row the- annotations are unknown, so the tool resolves as if it were destructive.- The result is never looser than `needs_approval`, the default for- unknown tools."""+ """Re-list an unknown tool and refuse it unless the server advertises it."""installation = MCPServerInstallation.objects.filter(id=installation_id, team_id=team_id).first()tool = _registered_tool(installation, tool_name) if installation is not None else None+ if tool is None or tool.removed_at is not None:+ return "do_not_use"+ if gateway_server_id is None:+ return "do_not_use" if tool.approval_state == "do_not_use" else "needs_approval"context = PolicyContext(team_id=team_id,caller=GatewayCaller(kind="member", user_id=user_id),gateway_server_id=gateway_server_id,legacy_rows={},)- if tool is not None and tool.removed_at is None:- state = _member_tool_state(context, tool_name, tool.annotations, block_locked_approvals=True)- else:- as_listed = _member_tool_state(context, tool_name, None, block_locked_approvals=True)- as_destructive = _member_tool_state(context, tool_name, {"destructiveHint": True}, block_locked_approvals=True)- state = as_destructive if is_policy_state_allowed(as_destructive, as_listed) else as_listed+ state = _member_tool_state(context, tool_name, tool.annotations, block_locked_approvals=True)return state if state == "do_not_use" else "needs_approval"diff --git a/products/mcp_store/backend/oauth.py b/products/mcp_store/backend/oauth.pyindex 8f35c1ec0212..1a720626fc1f 100644--- a/products/mcp_store/backend/oauth.py+++ b/products/mcp_store/backend/oauth.py@@ -9,12 +9,14 @@ from urllib.parse import urlparsefrom django.db import transaction-import requests+import httpximport structlogimport tldextractfrom posthog.dataclasses import frozenfrom posthog.egress.slack.observability import record_slack_api_response, slack_endpoint_from_url+from posthog.security.pinned_httpx import pinned_client+from posthog.security.pinned_requests import SSRFBlockedErrorfrom posthog.security.url_validation import is_url_allowedfrom .models import MCPServerInstallation, MCPServerTemplate, TemplateOAuthCredentials@@ -24,10 +26,12 @@ from .oauth_credentials import (resolve_oauth_credentials_source,validate_oauth_credentials_source_metadata,)+from .url_policy import resolve_mcp_url_policylogger = structlog.get_logger(__name__)TIMEOUT = 10+MAX_OAUTH_RESPONSE_BYTES = 1024 * 1024SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS = ("none", "client_secret_post", "client_secret_basic")DEFAULT_CONFIDENTIAL_TOKEN_ENDPOINT_AUTH_METHOD = "client_secret_basic"# Shared template clients are set up for client_secret_post. Some providers, such as HubSpot, reject HTTP Basic.@@ -35,10 +39,6 @@ SHARED_TEMPLATE_DEFAULT_TOKEN_ENDPOINT_AUTH_METHOD = "client_secret_post"TOKEN_REFRESH_REJECTION_ERRORS = frozenset({"invalid_client", "invalid_grant"})-class SSRFBlockedError(Exception):- pass--class OAuthTokenExchangeError(Exception):pass@@ -68,6 +68,21 @@ def _validate_url(url: str) -> None:raise SSRFBlockedError(f"URL blocked by SSRF protection: {reason} ({url})")+def _oauth_client(url: str) -> httpx.Client:+ verdict = resolve_mcp_url_policy(url, None)+ if not verdict.allowed:+ raise SSRFBlockedError(f"URL blocked by SSRF protection: {verdict.reason}")+ return pinned_client(+ url,+ verdict.pinned_ips,+ timeout=TIMEOUT,+ total_timeout=TIMEOUT,+ max_response_bytes=MAX_OAUTH_RESPONSE_BYTES,+ follow_redirects=True,+ max_redirects=3,+ )++def _canonical_origin(url: str) -> str | None:try:parsed = urlparse(url)@@ -201,9 +216,12 @@ def _fetch_auth_server_metadata(auth_server_url: str) -> dict:last_exc: Exception = RuntimeError("no discovery candidates were attempted")for metadata_url in candidates:_validate_url(metadata_url)- metadata_resp = requests.get(metadata_url, timeout=TIMEOUT)+ with _oauth_client(metadata_url) as client:+ metadata_resp = client.get(metadata_url, timeout=TIMEOUT)if metadata_resp.status_code in FALLBACK_STATUSES:- last_exc = requests.HTTPError(response=metadata_resp)+ last_exc = httpx.HTTPStatusError(+ "Metadata endpoint unavailable", request=metadata_resp.request, response=metadata_resp+ )continuemetadata_resp.raise_for_status()metadata = metadata_resp.json()@@ -334,13 +352,15 @@ def discover_oauth_metadata(server_url: str) -> dict:# Step 1: Try RFC 9728 Protected Resource Metadata to find the authorization serverresource_url = f"{origin}/.well-known/oauth-protected-resource{path}"_validate_url(resource_url)- resource_resp = requests.get(resource_url, timeout=TIMEOUT)+ with _oauth_client(resource_url) as client:+ resource_resp = client.get(resource_url, timeout=TIMEOUT)if resource_resp.status_code == 404 and path:fallback_url = f"{origin}/.well-known/oauth-protected-resource"_validate_url(fallback_url)- resource_resp = requests.get(fallback_url, timeout=TIMEOUT)+ with _oauth_client(fallback_url) as client:+ resource_resp = client.get(fallback_url, timeout=TIMEOUT)- if resource_resp.ok:+ if resource_resp.is_success:resource_data = resource_resp.json()bound_resource = Noneif "resource" in resource_data:@@ -378,7 +398,7 @@ class DcrClientRegistration:token_endpoint_auth_method: str-def _describe_dcr_rejection(resp: requests.Response) -> str:+def _describe_dcr_rejection(resp: httpx.Response) -> str:"""Build a short, user-safe message from an RFC 7591 error response."""try:body = resp.json()@@ -424,10 +444,11 @@ def register_dcr_client(payload["scope"] = " ".join(scopes)_validate_url(registration_endpoint)- resp = requests.post(registration_endpoint, json=payload, timeout=TIMEOUT, allow_redirects=False)+ with _oauth_client(registration_endpoint) as client:+ resp = client.post(registration_endpoint, json=payload, timeout=TIMEOUT, follow_redirects=False)if 300 <= resp.status_code < 400:raise ValueError("Dynamic Client Registration endpoint redirected")- if not resp.ok:+ if not resp.is_success:logger.error("DCR registration request rejected",status=resp.status_code,@@ -622,7 +643,7 @@ def _token_request_auth(return form, None-def _oauth_error_code(response: requests.Response | None) -> str | None:+def _oauth_error_code(response: httpx.Response | None) -> str | None:if response is None:return None@@ -668,7 +689,10 @@ def refresh_oauth_token(try:_validate_url(token_url)- resp = requests.post(token_url, data=data, auth=auth, timeout=TIMEOUT, allow_redirects=False)+ with _oauth_client(token_url) as client:+ resp = client.post(+ token_url, data=data, auth=auth or httpx.USE_CLIENT_DEFAULT, timeout=TIMEOUT, follow_redirects=False+ )if oauth_credentials_source in SUPPORTED_OAUTH_CREDENTIAL_SOURCES:record_slack_api_response(resp,@@ -683,9 +707,9 @@ def refresh_oauth_token(resp.raise_for_status()except SSRFBlockedError:raise TokenRefreshError(f"Token refresh URL blocked by SSRF protection: {token_url}")- except requests.RequestException as exc:- failed_status_code = getattr(exc.response, "status_code", None)- oauth_error_code = _oauth_error_code(exc.response)+ except httpx.HTTPError as exc:+ failed_status_code = getattr(getattr(exc, "response", None), "status_code", None)+ oauth_error_code = _oauth_error_code(getattr(exc, "response", None))logger.warning("OAuth token refresh request failed",token_url=token_url,@@ -840,7 +864,10 @@ def exchange_oauth_token(except ValueError as exc:raise OAuthTokenExchangeError(str(exc))- token_response = requests.post(token_endpoint, data=form, auth=auth, timeout=TIMEOUT, allow_redirects=False)+ with _oauth_client(token_endpoint) as client:+ token_response = client.post(+ token_endpoint, data=form, auth=auth or httpx.USE_CLIENT_DEFAULT, timeout=TIMEOUT, follow_redirects=False+ )oauth_credentials_source = installation.template.oauth_credentials_source if installation.template else ""if oauth_credentials_source in SUPPORTED_OAUTH_CREDENTIAL_SOURCES:record_slack_api_response(@@ -855,7 +882,7 @@ def exchange_oauth_token(# RFC 6749 specifies 200, but some providers (e.g. Supabase) return 201.if 300 <= token_response.status_code < 400:raise OAuthTokenExchangeError("Token endpoint redirected")- if not token_response.ok:+ if not token_response.is_success:logger.error("OAuth token exchange failed",status_code=token_response.status_code,diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.pyindex 336a5c969aa9..d3db7a825a17 100644--- a/products/mcp_store/backend/proxy.py+++ b/products/mcp_store/backend/proxy.py@@ -592,17 +592,17 @@ def proxy_mcp_request(**auth_headers,}- # Forward the full `x-posthog-*` namespace so the upstream server can- # identify the consumer, mode, and version that the caller declared, plus- # any custom PostHog-namespace headers the caller wants to pass through.- # Without this, the PostHog MCP cannot resolve single-exec mode for- # posthog-code-installed PostHog MCPs (the consumer header never reaches- # the resolver) and the `exec` tool comes back as "Tool exec not found".- # Non-PostHog upstreams ignore unknown headers in that namespace.for header_name in request.headers:- if header_name.lower().startswith("x-posthog-"):+ if header_name.lower().startswith("x-posthog-") and header_name.lower() not in {+ "x-posthog-mcp-mode",+ "x-posthog-mcp-store",+ }:headers[header_name] = request.headers[header_name]+ # Store policy must see leaf tools, and shared credentials must not expand nested connectors.+ headers["x-posthog-mcp-mode"] = "tools"+ headers["x-posthog-mcp-store"] = "true"+mcp_session_id = request.headers.get("mcp-session-id")if mcp_session_id:headers["Mcp-Session-Id"] = mcp_session_iddiff --git a/products/mcp_store/backend/test/conftest.py b/products/mcp_store/backend/test/conftest.pynew file mode 100644index 000000000000..67f40d1e09ac--- /dev/null+++ b/products/mcp_store/backend/test/conftest.py@@ -0,0 +1,15 @@+from collections.abc import Iterator++import pytest+from unittest.mock import patch++from posthog.security.url_validation import PinnedUrlVerdict+++def pin_oauth_urls() -> Iterator[None]:+ with patch(+ "products.mcp_store.backend.oauth.resolve_mcp_url_policy",+ return_value=PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set()),+ ):+ yielddiff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.pyindex 18eb922e2e00..41cf97d027dc 100644--- a/products/mcp_store/backend/test/test_api.py+++ b/products/mcp_store/backend/test/test_api.py@@ -2,6 +2,7 @@ import hashlibfrom datetime import UTC, datetime, timedeltafrom urllib.parse import parse_qs, urlparse, urlsplit+import pytestimport time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTestfrom unittest.mock import MagicMock, patch@@ -71,6 +72,9 @@ POLICY_REQUEST_SERIALIZER_CASES = []+pytestmark = pytest.mark.usefixtures("pin_oauth_urls")++class TestIsValidPosthogCodeCallbackUrl(SimpleTestCase):@parameterized.expand([@@ -3158,7 +3162,7 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):)@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_dcr_path_used_when_pkce_verifier_present(self, mock_post, _allow):installation = self._create_installation()@@ -3179,7 +3183,7 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert mock_post.call_args[1]["data"]["code_verifier"] == "test-pkce-verifier"@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_oauth_redirect_uses_posthog_code_callback_url(self, mock_post, _allow):installation = self._create_installation()@@ -3207,7 +3211,7 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert "status=success" in location@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_oauth_redirect_posthog_code_error_includes_error_param(self, mock_post, _allow):installation = self._create_installation()@@ -3253,7 +3257,7 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):@patch("products.mcp_store.backend.presentation.views.is_dev_mode", return_value=True)@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_callback_rejects_anonymous_posthog_consumer_in_dev(self, mock_post, _allow, _is_dev):mock_post.return_value.status_code = 200mock_post.return_value.json.return_value = {"access_token": "tok", "token_type": "bearer"}@@ -3277,7 +3281,7 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):@patch("products.mcp_store.backend.presentation.views.is_dev_mode", return_value=True)@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_callback_accepts_anonymous_consumer_in_dev(self, mock_post, _allow, _is_dev):mock_post.return_value.status_code = 200mock_post.return_value.json.return_value = {"access_token": "tok", "token_type": "bearer"}@@ -3359,7 +3363,7 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert response.status_code == status.HTTP_400_BAD_REQUEST@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_callback_happy_path_same_user(self, mock_post, _allow):"""Positive control: callback authenticated as the same user -> success."""mock_post.return_value.status_code = 200@@ -3378,7 +3382,7 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert installation.sensitive_configuration["access_token"] == "tok"@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_callback_happy_path_cross_client_same_user(self, mock_post, _allow):"""posthog-code scenario: initiate and callback happen in different HTTP clients.@@ -3405,7 +3409,7 @@ class TestOAuthCallback(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert installation.sensitive_configuration["access_token"] == "tok"@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_consumed_state_rejects_replay(self, mock_post, _allow):mock_post.return_value.status_code = 200mock_post.return_value.json.return_value = {"access_token": "tok", "token_type": "bearer"}@@ -3559,7 +3563,7 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryM@ALLOW_URL@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_discovery_reports_the_failed_metadata_check(self, mock_get, _allow_oauth, _allow):metadata = {"issuer": "https://evil.com",@@ -3590,7 +3594,7 @@ class TestOAuthIssuerSpoofingProtection(ClickhouseTestMixin, APIBaseTest, QueryM@ALLOW_URL@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")@patch("products.mcp_store.backend.presentation.views.discover_oauth_metadata")def test_google_install_gets_a_refresh_token_that_survives_the_refresh_threshold(self, mock_discover, mock_post, _allow_oauth, _allow@@ -4729,7 +4733,7 @@ class TestInstallDispatchesToolSync(ClickhouseTestMixin, APIBaseTest, QueryMatch@patch("products.mcp_store.backend.presentation.views.sync_installation_tools_task")@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_oauth_redirect_dispatches_background_sync(self, mock_post, _allow, mock_task):installation = MCPServerInstallation.objects.create(team=self.team,diff --git a/products/mcp_store/backend/test/test_oauth.py b/products/mcp_store/backend/test/test_oauth.pyindex 6bd14a39001c..3e05e1994d1e 100644--- a/products/mcp_store/backend/test/test_oauth.py+++ b/products/mcp_store/backend/test/test_oauth.py@@ -1,11 +1,12 @@from urllib.parse import urlparse+import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase-import requests+import httpxfrom parameterized import parameterizedfrom posthog.models.instance_setting import override_instance_config@@ -30,6 +31,8 @@ from products.mcp_store.backend.oauth import (select_token_endpoint_auth_method,)+pytestmark = pytest.mark.usefixtures("pin_oauth_urls")+class TestRefreshOauthToken(SimpleTestCase):@parameterized.expand(@@ -54,7 +57,7 @@ class TestRefreshOauthToken(SimpleTestCase):with (patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None)),- patch("products.mcp_store.backend.oauth.requests.post", return_value=mock_resp) as mock_post,+ patch("products.mcp_store.backend.oauth.httpx.Client.post", return_value=mock_resp) as mock_post,):result = refresh_oauth_token(token_url="https://example.com/token",@@ -73,11 +76,11 @@ class TestRefreshOauthToken(SimpleTestCase):else:self.assertEqual(call_data["client_id"], "my-client")self.assertNotIn("client_secret", call_data)- self.assertEqual(call_kwargs["auth"], expected_auth)+ self.assertEqual(call_kwargs["auth"], expected_auth or httpx.USE_CLIENT_DEFAULT)self.assertEqual(result["access_token"], "new-token")@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_refresh_sends_resource_and_disables_redirects(self, mock_post, _allow):mock_resp = MagicMock()mock_resp.status_code = 200@@ -93,7 +96,7 @@ class TestRefreshOauthToken(SimpleTestCase):)call_kwargs = mock_post.call_args.kwargs- assert call_kwargs["allow_redirects"] is False+ assert call_kwargs["follow_redirects"] is Falseassert call_kwargs["data"]["resource"] == "https://mcp.example.com/"@parameterized.expand(@@ -113,9 +116,11 @@ class TestRefreshOauthToken(SimpleTestCase):mock_resp = MagicMock()mock_resp.status_code = status_codemock_resp.json.return_value = response_data- mock_resp.raise_for_status.side_effect = requests.HTTPError(str(status_code), response=mock_resp)+ mock_resp.raise_for_status.side_effect = httpx.HTTPStatusError(+ str(status_code), request=httpx.Request("POST", "https://example.com"), response=mock_resp+ )- with patch("products.mcp_store.backend.oauth.requests.post", return_value=mock_resp):+ with patch("products.mcp_store.backend.oauth.httpx.Client.post", return_value=mock_resp):with self.assertRaises(TokenRefreshError) as ctx:refresh_oauth_token(token_url="https://example.com/token",@@ -131,7 +136,7 @@ class TestRefreshOauthToken(SimpleTestCase):mock_resp.json.return_value = {"error": "invalid_grant"}mock_resp.raise_for_status = MagicMock()- with patch("products.mcp_store.backend.oauth.requests.post", return_value=mock_resp):+ with patch("products.mcp_store.backend.oauth.httpx.Client.post", return_value=mock_resp):with self.assertRaises(TokenRefreshError) as ctx:refresh_oauth_token(token_url="https://example.com/token",@@ -154,12 +159,14 @@ class TestRefreshOauthToken(SimpleTestCase):class TestIssuerValidation(SimpleTestCase):def _make_response(self, *, ok=True, status_code=200, json_data=None):resp = MagicMock()- resp.ok = ok+ resp.is_success = okresp.status_code = status_coderesp.json.return_value = json_data or {}resp.raise_for_status = MagicMock()if status_code >= 400:- resp.raise_for_status.side_effect = requests.HTTPError(response=resp)+ resp.raise_for_status.side_effect = httpx.HTTPStatusError(+ "Upstream error", request=httpx.Request("GET", "https://example.com"), response=resp+ )return respdef _origin(self, url: str) -> str:@@ -265,7 +272,7 @@ class TestIssuerValidation(SimpleTestCase):])@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_step2_fallback_issuer_validation(self, _name, auth_metadata, server_url, should_raise, cross_val_metadata, mock_get, _allow):@@ -386,7 +393,7 @@ class TestIssuerValidation(SimpleTestCase):])@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_step1_protected_resource_issuer_validation(self, _name, auth_server_url, auth_metadata, should_raise, cross_val_metadata, mock_get, _allow):@@ -427,7 +434,7 @@ class TestIssuerValidation(SimpleTestCase):assert mock_get.call_args_list[index].kwargs["timeout"] == TIMEOUT@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_step1_preserves_same_origin_resource(self, mock_get, _allow):auth_server_url = "https://auth.example.com"resource_resp = self._make_response(@@ -451,7 +458,7 @@ class TestIssuerValidation(SimpleTestCase):assert mock_get.call_count == 2@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_step1_rejects_resource_on_unrelated_origin(self, mock_get, _allow):resource_resp = self._make_response(json_data={@@ -489,7 +496,7 @@ class TestIssuerValidation(SimpleTestCase):])@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_rejects_metadata_with_endpoints_off_issuer_origin(self, _name, auth_metadata, mock_get, _allow):"""A malicious MCP server cannot mix a legitimate issuer with an attacker-controlled endpoint.@@ -531,7 +538,7 @@ class TestRegisterDCRClient(SimpleTestCase):def test_omitted_supported_methods_default_to_basic_for_confidential_clients(self):assert select_token_endpoint_auth_method({}, has_client_secret=True) == "client_secret_basic"- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_rejects_dcr_when_provider_only_lists_unsupported_auth_methods(self, mock_post):with self.assertRaisesMessage(ValueError, "private_key_jwt"):register_dcr_client(@@ -588,12 +595,12 @@ class TestRegisterDCRClient(SimpleTestCase):])@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, ""))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_returns_client_secret_only_when_server_requires_it(self, _name, response_body, expected, mock_post, _allow):mock_response = MagicMock()- mock_response.ok = True+ mock_response.is_success = Truemock_response.status_code = 201mock_response.json.return_value = response_bodymock_post.return_value = mock_response@@ -606,10 +613,10 @@ class TestRegisterDCRClient(SimpleTestCase):assert result == expected@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, ""))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_registers_refresh_grant_without_refresh_scope(self, mock_post, _allow):mock_response = MagicMock()- mock_response.ok = True+ mock_response.is_success = Truemock_response.status_code = 201mock_response.json.return_value = {"client_id": "abc",@@ -637,13 +644,13 @@ class TestRegisterDCRClient(SimpleTestCase):assert payload["token_endpoint_auth_method"] == "client_secret_post"assert payload["scope"] == "read"assert "refresh_token" not in payload["scope"]- assert mock_post.call_args.kwargs["allow_redirects"] is False+ assert mock_post.call_args.kwargs["follow_redirects"] is False@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, ""))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_keeps_requested_basic_auth_when_dcr_response_omits_auth_method(self, mock_post, _allow):mock_response = MagicMock()- mock_response.ok = True+ mock_response.is_success = Truemock_response.status_code = 201mock_response.json.return_value = {"client_id": "abc",@@ -665,10 +672,10 @@ class TestRegisterDCRClient(SimpleTestCase):assert mock_post.call_args.kwargs["json"]["token_endpoint_auth_method"] == "client_secret_basic"@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, ""))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_client_name_has_no_parentheses(self, mock_post, _allow):mock_response = MagicMock()- mock_response.ok = True+ mock_response.is_success = Truemock_response.status_code = 201mock_response.json.return_value = {"client_id": "abc", "token_endpoint_auth_method": "none"}mock_post.return_value = mock_response@@ -682,10 +689,10 @@ class TestRegisterDCRClient(SimpleTestCase):assert "(" not in client_name and ")" not in client_name@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, ""))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_surfaces_provider_rejection_message(self, mock_post, _allow):mock_response = MagicMock()- mock_response.ok = False+ mock_response.is_success = Falsemock_response.status_code = 400mock_response.json.return_value = {"error": "invalid_client_metadata",@@ -909,7 +916,7 @@ class TestSourceBackedOauthMetadataBinding(BaseTest):)@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_exchange_rejects_modified_token_endpoint_before_sending_secret(self, mock_post, _allow):installation = self._installation()@@ -931,11 +938,11 @@ class TestSourceBackedOauthMetadataBinding(BaseTest):@parameterized.expand(["exchange", "refresh"])@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))@patch("products.mcp_store.backend.oauth.record_slack_api_response")- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_slack_dev_token_requests_are_recorded(self, operation, mock_post, record_response, _allow):response = MagicMock()response.status_code = 200- response.ok = True+ response.is_success = Trueresponse.headers = {}response.json.return_value = {"access_token": "access-token", "refresh_token": "refresh-token"}mock_post.return_value = response@@ -970,7 +977,7 @@ class TestSourceBackedOauthMetadataBinding(BaseTest):)@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_refresh_rejects_modified_token_endpoint_before_sending_secret(self, mock_post, _allow):installation = self._installation()@@ -996,11 +1003,11 @@ class TestExchangeOauthToken(BaseTest):)@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_confidential_custom_install_defaults_to_http_basic(self, mock_post, _allow):mock_resp = MagicMock()mock_resp.status_code = 200- mock_resp.ok = True+ mock_resp.is_success = Truemock_resp.json.return_value = {"access_token": "abc", "refresh_token": "def"}mock_post.return_value = mock_resp@@ -1026,14 +1033,14 @@ class TestExchangeOauthToken(BaseTest):assert sent_form["grant_type"] == "authorization_code"assert sent_form["code_verifier"] == "pkce-verifier"assert mock_post.call_args.kwargs["auth"] == ("confidential-client", "confidential-secret")- assert mock_post.call_args.kwargs["allow_redirects"] is False+ assert mock_post.call_args.kwargs["follow_redirects"] is False@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_client_secret_post_custom_install_sends_secret_in_form(self, mock_post, _allow):mock_resp = MagicMock()mock_resp.status_code = 200- mock_resp.ok = True+ mock_resp.is_success = Truemock_resp.json.return_value = {"access_token": "abc", "refresh_token": "def"}mock_post.return_value = mock_resp@@ -1059,10 +1066,10 @@ class TestExchangeOauthToken(BaseTest):assert sent_form["client_secret"] == "confidential-secret"assert sent_form["grant_type"] == "authorization_code"assert sent_form["code_verifier"] == "pkce-verifier"- assert mock_post.call_args.kwargs["auth"] is None+ assert mock_post.call_args.kwargs["auth"] is httpx.USE_CLIENT_DEFAULT@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_public_custom_install_omits_client_secret(self, mock_post, _allow):mock_resp = MagicMock()mock_resp.status_code = 200@@ -1085,11 +1092,11 @@ class TestExchangeOauthToken(BaseTest):assert "client_secret" not in sent_form@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_client_secret_basic_custom_install_uses_http_basic(self, mock_post, _allow):mock_resp = MagicMock()mock_resp.status_code = 200- mock_resp.ok = True+ mock_resp.is_success = Truemock_resp.json.return_value = {"access_token": "abc"}mock_post.return_value = mock_resp@@ -1115,11 +1122,11 @@ class TestExchangeOauthToken(BaseTest):assert mock_post.call_args.kwargs["auth"] == ("basic-client", "basic-secret")@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_token_exchange_includes_resource_indicator(self, mock_post, _allow):mock_resp = MagicMock()mock_resp.status_code = 200- mock_resp.ok = True+ mock_resp.is_success = Truemock_resp.json.return_value = {"access_token": "abc"}mock_post.return_value = mock_resp@@ -1168,12 +1175,12 @@ class TestExchangeOauthToken(BaseTest):])@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.post")+ @patch("products.mcp_store.backend.oauth.httpx.Client.post")def test_accepts_any_2xx_status(self, _name, status_code, ok, should_raise, mock_post, _allow):"""Some providers (e.g. Supabase) return 201 on token issue — we must accept it."""mock_resp = MagicMock()mock_resp.status_code = status_code- mock_resp.ok = ok+ mock_resp.is_success = okmock_resp.json.return_value = {"access_token": "abc", "refresh_token": "def"}mock_resp.text = "{}"mock_post.return_value = mock_resp@@ -1236,7 +1243,9 @@ class TestRefreshInstallationToken(BaseTest):response = MagicMock()response.status_code = status_coderesponse.json.return_value = response_data or {}- response.raise_for_status.side_effect = requests.HTTPError(str(status_code), response=response)+ response.raise_for_status.side_effect = httpx.HTTPStatusError(+ str(status_code), request=httpx.Request("POST", "https://example.com"), response=response+ )return response@staticmethod@@ -1251,7 +1260,7 @@ class TestRefreshInstallationToken(BaseTest):installation = self._make_installation()with patch(- "products.mcp_store.backend.oauth.requests.post",+ "products.mcp_store.backend.oauth.httpx.Client.post",return_value=self._post_answering(status_code, {"error": oauth_error}),):with self.assertRaises(TokenRefreshRejectedError):@@ -1298,7 +1307,7 @@ class TestRefreshInstallationToken(BaseTest):installation = self._make_installation()with patch(- "products.mcp_store.backend.oauth.requests.post",+ "products.mcp_store.backend.oauth.httpx.Client.post",return_value=self._post_answering(status_code, response_data),):with self.assertRaises(TokenRefreshError) as ctx:@@ -1310,14 +1319,14 @@ class TestRefreshInstallationToken(BaseTest):@parameterized.expand([- ("connection_error", requests.ConnectionError("connection reset")),- ("timeout", requests.Timeout("timed out")),+ ("connection_error", httpx.ConnectError("connection reset")),+ ("timeout", httpx.ReadTimeout("timed out")),])def test_network_failure_leaves_the_connection_alone(self, _name: str, error: Exception) -> None:installation = self._make_installation()- with patch("products.mcp_store.backend.oauth.requests.post", return_value=self._post_failing(error)):+ with patch("products.mcp_store.backend.oauth.httpx.Client.post", return_value=self._post_failing(error)):with self.assertRaises(TokenRefreshError) as ctx:refresh_installation_token(installation)@@ -1344,7 +1353,7 @@ class TestRefreshInstallationToken(BaseTest):response.raise_for_status = MagicMock()response.json.return_value = {"access_token": "fresh", "expires_in": 3600}- with patch("products.mcp_store.backend.oauth.requests.post", return_value=response):+ with patch("products.mcp_store.backend.oauth.httpx.Client.post", return_value=response):refresh_installation_token(installation)installation.refresh_from_db()diff --git a/products/mcp_store/backend/test/test_oauth_unit.py b/products/mcp_store/backend/test/test_oauth_unit.pyindex 2a2c189cfa3b..365738158901 100644--- a/products/mcp_store/backend/test/test_oauth_unit.py+++ b/products/mcp_store/backend/test/test_oauth_unit.py@@ -1,8 +1,9 @@+import pytestfrom unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase-import requests+import httpxfrom parameterized import parameterizedfrom products.mcp_store.backend.oauth import (@@ -14,6 +15,8 @@ from products.mcp_store.backend.oauth import (register_dcr_client,)+pytestmark = pytest.mark.usefixtures("pin_oauth_urls")+class TestResolveIssuer(SimpleTestCase):@parameterized.expand(@@ -49,7 +52,7 @@ class TestResolveIssuer(SimpleTestCase):self.assertEqual(result, expected_result)@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_mismatched_issuer_triggers_cross_validation(self, mock_get, _allow):cross_validated = {"issuer": "https://real-auth.example.com",@@ -57,7 +60,7 @@ class TestResolveIssuer(SimpleTestCase):"token_endpoint": "https://real-auth.example.com/token",}mock_resp = MagicMock()- mock_resp.ok = True+ mock_resp.is_success = Truemock_resp.json.return_value = cross_validatedmock_resp.raise_for_status = MagicMock()mock_get.return_value = mock_resp@@ -74,10 +77,10 @@ class TestResolveIssuer(SimpleTestCase):self.assertIn("real-auth.example.com", mock_get.call_args.args[0])@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_cross_validation_mismatch_raises(self, mock_get, _allow):mock_resp = MagicMock()- mock_resp.ok = True+ mock_resp.is_success = Truemock_resp.json.return_value = {"issuer": "https://someone-else.com","authorization_endpoint": "https://someone-else.com/authorize",@@ -95,10 +98,12 @@ class TestResolveIssuer(SimpleTestCase):_resolve_issuer(metadata, "https://origin.com")@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_cross_validation_fetch_fails(self, mock_get, _allow):mock_resp = MagicMock()- mock_resp.raise_for_status.side_effect = requests.HTTPError(response=mock_resp)+ mock_resp.raise_for_status.side_effect = httpx.HTTPStatusError(+ "Upstream error", request=httpx.Request("GET", "https://example.com"), response=mock_resp+ )mock_get.return_value = mock_respmetadata = {@@ -106,7 +111,7 @@ class TestResolveIssuer(SimpleTestCase):"authorization_endpoint": "https://origin.com/authorize","token_endpoint": "https://origin.com/token",}- with self.assertRaises(requests.HTTPError):+ with self.assertRaises(httpx.HTTPStatusError):_resolve_issuer(metadata, "https://origin.com")@@ -119,12 +124,14 @@ class TestAuthServerMetadataDiscoveryChain(SimpleTestCase):def _make_response(self, *, ok=True, status_code=200, json_data=None):resp = MagicMock()- resp.ok = ok+ resp.is_success = okresp.status_code = status_coderesp.json.return_value = json_data or {}resp.raise_for_status = MagicMock()if status_code >= 400:- resp.raise_for_status.side_effect = requests.HTTPError(response=resp)+ resp.raise_for_status.side_effect = httpx.HTTPStatusError(+ "Upstream error", request=httpx.Request("GET", "https://example.com"), response=resp+ )return respdef _valid_metadata(self, issuer: str) -> dict:@@ -135,7 +142,7 @@ class TestAuthServerMetadataDiscoveryChain(SimpleTestCase):}@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_variant_1_success_makes_no_fallback_calls(self, mock_get, _allow):"""Regression guard: when variant 1 succeeds, the loop stops — no fallback URLs are tried."""mcp_url = "https://mcp.example.com"@@ -157,7 +164,7 @@ class TestAuthServerMetadataDiscoveryChain(SimpleTestCase):assert mock_get.call_args_list[index].args[0] == expected_url@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_auth_server_with_path_falls_back_to_oidc_path_insertion(self, mock_get, _allow):"""Variant 1 404s, variant 2 (OIDC path insertion) succeeds."""mcp_url = "https://mcp.example.com"@@ -181,7 +188,7 @@ class TestAuthServerMetadataDiscoveryChain(SimpleTestCase):assert mock_get.call_args_list[index].args[0] == expected_url@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_auth_server_with_path_falls_back_to_oidc_path_append(self, mock_get, _allow):"""Variants 1 and 2 404, variant 3 (OIDC path append) succeeds — the BuildBetter case."""mcp_url = "https://mcp.example.com"@@ -206,7 +213,7 @@ class TestAuthServerMetadataDiscoveryChain(SimpleTestCase):assert mock_get.call_args_list[index].args[0] == expected_url@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_auth_server_without_path_falls_back_to_oidc(self, mock_get, _allow):"""Root auth-server URL: oauth-authorization-server 404, openid-configuration 200."""mcp_url = "https://mcp.example.com"@@ -230,7 +237,7 @@ class TestAuthServerMetadataDiscoveryChain(SimpleTestCase):assert mock_get.call_args_list[index].args[0] == expected_url@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_all_discovery_candidates_fail_raises(self, mock_get, _allow):"""When every spec-mandated candidate returns 404, discovery raises and the view layer surfaces the 400."""mcp_url = "https://mcp.example.com"@@ -240,11 +247,11 @@ class TestAuthServerMetadataDiscoveryChain(SimpleTestCase):mock_get.side_effect = [resource_resp, not_found, not_found, not_found]- with self.assertRaises(requests.HTTPError):+ with self.assertRaises(httpx.HTTPStatusError):discover_oauth_metadata(mcp_url)@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_variant_1_malformed_metadata_does_not_fall_back(self, mock_get, _allow):"""A 200 with malformed metadata is a real misconfiguration — surface it instead of probing fallbacks."""mcp_url = "https://mcp.example.com"@@ -260,7 +267,7 @@ class TestAuthServerMetadataDiscoveryChain(SimpleTestCase):assert mock_get.call_count == 2@patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None))- @patch("products.mcp_store.backend.oauth.requests.get")+ @patch("products.mcp_store.backend.oauth.httpx.Client.get")def test_variant_1_server_error_does_not_fall_back(self, mock_get, _allow):"""A 500 is a transient failure, not 'endpoint not implemented' — surface it without retrying variants."""mcp_url = "https://mcp.example.com"@@ -270,7 +277,7 @@ class TestAuthServerMetadataDiscoveryChain(SimpleTestCase):mock_get.side_effect = [resource_resp, server_error]- with self.assertRaises(requests.HTTPError):+ with self.assertRaises(httpx.HTTPStatusError):discover_oauth_metadata(mcp_url)assert mock_get.call_count == 2diff --git a/products/mcp_store/backend/test/test_probe.py b/products/mcp_store/backend/test/test_probe.pyindex 121f4d192b40..11da5f4ad257 100644--- a/products/mcp_store/backend/test/test_probe.py+++ b/products/mcp_store/backend/test/test_probe.py@@ -1,6 +1,7 @@import jsonfrom urllib.parse import parse_qs, urlparse+import pytestfrom unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase@@ -69,6 +70,9 @@ def _url_router(routes):return handle+pytestmark = pytest.mark.usefixtures("pin_oauth_urls")++class TestProbeMCPServer(SimpleTestCase):def _probe(self, *, post_routes, get_routes=None, scope_allowlist=None, shared_client_id=None):post_router = _url_router(post_routes)@@ -83,8 +87,8 @@ class TestProbeMCPServer(SimpleTestCase):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,+ patch("products.mcp_store.backend.oauth.httpx.Client.post", side_effect=post_router) as post,+ patch("products.mcp_store.backend.oauth.httpx.Client.get", side_effect=get_router) as get,):result = probe_mcp_server(SERVER_URL, scope_allowlist, shared_client_id)return result, post, get, pinneddiff --git a/products/mcp_store/backend/test/test_proxy.py b/products/mcp_store/backend/test/test_proxy.pyindex 7c6e74265af0..dd66265badbb 100644--- a/products/mcp_store/backend/test/test_proxy.py+++ b/products/mcp_store/backend/test/test_proxy.py@@ -209,11 +209,6 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):@patch("products.mcp_store.backend.proxy.pinned_client")def test_proxy_forwards_posthog_namespace_headers(self, mock_client_cls):- # Required for PostHog MCP installs through the Store: without- # `x-posthog-mcp-consumer` reaching the upstream, single-exec mode- # never resolves and `exec` comes back as "Tool exec not found".- # The full `x-posthog-*` namespace forwards so callers can also pass- # custom headers through.installation = self._create_installation(sensitive_configuration={"api_key": "sk-test-key"},)@@ -230,6 +225,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):headers={"x-posthog-mcp-consumer": "posthog-code","x-posthog-mcp-mode": "cli",+ "x-posthog-mcp-store": "false","x-posthog-mcp-version": "2","x-posthog-project-id": "42","x-posthog-read-only": "true",@@ -243,7 +239,8 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# Case-insensitive lookup since Django normalizes to title case.forwarded = {k.lower(): v for k, v in kwargs["headers"].items()}assert forwarded["x-posthog-mcp-consumer"] == "posthog-code"- assert forwarded["x-posthog-mcp-mode"] == "cli"+ assert forwarded["x-posthog-mcp-mode"] == "tools"+ assert forwarded["x-posthog-mcp-store"] == "true"assert forwarded["x-posthog-mcp-version"] == "2"assert forwarded["x-posthog-project-id"] == "42"assert forwarded["x-posthog-read-only"] == "true"diff --git a/products/mcp_store/backend/test/test_tools.py b/products/mcp_store/backend/test/test_tools.pyindex c1a4b4c9d884..bbf975402e2b 100644--- a/products/mcp_store/backend/test/test_tools.py+++ b/products/mcp_store/backend/test/test_tools.py@@ -1,13 +1,15 @@import osimport jsonimport uuid+import asyncioimport ipaddress+from collections.abc import AsyncIteratorimport pytestfrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import MagicMock, patch-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom django.utils import timezoneimport httpx@@ -17,6 +19,7 @@ from posthog.redis import get_clientfrom posthog.security.url_validation import PinnedUrlVerdictfrom products.mcp_store.backend.models import MCPServerInstallation, MCPServerInstallationTool+from products.mcp_store.backend.oauth import discover_oauth_metadatafrom products.mcp_store.backend.tools import (CALL_TIMEOUT,HANDSHAKE_TIMEOUT,@@ -32,6 +35,112 @@ from products.mcp_store.backend.tools import (ALLOWED_VERDICT = PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set())+class TestBoundedUpstreamResponses(SimpleTestCase):+ def test_oauth_discovery_follows_bounded_metadata_redirects(self) -> None:+ responses = [+ httpx.Response(302, headers={"Location": "/metadata"}, stream=httpx.ByteStream(b"")),+ httpx.Response(+ 200, stream=httpx.ByteStream(json.dumps({"authorization_servers": ["https://example.com"]}).encode())+ ),+ httpx.Response(+ 200,+ stream=httpx.ByteStream(+ json.dumps(+ {+ "issuer": "https://example.com",+ "authorization_endpoint": "https://example.com/authorize",+ "token_endpoint": "https://example.com/token",+ }+ ).encode()+ ),+ ),+ ]+ with (+ patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None)),+ patch("products.mcp_store.backend.oauth.resolve_mcp_url_policy", return_value=ALLOWED_VERDICT),+ patch("httpx.AsyncHTTPTransport.handle_async_request", side_effect=responses),+ ):+ metadata = discover_oauth_metadata("https://example.com/mcp")+ self.assertEqual(metadata["issuer"], "https://example.com")+ self.assertTrue(all(response.is_closed for response in responses))++ @parameterized.expand([("discovery", True), ("handshake", False)])+ def test_response_size_is_bounded(self, _name: str, discovery: bool) -> None:+ response = httpx.Response(200, stream=httpx.ByteStream(b"x" * (9 * 1024 * 1024)))+ installation = MCPServerInstallation(team_id=1, user_id=1, url="https://example.com/mcp", auth_type="api_key")+ with (+ patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None)),+ patch("products.mcp_store.backend.oauth.resolve_mcp_url_policy", return_value=ALLOWED_VERDICT),+ patch("products.mcp_store.backend.tools.resolve_mcp_url_policy", return_value=ALLOWED_VERDICT),+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),+ patch(+ "httpx.HTTPTransport.handle_request", return_value=httpx.Response(200, content=b"x" * (9 * 1024 * 1024))+ ),+ self.assertRaisesRegex(httpx.DecodingError if discovery else ToolsFetchError, "size limit"),+ ):+ if discovery:+ discover_oauth_metadata(installation.url)+ else:+ fetch_upstream_tools(installation)+ self.assertTrue(response.is_closed)++ @parameterized.expand(+ [+ ("oversized", {}, 9 * 1024 * 1024, "size limit"),+ ("compressed", {"Content-Encoding": "gzip"}, 1, "uncompressed"),+ ]+ )+ def test_rejected_tool_results_raise_tool_call_error(+ self, _name: str, headers: dict[str, str], body_size: int, message: str+ ) -> None:+ responses = [+ httpx.Response(+ 200,+ headers={"Mcp-Session-Id": "test-session"},+ stream=httpx.ByteStream(b'{"jsonrpc":"2.0","id":1,"result":{}}'),+ ),+ httpx.Response(202, stream=httpx.ByteStream(b"")),+ httpx.Response(200, headers=headers, stream=httpx.ByteStream(b"x" * body_size)),+ httpx.Response(200, stream=httpx.ByteStream(b"")),+ ]+ installation = MCPServerInstallation(team_id=1, user_id=1, url="https://example.com/mcp", auth_type="api_key")+ with (+ patch("products.mcp_store.backend.tools.resolve_mcp_url_policy", return_value=ALLOWED_VERDICT),+ patch("httpx.AsyncHTTPTransport.handle_async_request", side_effect=responses),+ self.assertRaisesRegex(ToolCallError, message),+ ):+ call_upstream_tool(installation, "search", {})+ self.assertTrue(all(response.is_closed for response in responses))++ @parameterized.expand([("discovery", True), ("handshake", False)])+ def test_slow_response_has_a_total_deadline(self, _name: str, discovery: bool) -> None:+ clock = [0.0]++ class Body(httpx.AsyncByteStream):+ async def __aiter__(self) -> AsyncIterator[bytes]:+ for _ in range(100):+ clock[0] += 1+ await asyncio.sleep(0)+ yield b"x"++ response = httpx.Response(200, stream=Body())+ installation = MCPServerInstallation(team_id=1, user_id=1, url="https://example.com/mcp", auth_type="api_key")+ with (+ patch("products.mcp_store.backend.oauth.is_url_allowed", return_value=(True, None)),+ patch("products.mcp_store.backend.oauth.resolve_mcp_url_policy", return_value=ALLOWED_VERDICT),+ patch("products.mcp_store.backend.tools.resolve_mcp_url_policy", return_value=ALLOWED_VERDICT),+ patch("asyncio.BaseEventLoop.time", side_effect=lambda: clock[0]),+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),+ patch("httpx.HTTPTransport.handle_request", return_value=httpx.Response(200, content=b"invalid")),+ self.assertRaisesRegex(httpx.ReadTimeout if discovery else ToolsFetchError, "deadline|timed out"),+ ):+ if discovery:+ discover_oauth_metadata(installation.url)+ else:+ fetch_upstream_tools(installation)+ self.assertTrue(response.is_closed)++def _build_response(*, status: int = 200, body: str = "", content_type: str = "application/json", session_id: str | None = None) -> MagicMock:@@ -129,6 +238,7 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):assert notify_call.kwargs["headers"]["Mcp-Session-Id"] == "sess-1"assert json.loads(list_call.kwargs["content"])["method"] == "tools/list"assert list_call.kwargs["headers"]["Authorization"] == "Bearer sk-test"+ assert list_call.kwargs["headers"]["x-posthog-mcp-store"] == "true"assert list_call.kwargs["headers"]["Mcp-Session-Id"] == "sess-1"# DELETE cleans up the session afterwards.assert client.delete.called@@ -223,24 +333,30 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):installation = self._installation(url="https://mcp.example.com/mcp")seen: list[httpx.Request] = []- def handle_request(_transport: httpx.HTTPTransport, request: httpx.Request) -> httpx.Response:+ async def handle_request(_transport: httpx.AsyncHTTPTransport, request: httpx.Request) -> httpx.Response:if route == "denied":raise httpx.ProxyError("403 Forbidden")seen.append(httpx.Request(request.method, request.url, headers=request.headers, extensions=request.extensions))+ request_id = json.loads(request.content).get("id") if request.content else Noneif request.method == "DELETE":- return httpx.Response(200)- request_id = json.loads(request.content).get("id")- if request_id == 1:- return httpx.Response(+ response = httpx.Response(200)+ elif request_id == 1:+ response = httpx.Response(200,json={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2024-11-05"}},headers={"mcp-session-id": "sess-1", "Set-Cookie": "mcp_session=fake-session; Path=/; Secure"},)- if request_id == 2:- return httpx.Response(200, json={"jsonrpc": "2.0", "id": 2, "result": {"tools": [{"name": "alpha"}]}})- return httpx.Response(202)+ elif request_id == 2:+ response = httpx.Response(+ 200, json={"jsonrpc": "2.0", "id": 2, "result": {"tools": [{"name": "alpha"}]}}+ )+ else:+ response = httpx.Response(202)+ return httpx.Response(+ response.status_code, headers=response.headers, stream=httpx.ByteStream(response.content)+ )no_proxies = {key: "" for key in os.environ if key.lower().endswith("_proxy")}environment = {} if route == "direct" else {"HTTPS_PROXY": "http://egress.example:3128"}@@ -248,7 +364,7 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):with (override_settings(SSRF_TRUSTED_PROXY_URLS=trusted_proxies),patch.dict(os.environ, {**no_proxies, **environment}),- patch.object(httpx.HTTPTransport, "handle_request", handle_request),+ patch.object(httpx.AsyncHTTPTransport, "handle_async_request", handle_request),):if route in {"untrusted", "denied"}:error_type = ToolsFetchError if operation == "fetch" else ToolCallError@@ -370,6 +486,7 @@ class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):assert result["content"] == [{"type": "text", "text": "ok"}]call_post = client.post.call_args_list[2]assert call_post.kwargs["headers"]["Mcp-Session-Id"] == "sess-1"+ assert call_post.kwargs["headers"]["x-posthog-mcp-store"] == "true"assert json.loads(call_post.kwargs["content"]) == {"jsonrpc": "2.0","id": 3,diff --git a/products/mcp_store/backend/tools.py b/products/mcp_store/backend/tools.pyindex 470b05a1b97b..1c5deb8f8d8b 100644--- a/products/mcp_store/backend/tools.py+++ b/products/mcp_store/backend/tools.py@@ -43,6 +43,7 @@ _CLIENT_INFO: dict[str, Any] = {"name": "posthog-mcp-store", "version": "1.0"}# We cap it aggressively (separate from the proxy's 180s, which# covers real tool execution) so a hung upstream can't pin a Django worker.HANDSHAKE_TIMEOUT = 10+MAX_RESPONSE_BYTES = 8 * 1024 * 1024# A real tool call does actual work upstream, so it needs more room than the# discovery handshake. Still well under the proxy's 180s: this path serves an@@ -111,6 +112,8 @@ def fetch_upstream_tools(installation: MCPServerInstallation) -> list[dict[str,"Content-Type": "application/json","Accept": "application/json, text/event-stream",**auth_headers,+ "x-posthog-mcp-mode": "tools",+ "x-posthog-mcp-store": "true",}try:@@ -118,6 +121,8 @@ def fetch_upstream_tools(installation: MCPServerInstallation) -> list[dict[str,installation.url,verdict.pinned_ips,timeout=HANDSHAKE_TIMEOUT,+ total_timeout=HANDSHAKE_TIMEOUT,+ max_response_bytes=MAX_RESPONSE_BYTES,trust_env=trust_environment_proxy(installation.url, installation.team_id),) as client:session_id, upstream_url = _mcp_initialize(client, installation.url, base_headers)@@ -174,6 +179,8 @@ def call_upstream_tool("Content-Type": "application/json","Accept": "application/json, text/event-stream",**auth_headers,+ "x-posthog-mcp-mode": "tools",+ "x-posthog-mcp-store": "true",}try:@@ -181,6 +188,8 @@ def call_upstream_tool(installation.url,verdict.pinned_ips,timeout=CALL_TIMEOUT,+ total_timeout=CALL_TIMEOUT,+ max_response_bytes=MAX_RESPONSE_BYTES,trust_env=trust_environment_proxy(installation.url, installation.team_id),) as client:session_id, upstream_url = _mcp_initialize(client, installation.url, base_headers)@@ -202,6 +211,8 @@ def call_upstream_tool(raise ToolCallError("Upstream MCP server unreachable") from excexcept httpx.TimeoutException as exc:raise ToolCallError("Upstream MCP server timed out") from exc+ except httpx.HTTPError as exc:+ raise ToolCallError(f"Upstream MCP tool call failed: {exc}") from excdef _post_with_same_origin_redirect(diff --git a/services/mcp/README.md b/services/mcp/README.mdindex 0aaf43ff337a..465249d4d589 100644--- a/services/mcp/README.md+++ b/services/mcp/README.md@@ -326,6 +326,8 @@ Other clients keep the full inline command reference.### Tool filtering+In CLI mode, `tools` and `exclude_tools` also apply to namespaced connected tools. A `features` filter excludes connected tools unless `tools` explicitly names them. Exclusions take precedence over explicit selections.+For finer-grained control you can allowlist specific tools by name using the `tools` query parameter. Only the exact tool names listed will be exposed, regardless of their feature category.```textdiff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.tsindex 739888aa1f62..81c139f00892 100644--- a/services/mcp/scripts/generate-tools.ts+++ b/services/mcp/scripts/generate-tools.ts@@ -903,7 +903,7 @@ function extractPathParams(urlPattern: string): string[] {}/** Build a template literal expression for the API path, interpolating auto-resolved IDs and path params.- * All interpolated values are wrapped with encodeURIComponent() to prevent path traversal.+ * Interpolated values are URL-encoded; ApiClient rejects paths that URL parsing would normalize.* Params in `localVarParams` use a bare variable name (no prefix) because they are resolved to local variables. */function buildPathExpr(urlPath: string,diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.tsindex 60cd48eb8253..e7e655557dff 100644--- a/services/mcp/src/api/client.ts+++ b/services/mcp/src/api/client.ts@@ -342,6 +342,14 @@ export class ApiClient {headers?: Record<string, string>responseType?: 'json' | 'text'}): Promise<T> {+ const pathname = opts.path.split(/[?#]/, 1)[0]!+ if (+ !pathname.startsWith('/') ||+ pathname.includes('//') ||+ new URL(pathname, this.baseUrl).pathname !== pathname+ ) {+ throw new Error('Invalid API path')+ }const searchParams = new URLSearchParams()if (opts.query) {for (const [k, v] of Object.entries(opts.query)) {diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.tsindex b0e2701f0f10..7039c97b6cc2 100644--- a/services/mcp/src/hono/request-state-resolver.ts+++ b/services/mcp/src/hono/request-state-resolver.ts@@ -51,6 +51,7 @@ export interface ResolvedState {reqCtx: RequestContextcontext: ContextuseSingleExec: boolean+ viaMcpStore?: boolean | undefinedtoolFeatureFlags: EvaluatedFlags | undefinedinterviewRecruitmentConfig?: InterviewRecruitmentConfigintentPrompt?: string@@ -78,6 +79,7 @@ export interface ResolvedState {* the full roster into the instructions payload.*/gatewayToolsEnabled: boolean+ gatewayToolFilter?: Pick<RequestProperties, 'tools' | 'features' | 'excludeTools'> | undefineddistinctId: stringrenderUiEnabled: boolean}@@ -310,6 +312,7 @@ export class RequestStateResolver {reqCtx,context,useSingleExec,+ viaMcpStore: props.viaMcpStore,toolFeatureFlags,interviewRecruitmentConfig,intentPrompt,@@ -324,6 +327,7 @@ export class RequestStateResolver {allTools,scopeGatedTools,flagGatedTools,+ gatewayToolFilter: { tools, features, excludeTools },gatewayToolsEnabled:useSingleExec &&!readOnly &&diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 0fd0547119dd..e6dd8570014a 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -271,6 +271,9 @@ export class ToolExecutor {analyticsMeta: ToolCallAnalyticsMeta): Promise<unknown> {if (toolName === 'exec') {+ if (state.viaMcpStore) {+ return { content: [{ type: 'text', text: 'Tool exec not found' }], isError: true }+ }return this.callExecTool(callParams, state, analyticsMeta)}@@ -844,7 +847,12 @@ export class ToolExecutor {),flagGatedTools: state.flagGatedTools,builtInSkillHint: this.builtInSkillHint(state),- ...(state.gatewayToolsEnabled ? { gatewayToolsProvider: () => this.gatewayToolsFor(state) } : {}),+ ...(state.gatewayToolsEnabled+ ? {+ gatewayToolsProvider: () => this.gatewayToolsFor(state),+ gatewayToolFilter: state.gatewayToolFilter,+ }+ : {}),// A verb-only report lands first; `search` then reports again with its query// and counts. Merge so the richer report wins without losing the verb.trackCommand: (meta) => {diff --git a/services/mcp/src/lib/request-properties.ts b/services/mcp/src/lib/request-properties.tsindex aad132aa5e33..91dbd140313b 100644--- a/services/mcp/src/lib/request-properties.ts+++ b/services/mcp/src/lib/request-properties.ts@@ -2,6 +2,7 @@// and query params into the same shape, so the logic lives here.import { resolveEffectiveClientName } from './client-detection'+import { isGatewayToolName } from './gateway-tools'import { extractBearerToken, hash, parseMcpMode, sanitizeHeaderValue, type McpMode } from './utils'export type Transport = 'streamable-http' | 'sse'@@ -26,6 +27,7 @@ export type RequestProperties = {mcpVendorClient?: string | undefinedreadOnly?: boolean | undefinedmode?: McpMode | undefined+ viaMcpStore?: boolean | undefinedtransport?: Transport | undefinedmcpSessionId?: string | undefinedmcpConversationId?: string | undefined@@ -75,8 +77,11 @@ function parseExcludeTools(value: string | undefined): string[] | undefined {const unique: string[] = []const seen = new Set<string>()for (const part of value.split(',')) {- const token = part.trim().toLowerCase()- if (!MCP_TOOL_NAME.test(token) || seen.has(token)) {+ const name = part.trim()+ const gateway = isGatewayToolName(name)+ const token = gateway ? name : name.toLowerCase()+ const validName = gateway ? /^[^\s,]{1,512}$/.test(token) : MCP_TOOL_NAME.test(token)+ if (!validName || seen.has(token)) {continue}seen.add(token)@@ -99,6 +104,7 @@ export function parseRequestProperties(const token = extractBearerToken(request) ?? ''const readOnlyRaw = header(request, 'x-posthog-read-only') || params.get('readonly')const vendorClient = sanitizeHeaderValue(header(request, 'x-anthropic-client'))+ const viaMcpStore = header(request, 'x-posthog-mcp-store') === 'true'return {apiToken: token,@@ -119,7 +125,8 @@ export function parseRequestProperties(mcpProtocolVersion: clientInfo.protocolVersion,mcpElicitationUrlSupported: clientInfo.elicitationUrlSupported,mcpVendorClient: vendorClient,- mode: parseMcpMode(header(request, 'x-posthog-mcp-mode') || params.get('mode')),+ mode: viaMcpStore ? 'tools' : parseMcpMode(header(request, 'x-posthog-mcp-mode') || params.get('mode')),+ viaMcpStore,taskId: sanitizeHeaderValue(header(request, 'x-posthog-task-id')),taskOriginProduct: sanitizeHeaderValue(header(request, 'x-posthog-task-origin')),excludeTools: parseExcludeTools(diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 0c66ae2b6c51..ad998d3ae861 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -17,6 +17,7 @@ import {import { estimateTokens } from '@/lib/estimate-tokens'import { GATEWAY_TOOL_SEPARATOR, isGatewayToolName } from '@/lib/gateway-tools'import { findIgnoredInputKeys, withIgnoredInputKeys } from '@/lib/ignored-input-keys'+import type { RequestProperties } from '@/lib/request-properties'import { formatResponse } from '@/lib/response'import { API_KEY_CACHE_TTL_MS } from '@/lib/StateManager'import { APP_DATA_META_KEY } from '@/ui-apps/types'@@ -240,6 +241,7 @@ export interface ExecToolOptions {* degrades to "no third-party tools", never to a broken `exec`.*/gatewayToolsProvider?: () => Promise<Tool<ZodObjectAny>[]>+ gatewayToolFilter?: Pick<RequestProperties, 'tools' | 'features' | 'excludeTools'> | undefined/** Reports what the agent asked for, so non-`call` verbs stop being invisible. */trackCommand?: ExecCommandTracker/**@@ -1736,6 +1738,12 @@ export function createExecTool(}if (gatewayTools === undefined) {gatewayTools = await options.gatewayToolsProvider()+ const filter = options.gatewayToolFilter+ gatewayTools = gatewayTools.filter(+ (tool) =>+ !filter?.excludeTools?.includes(tool.name) &&+ (!(filter?.tools?.length || filter?.features?.length) || filter?.tools?.includes(tool.name))+ )}return gatewayTools.length > 0 ? [...allTools, ...gatewayTools] : allTools}diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.tsindex 4db69da2237a..e09924de43ee 100644--- a/services/mcp/tests/hono/request-state-resolver.test.ts+++ b/services/mcp/tests/hono/request-state-resolver.test.ts@@ -814,6 +814,35 @@ describe('RequestStateResolver MCP client contexts', () => {expect(result.gatewayToolsEnabled).toBe(enabled)})+ it('keeps Store connections on individual tools without nested connectors', async () => {+ vi.mocked(resolveFeatureFlagOverrides).mockReturnValueOnce({ 'mcp-gateway': true })+ const props = parseRequestProperties(+ new Request('https://example.com/mcp?mode=cli', {+ headers: {+ Authorization: 'Bearer phx_test',+ 'x-posthog-mcp-store': 'true',+ 'x-posthog-mcp-mode': 'cli',+ },+ }),+ {}+ )+ const result = await makeResolver().resolve(props)+ expect(result.useSingleExec).toBe(false)+ expect(result.gatewayToolsEnabled).toBe(false)+ expect(result.viaMcpStore).toBe(true)+ })++ it('carries connected-tool restrictions to execution', async () => {+ const filters = {+ tools: ['linear__create_issue'],+ features: ['dashboards'],+ excludeTools: ['linear__delete_issue'],+ }+ const result = await makeResolver().resolve(makeProps(filters))+ expect(result.gatewayToolFilter).toMatchObject({ tools: filters.tools, features: filters.features })+ expect(result.gatewayToolFilter?.excludeTools).toContain('linear__delete_issue')+ })+it.each([['PostHog Code task', { mcpConsumer: 'posthog-code', taskId: 'task-1' }, false],['PostHog Code without a task', { mcpConsumer: 'posthog-code', taskId: undefined }, true],diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex a735c55c0267..5789d5240a6d 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -46,6 +46,14 @@ describe('ToolExecutor', () => {})describe('handleToolCall', () => {+ it('refuses cached exec calls through Store connections', async () => {+ const result = await executor.handleToolCall(+ { name: 'exec', arguments: { command: 'tools' } },+ makeToolExecutorState([], { useSingleExec: false, viaMcpStore: true })+ )+ expect(result).toMatchObject({ isError: true, content: [{ type: 'text', text: 'Tool exec not found' }] })+ })+it('returns error when tool name is missing', async () => {const result = (await executor.handleToolCall({}, makeToolExecutorState([]))) as anyexpect(result.isError).toBe(true)diff --git a/services/mcp/tests/unit/api-client.test.ts b/services/mcp/tests/unit/api-client.test.tsindex 1f86bc829c3f..2500392f06fe 100644--- a/services/mcp/tests/unit/api-client.test.ts+++ b/services/mcp/tests/unit/api-client.test.ts@@ -5,10 +5,42 @@ import { MCP_CLIENT_IP_HEADERS, verifySignedClientIp } from '@/lib/client-ip-sigimport { USER_AGENT, getUserAgent } from '@/lib/constants'import { PostHogTransportError } from '@/lib/errors'import { getToolByName } from '@/shared/test-utils'+import { GENERATED_TOOLS as PROXY_TOOLS } from '@/tools/generated/proxy-records'import { GENERATED_TOOLS } from '@/tools/generated/skills'import type { Context } from '@/tools/types'describe('ApiClient', () => {+ it('validates the resource path of a generated tool before fetching', async () => {+ const send = vi.fn().mockResolvedValue(new Response('{}'))+ vi.stubGlobal('fetch', send)+ const client = new ApiClient({ apiToken: 'test-token', baseUrl: 'https://example.com' })+ const context = { api: client, stateManager: { getOrgID: async () => 'example' } } as unknown as Context+ const tool = getToolByName(PROXY_TOOLS, 'proxy-delete')+ try {+ await expect(tool.handler(context, tool.schema.parse({ id: '..' }))).rejects.toThrow('Invalid API path')+ expect(send).not.toHaveBeenCalled()+ } finally {+ vi.unstubAllGlobals()+ }+ })++ it.each(['.', '..', '%2e', '.%2e', '%2e.', '%2e%2e', ''])(+ 'rejects invalid resource segment case %# before sending',+ async (id) => {+ const send = vi.fn().mockResolvedValue(new Response('{}'))+ vi.stubGlobal('fetch', send)+ const client = new ApiClient({ apiToken: 'test-token', baseUrl: 'https://example.com' })+ try {+ await expect(+ client.request({ method: 'DELETE', path: `/api/organizations/example/proxy_records/${id}/` })+ ).rejects.toThrow('Invalid API path')+ expect(send).not.toHaveBeenCalled()+ } finally {+ vi.unstubAllGlobals()+ }+ }+ )+it.each([200, 403, 500])('reads privacy only from the API response before handling status %s', async (status) => {const shared = new ApiClient({ apiToken: 'test-token', baseUrl: 'https://example.com' })const suppress = vi.fn()diff --git a/services/mcp/tests/unit/gateway-tools.test.ts b/services/mcp/tests/unit/gateway-tools.test.tsindex e3995e071753..699c2519de5c 100644--- a/services/mcp/tests/unit/gateway-tools.test.ts+++ b/services/mcp/tests/unit/gateway-tools.test.ts@@ -4,7 +4,7 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import { ExecCommandError } from '@/lib/errors'import { buildGatewayTools } from '@/lib/gateway-tools'-import { createExecTool, type ExecCommandMeta } from '@/tools/exec'+import { createExecTool, type ExecCommandMeta, type ExecToolOptions } from '@/tools/exec'import type { Context, Tool, ZodObjectAny } from '@/tools/types'const INPUT_SCHEMA = {@@ -57,7 +57,8 @@ function posthogTool(): Tool<ZodObjectAny> {function createExec(gatewayTools: Tool<ZodObjectAny>[],- provider = vi.fn(async () => gatewayTools)+ provider = vi.fn(async () => gatewayTools),+ options: ExecToolOptions = {}): {exec: Tool<any>provider: ReturnType<typeof vi.fn>@@ -70,12 +71,38 @@ function createExec(undefined,undefined,[],- { gatewayToolsProvider: provider }+ { gatewayToolsProvider: provider, ...options })return { exec, provider }}describe('gateway tools', () => {+ it.each([+ { tools: ['feature-flag-create'] },+ { excludeTools: ['linear__create_issue'] },+ { features: ['dashboards'] },+ { tools: ['linear__create_issue'], excludeTools: ['linear__create_issue'] },+ ])('applies connection filters %j to connected tools', async (gatewayToolFilter) => {+ const request = vi.fn()+ const tools = buildGatewayTools(payload(), mockContext(request), '1')+ const { exec } = createExec(tools, undefined, { gatewayToolFilter })+ expect(await exec.handler(mockContext(), { command: 'search create' })).not.toContain('linear__create_issue')+ await expect(exec.handler(mockContext(), { command: 'info linear__create_issue' })).rejects.toThrow()+ await expect(+ exec.handler(mockContext(), { command: 'call --confirm linear__create_issue {"title":"Example"}' })+ ).rejects.toThrow()+ expect(request).not.toHaveBeenCalled()+ })++ it('allows explicitly selected connected tools', async () => {+ const request = vi.fn().mockResolvedValue({ ok: true })+ const { exec } = createExec(buildGatewayTools(payload(), mockContext(request), '1'), undefined, {+ gatewayToolFilter: { tools: ['linear__create_issue'], features: ['dashboards'] },+ })+ await exec.handler(mockContext(), { command: 'call --confirm linear__create_issue {"title":"Example"}' })+ expect(request).toHaveBeenCalledOnce()+ })+it('namespaces tool names by server slug and keeps the upstream JSON Schema', () => {const tools = buildGatewayTools(payload(), mockContext(), '1')diff --git a/services/mcp/tests/unit/url-routing.test.ts b/services/mcp/tests/unit/url-routing.test.tsindex dbb1fc80018c..d9e236e86238 100644--- a/services/mcp/tests/unit/url-routing.test.ts+++ b/services/mcp/tests/unit/url-routing.test.ts@@ -349,6 +349,14 @@ describe('URL Routing', () => {})describe('excludeTools parsing', () => {+ it.each(['linear__CreateIssue', `linear__${'a'.repeat(80)}`, 'linear__issues.create'])(+ 'preserves connected tool name %s',+ (name) => {+ const request = new Request(`https://example.com/mcp?exclude_tools=${encodeURIComponent(name)}`)+ expect(parseRequestProperties(request, {}).excludeTools).toEqual([name])+ }+ )+it('parses x-posthog-exclude-tools and drops duplicates and invalid names', () => {const request = new Request('https://example.com/mcp', {headers: {