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): call connected MCP servers from the PostHog MCP (#78428)

Tom Owers6bcc2cedb135
diff --git a/products/mcp_store/README.md b/products/mcp_store/README.md
index 8fac545e7245..a1a242fcccf0 100644
--- a/products/mcp_store/README.md
+++ b/products/mcp_store/README.md
@@ -115,6 +115,22 @@ To show brand icons on a self-hosted instance, create a logo.dev account, genera
3. `oauth_metadata` should already be populated by the sync; if empty, run the "Discover metadata" admin action.
4. Tick "is active". Repeat per environment — templates are per-database rows.
+## Reaching connected servers from an agent
+
+There are two ways a caller uses a connection, and they differ in who speaks MCP.
+
+- **`POST .../mcp_server_installations/:id/proxy/`** is a transparent JSON-RPC passthrough.
+ The caller is an MCP client that runs its own `initialize` handshake and holds the session — PostHog Code points a sandbox at this URL as if it were the vendor's server.
+ Built-in agents get the equivalent root-level route with a signed token (see `backend/facade/api.py`).
+- **`POST .../mcp_server_installations/:id/call_tool/`** takes `{tool_name, arguments}` and returns one tool result.
+ The caller wants a result, not a transport, so PostHog runs the handshake server-side (`call_upstream_tool` in `backend/tools.py`).
+ This is what the PostHog MCP's `exec` uses, so an external agent (Claude Code, Codex) can call a connected server's tools through its existing PostHog connection instead of authenticating each vendor separately.
+ Discovery for that path is `GET .../mcp_server_installations/available_tools/`, which returns every callable tool across the caller's connections in one request, each namespaced by a server slug (`linear__create_issue`).
+ The `exec` side lives in `services/mcp/src/lib/gateway-tools.ts` and is gated on the `mcp-gateway` flag.
+
+Both paths resolve policy through the same `resolve_call_decision` / `_gateway_decision` in `backend/proxy.py` and write the same `MCPAuditEvent` rows, so approval state and the audit trail cannot diverge between them.
+`needs_approval` and `do_not_use` tools are refused before any upstream request.
+
## Key modules
| Path | What it is |
@@ -124,6 +140,6 @@ To show brand icons on a self-hosted instance, create a logo.dev account, genera
| `backend/probe.py` | Live server verification, up to the OAuth consent screen |
| `backend/models.py` | `MCPServerTemplate`, `MCPServerInstallation` (+ per-install tools, OAuth state) |
| `backend/oauth.py` | RFC 9728/8414 discovery, RFC 7591 DCR, token exchange/refresh |
-| `backend/proxy.py`, `backend/tools.py` | MCP request proxying and tool discovery |
+| `backend/proxy.py`, `backend/tools.py` | MCP request proxying, tool discovery, and single tool calls |
| `backend/facade/` | The only cross-product import surface |
| `frontend/scene/` | Marketplace UI (`MarketplaceBrowser`, `ServerCard`, ...) |
diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.py
index 171d40f61878..3ee0bc5c707a 100644
--- a/products/mcp_store/backend/presentation/views.py
+++ b/products/mcp_store/backend/presentation/views.py
@@ -1,3 +1,5 @@
+import re
+import json
import time
import hashlib
import secrets
@@ -16,6 +18,7 @@ from django.http.response import HttpResponseBase
from django.utils import timezone
import structlog
+from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
from rest_framework import mixins, renderers, serializers, status, viewsets
from rest_framework.authentication import SessionAuthentication
@@ -44,6 +47,7 @@ from posthog.rate_limit import (
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 ..gateway import link_installation_to_gateway, members_can_manage_agent_access, server_disabled_reason
from ..models import (
APPROVAL_STATES,
@@ -71,9 +75,9 @@ from ..oauth import (
select_token_endpoint_auth_method,
)
from ..policy import GatewayCaller, PolicyContext, ResolvedPolicy, is_policy_state_allowed
-from ..proxy import proxy_mcp_request, validate_installation_auth
+from ..proxy import proxy_mcp_request, record_tool_call_audit, resolve_call_decision, validate_installation_auth
from ..tasks import sync_installation_tools_task
-from ..tools import ToolsFetchError, sync_installation_tools
+from ..tools import ToolCallError, ToolsFetchError, call_upstream_tool, sync_installation_tools
class MCPProxyRenderer(renderers.BaseRenderer):
@@ -542,6 +546,112 @@ class ToolApprovalUpdateSerializer(serializers.Serializer):
approval_state = serializers.ChoiceField(choices=["approved", "needs_approval", "do_not_use"])
+def _installation_display_name(installation: MCPServerInstallation) -> str:
+ if installation.display_name:
+ return installation.display_name
+ if installation.template and installation.template.name:
+ return installation.template.name
+ return installation.url
+
+
+def _unique_server_slug(name: str, url: str, used: set[str]) -> str:
+ """A short lowercase identifier callers use to namespace tool names.
+
+ Stable across requests because callers iterate installations in id order, and
+ unique within a response because two connections can legitimately share a
+ display name (for example a personal and a shared install of one server).
+ """
+ base = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
+ if not base:
+ base = re.sub(r"[^a-z0-9]+", "-", (urlparse(url).hostname or "server").lower()).strip("-")
+ slug = base or "server"
+ if slug in used:
+ suffix = 2
+ while f"{slug}-{suffix}" in used:
+ suffix += 1
+ slug = f"{slug}-{suffix}"
+ used.add(slug)
+ return slug
+
+
+@extend_schema_field(OpenApiTypes.OBJECT)
+class MCPJSONObjectField(serializers.JSONField):
+ """A free-form JSON object whose shape the upstream MCP server owns — tool
+ input schemas, tool arguments, MCP content blocks."""
+
+
+class CallToolRequestSerializer(serializers.Serializer):
+ tool_name = serializers.CharField(
+ max_length=200,
+ help_text="Name of the tool to invoke, exactly as the upstream server reports it.",
+ )
+ arguments = MCPJSONObjectField(
+ required=False,
+ default=dict,
+ help_text="Arguments object passed straight to the tool, matching its input schema.",
+ )
+
+
+class CallToolResponseSerializer(serializers.Serializer):
+ content = serializers.ListField(
+ child=MCPJSONObjectField(),
+ help_text="MCP content blocks the tool returned, in upstream order.",
+ )
+ is_error = serializers.BooleanField(
+ help_text="True when the tool itself reported failure (for example bad arguments). "
+ "The call reached the server; read `content` for the reason."
+ )
+ structured_content = MCPJSONObjectField(
+ required=False,
+ allow_null=True,
+ help_text="Structured result the tool returned alongside `content`, when it provides one.",
+ )
+
+
+class CallToolBlockedSerializer(serializers.Serializer):
+ detail = serializers.CharField(help_text="Why the call was refused, phrased for the calling agent.")
+ reason = serializers.ChoiceField(
+ choices=["needs_approval", "disabled", "removed", "upstream_error"],
+ help_text="Machine-readable refusal cause, so callers can prompt for approval instead of retrying.",
+ )
+
+
+# Phrased for the agent reading the refusal: say what happened and where the human
+# fixes it, since approval lives in PostHog and not inline in the conversation.
+_BLOCKED_CALL_DETAIL = {
+ "needs_approval": "Tool '{tool_name}' needs approval before it can run. "
+ "Ask the user to approve it in PostHog under Settings → MCP servers.",
+ "disabled": "Tool '{tool_name}' is turned off by team policy. An admin controls this in PostHog.",
+ "removed": "Tool '{tool_name}' is no longer available on the upstream server.",
+}
+
+
+class AvailableToolSerializer(serializers.Serializer):
+ name = serializers.CharField(help_text="Tool name as the upstream server reports it.")
+ description = serializers.CharField(help_text="Upstream tool description.", allow_blank=True)
+ input_schema = MCPJSONObjectField(help_text="JSON Schema for the tool's arguments.")
+ annotations = MCPJSONObjectField(
+ help_text="MCP tool annotations the upstream server declared (destructiveHint, readOnlyHint, ...). "
+ "Advisory only — policy may escalate them, never loosen them."
+ )
+ approval_state = serializers.ChoiceField(
+ choices=APPROVAL_STATES,
+ help_text="Effective gateway state. `needs_approval` tools are listed so callers can explain "
+ "why a call would fail rather than pretending the capability is missing.",
+ )
+
+
+class AvailableServerSerializer(serializers.Serializer):
+ installation_id = serializers.UUIDField(help_text="Installation to send `call_tool` requests to.")
+ name = serializers.CharField(help_text="Human-readable server name.")
+ slug = serializers.CharField(help_text="Stable lowercase identifier used to namespace tool names.")
+ tools = AvailableToolSerializer(many=True, help_text="Callable tools on this server.")
+
+
+class AvailableToolsResponseSerializer(serializers.Serializer):
+ servers = AvailableServerSerializer(many=True, help_text="Connected servers the caller can reach.")
+
+
class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "project"
scope_object_read_actions = ["list", "retrieve", "authorize", "list_tools"]
@@ -980,6 +1090,32 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
)
return Response(self.get_serializer(installation).data)
+ def _gateway_preflight(self, installation: MCPServerInstallation, request: Request) -> HttpResponse | None:
+ """Gate a call on the admin kill switch, member revocation and credential
+ health. Returns an error response to send back, or None to proceed.
+ Shared by `proxy` and `call_tool` so the two cannot drift apart."""
+ gateway_server = installation.gateway_server
+ if gateway_server is not None:
+ if not gateway_server.is_team_enabled:
+ return HttpResponse(
+ '{"error": "Server is disabled for this team"}',
+ content_type="application/json",
+ status=403,
+ )
+ if MCPMemberServerRevocation.objects.filter(
+ gateway_server=gateway_server, user=cast(User, request.user)
+ ).exists():
+ return HttpResponse(
+ '{"error": "Your access to this server has been turned off by an admin"}',
+ content_type="application/json",
+ status=403,
+ )
+
+ ok, error_response = validate_installation_auth(installation)
+ if not ok and error_response is not None:
+ return error_response
+ return None
+
@action(
detail=True,
methods=["post"],
@@ -1002,27 +1138,11 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
user_id=request.user.id,
)
- gateway_server = installation.gateway_server
- if gateway_server is not None:
- if not gateway_server.is_team_enabled:
- return HttpResponse(
- '{"error": "Server is disabled for this team"}',
- content_type="application/json",
- status=403,
- )
- if MCPMemberServerRevocation.objects.filter(
- gateway_server=gateway_server, user=cast(User, request.user)
- ).exists():
- return HttpResponse(
- '{"error": "Your access to this server has been turned off by an admin"}',
- content_type="application/json",
- status=403,
- )
-
- ok, error_response = validate_installation_auth(installation)
- if not ok and error_response is not None:
- return error_response
+ preflight_error = self._gateway_preflight(installation, request)
+ if preflight_error is not None:
+ return preflight_error
+ gateway_server = installation.gateway_server
caller = GatewayCaller(kind="member", user_id=request.user.id)
return proxy_mcp_request(
request,
@@ -1032,6 +1152,112 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
actor_label=cast(User, request.user).email or "",
)
+ @validated_request(
+ CallToolRequestSerializer,
+ responses={
+ 200: OpenApiResponse(response=CallToolResponseSerializer),
+ 403: OpenApiResponse(response=CallToolBlockedSerializer),
+ 404: OpenApiResponse(response=CallToolBlockedSerializer),
+ },
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="call_tool",
+ throttle_classes=[MCPProxyBurstThrottle, MCPProxySustainedThrottle],
+ required_scopes=["project:read"],
+ )
+ def call_tool(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Invoke one tool on a connected MCP server.
+
+ The request/response shape is plain REST rather than the JSON-RPC envelope
+ `proxy` speaks, because the caller here is an agent surface (the PostHog MCP's
+ `exec`) that wants one tool result, not an MCP transport of its own.
+ """
+ installation = self.get_object()
+ data = request.validated_data
+ tool_name = data["tool_name"]
+ arguments = data.get("arguments") or {}
+
+ preflight_error = self._gateway_preflight(installation, request)
+ if preflight_error is not None:
+ # Reuse the proxy's bodies verbatim so both surfaces explain a disabled
+ # server or revoked member the same way.
+ return Response(
+ {"detail": json.loads(preflight_error.content)["error"], "reason": "disabled"},
+ status=preflight_error.status_code,
+ )
+
+ tool = installation.tools.filter(tool_name=tool_name).first()
+ if tool is None:
+ return Response(
+ {
+ "detail": f"Tool '{tool_name}' is not registered for this connection. "
+ "Refresh the connection's tools if you expect it to exist.",
+ "reason": "removed",
+ },
+ status=status.HTTP_404_NOT_FOUND,
+ )
+
+ gateway_server = installation.gateway_server
+ policy_context = (
+ PolicyContext(
+ team_id=installation.team_id,
+ caller=GatewayCaller(kind="member", user_id=request.user.id),
+ gateway_server=gateway_server,
+ installation=installation,
+ )
+ if gateway_server is not None
+ else None
+ )
+ decision, block_reason = resolve_call_decision(tool, policy_context)
+
+ if gateway_server is not None:
+ record_tool_call_audit(
+ installation,
+ gateway_server,
+ GatewayCaller(kind="member", user_id=request.user.id),
+ cast(User, request.user).email or "",
+ tool_name,
+ decision,
+ )
+
+ if block_reason is not None:
+ return Response(
+ {"detail": _BLOCKED_CALL_DETAIL[block_reason].format(tool_name=tool_name), "reason": block_reason},
+ status=status.HTTP_404_NOT_FOUND if block_reason == "removed" else status.HTTP_403_FORBIDDEN,
+ )
+
+ try:
+ result = call_upstream_tool(installation, tool_name, arguments)
+ except (ToolCallError, ToolsFetchError) as exc:
+ logger.warning(
+ "mcp_store call_tool failed",
+ team_id=self.team_id,
+ installation_id=str(installation.id),
+ tool_name=tool_name,
+ error=str(exc),
+ )
+ return Response(
+ {"detail": f"The upstream MCP server could not run '{tool_name}': {exc}", "reason": "upstream_error"},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ # The upstream server is untrusted input — `content` isn't guaranteed to be a list,
+ # so a malformed response degrades to an empty content array instead of raising.
+ content = result.get("content")
+ content_blocks = [block for block in content if isinstance(block, dict)] if isinstance(content, list) else []
+
+ return Response(
+ CallToolResponseSerializer(
+ {
+ "content": content_blocks,
+ "is_error": bool(result.get("isError")),
+ "structured_content": result.get("structuredContent"),
+ }
+ ).data
+ )
+
@validated_request(
InstallTemplateSerializer,
responses={
@@ -1717,6 +1943,69 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
return _oauth_authorize_response(authorize_url, install_source)
+ @extend_schema(responses={200: OpenApiResponse(response=AvailableToolsResponseSerializer)})
+ @action(detail=False, methods=["get"], url_path="available_tools", pagination_class=None)
+ def available_tools(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Every tool the caller can currently reach, across all their connections.
+
+ One request instead of one per connection: an agent surface resolving its
+ tool list on each session cannot afford a fan-out. `do_not_use` and removed
+ tools are omitted — an agent should not see what it cannot call — while
+ `needs_approval` tools are listed with their state so the caller can explain
+ the block rather than report the capability as missing.
+ """
+ user = cast(User, request.user)
+ installations = (
+ MCPServerInstallation.objects.filter(team_id=self.team_id, is_enabled=True)
+ .filter(Q(user=user) | Q(scope="shared"))
+ .filter(Q(gateway_server__isnull=True) | Q(gateway_server__is_team_enabled=True))
+ .exclude(gateway_server__member_revocations__user=user)
+ .select_related("template", "gateway_server")
+ .prefetch_related("tools")
+ .order_by("id")
+ )
+
+ used_slugs: set[str] = set()
+ servers: list[dict[str, Any]] = []
+ for installation in installations:
+ # The same credential check `call_tool` runs, so the list can never
+ # advertise a connection the call path would immediately reject.
+ ok, _error = validate_installation_auth(installation)
+ if not ok:
+ continue
+
+ states = resolve_member_tool_states(
+ str(installation.id),
+ installation.team_id,
+ installation.gateway_server_id,
+ user.id,
+ )
+ tools = [
+ {
+ "name": tool.tool_name,
+ "description": tool.description,
+ "input_schema": tool.input_schema,
+ "annotations": tool.annotations,
+ "approval_state": states.get(tool.tool_name, "needs_approval"),
+ }
+ for tool in installation.tools.all()
+ if tool.removed_at is None and states.get(tool.tool_name, "needs_approval") != "do_not_use"
+ ]
+ if not tools:
+ continue
+
+ name = _installation_display_name(installation)
+ servers.append(
+ {
+ "installation_id": installation.id,
+ "name": name,
+ "slug": _unique_server_slug(name, installation.url, used_slugs),
+ "tools": sorted(tools, key=lambda t: t["name"]),
+ }
+ )
+
+ return Response(AvailableToolsResponseSerializer({"servers": servers}).data)
+
@extend_schema(responses={200: OpenApiResponse(response=MCPServerInstallationToolSerializer(many=True))})
@action(detail=True, methods=["get"], url_path="tools")
def list_tools(self, request: Request, *args: Any, **kwargs: Any) -> Response:
diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.py
index 1d37e1411912..7930e40102ca 100644
--- a/products/mcp_store/backend/proxy.py
+++ b/products/mcp_store/backend/proxy.py
@@ -226,6 +226,47 @@ def _gateway_decision(policy_context: PolicyContext, tool: MCPServerInstallation
return "auto", False
+def resolve_call_decision(
+ tool: MCPServerInstallationTool,
+ policy_context: PolicyContext | None,
+) -> tuple[str, str | None]:
+ """Decide one tool call outside the JSON-RPC proxy path.
+
+ Returns ``(audit_decision, block_reason)`` where ``block_reason`` is None when
+ the call may proceed, else one of ``"removed"``, ``"needs_approval"`` or
+ ``"disabled"``. Shares :func:`_gateway_decision` with the proxy so policy
+ resolution cannot diverge between the two entry points; the proxy keeps its own
+ JSON-RPC error mapping because its wire format is fixed by the MCP spec.
+ """
+ if tool.removed_at is not None:
+ return "blocked", "removed"
+
+ if policy_context is not None:
+ decision, blocked = _gateway_decision(policy_context, tool)
+ if not blocked:
+ return decision, None
+ return decision, "needs_approval" if decision == "pending" else "disabled"
+
+ # Pre-gateway installations fall back to the cached per-tool approval flag.
+ if tool.approval_state == "approved":
+ return "approved", None
+ if tool.approval_state == "needs_approval":
+ return "pending", "needs_approval"
+ return "blocked", "disabled"
+
+
+def record_tool_call_audit(
+ installation: MCPServerInstallation,
+ gateway_server: MCPGatewayServer,
+ caller: GatewayCaller,
+ actor_label: str,
+ tool_name: str,
+ decision: str,
+) -> None:
+ """Audit a single tool call. Same writer the proxy uses, one entry at a time."""
+ _write_audit_events(installation, gateway_server, caller, actor_label, [(tool_name, decision)])
+
+
def _evaluate_tool_call(
tools_by_name: dict[str, MCPServerInstallationTool],
item: dict[str, Any],
diff --git a/products/mcp_store/backend/test/test_gateway_exec_tools.py b/products/mcp_store/backend/test/test_gateway_exec_tools.py
new file mode 100644
index 000000000000..2e7b8ee5021c
--- /dev/null
+++ b/products/mcp_store/backend/test/test_gateway_exec_tools.py
@@ -0,0 +1,243 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+from rest_framework import status
+
+from products.mcp_store.backend.models import (
+ MCPAuditEvent,
+ MCPGatewayServer,
+ MCPMemberServerRevocation,
+ MCPServerInstallation,
+ MCPServerInstallationTool,
+)
+
+_UPSTREAM_RESULT = {"content": [{"type": "text", "text": "done"}], "isError": False}
+
+
+class TestGatewayExecTools(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.server = MCPGatewayServer.objects.for_team(self.team.id).create(
+ team=self.team,
+ name="Linear",
+ url="https://mcp.linear.example.com/mcp",
+ )
+ self.installation = MCPServerInstallation.objects.create(
+ team=self.team,
+ user=self.user,
+ gateway_server=self.server,
+ display_name="Linear",
+ url=self.server.url,
+ auth_type="api_key",
+ sensitive_configuration={"api_key": "sk-test"},
+ )
+
+ def _tool(self, *, name: str = "create_issue", state: str = "approved", removed: bool = False, **kwargs):
+ return MCPServerInstallationTool.objects.create(
+ installation=kwargs.pop("installation", self.installation),
+ tool_name=name,
+ description=kwargs.pop("description", "Create an issue"),
+ input_schema=kwargs.pop("input_schema", {"type": "object", "properties": {"title": {"type": "string"}}}),
+ approval_state=state,
+ last_seen_at=timezone.now(),
+ removed_at=timezone.now() if removed else None,
+ **kwargs,
+ )
+
+ def _call(self, installation_id=None, tool_name: str = "create_issue", arguments=None):
+ return self.client.post(
+ f"/api/projects/{self.team.id}/mcp_server_installations/{installation_id or self.installation.id}/call_tool/",
+ {"tool_name": tool_name, "arguments": arguments or {"title": "Bug"}},
+ format="json",
+ )
+
+ def _available(self):
+ return self.client.get(f"/api/projects/{self.team.id}/mcp_server_installations/available_tools/")
+
+ @parameterized.expand(
+ [
+ ("approved", "approved", False, status.HTTP_200_OK, True, "approved"),
+ ("needs_approval", "needs_approval", False, status.HTTP_403_FORBIDDEN, False, "pending"),
+ ("do_not_use", "do_not_use", False, status.HTTP_403_FORBIDDEN, False, "blocked"),
+ ("removed_upstream", "approved", True, status.HTTP_404_NOT_FOUND, False, "blocked"),
+ ]
+ )
+ @patch("products.mcp_store.backend.presentation.views.call_upstream_tool", return_value=_UPSTREAM_RESULT)
+ def test_call_tool_enforces_policy_and_audits(
+ self, _name, state, removed, expected_status, expect_upstream, expected_decision, mock_call
+ ):
+ self._tool(state=state, removed=removed)
+
+ response = self._call()
+
+ assert response.status_code == expected_status, response.json()
+ assert mock_call.called is expect_upstream
+ audit = MCPAuditEvent.objects.for_team(self.team.id).get(tool_name="create_issue")
+ assert audit.decision == expected_decision
+ assert audit.actor_user_id == self.user.id
+
+ @patch("products.mcp_store.backend.presentation.views.call_upstream_tool", return_value=_UPSTREAM_RESULT)
+ def test_call_tool_returns_upstream_text(self, mock_call):
+ self._tool()
+
+ response = self._call()
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {
+ "content": [{"type": "text", "text": "done"}],
+ "is_error": False,
+ "structured_content": None,
+ }
+ assert mock_call.call_args.args[1:] == ("create_issue", {"title": "Bug"})
+
+ @parameterized.expand(
+ [
+ ("string", "not a list"),
+ ("int", 42),
+ ("dict", {"type": "text", "text": "done"}),
+ ]
+ )
+ def test_call_tool_tolerates_non_list_upstream_content(self, _name, malformed_content):
+ self._tool()
+
+ with patch(
+ "products.mcp_store.backend.presentation.views.call_upstream_tool",
+ return_value={"content": malformed_content, "isError": False},
+ ):
+ response = self._call()
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["content"] == []
+
+ @patch("products.mcp_store.backend.presentation.views.call_upstream_tool")
+ def test_call_tool_rejects_unregistered_tool_without_calling_upstream(self, mock_call):
+ self._tool()
+
+ response = self._call(tool_name="delete_everything")
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ assert response.json()["reason"] == "removed"
+ assert not mock_call.called
+ assert not MCPAuditEvent.objects.for_team(self.team.id).exists()
+
+ @parameterized.expand([("server_disabled_for_team",), ("member_revoked",)])
+ @patch("products.mcp_store.backend.presentation.views.call_upstream_tool")
+ def test_call_tool_honors_admin_kill_switches(self, scenario, mock_call):
+ self._tool()
+ if scenario == "server_disabled_for_team":
+ self.server.is_team_enabled = False
+ self.server.save()
+ else:
+ MCPMemberServerRevocation.objects.for_team(self.team.id).create(
+ team=self.team, gateway_server=self.server, user=self.user
+ )
+
+ response = self._call()
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not mock_call.called
+
+ def test_available_tools_lists_callable_tools_with_schema(self):
+ self._tool()
+
+ response = self._available()
+
+ assert response.status_code == status.HTTP_200_OK
+ servers = response.json()["servers"]
+ assert len(servers) == 1
+ assert servers[0]["slug"] == "linear"
+ assert servers[0]["installation_id"] == str(self.installation.id)
+ assert servers[0]["tools"] == [
+ {
+ "name": "create_issue",
+ "description": "Create an issue",
+ "input_schema": {"type": "object", "properties": {"title": {"type": "string"}}},
+ "annotations": {},
+ "approval_state": "approved",
+ }
+ ]
+
+ @parameterized.expand(
+ [
+ ("do_not_use_tool",),
+ ("removed_tool",),
+ ("another_users_personal_install",),
+ ("server_disabled_for_team",),
+ ("member_revoked",),
+ ("installation_disabled",),
+ ("oauth_needs_reauth",),
+ ]
+ )
+ def test_available_tools_omits_unreachable_tools(self, scenario):
+ if scenario == "another_users_personal_install":
+ other = self._create_user("[email protected]")
+ other_installation = MCPServerInstallation.objects.create(
+ team=self.team,
+ user=other,
+ gateway_server=self.server,
+ display_name="Linear",
+ url="https://mcp.linear-other.example.com/mcp",
+ auth_type="api_key",
+ sensitive_configuration={"api_key": "sk-other"},
+ )
+ self._tool(installation=other_installation)
+ else:
+ self._tool(
+ state="do_not_use" if scenario == "do_not_use_tool" else "approved",
+ removed=scenario == "removed_tool",
+ )
+
+ if scenario == "server_disabled_for_team":
+ self.server.is_team_enabled = False
+ self.server.save()
+ elif scenario == "member_revoked":
+ MCPMemberServerRevocation.objects.for_team(self.team.id).create(
+ team=self.team, gateway_server=self.server, user=self.user
+ )
+ elif scenario == "installation_disabled":
+ self.installation.is_enabled = False
+ self.installation.save()
+ elif scenario == "oauth_needs_reauth":
+ self.installation.auth_type = "oauth"
+ self.installation.sensitive_configuration = {"access_token": "tok", "needs_reauth": True}
+ self.installation.save()
+
+ assert self._available().json()["servers"] == []
+
+ def test_available_tools_includes_a_teammates_shared_connection(self):
+ other = self._create_user("[email protected]")
+ shared = MCPServerInstallation.objects.create(
+ team=self.team,
+ user=other,
+ scope="shared",
+ gateway_server=self.server,
+ display_name="Linear",
+ url="https://mcp.linear-shared.example.com/mcp",
+ auth_type="api_key",
+ sensitive_configuration={"api_key": "sk-shared"},
+ )
+ self._tool(installation=shared)
+
+ servers = self._available().json()["servers"]
+
+ assert [s["installation_id"] for s in servers] == [str(shared.id)]
+
+ def test_available_tools_gives_same_named_connections_distinct_slugs(self):
+ self._tool()
+ second = MCPServerInstallation.objects.create(
+ team=self.team,
+ user=self.user,
+ gateway_server=self.server,
+ display_name="Linear",
+ url="https://mcp.linear-second.example.com/mcp",
+ auth_type="api_key",
+ sensitive_configuration={"api_key": "sk-second"},
+ )
+ self._tool(installation=second)
+
+ slugs = [s["slug"] for s in self._available().json()["servers"]]
+
+ assert sorted(slugs) == ["linear", "linear-2"]
diff --git a/products/mcp_store/backend/test/test_tools.py b/products/mcp_store/backend/test/test_tools.py
index 23d662b2d5b0..a20c7fd87e6b 100644
--- a/products/mcp_store/backend/test/test_tools.py
+++ b/products/mcp_store/backend/test/test_tools.py
@@ -8,11 +8,15 @@ from unittest.mock import MagicMock, patch
from django.utils import timezone
import httpx
+from parameterized import parameterized
from products.mcp_store.backend.models import MCPServerInstallation, MCPServerInstallationTool
from products.mcp_store.backend.tools import (
+ CALL_TIMEOUT,
HANDSHAKE_TIMEOUT,
+ ToolCallError,
ToolsFetchError,
+ call_upstream_tool,
fetch_upstream_tools,
sync_installation_tools,
)
@@ -228,6 +232,112 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
fetch_upstream_tools(installation)
+class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):
+ def _installation(self) -> MCPServerInstallation:
+ return MCPServerInstallation.objects.create(
+ team=self.team,
+ user=self.user,
+ url=f"https://mcp-{uuid.uuid4().hex[:8]}.example.com/mcp",
+ display_name="Test",
+ auth_type="api_key",
+ sensitive_configuration={"api_key": "sk-test"},
+ )
+
+ @patch("products.mcp_store.backend.tools.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
+ # initialize, so losing the session header would break every real call while
+ # still passing a test that only inspects the JSON body.
+ installation = self._installation()
+ call_body = json.dumps({"jsonrpc": "2.0", "id": 3, "result": {"content": [{"type": "text", "text": "ok"}]}})
+ client = _install_handshake_mock(mock_client_cls, tools_list_response=_build_response(body=call_body))
+
+ result = call_upstream_tool(installation, "create_issue", {"title": "Bug"})
+
+ 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 json.loads(call_post.kwargs["content"]) == {
+ "jsonrpc": "2.0",
+ "id": 3,
+ "method": "tools/call",
+ "params": {"name": "create_issue", "arguments": {"title": "Bug"}},
+ }
+ # A real tool call does upstream work, so it must not inherit the tight
+ # discovery timeout.
+ assert mock_client_cls.call_args.kwargs["timeout"] == CALL_TIMEOUT
+
+ @parameterized.expand(
+ [
+ (
+ "plain_json",
+ json.dumps({"jsonrpc": "2.0", "id": 3, "result": {"content": [{"type": "text", "text": "ok"}]}}),
+ "application/json",
+ ),
+ (
+ "sse_framed",
+ 'event: message\ndata: {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"ok"}]}}\n\n',
+ "text/event-stream",
+ ),
+ ]
+ )
+ @patch("products.mcp_store.backend.tools.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()
+ _install_handshake_mock(
+ mock_client_cls, tools_list_response=_build_response(body=body, content_type=content_type)
+ )
+
+ 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.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).
+ # Raising here would hide the reason the agent needs in order to retry.
+ installation = self._installation()
+ body = json.dumps(
+ {
+ "jsonrpc": "2.0",
+ "id": 3,
+ "result": {"content": [{"type": "text", "text": "title is required"}], "isError": True},
+ }
+ )
+ _install_handshake_mock(mock_client_cls, tools_list_response=_build_response(body=body))
+
+ result = call_upstream_tool(installation, "create_issue", {})
+
+ assert result["isError"] is True
+ assert result["content"] == [{"type": "text", "text": "title is required"}]
+
+ @parameterized.expand(
+ [
+ (
+ "jsonrpc_error",
+ json.dumps({"jsonrpc": "2.0", "id": 3, "error": {"code": -32602, "message": "bad params"}}),
+ "returned error",
+ ),
+ ("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.tools.httpx.Client")
+ def test_call_raises_on_protocol_failures(self, _name, body, expected_message, mock_client_cls, _allow):
+ installation = self._installation()
+ _install_handshake_mock(mock_client_cls, tools_list_response=_build_response(body=body))
+
+ 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"))
+ def test_call_refuses_a_blocked_url(self, _allow):
+ installation = self._installation()
+ with pytest.raises(ToolCallError, match="URL not allowed"):
+ call_upstream_tool(installation, "create_issue", {})
+
+
class TestSyncInstallationTools(ClickhouseTestMixin, APIBaseTest):
def _installation(self) -> MCPServerInstallation:
return MCPServerInstallation.objects.create(
diff --git a/products/mcp_store/backend/tools.py b/products/mcp_store/backend/tools.py
index 65da2f5b7d6d..fbdcfdc9e46b 100644
--- a/products/mcp_store/backend/tools.py
+++ b/products/mcp_store/backend/tools.py
@@ -26,6 +26,7 @@ logger = structlog.get_logger(__name__)
# pick stable ones so response matching in _parse_jsonrpc_response is trivial.
_INITIALIZE_ID = 1
_TOOLS_LIST_ID = 2
+_TOOLS_CALL_ID = 3
# MCP protocol version we claim to speak. Kept in sync with what the PostHog
# MCP reference client sends; bump when the spec changes in a backwards-
@@ -38,11 +39,22 @@ _CLIENT_INFO: dict[str, Any] = {"name": "posthog-mcp-store", "version": "1.0"}
# covers real tool execution) so a hung upstream can't pin a Django worker.
HANDSHAKE_TIMEOUT = 10
+# 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
+# interactive agent, and a worker blocked for minutes is worse than a retry.
+CALL_TIMEOUT = 60
+
class ToolsFetchError(Exception):
pass
+class ToolCallError(Exception):
+ """An upstream ``tools/call`` failed. Distinct from ToolsFetchError so
+ callers can tell "we couldn't discover tools" from "the call itself
+ failed" — they surface differently to an agent."""
+
+
def _ensure_valid_token_for_fetch(installation: MCPServerInstallation) -> None:
if installation.auth_type != "oauth":
return
@@ -100,6 +112,53 @@ def fetch_upstream_tools(installation: MCPServerInstallation) -> list[dict[str,
raise ToolsFetchError("Upstream MCP server timed out") from exc
+def call_upstream_tool(
+ installation: MCPServerInstallation,
+ tool_name: str,
+ arguments: dict[str, Any],
+) -> dict[str, Any]:
+ """Invoke one tool on the upstream MCP server and return its ``result`` object.
+
+ Same short-lived handshake as :func:`fetch_upstream_tools` — servers hand out a
+ session on ``initialize`` and most reject ``tools/call`` without it — so the two
+ paths share the SSRF guard, auth headers and redirect handling.
+
+ Approval and audit are *not* handled here: the caller runs the request through
+ the gateway's policy engine first (see ``enforce_tool_approval``), so this stays
+ a transport concern.
+ """
+ allowed, reason = is_url_allowed(installation.url)
+ if not allowed:
+ raise ToolCallError(f"URL not allowed: {reason}")
+
+ _ensure_valid_token_for_fetch(installation)
+
+ auth_headers = build_upstream_auth_headers(installation)
+ base_headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ **auth_headers,
+ }
+
+ try:
+ with httpx.Client(timeout=CALL_TIMEOUT) as client:
+ session_id, upstream_url = _mcp_initialize(client, installation.url, base_headers)
+ session_headers = dict(base_headers)
+ if session_id:
+ session_headers["Mcp-Session-Id"] = session_id
+
+ _mcp_send_initialized(client, upstream_url, session_headers)
+ try:
+ return _mcp_call_tool(client, upstream_url, session_headers, tool_name, arguments)
+ finally:
+ if session_id:
+ _mcp_terminate_session(client, upstream_url, session_headers)
+ except httpx.ConnectError as exc:
+ raise ToolCallError("Upstream MCP server unreachable") from exc
+ except httpx.TimeoutException as exc:
+ raise ToolCallError("Upstream MCP server timed out") from exc
+
+
def _post_with_same_origin_redirect(
client: httpx.Client,
url: str,
@@ -200,6 +259,53 @@ def _mcp_list_tools(client: httpx.Client, url: str, headers: dict[str, str]) ->
return [t for t in tools if isinstance(t, dict) and t.get("name")]
+def _mcp_call_tool(
+ client: httpx.Client,
+ url: str,
+ headers: dict[str, str],
+ tool_name: str,
+ arguments: dict[str, Any],
+) -> dict[str, Any]:
+ body = json.dumps(
+ {
+ "jsonrpc": "2.0",
+ "id": _TOOLS_CALL_ID,
+ "method": "tools/call",
+ "params": {"name": tool_name, "arguments": arguments},
+ }
+ ).encode()
+
+ response, upstream_url = _post_with_same_origin_redirect(client, url, content=body, headers=headers)
+ if response.status_code >= 400:
+ logger.warning(
+ "tools/call request returned error",
+ url=upstream_url,
+ tool_name=tool_name,
+ status_code=response.status_code,
+ body=response.text[:500],
+ )
+ raise ToolCallError(f"Upstream returned status {response.status_code}")
+
+ payload = _parse_jsonrpc_response(
+ response.text,
+ response.headers.get("content-type", ""),
+ _TOOLS_CALL_ID,
+ request_name="tools/call",
+ error_class=ToolCallError,
+ )
+ if isinstance(payload, dict) and payload.get("error"):
+ raise ToolCallError(f"Upstream tools/call returned error: {payload['error']}")
+
+ result = (payload or {}).get("result") if isinstance(payload, dict) else None
+ if not isinstance(result, dict):
+ raise ToolCallError("tools/call response missing 'result' object")
+
+ # A result with `isError` set is the tool telling the *model* it failed (bad
+ # arguments, not-found, ...), not a transport fault. Pass it through so the
+ # agent can correct itself instead of seeing an opaque gateway error.
+ return result
+
+
def _mcp_terminate_session(client: httpx.Client, url: str, headers: dict[str, str]) -> None:
try:
client.delete(url, headers=headers)
@@ -207,7 +313,14 @@ def _mcp_terminate_session(client: httpx.Client, url: str, headers: dict[str, st
logger.warning("session DELETE failed; ignoring", url=url, error=str(exc))
-def _parse_jsonrpc_response(body: str, content_type: str, expected_id: int, *, request_name: str) -> dict[str, Any]:
+def _parse_jsonrpc_response(
+ body: str,
+ content_type: str,
+ expected_id: int,
+ *,
+ request_name: str,
+ error_class: type[Exception] = ToolsFetchError,
+) -> dict[str, Any]:
"""Parse a JSON-RPC response body that may be plain JSON or SSE-wrapped.
MCP streamable HTTP servers can reply either directly with JSON or over an
@@ -231,13 +344,13 @@ def _parse_jsonrpc_response(body: str, content_type: str, expected_id: int, *, r
continue
if isinstance(parsed, dict) and parsed.get("id") == expected_id:
return parsed
- raise ToolsFetchError(
+ raise error_class(
f"Upstream {request_name} SSE response did not contain a JSON-RPC message with id={expected_id}"
)
try:
return json.loads(body)
except ValueError as exc:
- raise ToolsFetchError(
+ raise error_class(
f"Upstream {request_name} response was not JSON "
f"(content-type={content_type_lower!r}, body_preview={body[:200]!r})"
) from exc
diff --git a/products/mcp_store/frontend/generated/api.schemas.ts b/products/mcp_store/frontend/generated/api.schemas.ts
index 367cf62c329f..277308470afb 100644
--- a/products/mcp_store/frontend/generated/api.schemas.ts
+++ b/products/mcp_store/frontend/generated/api.schemas.ts
@@ -567,6 +567,11 @@ export const ScopeTypeEnumApi = {
Agent: 'agent',
} as const
+/**
+ * * `approved` - Approved
+ * * `needs_approval` - Needs approval
+ * * `do_not_use` - Do not use
+ */
export type MCPToolApprovalStateEnumApi = (typeof MCPToolApprovalStateEnumApi)[keyof typeof MCPToolApprovalStateEnumApi]
export const MCPToolApprovalStateEnumApi = {
@@ -855,6 +860,69 @@ export interface PatchedMCPServerInstallationUpdateApi {
is_enabled?: boolean
}
+/**
+ * Arguments object passed straight to the tool, matching its input schema.
+ */
+export type CallToolRequestApiArguments = { [key: string]: unknown }
+
+export interface CallToolRequestApi {
+ /**
+ * Name of the tool to invoke, exactly as the upstream server reports it.
+ * @maxLength 200
+ */
+ tool_name: string
+ /** Arguments object passed straight to the tool, matching its input schema. */
+ arguments?: CallToolRequestApiArguments
+}
+
+export type CallToolResponseApiContentItem = { [key: string]: unknown }
+
+/**
+ * Structured result the tool returned alongside `content`, when it provides one.
+ * @nullable
+ */
+export type CallToolResponseApiStructuredContent = { [key: string]: unknown } | null
+
+export interface CallToolResponseApi {
+ /** MCP content blocks the tool returned, in upstream order. */
+ content: CallToolResponseApiContentItem[]
+ /** True when the tool itself reported failure (for example bad arguments). The call reached the server; read `content` for the reason. */
+ is_error: boolean
+ /**
+ * Structured result the tool returned alongside `content`, when it provides one.
+ * @nullable
+ */
+ structured_content?: CallToolResponseApiStructuredContent
+}
+
+/**
+ * * `needs_approval` - needs_approval
+ * * `disabled` - disabled
+ * * `removed` - removed
+ * * `upstream_error` - upstream_error
+ */
+export type CallToolBlockedReasonEnumApi =
+ (typeof CallToolBlockedReasonEnumApi)[keyof typeof CallToolBlockedReasonEnumApi]
+
+export const CallToolBlockedReasonEnumApi = {
+ NeedsApproval: 'needs_approval',
+ Disabled: 'disabled',
+ Removed: 'removed',
+ UpstreamError: 'upstream_error',
+} as const
+
+export interface CallToolBlockedApi {
+ /** Why the call was refused, phrased for the calling agent. */
+ detail: string
+ /** Machine-readable refusal cause, so callers can prompt for approval instead of retrying.
+ *
+ * * `needs_approval` - needs_approval
+ * * `disabled` - disabled
+ * * `removed` - removed
+ * * `upstream_error` - upstream_error */
+ reason: CallToolBlockedReasonEnumApi
+}
+
export interface MCPServerInstallationToolApi {
readonly id: string
readonly tool_name: string
@@ -904,6 +972,49 @@ export interface PatchedToolApprovalUpdateApi {
approval_state?: ToolApprovalUpdateApprovalStateEnumApi
}
+/**
+ * JSON Schema for the tool's arguments.
+ */
+export type AvailableToolApiInputSchema = { [key: string]: unknown }
+
+/**
+ * MCP tool annotations the upstream server declared (destructiveHint, readOnlyHint, ...). Advisory only — policy may escalate them, never loosen them.
+ */
+export type AvailableToolApiAnnotations = { [key: string]: unknown }
+
+export interface AvailableToolApi {
+ /** Tool name as the upstream server reports it. */
+ name: string
+ /** Upstream tool description. */
+ description: string
+ /** JSON Schema for the tool's arguments. */
+ input_schema: AvailableToolApiInputSchema
+ /** MCP tool annotations the upstream server declared (destructiveHint, readOnlyHint, ...). Advisory only — policy may escalate them, never loosen them. */
+ annotations: AvailableToolApiAnnotations
+ /** Effective gateway state. `needs_approval` tools are listed so callers can explain why a call would fail rather than pretending the capability is missing.
+ *
+ * * `approved` - Approved
+ * * `needs_approval` - Needs approval
+ * * `do_not_use` - Do not use */
+ approval_state: MCPToolApprovalStateEnumApi
+}
+
+export interface AvailableServerApi {
+ /** Installation to send `call_tool` requests to. */
+ installation_id: string
+ /** Human-readable server name. */
+ name: string
+ /** Stable lowercase identifier used to namespace tool names. */
+ slug: string
+ /** Callable tools on this server. */
+ tools: AvailableToolApi[]
+}
+
+export interface AvailableToolsResponseApi {
+ /** Connected servers the caller can reach. */
+ servers: AvailableServerApi[]
+}
+
/**
* * `api_key` - api_key
* * `oauth` - oauth
diff --git a/products/mcp_store/frontend/generated/api.ts b/products/mcp_store/frontend/generated/api.ts
index 6de215119e25..fc7568934218 100644
--- a/products/mcp_store/frontend/generated/api.ts
+++ b/products/mcp_store/frontend/generated/api.ts
@@ -11,6 +11,9 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
ApplyPresetApi,
AuditCountsApi,
+ AvailableToolsResponseApi,
+ CallToolRequestApi,
+ CallToolResponseApi,
GatewayConfigUpdateApi,
GatewayMemberSummaryApi,
GatewayPoliciesUpsertApi,
@@ -864,6 +867,31 @@ export const mcpServerInstallationsDestroy = async (
})
}
+export const getMcpServerInstallationsCallToolCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/mcp_server_installations/${id}/call_tool/`
+}
+
+/**
+ * Invoke one tool on a connected MCP server.
+ *
+ * The request/response shape is plain REST rather than the JSON-RPC envelope
+ * `proxy` speaks, because the caller here is an agent surface (the PostHog MCP's
+ * `exec`) that wants one tool result, not an MCP transport of its own.
+ */
+export const mcpServerInstallationsCallToolCreate = async (
+ projectId: string,
+ id: string,
+ callToolRequestApi: CallToolRequestApi,
+ options?: RequestInit
+): Promise<CallToolResponseApi> => {
+ return apiMutator<CallToolResponseApi>(getMcpServerInstallationsCallToolCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(callToolRequestApi),
+ })
+}
+
export const getMcpServerInstallationsProxyCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/mcp_server_installations/${id}/proxy/`
}
@@ -1025,6 +1053,29 @@ export const mcpServerInstallationsAuthorizeRetrieve = async (
})
}
+export const getMcpServerInstallationsAvailableToolsRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/mcp_server_installations/available_tools/`
+}
+
+/**
+ * Every tool the caller can currently reach, across all their connections.
+ *
+ * One request instead of one per connection: an agent surface resolving its
+ * tool list on each session cannot afford a fan-out. `do_not_use` and removed
+ * tools are omitted — an agent should not see what it cannot call — while
+ * `needs_approval` tools are listed with their state so the caller can explain
+ * the block rather than report the capability as missing.
+ */
+export const mcpServerInstallationsAvailableToolsRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<AvailableToolsResponseApi> => {
+ return apiMutator<AvailableToolsResponseApi>(getMcpServerInstallationsAvailableToolsRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getMcpServerInstallationsInstallCustomCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/mcp_server_installations/install_custom/`
}
diff --git a/products/mcp_store/frontend/generated/api.zod.ts b/products/mcp_store/frontend/generated/api.zod.ts
index 452e3637fc06..c1fff8bb97bc 100644
--- a/products/mcp_store/frontend/generated/api.zod.ts
+++ b/products/mcp_store/frontend/generated/api.zod.ts
@@ -289,6 +289,9 @@ export const McpGatewayServersPoliciesCreateBody = /* @__PURE__ */ zod.object({
.describe('Tool to set the policy for, up to 200 characters.'),
policy_state: zod
.enum(['approved', 'needs_approval', 'do_not_use'])
+ .describe(
+ '\* `approved` - Approved\n\* `needs_approval` - Needs approval\n\* `do_not_use` - Do not use'
+ )
.describe(
'State to apply for this scope.\n\n\* `approved` - Approved\n\* `needs_approval` - Needs approval\n\* `do_not_use` - Do not use'
),
@@ -356,6 +359,9 @@ export const McpGatewayServiceAccountsAccessCreateBody = /* @__PURE__ */ zod.obj
.describe('Tool to set the policy for, up to 200 characters.'),
policy_state: zod
.enum(['approved', 'needs_approval', 'do_not_use'])
+ .describe(
+ '\* `approved` - Approved\n\* `needs_approval` - Needs approval\n\* `do_not_use` - Do not use'
+ )
.describe(
'State to apply for this scope.\n\n\* `approved` - Approved\n\* `needs_approval` - Needs approval\n\* `do_not_use` - Do not use'
),
@@ -396,6 +402,26 @@ export const McpServerInstallationsPartialUpdateBody = /* @__PURE__ */ zod.objec
is_enabled: zod.boolean().optional(),
})
+/**
+ * Invoke one tool on a connected MCP server.
+ *
+ * The request/response shape is plain REST rather than the JSON-RPC envelope
+ * `proxy` speaks, because the caller here is an agent surface (the PostHog MCP's
+ * `exec`) that wants one tool result, not an MCP transport of its own.
+ */
+export const mcpServerInstallationsCallToolCreateBodyToolNameMax = 200
+
+export const McpServerInstallationsCallToolCreateBody = /* @__PURE__ */ zod.object({
+ tool_name: zod
+ .string()
+ .max(mcpServerInstallationsCallToolCreateBodyToolNameMax)
+ .describe('Name of the tool to invoke, exactly as the upstream server reports it.'),
+ arguments: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe('Arguments object passed straight to the tool, matching its input schema.'),
+})
+
export const mcpServerInstallationsProxyCreateBodyDisplayNameMax = 200
export const mcpServerInstallationsProxyCreateBodyUrlMax = 2048
diff --git a/products/mcp_store/mcp/tools.yaml b/products/mcp_store/mcp/tools.yaml
index 89db044d2634..e01b27e23169 100644
--- a/products/mcp_store/mcp/tools.yaml
+++ b/products/mcp_store/mcp/tools.yaml
@@ -162,6 +162,12 @@ tools:
mcp-gateway-service-accounts-update:
operation: mcp_gateway_service_accounts_update
enabled: false
+ mcp-server-installations-available-tools-retrieve:
+ operation: mcp_server_installations_available_tools_retrieve
+ enabled: false
+ mcp-server-installations-call-tool-create:
+ operation: mcp_server_installations_call_tool_create
+ enabled: false
mcp-server-installations-share-create:
operation: mcp_server_installations_share_create
enabled: false
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 0090b4c43bb1..b394af4229d3 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -1457,4 +1457,15 @@ export class ApiClient {
}
return result.data
}
+
+ /** Every third-party MCP tool the caller can reach, across all their gateway connections. */
+ async getGatewayTools(projectId: string): Promise<Schemas.AvailableToolsResponse> {
+ const result = await this.fetchJson<Schemas.AvailableToolsResponse>(
+ `${this.baseUrl}/api/projects/${projectId}/mcp_server_installations/available_tools/`
+ )
+ if (!result.success) {
+ throw new Error(result.error.message)
+ }
+ return result.data
+ }
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bc07dda5ad8e..cbdbc532f532 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9636,6 +9636,58 @@ export namespace Schemas {
detail_fields: AvailableFiltersResponseDetailFields;
}
+ /**
+ * * `approved` - Approved
+ * * `needs_approval` - Needs approval
+ * * `do_not_use` - Do not use
+ */
+ export type MCPToolApprovalStateEnum = typeof MCPToolApprovalStateEnum[keyof typeof MCPToolApprovalStateEnum];
+
+
+ export const MCPToolApprovalStateEnum = {
+ Approved: 'approved',
+ NeedsApproval: 'needs_approval',
+ DoNotUse: 'do_not_use',
+ } as const;
+
+ /**
+ * JSON Schema for the tool's arguments.
+ */
+ export type AvailableToolInputSchema = { [key: string]: unknown };
+
+ /**
+ * MCP tool annotations the upstream server declared (destructiveHint, readOnlyHint, ...). Advisory only — policy may escalate them, never loosen them.
+ */
+ export type AvailableToolAnnotations = { [key: string]: unknown };
+
+ export interface AvailableTool {
+ /** Tool name as the upstream server reports it. */
+ name: string;
+ /** Upstream tool description. */
+ description: string;
+ /** JSON Schema for the tool's arguments. */
+ input_schema: AvailableToolInputSchema;
+ /** MCP tool annotations the upstream server declared (destructiveHint, readOnlyHint, ...). Advisory only — policy may escalate them, never loosen them. */
+ annotations: AvailableToolAnnotations;
+ /** Effective gateway state. `needs_approval` tools are listed so callers can explain why a call would fail rather than pretending the capability is missing.
+ *
+ * * `approved` - Approved
+ * * `needs_approval` - Needs approval
+ * * `do_not_use` - Do not use */
+ approval_state: MCPToolApprovalStateEnum;
+ }
+
+ export interface AvailableServer {
+ /** Installation to send `call_tool` requests to. */
+ installation_id: string;
+ /** Human-readable server name. */
+ name: string;
+ /** Stable lowercase identifier used to namespace tool names. */
+ slug: string;
+ /** Callable tools on this server. */
+ tools: AvailableTool[];
+ }
+
/**
* * `ingest_first_event` - ingest_first_event
* * `set_up_reverse_proxy` - set_up_reverse_proxy
@@ -9776,6 +9828,11 @@ export namespace Schemas {
UsePosthogInSlack: 'use_posthog_in_slack',
} as const;
+ export interface AvailableToolsResponse {
+ /** Connected servers the caller can reach. */
+ servers: AvailableServer[];
+ }
+
export type AwsS3DestinationConfigType = typeof AwsS3DestinationConfigType[keyof typeof AwsS3DestinationConfigType];
@@ -13178,6 +13235,69 @@ export namespace Schemas {
version?: number | null;
}
+ /**
+ * * `needs_approval` - needs_approval
+ * * `disabled` - disabled
+ * * `removed` - removed
+ * * `upstream_error` - upstream_error
+ */
+ export type CallToolBlockedReasonEnum = typeof CallToolBlockedReasonEnum[keyof typeof CallToolBlockedReasonEnum];
+
+
+ export const CallToolBlockedReasonEnum = {
+ NeedsApproval: 'needs_approval',
+ Disabled: 'disabled',
+ Removed: 'removed',
+ UpstreamError: 'upstream_error',
+ } as const;
+
+ export interface CallToolBlocked {
+ /** Why the call was refused, phrased for the calling agent. */
+ detail: string;
+ /** Machine-readable refusal cause, so callers can prompt for approval instead of retrying.
+ *
+ * * `needs_approval` - needs_approval
+ * * `disabled` - disabled
+ * * `removed` - removed
+ * * `upstream_error` - upstream_error */
+ reason: CallToolBlockedReasonEnum;
+ }
+
+ /**
+ * Arguments object passed straight to the tool, matching its input schema.
+ */
+ export type CallToolRequestArguments = { [key: string]: unknown };
+
+ export interface CallToolRequest {
+ /**
+ * Name of the tool to invoke, exactly as the upstream server reports it.
+ * @maxLength 200
+ */
+ tool_name: string;
+ /** Arguments object passed straight to the tool, matching its input schema. */
+ arguments?: CallToolRequestArguments;
+ }
+
+ export type CallToolResponseContentItem = { [key: string]: unknown };
+
+ /**
+ * Structured result the tool returned alongside `content`, when it provides one.
+ * @nullable
+ */
+ export type CallToolResponseStructuredContent = { [key: string]: unknown } | null;
+
+ export interface CallToolResponse {
+ /** MCP content blocks the tool returned, in upstream order. */
+ content: CallToolResponseContentItem[];
+ /** True when the tool itself reported failure (for example bad arguments). The call reached the server; read `content` for the reason. */
+ is_error: boolean;
+ /**
+ * Structured result the tool returned alongside `content`, when it provides one.
+ * @nullable
+ */
+ structured_content?: CallToolResponseStructuredContent;
+ }
+
/**
* * `error` - error
* * `warning` - warning
@@ -34180,15 +34300,6 @@ export namespace Schemas {
Agent: 'agent',
} as const;
- export type MCPToolApprovalStateEnum = typeof MCPToolApprovalStateEnum[keyof typeof MCPToolApprovalStateEnum];
-
-
- export const MCPToolApprovalStateEnum = {
- Approved: 'approved',
- NeedsApproval: 'needs_approval',
- DoNotUse: 'do_not_use',
- } as const;
-
export interface ToolPolicyEntry {
/**
* Tool to set the policy for, up to 200 characters.
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index bfaf618e22c1..89d86fe2b473 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -1,7 +1,7 @@
import type { GroupType } from '@/api/client'
import { hasScope } from '@/lib/api'
import { MCPClientProfile } from '@/lib/client-detection'
-import { isCloudApi, isLocalApi, PRODUCT_DATA_CATALOG_FLAG } from '@/lib/constants'
+import { isCloudApi, isLocalApi, MCP_GATEWAY_FLAG, PRODUCT_DATA_CATALOG_FLAG } from '@/lib/constants'
import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'
import {
type EvaluatedFlags,
@@ -39,6 +39,18 @@ export interface ResolvedState {
sessionContext: MCPSessionContext | null
allTools: Tool<ZodObjectAny>[]
scopeGatedTools: ScopeGatedTool[]
+ /**
+ * Whether the caller's team may reach third-party MCP tools through `exec`.
+ * Gated on the same flag as the gateway UI — the tools are the gateway's payoff,
+ * so they roll out together. Also forced off in read-only mode: a connected
+ * server's tools can mutate and PostHog can't prove otherwise, so the catalog's
+ * read-only filter has no equivalent to apply to them.
+ *
+ * Deliberately not folded into `allTools`: `instructions.ts` looks every entry up in
+ * the static tool-definition registry (which throws on an unknown name) and renders
+ * the full roster into the instructions payload.
+ */
+ gatewayToolsEnabled: boolean
distinctId: string
renderUiEnabled: boolean
// Active project/user environment prompt and group types. Rendered into the
@@ -127,9 +139,10 @@ export class RequestStateResolver {
])
const clientContext = getEffectiveMCPClientContext(requestContext, sessionContext)
- // PRODUCT_DATA_CATALOG_FLAG gates instructions content (the metric-discovery prompt
- // section), not a tool, so the tool-definition scan can't discover it.
- const allFlagKeys = [...new Set([...getRequiredFeatureFlags(), PRODUCT_DATA_CATALOG_FLAG])]
+ // Neither of these gates a catalog tool, so the tool-definition scan can't discover
+ // them: PRODUCT_DATA_CATALOG_FLAG gates instructions content (the metric-discovery
+ // prompt section), MCP_GATEWAY_FLAG gates the third-party tools `exec` resolves.
+ const allFlagKeys = [...new Set([...getRequiredFeatureFlags(), PRODUCT_DATA_CATALOG_FLAG, MCP_GATEWAY_FLAG])]
const flagAnalyticsContext = await reqCtx.safelyGetAnalyticsContext(context)
const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefined
@@ -222,6 +235,7 @@ export class RequestStateResolver {
sessionContext,
allTools,
scopeGatedTools,
+ gatewayToolsEnabled: useSingleExec && !readOnly && mergedFlags[MCP_GATEWAY_FLAG] === true,
distinctId,
renderUiEnabled,
metadata,
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 5d771f170371..423dde8721e2 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -18,6 +18,7 @@ import {
findRecoverableApiError,
} from '@/lib/errors'
import { estimateTokens } from '@/lib/estimate-tokens'
+import { resolveGatewayTools } from '@/lib/gateway-tools'
import { getPostHogClient } from '@/lib/posthog'
import {
createExecTool,
@@ -29,7 +30,7 @@ import {
} from '@/tools/exec'
import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'
import { createRenderUiTool } from '@/tools/render-ui'
-import type { Context, ZodObjectAny } from '@/tools/types'
+import type { Context, Tool, ZodObjectAny } from '@/tools/types'
import {
trackExecuteSqlGeneration,
@@ -426,6 +427,24 @@ export class ToolExecutor {
}
}
+ /**
+ * Third-party MCP tools for this caller, or none if the gateway can't be reached.
+ * Swallows failures on purpose: a connected server having a bad day must not stop
+ * PostHog's own tools from working.
+ */
+ private async gatewayToolsFor(state: ResolvedState): Promise<Tool<ZodObjectAny>[]> {
+ const projectId = await state.context.stateManager.getProjectId().catch(() => undefined)
+ if (!projectId) {
+ return []
+ }
+ try {
+ return await resolveGatewayTools(state.context, projectId)
+ } catch (error) {
+ console.warn('[gateway-tools] failed to resolve connected MCP tools', error)
+ return []
+ }
+ }
+
private resolveExecTool(
state: ResolvedState,
execMetrics: ExecMetricState,
@@ -494,6 +513,7 @@ export class ToolExecutor {
{
isInlineExecUiHost: state.clientProfile.isInlineExecUiHost(),
helpCatalog: this.instructionsBuilder.buildExecHelpCatalog(state),
+ ...(state.gatewayToolsEnabled ? { gatewayToolsProvider: () => this.gatewayToolsFor(state) } : {}),
}
)
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index 2fc09cfc6c27..c7e2b54a0729 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -11,10 +11,12 @@ import {
import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'
import { getPostHogClient } from '@/lib/posthog'
import { sanitizeHeaderValue } from '@/lib/utils'
+import type { Schemas } from '@/api/generated'
import type { ApiUser } from '@/schema/api'
import type { CachedOrg, CachedProject, CachedUser, State } from '@/tools/types'
const CACHE_TTL_MS = 10 * 60 * 1000 // 10 minutes
+const GATEWAY_TOOLS_CACHE_TTL_MS = 2 * 60 * 1000 // 2 minutes
// Entitlement-related fields shared by both org shapes we read from — the
// standalone org endpoint and the org embedded in `/api/users/@me/`.
@@ -283,8 +285,8 @@ export class StateManager {
return projectId
}
- private isCacheStale(fetchedAt: number | undefined): boolean {
- return !fetchedAt || Date.now() - fetchedAt > CACHE_TTL_MS
+ private isCacheStale(fetchedAt: number | undefined, ttlMs: number = CACHE_TTL_MS): boolean {
+ return !fetchedAt || Date.now() - fetchedAt > ttlMs
}
/**
@@ -298,13 +300,14 @@ export class StateManager {
cacheKey: D
fetchedAtKey: F
fetcher: () => Promise<NonNullable<State[D]>>
+ ttlMs?: number
}): Promise<State[D]> {
const [cached, fetchedAt] = (await Promise.all([
this._cache.get(opts.cacheKey),
this._cache.get(opts.fetchedAtKey),
])) as [State[D], number | undefined]
- if (!this.isCacheStale(fetchedAt)) {
+ if (!this.isCacheStale(fetchedAt, opts.ttlMs)) {
return cached
}
@@ -389,6 +392,23 @@ export class StateManager {
})
}
+ /**
+ * The third-party MCP tools this user can reach, from the gateway.
+ *
+ * Shorter TTL than the other cached entities: connecting a server is a deliberate
+ * act and the user expects its tools to appear on the next command, not ten minutes
+ * later. Cheap enough to re-fetch — it's one request, and only `exec` triggers it.
+ */
+ async getOrFetchGatewayTools(projectId: string): Promise<Schemas.AvailableToolsResponse | undefined> {
+ return this.getOrFetchCached({
+ name: 'gateway_tools',
+ cacheKey: `gatewayTools:${projectId}` as const,
+ fetchedAtKey: `gatewayToolsFetchedAt:${projectId}` as const,
+ fetcher: () => this._api.getGatewayTools(projectId),
+ ttlMs: GATEWAY_TOOLS_CACHE_TTL_MS,
+ })
+ }
+
async getEnvironmentPrompt(): Promise<string | undefined> {
const [user, org, project] = await Promise.all([
this.getCachedOrFetchUser().catch(() => undefined),
diff --git a/services/mcp/src/lib/constants.ts b/services/mcp/src/lib/constants.ts
index ca1eec471280..7af242779599 100644
--- a/services/mcp/src/lib/constants.ts
+++ b/services/mcp/src/lib/constants.ts
@@ -26,3 +26,7 @@ export const MCP_ANALYTICS_SOURCE = 'posthog_mcp_analytics'
// Gates the semantic layer (governed-metrics catalog) — no tool declares it, so it must be
// joined into the evaluated flag set explicitly; instructions content branches on it.
export const PRODUCT_DATA_CATALOG_FLAG = 'product-data-catalog'
+
+// Gates reaching third-party MCP servers connected through the MCP gateway. Same flag as
+// the gateway's own UI in the main app, so a team gets the tools when it gets the gateway.
+export const MCP_GATEWAY_FLAG = 'mcp-gateway'
diff --git a/services/mcp/src/lib/gateway-tools.ts b/services/mcp/src/lib/gateway-tools.ts
new file mode 100644
index 000000000000..5ee61de53e62
--- /dev/null
+++ b/services/mcp/src/lib/gateway-tools.ts
@@ -0,0 +1,178 @@
+/**
+ * Third-party MCP tools, reachable through the PostHog MCP.
+ *
+ * The MCP gateway (`products/mcp_store`) already holds the credentials, per-tool policy
+ * and audit trail for the servers a team has connected. This module surfaces those tools
+ * to `exec` so an external agent can search and call them without authenticating each
+ * vendor separately.
+ *
+ * Tools resolved here are deliberately kept out of `ResolvedState.allTools`: the
+ * instructions builder looks every entry up in the static tool-definition registry, and
+ * a vendor tool has no definition there. They ride a separate channel into `exec`
+ * instead (see `createExecTool`'s `gatewayToolsProvider`).
+ */
+
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import { ExecCommandError } from '@/lib/errors'
+import type { Context, Tool, ZodObjectAny } from '@/tools/types'
+
+/** Separates the server slug from the upstream tool name. PostHog's own tool names are
+ * kebab-case and never contain `__`, so a namespaced name can't collide with one. */
+export const GATEWAY_TOOL_SEPARATOR = '__'
+
+type AvailableServer = Schemas.AvailableServer
+type AvailableTool = Schemas.AvailableTool
+
+/** Where a namespaced tool name routes to, resolved once per session. */
+interface GatewayToolTarget {
+ installationId: string
+ serverName: string
+ toolName: string
+}
+
+export function gatewayToolName(slug: string, toolName: string): string {
+ return `${slug}${GATEWAY_TOOL_SEPARATOR}${toolName}`
+}
+
+/**
+ * Upstream tools declare their contract as JSON Schema, which the upstream server also
+ * enforces. Validating a second time here would only add a way for us to reject a call
+ * the vendor would have accepted, so the Zod schema stays permissive and the real schema
+ * travels on `rawInputSchema` for `exec info` to render.
+ */
+const PERMISSIVE_ARGS_SCHEMA = z.looseObject({})
+
+function annotationsFor(tool: AvailableTool): Tool['annotations'] {
+ const declared = (tool.annotations ?? {}) as Record<string, unknown>
+ // Absent hints take the MCP spec's defaults, which are also the cautious reading:
+ // a tool is assumed destructive and non-read-only until it says otherwise. Inverting
+ // that would let a server that declares nothing look safer than one that does.
+ return {
+ destructiveHint: declared['destructiveHint'] !== false,
+ idempotentHint: declared['idempotentHint'] === true,
+ openWorldHint: declared['openWorldHint'] !== false,
+ readOnlyHint: declared['readOnlyHint'] === true,
+ }
+}
+
+function describeTool(server: AvailableServer, tool: AvailableTool): string {
+ const base = tool.description?.trim() || `Tool exposed by ${server.name}.`
+ if (tool.approval_state === 'needs_approval') {
+ return `${base}\n\n[Not yet approved: calling this will fail until someone approves it in PostHog under Settings → MCP servers.]`
+ }
+ return `${base}\n\n[Runs on ${server.name} via your PostHog MCP connection.]`
+}
+
+function extractText(content: Record<string, unknown>[]): string {
+ const parts = content
+ .filter((block) => block['type'] === 'text' && typeof block['text'] === 'string')
+ .map((block) => block['text'] as string)
+ return parts.join('\n')
+}
+
+async function callGatewayTool(
+ context: Context,
+ projectId: string,
+ target: GatewayToolTarget,
+ args: Record<string, unknown>
+): Promise<unknown> {
+ let response: Schemas.CallToolResponse
+ try {
+ response = await context.api.request<Schemas.CallToolResponse>({
+ method: 'POST',
+ path: `/api/projects/${projectId}/mcp_server_installations/${target.installationId}/call_tool/`,
+ body: { tool_name: target.toolName, arguments: args },
+ })
+ } catch (error) {
+ // The gateway refuses a call with a typed reason (needs approval, disabled by
+ // policy, removed upstream). Surface that verbatim: it tells the agent whether
+ // to stop or to ask the user for something, which a bare HTTP error does not.
+ const refusal = parseRefusal(error)
+ if (refusal) {
+ throw new ExecCommandError(refusal, 'unknown_tool')
+ }
+ throw error
+ }
+
+ const content = (response.content ?? []) as Record<string, unknown>[]
+ const text = extractText(content)
+ if (response.is_error) {
+ // The tool ran and reported failure. Not an exec-level error — hand the reason
+ // back so the agent can fix its arguments and retry.
+ return { error: text || `${target.toolName} reported an error`, server: target.serverName }
+ }
+ if (response.structured_content) {
+ return response.structured_content
+ }
+ return text || content
+}
+
+/** Pull the gateway's `{detail, reason}` body out of an API error, if that's what it is. */
+function parseRefusal(error: unknown): string | undefined {
+ const body = (error as { body?: unknown } | undefined)?.body
+ if (typeof body !== 'string') {
+ return undefined
+ }
+ try {
+ const parsed = JSON.parse(body) as { detail?: unknown; reason?: unknown }
+ if (typeof parsed.detail === 'string' && typeof parsed.reason === 'string') {
+ return parsed.detail
+ }
+ } catch {
+ return undefined
+ }
+ return undefined
+}
+
+/**
+ * Turn the gateway's `available_tools` payload into callable `Tool`s.
+ *
+ * Names are namespaced by the server slug the backend assigned, which is stable across
+ * requests and unique within a payload — so a name resolved by `exec search` still routes
+ * correctly when `exec call` runs later in the session.
+ */
+export function buildGatewayTools(
+ payload: Schemas.AvailableToolsResponse,
+ context: Context,
+ projectId: string
+): Tool<ZodObjectAny>[] {
+ const tools: Tool<ZodObjectAny>[] = []
+
+ for (const server of payload.servers ?? []) {
+ for (const tool of server.tools ?? []) {
+ const target: GatewayToolTarget = {
+ installationId: String(server.installation_id),
+ serverName: server.name,
+ toolName: tool.name,
+ }
+ tools.push({
+ name: gatewayToolName(server.slug, tool.name),
+ title: `${server.name}: ${tool.name}`,
+ description: describeTool(server, tool),
+ schema: PERMISSIVE_ARGS_SCHEMA,
+ rawInputSchema: (tool.input_schema ?? {}) as Record<string, unknown>,
+ scopes: [],
+ annotations: annotationsFor(tool),
+ handler: (_ctx, params) =>
+ callGatewayTool(context, projectId, target, params as Record<string, unknown>),
+ })
+ }
+ }
+
+ return tools
+}
+
+/**
+ * Resolve the caller's third-party tools, cached per project for a short window so a
+ * newly connected server shows up without a session restart. Never throws: a gateway
+ * that is unreachable or disabled must not take PostHog's own tools down with it.
+ */
+export async function resolveGatewayTools(context: Context, projectId: string): Promise<Tool<ZodObjectAny>[]> {
+ const payload = await context.stateManager.getOrFetchGatewayTools(projectId)
+ if (!payload) {
+ return []
+ }
+ return buildGatewayTools(payload, context, projectId)
+}
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 0bf079cdacdf..0d97c5b803df 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -9,6 +9,8 @@ import { formatResponse } from '@/lib/response'
import type { ExecHelpCatalog } from './exec-help'
import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'
+import { GATEWAY_TOOL_SEPARATOR } from '@/lib/gateway-tools'
+
import { isRegexPattern, searchToolsRanked, searchToolsRegex } from './tool-search'
import type { ScopeGatedTool } from './toolDefinitions'
import {
@@ -24,6 +26,23 @@ import {
* forcing catastrophic backtracking against tool metadata. */
const MAX_SEARCH_PATTERN_LENGTH = 400
+/** One line telling the agent third-party tools exist and how to find them, for the
+ * `tools` listing. Returns undefined when nothing is connected. */
+async function resolveConnectedSummary(
+ resolveTools: () => Promise<Tool<ZodObjectAny>[]>,
+ posthogToolCount: number
+): Promise<string | undefined> {
+ const combined = await resolveTools()
+ const extra = combined.length - posthogToolCount
+ if (extra <= 0) {
+ return undefined
+ }
+ const servers = new Set(
+ combined.slice(posthogToolCount).map((tool) => tool.name.split(GATEWAY_TOOL_SEPARATOR)[0] ?? '')
+ )
+ return `${extra} tool${extra === 1 ? '' : 's'} from ${servers.size} connected MCP server${servers.size === 1 ? '' : 's'} (${[...servers].sort().join(', ')}) are also callable — find them with "search <what you need>".`
+}
+
/** Ranked (plain-word) search can match loosely on a common token like
* "create"; cap the returned names so a vague query can't dump the catalog. */
const MAX_RANKED_SEARCH_RESULTS = 25
@@ -69,6 +88,13 @@ export interface ExecToolOptions {
* re-homed onto `_meta`. Computed from the client profile at the call site.
*/
isInlineExecUiHost?: boolean
+ /**
+ * Resolves the caller's third-party MCP tools (see `lib/gateway-tools.ts`). Awaited
+ * lazily by the commands that need a tool roster, so a session that never reaches for
+ * a connected server pays nothing for having one. Must not throw: a failing gateway
+ * degrades to "no third-party tools", never to a broken `exec`.
+ */
+ gatewayToolsProvider?: () => Promise<Tool<ZodObjectAny>[]>
}
function makeExecSchema(commandReference: string): z.ZodObject<{ command: z.ZodString }> {
@@ -551,6 +577,20 @@ export function createExecTool(
handler: async (_context: Context, params: z.infer<ExecSchema>) => {
const { verb, rest } = parseCommand(params.command)
+ let gatewayTools: Tool<ZodObjectAny>[] | undefined
+ /** PostHog's tools plus any third-party tools the caller has connected.
+ * Resolved at most once per command, and only for commands that need a
+ * roster — `learn` never touches the gateway. */
+ const resolveTools = async (): Promise<Tool<ZodObjectAny>[]> => {
+ if (!options.gatewayToolsProvider) {
+ return allTools
+ }
+ if (gatewayTools === undefined) {
+ gatewayTools = await options.gatewayToolsProvider()
+ }
+ return gatewayTools.length > 0 ? [...allTools, ...gatewayTools] : allTools
+ }
+
switch (verb) {
case 'learn': {
const helpCatalog = options.helpCatalog
@@ -587,7 +627,15 @@ export function createExecTool(
}
case 'tools': {
- return JSON.stringify(allTools.map((t) => t.name))
+ const names = allTools.map((t) => t.name)
+ const connected = await resolveConnectedSummary(resolveTools, allTools.length)
+ if (!connected) {
+ return JSON.stringify(names)
+ }
+ // Summarize rather than list: a user with several connected servers can
+ // have hundreds of third-party tools, and dumping them all here would
+ // cost more context than `search` ever does.
+ return JSON.stringify({ tools: names, connected_servers: connected })
}
case 'search': {
@@ -607,18 +655,19 @@ export function createExecTool(
// (e.g. `query-`, `feature-flag`) keeps the original regex
// predicate; plain words — including multi-word, natural-
// language queries — use forgiving token ranking.
+ const searchableTools = await resolveTools()
let matches: string[]
let gatedMatches: ScopeGatedTool[]
let truncatedFrom = 0
if (isRegexPattern(rest)) {
try {
- matches = searchToolsRegex(allTools, rest).map((t) => t.name)
+ matches = searchToolsRegex(searchableTools, rest).map((t) => t.name)
gatedMatches = searchToolsRegex(scopeGatedTools, rest)
} catch {
throw new ExecCommandError(`Invalid regex pattern: "${rest}"`, 'invalid_regex')
}
} else {
- const ranked = searchToolsRanked(allTools, rest)
+ const ranked = searchToolsRanked(searchableTools, rest)
truncatedFrom = ranked.length > MAX_RANKED_SEARCH_RESULTS ? ranked.length : 0
matches = ranked.slice(0, MAX_RANKED_SEARCH_RESULTS).map((r) => r.name)
// Preserve ranked order for gated matches too, then map
@@ -667,14 +716,16 @@ export function createExecTool(
if (!infoArgs) {
throw new ExecCommandError('Usage: info [--json] <tool_name>', 'usage')
}
- const tool = findTool(allTools, scopeGatedTools, infoArgs)
+ const tool = findTool(await resolveTools(), scopeGatedTools, infoArgs)
// `io: 'input'` mirrors the advertised `tools/list` schema and the executor's
// validation: fields with a Zod `.default()` (e.g. a query `kind` discriminator)
// are optional and auto-filled. The default `io: 'output'` would list them as
// required, misrepresenting them as mandatory input the caller must supply.
- const fullSchema = stripOutputFormatProperty(
- z.toJSONSchema(tool.schema, { io: 'input' }) as Record<string, unknown>
- )
+ const fullSchema =
+ tool.rawInputSchema ??
+ stripOutputFormatProperty(
+ z.toJSONSchema(tool.schema, { io: 'input' }) as Record<string, unknown>
+ )
// YAML for the top shape, but inputSchema stays as a JSON
// string dumped inside the YAML — JSON Schema is conventionally
// JSON and converting it to YAML obscures `$ref`, `oneOf`, etc.
@@ -710,12 +761,14 @@ export function createExecTool(
throw new ExecCommandError('Usage: schema <tool_name> [field_path]', 'usage')
}
const { verb: schemaToolName, rest: fieldPath } = parseCommand(rest)
- const schemaTool = findTool(allTools, scopeGatedTools, schemaToolName)
+ const schemaTool = findTool(await resolveTools(), scopeGatedTools, schemaToolName)
// See the `info` command: `io: 'input'` keeps this in sync with the advertised
// schema and validation, so `.default()` fields aren't shown as required.
- const fullJsonSchema = stripOutputFormatProperty(
- z.toJSONSchema(schemaTool.schema, { io: 'input' }) as Record<string, unknown>
- )
+ const fullJsonSchema =
+ schemaTool.rawInputSchema ??
+ stripOutputFormatProperty(
+ z.toJSONSchema(schemaTool.schema, { io: 'input' }) as Record<string, unknown>
+ )
if (!fieldPath) {
// The bare `schema <tool>` view is always a summary. Any
@@ -765,7 +818,7 @@ export function createExecTool(
throw new ExecCommandError('Usage: call [--json] [--confirm] <tool_name> <json_input>', 'usage')
}
const { verb: toolName, rest: jsonBody } = parseCommand(callArgs)
- const tool = findTool(allTools, scopeGatedTools, toolName)
+ const tool = findTool(await resolveTools(), scopeGatedTools, toolName)
if (options.requireDestructiveConfirmation && tool.annotations.destructiveHint && !confirmed) {
throw new ExecCommandError(
`Tool "${tool.name}" is destructive. Re-run with "call --confirm ${tool.name} ..." after verifying the target IDs. Use "info ${tool.name}" to inspect the tool first.`,
diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.ts
index 1bdb34dba3a7..4f1f57df9416 100644
--- a/services/mcp/src/tools/types.ts
+++ b/services/mcp/src/tools/types.ts
@@ -39,7 +39,9 @@ export type State = {
Record<PrefixedString<'cachedOrg'>, CachedOrg | undefined> &
Record<PrefixedString<'cachedOrgFetchedAt'>, number | undefined> &
Record<PrefixedString<'cachedProject'>, CachedProject | undefined> &
- Record<PrefixedString<'cachedProjectFetchedAt'>, number | undefined>
+ Record<PrefixedString<'cachedProjectFetchedAt'>, number | undefined> &
+ Record<PrefixedString<'gatewayTools'>, Schemas.AvailableToolsResponse | undefined> &
+ Record<PrefixedString<'gatewayToolsFetchedAt'>, number | undefined>
export type Env = {
/**
@@ -114,6 +116,13 @@ export type Tool<TSchema extends z.ZodType = z.ZodType, TResult = unknown> = {
title: string
description: string
schema: TSchema
+ /**
+ * JSON Schema to advertise instead of deriving one from `schema`. Set for proxied
+ * third-party tools, whose contract is defined upstream as JSON Schema: their `schema`
+ * is permissive (the upstream server validates), so deriving from it would describe
+ * nothing. PostHog's own tools leave this unset and stay Zod-derived.
+ */
+ rawInputSchema?: Record<string, unknown>
handler: (context: Context, params: z.infer<TSchema>) => Promise<TResult>
scopes: string[]
annotations: {
diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.ts
index ec2c12807bd4..89dbda321dd8 100644
--- a/services/mcp/tests/hono/analytics.test.ts
+++ b/services/mcp/tests/hono/analytics.test.ts
@@ -61,6 +61,7 @@ function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {
},
allTools: [],
scopeGatedTools: [],
+ gatewayToolsEnabled: false,
distinctId: 'distinct-id',
renderUiEnabled: false,
metadata: undefined,
diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.ts
index d07144a4f8c4..5998b5de2c04 100644
--- a/services/mcp/tests/hono/tool-executor-intent.test.ts
+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts
@@ -66,6 +66,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
sessionContext: null,
allTools: tools as any,
scopeGatedTools: [],
+ gatewayToolsEnabled: false,
distinctId: 'test-distinct-id',
renderUiEnabled: false,
metadata: undefined,
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index feebae86fad6..5125e402fa69 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -98,6 +98,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
sessionContext: null,
allTools: tools as any,
scopeGatedTools: [],
+ gatewayToolsEnabled: false,
distinctId: 'test-distinct-id',
renderUiEnabled: false,
metadata: undefined,
diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.ts
index e7725989a5b4..8f6dcf224c14 100644
--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts
+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts
@@ -69,6 +69,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
sessionContext: null,
allTools: tools as any,
scopeGatedTools: [],
+ gatewayToolsEnabled: false,
distinctId: 'test-distinct-id',
renderUiEnabled: false,
metadata: undefined,
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 05bdd6f3cdc8..4e7e347c9ac1 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -64,6 +64,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
sessionContext: null,
allTools: tools as any,
scopeGatedTools: [],
+ gatewayToolsEnabled: false,
distinctId: 'test-distinct-id',
renderUiEnabled: false,
metadata: undefined,
diff --git a/services/mcp/tests/unit/gateway-tools.test.ts b/services/mcp/tests/unit/gateway-tools.test.ts
new file mode 100644
index 000000000000..4bf44148b133
--- /dev/null
+++ b/services/mcp/tests/unit/gateway-tools.test.ts
@@ -0,0 +1,208 @@
+import { describe, expect, it, vi } from 'vitest'
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import { ExecCommandError } from '@/lib/errors'
+import { buildGatewayTools } from '@/lib/gateway-tools'
+import { createExecTool } from '@/tools/exec'
+import type { Context, Tool, ZodObjectAny } from '@/tools/types'
+
+const INPUT_SCHEMA = {
+ type: 'object',
+ properties: { title: { type: 'string', description: 'Issue title' } },
+ required: ['title'],
+}
+
+function payload(
+ overrides: Partial<Schemas.AvailableTool> = {},
+ serverName = 'Linear',
+ slug = 'linear'
+): Schemas.AvailableToolsResponse {
+ return {
+ servers: [
+ {
+ installation_id: 'inst-1',
+ name: serverName,
+ slug,
+ tools: [
+ {
+ name: 'create_issue',
+ description: 'Create an issue',
+ input_schema: INPUT_SCHEMA,
+ annotations: {},
+ approval_state: 'approved',
+ ...overrides,
+ } as Schemas.AvailableTool,
+ ],
+ },
+ ],
+ } as Schemas.AvailableToolsResponse
+}
+
+function mockContext(request = vi.fn()): Context {
+ return { api: { request }, getDistinctId: async () => 'distinct-id' } as unknown as Context
+}
+
+function posthogTool(): Tool<ZodObjectAny> {
+ return {
+ name: 'feature-flag-create',
+ title: 'Create feature flag',
+ description: 'Create a PostHog feature flag',
+ schema: z.object({ key: z.string() }),
+ scopes: [],
+ annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: false, readOnlyHint: false },
+ handler: async () => ({ ok: true }),
+ }
+}
+
+function createExec(
+ gatewayTools: Tool<ZodObjectAny>[],
+ provider = vi.fn(async () => gatewayTools)
+): {
+ exec: Tool<any>
+ provider: ReturnType<typeof vi.fn>
+} {
+ const exec = createExecTool(
+ [posthogTool()],
+ mockContext(),
+ 'description',
+ 'command reference',
+ undefined,
+ undefined,
+ [],
+ { gatewayToolsProvider: provider }
+ )
+ return { exec, provider }
+}
+
+describe('gateway tools', () => {
+ it('namespaces tool names by server slug and keeps the upstream JSON Schema', () => {
+ const tools = buildGatewayTools(payload(), mockContext(), '1')
+
+ expect(tools).toHaveLength(1)
+ expect(tools[0]!.name).toBe('linear__create_issue')
+ // PostHog's own names are kebab-case and never contain `__`, so the prefix is what
+ // keeps a vendor tool from shadowing one of ours.
+ expect(tools[0]!.name).toContain('__')
+ expect(tools[0]!.rawInputSchema).toEqual(INPUT_SCHEMA)
+ })
+
+ it.each([
+ ['omitted', {}, { destructiveHint: true, readOnlyHint: false, openWorldHint: true }],
+ [
+ 'declared safe',
+ { destructiveHint: false, readOnlyHint: true, openWorldHint: false },
+ { destructiveHint: false, readOnlyHint: true, openWorldHint: false },
+ ],
+ ['declared destructive', { destructiveHint: true }, { destructiveHint: true, readOnlyHint: false }],
+ ])('takes MCP spec defaults when annotations are %s', (_label, annotations, expected) => {
+ // A server that declares nothing must not look safer than one that declares
+ // itself destructive — the spec defaults destructiveHint to true.
+ const tools = buildGatewayTools(payload({ annotations }), mockContext(), '1')
+
+ expect(tools[0]!.annotations).toMatchObject(expected)
+ })
+
+ it('routes a call to the owning installation and returns the tool text', async () => {
+ const request = vi.fn(async () => ({
+ content: [{ type: 'text', text: 'ENG-1 created' }],
+ is_error: false,
+ }))
+ const tools = buildGatewayTools(payload(), mockContext(request), '42')
+
+ const result = await tools[0]!.handler(mockContext(), { title: 'Bug' })
+
+ expect(result).toBe('ENG-1 created')
+ expect(request).toHaveBeenCalledWith({
+ method: 'POST',
+ path: '/api/projects/42/mcp_server_installations/inst-1/call_tool/',
+ body: { tool_name: 'create_issue', arguments: { title: 'Bug' } },
+ })
+ })
+
+ it('surfaces a tool-reported failure as data so the agent can retry', async () => {
+ const request = vi.fn(async () => ({
+ content: [{ type: 'text', text: 'title is required' }],
+ is_error: true,
+ }))
+ const tools = buildGatewayTools(payload(), mockContext(request), '1')
+
+ await expect(tools[0]!.handler(mockContext(), {})).resolves.toEqual({
+ error: 'title is required',
+ server: 'Linear',
+ })
+ })
+
+ it('turns a gateway refusal into an actionable error instead of a bare HTTP failure', async () => {
+ // Without this the agent sees a 403 and retries forever, rather than learning it
+ // needs a human to approve the tool in PostHog.
+ const request = vi.fn(async () => {
+ throw Object.assign(new Error('Forbidden'), {
+ body: JSON.stringify({ detail: 'Tool needs approval in PostHog.', reason: 'needs_approval' }),
+ })
+ })
+ const tools = buildGatewayTools(payload(), mockContext(request), '1')
+
+ await expect(tools[0]!.handler(mockContext(), {})).rejects.toThrow(ExecCommandError)
+ await expect(tools[0]!.handler(mockContext(), {})).rejects.toThrow('needs approval in PostHog')
+ })
+
+ it('rethrows an unrecognized API failure untouched', async () => {
+ const boom = new Error('upstream exploded')
+ const request = vi.fn(async () => {
+ throw boom
+ })
+ const tools = buildGatewayTools(payload(), mockContext(request), '1')
+
+ await expect(tools[0]!.handler(mockContext(), {})).rejects.toBe(boom)
+ })
+
+ it('finds and calls a gateway tool through exec', async () => {
+ const handler = vi.fn(async () => 'called')
+ const gatewayTool = { ...buildGatewayTools(payload(), mockContext(), '1')[0]!, handler }
+ const { exec } = createExec([gatewayTool])
+
+ const found = await exec.handler(mockContext(), { command: 'search create issue' })
+ expect(found).toContain('linear__create_issue')
+
+ await exec.handler(mockContext(), { command: 'call linear__create_issue {"title":"Bug"}' })
+ expect(handler).toHaveBeenCalledWith(expect.anything(), { title: 'Bug' })
+ })
+
+ it('renders the upstream JSON Schema for info, not an empty derived one', async () => {
+ const { exec } = createExec(buildGatewayTools(payload(), mockContext(), '1'))
+
+ const info = (await exec.handler(mockContext(), {
+ command: 'info --json linear__create_issue',
+ })) as string
+
+ expect(JSON.parse(info).inputSchema).toEqual(INPUT_SCHEMA)
+ })
+
+ it('summarizes connected tools in the listing rather than dumping them', async () => {
+ const { exec } = createExec(buildGatewayTools(payload(), mockContext(), '1'))
+
+ const listed = JSON.parse((await exec.handler(mockContext(), { command: 'tools' })) as string)
+
+ expect(listed.tools).toEqual(['feature-flag-create'])
+ expect(listed.connected_servers).toContain('linear')
+ })
+
+ it('does not touch the gateway for commands that need no tool roster', async () => {
+ // The provider costs an API round trip, so `exec` must stay free for sessions
+ // that never reach for a connected tool.
+ const { exec, provider } = createExec(buildGatewayTools(payload(), mockContext(), '1'))
+
+ await expect(exec.handler(mockContext(), { command: 'learn' })).rejects.toThrow()
+
+ expect(provider).not.toHaveBeenCalled()
+ })
+
+ it('resolves the gateway once per command even when a lookup repeats', async () => {
+ const { exec, provider } = createExec(buildGatewayTools(payload(), mockContext(), '1'))
+
+ await exec.handler(mockContext(), { command: 'search issue' })
+
+ expect(provider).toHaveBeenCalledTimes(1)
+ })
+})