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): team-scoped allowlist for internal MCP endpoints (#90081)

Keelan J.deb96a65591e
diff --git a/ee/hogai/tools/call_mcp_server/mcp_client.py b/ee/hogai/tools/call_mcp_server/mcp_client.py
index dcd4540aa843..8a2df0aa5afe 100644
--- a/ee/hogai/tools/call_mcp_server/mcp_client.py
+++ b/ee/hogai/tools/call_mcp_server/mcp_client.py
@@ -9,6 +9,8 @@ from mcp.client.sse import sse_client
from mcp.client.streamable_http import streamable_http_client
from mcp.types import TextContent
+from products.mcp_store.backend.url_policy import trust_environment_proxy
+
class MCPClientError(Exception):
pass
@@ -20,9 +22,10 @@ CLIENT_TIMEOUT = 60.0
class MCPClient:
"""MCP client wrapping the official SDK with Streamable HTTP → SSE fallback."""
- def __init__(self, server_url: str, headers: dict[str, str] | None = None):
+ def __init__(self, server_url: str, headers: dict[str, str] | None = None, team_id: int | None = None):
self._server_url = server_url
self._headers = headers
+ self._team_id = team_id
self._stack = AsyncExitStack()
self._session: ClientSession | None = None
@@ -42,7 +45,11 @@ class MCPClient:
async def _connect_streamable_http(self) -> None:
http_client = await self._stack.enter_async_context(
- httpx.AsyncClient(headers=self._headers, timeout=CLIENT_TIMEOUT)
+ httpx.AsyncClient(
+ headers=self._headers,
+ timeout=CLIENT_TIMEOUT,
+ trust_env=trust_environment_proxy(self._server_url, self._team_id),
+ )
)
read, write, _get_session_id = await self._stack.enter_async_context(
streamable_http_client(self._server_url, http_client=http_client)
diff --git a/ee/hogai/tools/call_mcp_server/test/test_tool.py b/ee/hogai/tools/call_mcp_server/test/test_tool.py
index 13c94725d013..fe2f8459fd34 100644
--- a/ee/hogai/tools/call_mcp_server/test/test_tool.py
+++ b/ee/hogai/tools/call_mcp_server/test/test_tool.py
@@ -37,7 +37,7 @@ class TestCallMCPServerTool(BaseTest):
self.context_manager = AssistantContextManager(self.team, self.user, {})
self.node_path = (NodePath(name="test_node", tool_call_id="test_call", message_id="test"),)
# Bypass SSRF DNS resolution for fake test domains
- patcher = patch("ee.hogai.tools.call_mcp_server.tool.is_url_allowed", return_value=(True, None))
+ patcher = patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
self.mock_is_url_allowed = patcher.start()
self.addCleanup(patcher.stop)
diff --git a/ee/hogai/tools/call_mcp_server/tool.py b/ee/hogai/tools/call_mcp_server/tool.py
index 9ded480c5a7a..c6e2af9c5402 100644
--- a/ee/hogai/tools/call_mcp_server/tool.py
+++ b/ee/hogai/tools/call_mcp_server/tool.py
@@ -9,10 +9,10 @@ from pydantic import BaseModel, Field, ValidationError
from posthog.schema import AssistantTool
from posthog.models import Team, User
-from posthog.security.url_validation import is_url_allowed
from posthog.sync import database_sync_to_async
from products.mcp_store.backend.oauth import is_token_expiring
+from products.mcp_store.backend.url_policy import check_mcp_url_policy
from ee.hogai.context.context import AssistantContextManager
from ee.hogai.tool import MaxTool
@@ -217,7 +217,7 @@ class CallMCPServerTool(MaxTool):
async def _attempt_call(self, server_url: str, tool_name: str, arguments: dict | None) -> str:
headers = self._server_headers.get(server_url)
- client = MCPClient(server_url, headers=headers)
+ client = MCPClient(server_url, headers=headers, team_id=self._team.id)
try:
# We build up and tear down the client session with every request.
# This lets us use the same code in cloud, our backend, and when proxying via the server.
@@ -304,7 +304,7 @@ class CallMCPServerTool(MaxTool):
f"Server URL '{server_url}' is not in the user's installed MCP servers. "
f"Allowed URLs: {', '.join(sorted(self._allowed_server_urls))}"
)
- allowed, error = is_url_allowed(server_url)
+ allowed, error = check_mcp_url_policy(server_url, self._team.id)
if not allowed:
raise MaxToolFatalError(f"MCP server URL blocked by security policy")
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index fa743a97581f..e59a237fdda4 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1473,6 +1473,21 @@ WIZARD_GATEWAY_TOKEN_CAP_USD = get_from_env("WIZARD_GATEWAY_TOKEN_CAP_USD", "20"
WIZARD_GATEWAY_PROGRAM_IDS = get_list(get_from_env("WIZARD_GATEWAY_PROGRAM_IDS", ""))
WIZARD_GATEWAY_TOKEN_TTL_SECONDS = get_from_env("WIZARD_GATEWAY_TOKEN_TTL_SECONDS", 86400, type_cast=int)
+# Exact MCP endpoints that operators explicitly allow the MCP Store to reach even
+# when normal SSRF validation rejects their private/internal address. This is an
+# internal dogfooding escape hatch, not a hostname or CIDR allowlist: callers must
+# match one of these complete URLs byte-for-byte. Internal endpoints also bypass
+# the process HTTP proxy so cluster-local traffic is not sent to Smokescreen.
+# Parsed defensively like AI_GATEWAY_TEAM_TIER_OVERRIDES above: a malformed value
+# must not take every process down at settings import; the URL policy degrades to
+# an empty allowlist (everything internal stays blocked).
+try:
+ MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM: dict[str, list[str]] = json.loads(
+ get_from_env("MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM", "{}")
+ )
+except ValueError:
+ MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM = {}
+
# Sharing configuration settings
SHARING_TOKEN_GRACE_PERIOD_SECONDS = 60 * 5 # 5 minutes
diff --git a/products/mcp_store/README.md b/products/mcp_store/README.md
index 909bd0e52a70..e986826db074 100644
--- a/products/mcp_store/README.md
+++ b/products/mcp_store/README.md
@@ -98,6 +98,28 @@ Can't be added:
- Non-HTTP transports (WebSocket-only) and legacy HTTP+SSE dual-endpoint servers — the probe and proxy speak streamable HTTP only.
- Any URL that fails the probe (`speaks_mcp: false`) — never ship an unprobed URL.
+### Internal endpoint escape hatch
+
+Cloud operators can allow a small number of private Streamable HTTP endpoints
+for internal dogfooding with the `MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM`
+environment variable. Its value is a JSON object keyed by team ID; every entry
+must be a complete MCP URL, for example:
+
+```text
+MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM={"2":["http://grafana-mcp.monitoring.svc.cluster.local/mcp"]}
+```
+
+Matching is byte-for-byte and team-scoped. Configuring an endpoint does not
+allow another team, path, host, port, trailing-slash variant, or any other
+private address. Requests to an allowed endpoint bypass the process HTTP proxy on this MCP-only code path so
+cluster-local traffic is not sent to Smokescreen; the process-wide `NO_PROXY`
+configuration is unchanged.
+
+This setting only makes the endpoint reachable. Operators must separately
+restrict it with a NetworkPolicy and application authentication, and create the
+internal installation explicitly. Internal endpoints do not belong in
+`backend/catalog.py` and are never made visible in the public marketplace.
+
Known gap: API keys are sent as `Authorization: Bearer <key>`, so servers that require a custom header (`X-API-Key`, ...) or exotic auth (signed JWTs, mTLS, IP allowlists) pass the probe but fail at first real install.
A real end-to-end install (Gate B in the skill) is the only check that catches these.
diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.py
index 8acfd4612cb1..dc9c560f4bb4 100644
--- a/products/mcp_store/backend/facade/api.py
+++ b/products/mcp_store/backend/facade/api.py
@@ -34,6 +34,11 @@ from products.mcp_store.backend.models import (
)
from products.mcp_store.backend.policy import GatewayCaller, PolicyContext
+# Re-exported for the presentation layer ("presentation must use facade"
+# import-linter contract): the single MCP URL policy entry point — shared SSRF
+# validation, overridden only by the exact team-scoped internal allowlist.
+from products.mcp_store.backend.url_policy import check_mcp_url_policy as check_mcp_url_policy
+
logger = structlog.get_logger(__name__)
diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.py
index 4022173fbbb8..f0d993db9483 100644
--- a/products/mcp_store/backend/presentation/views.py
+++ b/products/mcp_store/backend/presentation/views.py
@@ -46,10 +46,9 @@ from posthog.rate_limit import (
MCPProxyBurstThrottle,
MCPProxySustainedThrottle,
)
-from posthog.security.url_validation import is_url_allowed
from ..agents import sync_built_in_agents
-from ..facade.api import resolve_member_tool_states
+from ..facade.api import check_mcp_url_policy, resolve_member_tool_states
from ..gateway import link_installation_to_gateway, members_can_manage_agent_access, server_disabled_reason
from ..models import (
AGENT_GRANT_SCOPE_CHOICES,
@@ -425,7 +424,8 @@ class InstallCustomSerializer(serializers.Serializer):
)
def validate_url(self, value: str) -> str:
- allowed, error = is_url_allowed(value)
+ team = self.context.get("team")
+ allowed, error = check_mcp_url_policy(value, getattr(team, "id", None))
if not allowed:
raise serializers.ValidationError(f"URL not allowed: {error}")
return value
@@ -982,7 +982,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
return Response(status=status.HTTP_204_NO_CONTENT)
def _validate_mcp_url_or_error_response(self, mcp_url: str) -> Response | None:
- allowed, reason = is_url_allowed(mcp_url)
+ allowed, reason = check_mcp_url_policy(mcp_url, self.team_id)
if not allowed:
logger.warning("SSRF blocked MCP server URL", url=mcp_url, reason=reason)
return Response({"detail": "Server URL blocked by security policy"}, status=status.HTTP_400_BAD_REQUEST)
@@ -1540,6 +1540,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
@validated_request(
InstallCustomSerializer,
+ include_serializer_context=True,
responses={
200: OpenApiResponse(response=OAuthRedirectResponseSerializer),
201: OpenApiResponse(response=MCPServerInstallationSerializer),
diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.py
index 97a4616fbe7e..423e933b4418 100644
--- a/products/mcp_store/backend/proxy.py
+++ b/products/mcp_store/backend/proxy.py
@@ -19,6 +19,7 @@ from ee.hogai.utils.asgi import SyncIterableToAsync
from .models import MCPAuditEvent, MCPGatewayServer, MCPServerInstallation, MCPServerInstallationTool
from .oauth import TokenRefreshError, is_token_expiring, refresh_installation_token
from .policy import GatewayCaller, PolicyContext
+from .url_policy import check_mcp_url_policy, trust_environment_proxy
logger = structlog.get_logger(__name__)
@@ -457,7 +458,7 @@ def proxy_mcp_request(
rides, so the audit trail answers whose connection an agent used. Both are
empty for member calls, where the actor already is the credential owner.
"""
- allowed, error = is_url_allowed(installation.url)
+ allowed, error = check_mcp_url_policy(installation.url, installation.team_id)
if not allowed:
logger.warning("SSRF: blocked proxy request", url=installation.url, reason=error)
return HttpResponse(
@@ -531,7 +532,10 @@ def proxy_mcp_request(
if mcp_session_id:
headers["Mcp-Session-Id"] = mcp_session_id
- client = httpx.Client(timeout=UPSTREAM_TIMEOUT)
+ client = httpx.Client(
+ timeout=UPSTREAM_TIMEOUT,
+ trust_env=trust_environment_proxy(installation.url, installation.team_id),
+ )
try:
upstream_response, upstream_url = send_mcp_request_with_same_origin_redirect(
client,
diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.py
index d32b2a49357c..d4980cff8314 100644
--- a/products/mcp_store/backend/test/test_api.py
+++ b/products/mcp_store/backend/test/test_api.py
@@ -44,7 +44,7 @@ from products.mcp_store.backend.presentation.gateway_views import (
)
from products.mcp_store.backend.presentation.views import _is_valid_posthog_code_callback_url
-ALLOW_URL = patch("products.mcp_store.backend.presentation.views.is_url_allowed", return_value=(True, None))
+ALLOW_URL = patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
POLICY_REQUEST_SERIALIZER_CASES = [
("policy_upsert", GatewayPoliciesUpsertSerializer, {}),
@@ -2141,7 +2141,7 @@ class TestMCPServiceAccountAPI(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
mock_proxy.assert_not_called()
- @patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.proxy.httpx.Client")
def test_agent_grant_enforces_agent_scope_policy(self, mock_http_client, _mock_is_url_allowed) -> None:
account = self._active_scout_account()
@@ -2697,7 +2697,7 @@ class TestInstallCustomAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- @patch("products.mcp_store.backend.presentation.views.is_url_allowed", return_value=(False, "Private IP"))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(False, "Private IP"))
def test_install_custom_ssrf_blocked(self, _mock):
response = self.client.post(
f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",
@@ -2706,7 +2706,7 @@ class TestInstallCustomAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- @patch("products.mcp_store.backend.presentation.views.is_url_allowed", return_value=(False, "Local/metadata host"))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(False, "Local/metadata host"))
def test_install_custom_oauth_ssrf_blocked(self, _mock):
response = self.client.post(
f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",
@@ -4485,7 +4485,7 @@ class TestMCPInstallationScopeAccess(ClickhouseTestMixin, APIBaseTest, QueryMatc
other = User.objects.create_and_join(self.organization, "[email protected]", "password")
shared = self._create_installation(user=other, scope="shared", sensitive_configuration={"api_key": "k"})
- with mock_patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None)):
+ with mock_patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None)):
with mock_patch("products.mcp_store.backend.proxy.httpx.Client") as mock_client_cls:
mock_resp = MagicMock()
mock_resp.status_code = 200
diff --git a/products/mcp_store/backend/test/test_proxy.py b/products/mcp_store/backend/test/test_proxy.py
index 9dcbbc9ad3ba..49d0f9907a18 100644
--- a/products/mcp_store/backend/test/test_proxy.py
+++ b/products/mcp_store/backend/test/test_proxy.py
@@ -28,9 +28,15 @@ from products.mcp_store.backend.proxy import _build_sse_response
class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
def setUp(self):
super().setUp()
- patcher = patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None))
- patcher.start()
- self.addCleanup(patcher.stop)
+ # Policy checks now flow through url_policy (check_mcp_url_policy);
+ # proxy.is_url_allowed still guards same-origin redirect targets.
+ for target in (
+ "products.mcp_store.backend.url_policy.is_url_allowed",
+ "products.mcp_store.backend.proxy.is_url_allowed",
+ ):
+ patcher = patch(target, return_value=(True, None))
+ patcher.start()
+ self.addCleanup(patcher.stop)
def _proxy_url(self, installation_id: str) -> str:
return f"/api/environments/{self.team.id}/mcp_server_installations/{installation_id}/proxy/"
@@ -504,7 +510,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert response.json()["error"] == "No credentials configured"
- @patch("products.mcp_store.backend.proxy.is_url_allowed")
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed")
def test_proxy_rejects_ssrf_private_ips(self, mock_is_url_allowed):
mock_is_url_allowed.return_value = (False, "Private IP address not allowed")
installation = self._create_installation(
@@ -541,9 +547,15 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
def setUp(self):
super().setUp()
- patcher = patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None))
- patcher.start()
- self.addCleanup(patcher.stop)
+ # Policy checks now flow through url_policy (check_mcp_url_policy);
+ # proxy.is_url_allowed still guards same-origin redirect targets.
+ for target in (
+ "products.mcp_store.backend.url_policy.is_url_allowed",
+ "products.mcp_store.backend.proxy.is_url_allowed",
+ ):
+ patcher = patch(target, return_value=(True, None))
+ patcher.start()
+ self.addCleanup(patcher.stop)
def _proxy_url(self, installation_id: str) -> str:
return f"/api/environments/{self.team.id}/mcp_server_installations/{installation_id}/proxy/"
@@ -853,9 +865,15 @@ class TestMCPProxyAccessControl(ClickhouseTestMixin, APIBaseTest, QueryMatchingT
def setUp(self):
super().setUp()
- patcher = patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None))
- patcher.start()
- self.addCleanup(patcher.stop)
+ # Policy checks now flow through url_policy (check_mcp_url_policy);
+ # proxy.is_url_allowed still guards same-origin redirect targets.
+ for target in (
+ "products.mcp_store.backend.url_policy.is_url_allowed",
+ "products.mcp_store.backend.proxy.is_url_allowed",
+ ):
+ patcher = patch(target, return_value=(True, None))
+ patcher.start()
+ self.addCleanup(patcher.stop)
def _proxy_url(self, installation_id: str, team_id: int | None = None) -> str:
tid = team_id if team_id is not None else self.team.id
diff --git a/products/mcp_store/backend/test/test_tools.py b/products/mcp_store/backend/test/test_tools.py
index a20c7fd87e6b..26046979f258 100644
--- a/products/mcp_store/backend/test/test_tools.py
+++ b/products/mcp_store/backend/test/test_tools.py
@@ -74,7 +74,7 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
defaults.update(overrides)
return MCPServerInstallation.objects.create(**defaults)
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_fetch_upstream_tools_uses_handshake_timeout(self, mock_client_cls, _allow):
# The handshake must not inherit the proxy's 180s budget — that would let a
@@ -88,7 +88,7 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
assert mock_client_cls.call_args.kwargs["timeout"] == HANDSHAKE_TIMEOUT
assert HANDSHAKE_TIMEOUT <= 30 # guard against accidental regression
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_fetch_upstream_tools_parses_result(self, mock_client_cls, _allow):
installation = self._installation()
@@ -125,7 +125,7 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
assert client.delete.call_args.kwargs["headers"]["Mcp-Session-Id"] == "sess-1"
@patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_fetch_upstream_tools_follows_same_origin_initialize_redirect(
self, mock_client_cls, _allow_tools, _allow_proxy
@@ -155,7 +155,7 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
assert client.post.call_args_list[3].args[0] == "https://mcp.example.com/mcp/"
assert client.delete.call_args.args[0] == "https://mcp.example.com/mcp/"
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_fetch_upstream_tools_parses_sse_tools_list(self, mock_client_cls, _allow):
# Some MCP servers reply to tools/list over SSE even though initialize
@@ -170,7 +170,7 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
tools = fetch_upstream_tools(installation)
assert [t["name"] for t in tools] == ["alpha"]
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_fetch_upstream_tools_works_without_session_id(self, mock_client_cls, _allow):
# Servers that don't require a session simply omit Mcp-Session-Id on the
@@ -193,13 +193,13 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
assert [t["name"] for t in tools] == ["alpha"]
assert not client.delete.called
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(False, "Private IP"))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(False, "Private IP"))
def test_fetch_upstream_tools_raises_on_blocked_url(self, _allow):
installation = self._installation()
with pytest.raises(ToolsFetchError, match="URL not allowed"):
fetch_upstream_tools(installation)
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_fetch_upstream_tools_raises_on_connect_error(self, mock_client_cls, _allow):
installation = self._installation()
@@ -210,7 +210,7 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
with pytest.raises(ToolsFetchError, match="unreachable"):
fetch_upstream_tools(installation)
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_fetch_upstream_tools_raises_on_initialize_error(self, mock_client_cls, _allow):
installation = self._installation()
@@ -221,7 +221,7 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
with pytest.raises(ToolsFetchError, match="initialize returned status 401"):
fetch_upstream_tools(installation)
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_fetch_upstream_tools_raises_when_result_missing(self, mock_client_cls, _allow):
installation = self._installation()
@@ -243,7 +243,7 @@ class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):
sensitive_configuration={"api_key": "sk-test"},
)
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_call_carries_the_session_from_initialize(self, mock_client_cls, _allow):
# Most servers reject tools/call without the Mcp-Session-Id they handed out on
@@ -282,7 +282,7 @@ class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):
),
]
)
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_call_parses_both_response_framings(self, _name, body, content_type, mock_client_cls, _allow):
installation = self._installation()
@@ -292,7 +292,7 @@ class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):
assert call_upstream_tool(installation, "create_issue", {})["content"] == [{"type": "text", "text": "ok"}]
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_call_returns_tool_reported_errors_instead_of_raising(self, mock_client_cls, _allow):
# `isError` is the tool telling the model it failed (bad arguments, not found).
@@ -322,7 +322,7 @@ class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):
("missing_result", json.dumps({"jsonrpc": "2.0", "id": 3}), "missing 'result'"),
]
)
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(True, None))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
@patch("products.mcp_store.backend.tools.httpx.Client")
def test_call_raises_on_protocol_failures(self, _name, body, expected_message, mock_client_cls, _allow):
installation = self._installation()
@@ -331,7 +331,7 @@ class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):
with pytest.raises(ToolCallError, match=expected_message):
call_upstream_tool(installation, "create_issue", {})
- @patch("products.mcp_store.backend.tools.is_url_allowed", return_value=(False, "Private IP"))
+ @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(False, "Private IP"))
def test_call_refuses_a_blocked_url(self, _allow):
installation = self._installation()
with pytest.raises(ToolCallError, match="URL not allowed"):
diff --git a/products/mcp_store/backend/test/test_url_policy.py b/products/mcp_store/backend/test/test_url_policy.py
new file mode 100644
index 000000000000..5f32d0b4b52a
--- /dev/null
+++ b/products/mcp_store/backend/test/test_url_policy.py
@@ -0,0 +1,66 @@
+from django.test import override_settings
+
+from products.mcp_store.backend.url_policy import (
+ allow_internal_mcp_url,
+ check_mcp_url_policy,
+ is_internal_mcp_url,
+ trust_environment_proxy,
+)
+
+
+@override_settings(
+ MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM={"42": ["http://grafana-mcp.monitoring.svc.cluster.local/mcp"]}
+)
+def test_internal_mcp_url_requires_an_exact_match() -> None:
+ configured = "http://grafana-mcp.monitoring.svc.cluster.local/mcp"
+
+ assert is_internal_mcp_url(configured, 42)
+ assert not is_internal_mcp_url(configured, 43)
+ assert not is_internal_mcp_url(configured, None)
+ assert not is_internal_mcp_url(f"{configured}/", 42)
+ assert not is_internal_mcp_url("http://grafana-mcp.monitoring.svc.cluster.local/other", 42)
+ assert not is_internal_mcp_url("http://other.monitoring.svc.cluster.local/mcp", 42)
+
+
+@override_settings(
+ MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM={"42": ["http://grafana-mcp.monitoring.svc.cluster.local/mcp"]}
+)
+def test_internal_mcp_url_can_override_a_failed_public_ssrf_check() -> None:
+ configured = "http://grafana-mcp.monitoring.svc.cluster.local/mcp"
+
+ assert allow_internal_mcp_url(configured, 42, False, "Internal domain") == (True, None)
+ assert allow_internal_mcp_url(configured, 43, False, "Internal domain") == (False, "Internal domain")
+ assert allow_internal_mcp_url("http://other.svc.cluster.local/mcp", 42, False, "Internal domain") == (
+ False,
+ "Internal domain",
+ )
+
+
+@override_settings(
+ MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM={"42": ["http://grafana-mcp.monitoring.svc.cluster.local/mcp"]}
+)
+def test_check_mcp_url_policy_is_the_single_entry_point() -> None:
+ # The real SSRF check rejects cluster-local hosts on the internal-domain
+ # pattern (no DNS involved), so these exercise the composed path end to end.
+ configured = "http://grafana-mcp.monitoring.svc.cluster.local/mcp"
+
+ assert check_mcp_url_policy(configured, 42) == (True, None)
+
+ allowed, reason = check_mcp_url_policy(configured, 43)
+ assert not allowed
+ assert reason is not None
+
+ allowed, reason = check_mcp_url_policy(f"{configured}/", 42)
+ assert not allowed
+ assert reason is not None
+
+
+@override_settings(
+ MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM={"42": ["http://grafana-mcp.monitoring.svc.cluster.local/mcp"]}
+)
+def test_internal_mcp_url_bypasses_environment_proxy_only_for_exact_match() -> None:
+ configured = "http://grafana-mcp.monitoring.svc.cluster.local/mcp"
+
+ assert not trust_environment_proxy(configured, 42)
+ assert trust_environment_proxy(configured, 43)
+ assert trust_environment_proxy("https://mcp.example.com/mcp", 42)
diff --git a/products/mcp_store/backend/tools.py b/products/mcp_store/backend/tools.py
index fbdcfdc9e46b..05d04fe0a057 100644
--- a/products/mcp_store/backend/tools.py
+++ b/products/mcp_store/backend/tools.py
@@ -13,12 +13,11 @@ from django.utils import timezone
import httpx
import structlog
-from posthog.security.url_validation import is_url_allowed
-
from .models import MCPServerInstallation, MCPServerInstallationTool
from .oauth import TokenRefreshError, is_token_expiring, refresh_installation_token
from .policy import SYNC_DEFAULT_APPROVAL_STATE
from .proxy import build_upstream_auth_headers, validated_same_origin_redirect_url
+from .url_policy import check_mcp_url_policy, trust_environment_proxy
logger = structlog.get_logger(__name__)
@@ -78,7 +77,7 @@ def fetch_upstream_tools(installation: MCPServerInstallation) -> list[dict[str,
Shares the proxy's SSRF guard + timeout + auth-header builder so behavior stays
consistent between proxy traffic and sync traffic.
"""
- allowed, reason = is_url_allowed(installation.url)
+ allowed, reason = check_mcp_url_policy(installation.url, installation.team_id)
if not allowed:
raise ToolsFetchError(f"URL not allowed: {reason}")
@@ -92,7 +91,10 @@ def fetch_upstream_tools(installation: MCPServerInstallation) -> list[dict[str,
}
try:
- with httpx.Client(timeout=HANDSHAKE_TIMEOUT) as client:
+ with httpx.Client(
+ timeout=HANDSHAKE_TIMEOUT,
+ trust_env=trust_environment_proxy(installation.url, installation.team_id),
+ ) as client:
session_id, upstream_url = _mcp_initialize(client, installation.url, base_headers)
session_headers = dict(base_headers)
if session_id:
@@ -127,7 +129,7 @@ def call_upstream_tool(
the gateway's policy engine first (see ``enforce_tool_approval``), so this stays
a transport concern.
"""
- allowed, reason = is_url_allowed(installation.url)
+ allowed, reason = check_mcp_url_policy(installation.url, installation.team_id)
if not allowed:
raise ToolCallError(f"URL not allowed: {reason}")
@@ -141,7 +143,10 @@ def call_upstream_tool(
}
try:
- with httpx.Client(timeout=CALL_TIMEOUT) as client:
+ with httpx.Client(
+ timeout=CALL_TIMEOUT,
+ trust_env=trust_environment_proxy(installation.url, installation.team_id),
+ ) as client:
session_id, upstream_url = _mcp_initialize(client, installation.url, base_headers)
session_headers = dict(base_headers)
if session_id:
diff --git a/products/mcp_store/backend/url_policy.py b/products/mcp_store/backend/url_policy.py
new file mode 100644
index 000000000000..9d046fc3efbe
--- /dev/null
+++ b/products/mcp_store/backend/url_policy.py
@@ -0,0 +1,42 @@
+"""Narrow operator-controlled URL policy for internal MCP dogfooding.
+
+Normal MCP Store URLs must pass PostHog's shared SSRF validation. Cloud operators
+may additionally configure complete internal endpoint URLs per team through
+``MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM``. Matching is deliberately exact:
+this is not a domain, suffix, origin, or CIDR allowlist and cannot authorize
+sibling paths or grant another team access.
+"""
+
+from django.conf import settings
+
+from posthog.security.url_validation import is_url_allowed
+
+
+def is_internal_mcp_url(url: str, team_id: int | None) -> bool:
+ if team_id is None:
+ return False
+ urls = settings.MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM.get(str(team_id), [])
+ return isinstance(urls, list) and url in urls
+
+
+def check_mcp_url_policy(url: str, team_id: int | None) -> tuple[bool, str | None]:
+ """The single entry point for MCP URL policy: shared SSRF validation,
+ overridden only by an exact team-scoped internal-allowlist match.
+
+ Call sites must use this rather than composing ``is_url_allowed`` with
+ ``allow_internal_mcp_url`` themselves — a caller that forgets one half (or
+ reorders the splatted positional results) silently drops the policy.
+ """
+ return allow_internal_mcp_url(url, team_id, *is_url_allowed(url))
+
+
+def allow_internal_mcp_url(url: str, team_id: int | None, allowed: bool, reason: str | None) -> tuple[bool, str | None]:
+ if not allowed and is_internal_mcp_url(url, team_id):
+ return True, None
+ return allowed, reason
+
+
+def trust_environment_proxy(url: str, team_id: int | None) -> bool:
+ """Internal Services must be reached directly instead of via HTTP_PROXY."""
+
+ return not is_internal_mcp_url(url, team_id)
diff --git a/tach.toml b/tach.toml
index b274fb5fb6b9..6a8d9f7ab744 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1103,6 +1103,8 @@ expose = [
"backend\\.admin.*",
"backend\\.models.*",
"backend\\.oauth.*",
+ "backend\\.url_policy\\.check_mcp_url_policy",
+ "backend\\.url_policy\\.trust_environment_proxy",
]
from = [
"products.mcp_store",