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(webmcp): expose the posthog mcp to browser agents through webmcp (#109255)

Rafael Audibertfbf60169ff50
diff --git a/frontend/package.json b/frontend/package.json
index f54e972a73db..54a4df20d319 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -155,6 +155,7 @@
"@posthog/products-visual-review": "workspace:*",
"@posthog/products-warehouse-sources": "workspace:*",
"@posthog/products-web-analytics": "workspace:*",
+ "@posthog/products-webmcp": "workspace:*",
"@posthog/products-wizard": "workspace:*",
"@posthog/products-workflows": "workspace:*",
"@posthog/quill": "workspace:*",
diff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsx
index ad17bdd58dd5..bd96c75f29c5 100644
--- a/frontend/src/scenes/AuthenticatedShell.tsx
+++ b/frontend/src/scenes/AuthenticatedShell.tsx
@@ -22,6 +22,7 @@ import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'
import { ImpersonationNotice } from '~/layout/navigation/ImpersonationNotice'
+import { webmcpLogic } from 'products/webmcp/frontend/logics/webmcpLogic'
import { WizardRunSyncFab } from 'products/wizard/frontend/runs/WizardRunSyncFab'
import { sceneLogic } from './sceneLogic'
@@ -35,6 +36,7 @@ export default function AuthenticatedShell({ children }: { children: React.React
useMountedLogic(eventIngestionRestrictionLogic)
useMountedLogic(breadcrumbsLogic)
useMountedLogic(globalSetupLogic)
+ useMountedLogic(webmcpLogic)
useSetupHighlight()
const { sceneConfig } = useValues(sceneLogic)
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 089fd1401054..b33d2aae9167 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4752,6 +4752,8 @@ export interface PreflightStatus {
buffer_conversion_seconds?: number
/** Public base URL of the LLM gateway, for per-gateway endpoint examples. Null until configured. */
ai_gateway_url?: string | null
+ /** Whether the instance has an MCP server that the WebMCP proxy can reach. */
+ webmcp_available?: boolean
object_storage: boolean
wizard_cloud_run_available: boolean
public_egress_ip_addresses?: string[]
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b53a5bb399cb..31935246a363 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -866,6 +866,9 @@ importers:
'@posthog/products-web-analytics':
specifier: workspace:*
version: link:../products/web_analytics
+ '@posthog/products-webmcp':
+ specifier: workspace:*
+ version: link:../products/webmcp
'@posthog/products-wizard':
specifier: workspace:*
version: link:../products/wizard
@@ -5316,6 +5319,28 @@ importers:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ products/webmcp:
+ dependencies:
+ '@types/react':
+ specifier: 18.3.27
+ version: 18.3.27
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
+ posthog-js:
+ specifier: 'catalog:'
+ version: 1.435.5(@types/[email protected])([email protected])
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
+ typescript:
+ specifier: 6.0.3
+ version: 6.0.3
+ devDependencies:
+ '@testing-library/react':
+ specifier: '*'
+
products/wizard:
dependencies:
'@pierre/diffs':
@@ -23049,8 +23074,8 @@ packages:
resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}
engines: {node: '>= 10.0.0'}
- resolution: {integrity: sha512-M6gUG8j46DJAm8fZzj7+LwSZP1VsbpIQu+lIIDhN3QOYCWq65AvxL2dfwMLyt+t/cXyQhz61Txirs/nPtQQCSg==}
+ resolution: {integrity: sha512-1WVpcvZaAvv5+EhVrVfpl2XKmiNQLSm68DjxFyQohbGGXwvo8dWHPWWKRbAqmiKrKET4ZUJYl3PgZFw2o6ab/A==}
resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}
@@ -43545,7 +43570,7 @@ snapshots:
dependencies:
react: 18.3.1
- unlayer-types: 1.500.0
+ unlayer-types: 1.501.0
dependencies:
@@ -45864,7 +45889,7 @@ snapshots:
diff --git a/posthog/api/test/test_preflight.py b/posthog/api/test/test_preflight.py
index f713792a722b..ca8b40b59040 100644
--- a/posthog/api/test/test_preflight.py
+++ b/posthog/api/test/test_preflight.py
@@ -74,6 +74,7 @@ class TestPreflight(APIBaseTest, QueryMatchingTest):
# it can be overridden in tests by passing in options
"openai_available": bool(os.environ.get("OPENAI_API_KEY")),
"anthropic_available": bool(os.environ.get("ANTHROPIC_API_KEY")),
+ "webmcp_available": False,
"is_test": True,
**options,
}
diff --git a/posthog/event_usage.py b/posthog/event_usage.py
index a956e4e2ca8d..2b60f268e393 100644
--- a/posthog/event_usage.py
+++ b/posthog/event_usage.py
@@ -21,7 +21,7 @@ from posthog.models.team import Team
from posthog.oauth_provenance import get_oauth_client_id, is_first_party_oauth_client, is_interactive_desktop_grant
from posthog.settings import SITE_URL
from posthog.synthetic_user import SyntheticUser
-from posthog.temporal.oauth import POSTHOG_AI_OAUTH_APP_CLIENT_IDS, SIGNALS_OAUTH_APP_CLIENT_IDS
+from posthog.temporal.oauth import POSTHOG_AI_OAUTH_APP_CLIENT_IDS, SIGNALS_OAUTH_APP_CLIENT_IDS, WEBMCP_APP_CLIENT_ID
from posthog.utils import get_instance_realm, get_instance_region
if TYPE_CHECKING:
@@ -345,6 +345,8 @@ class EventSource(StrEnum):
# Signals OAuth application, which is what tells them apart from the coding agents they
# otherwise look identical to.
SELF_DRIVING = "self_driving"
+ # A browser agent driving a logged-in tab through the WebMCP tool the web app registers.
+ WEBMCP = "webmcp"
DESKTOP = "desktop"
MOBILE = "mobile"
SLACK = "slack"
@@ -376,6 +378,7 @@ AGENT_EVENT_SOURCES = frozenset(
EventSource.WIZARD,
EventSource.CLI,
EventSource.POSTHOG_AI,
+ EventSource.WEBMCP,
}
)
@@ -395,6 +398,7 @@ MCP_TRANSPORT_EVENT_SOURCES = frozenset(
EventSource.SLACK,
EventSource.POSTHOG_CODE,
EventSource.SELF_DRIVING,
+ EventSource.WEBMCP,
}
)
@@ -493,6 +497,8 @@ def get_event_source(request) -> EventSource:
# declares the posthog-code MCP consumer. Only the application it minted under separates it.
if client_id in SIGNALS_OAUTH_APP_CLIENT_IDS:
return EventSource.SELF_DRIVING
+ if client_id == WEBMCP_APP_CLIENT_ID:
+ return EventSource.WEBMCP
user_agent = request.headers.get("user-agent", "") or ""
if not isinstance(user_agent, str):
user_agent = ""
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index ae11551b4264..e85a1955f1c7 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -123,6 +123,7 @@ PRODUCTS_APPS = [
"products.data_catalog.backend.apps.DataCatalogConfig",
"products.data_quality.backend.apps.DataQualityConfig",
"products.security.backend.apps.SecurityConfig",
+ "products.webmcp.backend.apps.WebmcpConfig",
]
INSTALLED_APPS = [
@@ -917,6 +918,10 @@ GZIP_RESPONSE_ALLOW_LIST = get_list(
# We keep the number of buckets low to reduce resource usage on the Prometheus
PROMETHEUS_LATENCY_BUCKETS = [0.1, 0.3, 0.9, 2.7, 8.1, float("inf")]
+# Chrome origin trial tokens, comma-separated. Each token is bound to one origin, so each deployment sets its own.
+# Tokens are base64, so they never contain a comma.
+ORIGIN_TRIAL_TOKENS = get_list(os.getenv("ORIGIN_TRIAL_TOKENS", ""))
+
####
# Proxy and IP egress config
diff --git a/posthog/templates/head.html b/posthog/templates/head.html
index 0993635ae6bf..9f068544a982 100644
--- a/posthog/templates/head.html
+++ b/posthog/templates/head.html
@@ -1,6 +1,9 @@
<title>PostHog</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
+{% for token in origin_trial_tokens %}
+ <meta http-equiv="origin-trial" content="{{ token }}">
+{% endfor %}
<!-- Favicons & OS-theme configurations -->
<link rel="apple-touch-icon"
sizes="180x180"
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index 94c858fc1dca..32eeafa177a5 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -106,6 +106,11 @@ POSTHOG_AI_OAUTH_APP_CLIENT_IDS = frozenset(
}
)
+# The WebMCP proxy mints its tokens server-side against this CIMD application, so a request
+# bearing one is attributable to WebMCP for the same reason as above. The CIMD document lives in
+# the posthog.com repo, so one client_id serves every region.
+WEBMCP_APP_CLIENT_ID = "https://posthog.com/.well-known/oauth/webmcp/client-metadata.json"
+
McpScopePreset = Literal[
"read_only",
"full",
diff --git a/posthog/test/test_event_usage.py b/posthog/test/test_event_usage.py
index d1118a342c11..f969b3d70bf0 100644
--- a/posthog/test/test_event_usage.py
+++ b/posthog/test/test_event_usage.py
@@ -22,7 +22,12 @@ from posthog.event_usage import (
sanitize_header_value,
)
from posthog.models.oauth import OAuthAccessToken
-from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV, SIGNALS_APP_CLIENT_ID_DEV
+from posthog.temporal.oauth import (
+ ARRAY_APP_CLIENT_ID_DEV,
+ POSTHOG_AI_APP_CLIENT_ID_DEV,
+ SIGNALS_APP_CLIENT_ID_DEV,
+ WEBMCP_APP_CLIENT_ID,
+)
# The MCP server's catch-all consumer, sent by every sandbox agent and by the agent PostHog
# Desktop hosts locally.
@@ -321,13 +326,19 @@ class TestGetEventSource(BaseTest):
request = factory.get("/fake", HTTP_X_POSTHOG_CLIENT="mcp")
assert get_event_source(request) == EventSource.MCP
- def test_posthog_ai_oauth_app_beats_the_mcp_header(self):
+ @parameterized.expand(
+ [
+ ("posthog_ai", POSTHOG_AI_APP_CLIENT_ID_DEV, EventSource.POSTHOG_AI),
+ ("webmcp", WEBMCP_APP_CLIENT_ID, EventSource.WEBMCP),
+ ]
+ )
+ def test_server_minted_oauth_app_beats_the_mcp_header(self, _name, client_id, expected):
request = SimpleNamespace(
META={},
headers={"X-Posthog-Client": "mcp"},
- successful_authenticator=_oauth_authenticator(POSTHOG_AI_APP_CLIENT_ID_DEV),
+ successful_authenticator=_oauth_authenticator(client_id),
)
- assert get_event_source(request) == EventSource.POSTHOG_AI
+ assert get_event_source(request) == expected
@parameterized.expand(
[
@@ -406,7 +417,7 @@ class TestGetEventSource(BaseTest):
# that is not an EventSource drops out of every breakdown that joins the two. This list is
# EVENT_SOURCE in `services/mcp/src/lib/event-source.ts`, which its own test pins; removing
# a surface here without removing it there fails this.
- mcp_server_sources = {"mcp", "cli", "wizard", "slack", "posthog_ai", "posthog_code", "self_driving"}
+ mcp_server_sources = {"mcp", "cli", "wizard", "slack", "posthog_ai", "posthog_code", "self_driving", "webmcp"}
assert mcp_server_sources <= {source.value for source in EventSource}
@parameterized.expand(
diff --git a/posthog/test/test_get_context_for_template.py b/posthog/test/test_get_context_for_template.py
index a9f1f1c4b586..10d67bdc13d1 100644
--- a/posthog/test/test_get_context_for_template.py
+++ b/posthog/test/test_get_context_for_template.py
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.middleware import SessionMiddleware
from django.http import HttpResponse
+from django.template.loader import render_to_string
from django.test import RequestFactory
from parameterized import parameterized
@@ -60,6 +61,16 @@ class TestGetContextForTemplate(APIBaseTest):
assert actual["stripe_public_key"] == "pk_test_12345"
+ def test_renders_one_origin_trial_meta_tag_per_token(self):
+ request = RequestFactory().get("/")
+ request.user = AnonymousUser()
+ with self.settings(ORIGIN_TRIAL_TOKENS=["tokenA+/=", "tokenB"]):
+ html = render_to_string("head.html", get_context_for_template("layout", request), request=request)
+
+ assert html.count('http-equiv="origin-trial"') == 2
+ assert '<meta http-equiv="origin-trial" content="tokenA+/=">' in html
+ assert '<meta http-equiv="origin-trial" content="tokenB">' in html
+
@parameterized.expand(
[
("configured", {"pathname": "/dashboard/42", "pinned": True, "title": "Default dashboard"}),
diff --git a/posthog/utils.py b/posthog/utils.py
index e6dddf117d9c..29235e167e32 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -513,6 +513,9 @@ def _build_template_context(
if settings.STRIPE_PUBLIC_KEY:
context["stripe_public_key"] = settings.STRIPE_PUBLIC_KEY
+ if settings.ORIGIN_TRIAL_TOKENS:
+ context["origin_trial_tokens"] = settings.ORIGIN_TRIAL_TOKENS
+
context["git_rev"] = get_git_commit_short() # Include commit in prod for the `console.info()` message
if settings.DEBUG and not settings.TEST:
context["debug"] = True
diff --git a/posthog/views.py b/posthog/views.py
index 4d1b6baf734e..424e61842cc8 100644
--- a/posthog/views.py
+++ b/posthog/views.py
@@ -252,6 +252,10 @@ def preflight_check(request: HttpRequest) -> JsonResponse:
response["dev_disable_navigation_hooks"] = True
if request.user.is_authenticated:
+ from products.webmcp.backend.facade import ( # noqa: PLC0415 - circular via posthog.api.oauth, which imports this module
+ api as webmcp_api,
+ )
+
response = {
**response,
"available_timezones": _traced("preflight.available_timezones", get_available_timezones_with_offsets),
@@ -267,6 +271,7 @@ def preflight_check(request: HttpRequest) -> JsonResponse:
"instance_preferences": settings.INSTANCE_PREFERENCES,
"buffer_conversion_seconds": settings.BUFFER_CONVERSION_SECONDS,
"ai_gateway_url": settings.AI_GATEWAY_PUBLIC_URL or None,
+ "webmcp_available": webmcp_api.is_available(),
}
return JsonResponse(response)
diff --git a/products/data_warehouse/backend/presentation/views/table.py b/products/data_warehouse/backend/presentation/views/table.py
index 7d0e72758738..b3afcfb20ad0 100644
--- a/products/data_warehouse/backend/presentation/views/table.py
+++ b/products/data_warehouse/backend/presentation/views/table.py
@@ -65,7 +65,7 @@ MAX_UPLOAD_REQUEST_BODY_BYTES = MAX_FILE_UPLOAD_SIZE_BYTES + 1024 * 1024
# Which request surface each transport attributes a table to. The PostHog apps and the headless
# agents share `self_driving`, matching how the source path collapses them. Agent transports that
-# wrap MCP but aren't separately tracked (the CLI, Slack, Max) land on `mcp` alongside plain MCP
+# wrap MCP but aren't separately tracked (the CLI, Slack, Max, WebMCP) land on `mcp` alongside plain MCP
# clients, and anything without a surface of its own is a plain API caller.
_EVENT_SOURCE_TO_CREATED_VIA = {
EventSource.WEB: DataWarehouseTableCreatedVia.WEB,
@@ -77,6 +77,7 @@ _EVENT_SOURCE_TO_CREATED_VIA = {
EventSource.SLACK: DataWarehouseTableCreatedVia.MCP,
EventSource.CLI: DataWarehouseTableCreatedVia.MCP,
EventSource.POSTHOG_AI: DataWarehouseTableCreatedVia.MCP,
+ EventSource.WEBMCP: DataWarehouseTableCreatedVia.MCP,
}
diff --git a/products/webmcp/__init__.py b/products/webmcp/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/webmcp/backend/__init__.py b/products/webmcp/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/webmcp/backend/apps.py b/products/webmcp/backend/apps.py
new file mode 100644
index 000000000000..e58e83331f19
--- /dev/null
+++ b/products/webmcp/backend/apps.py
@@ -0,0 +1,8 @@
+"""Django app configuration for webmcp."""
+
+from django.apps import AppConfig
+
+
+class WebmcpConfig(AppConfig):
+ name = "products.webmcp.backend"
+ label = "webmcp"
diff --git a/products/webmcp/backend/facade/__init__.py b/products/webmcp/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/webmcp/backend/facade/api.py b/products/webmcp/backend/facade/api.py
new file mode 100644
index 000000000000..454250d9ec02
--- /dev/null
+++ b/products/webmcp/backend/facade/api.py
@@ -0,0 +1,26 @@
+"""
+Facade for webmcp.
+
+The ONLY module other products are allowed to import.
+Accept frozen dataclasses, call logic/, return frozen
+dataclasses. Never return ORM instances or import DRF.
+"""
+
+from __future__ import annotations
+
+from posthog.models import User
+
+from ..logic.mcp_server import McpServerClient, get_mcp_server_url
+from . import contracts
+
+
+def is_available() -> bool:
+ return get_mcp_server_url() is not None
+
+
+def get_exec_tool(user_id: int, team_id: int) -> contracts.ExecTool:
+ return McpServerClient.for_user(User.objects.get(id=user_id), team_id).get_exec_tool()
+
+
+def run_exec(input: contracts.RunExecInput) -> contracts.ExecResult:
+ return McpServerClient.for_user(User.objects.get(id=input.user_id), input.team_id).call_exec(input.command)
diff --git a/products/webmcp/backend/facade/contracts.py b/products/webmcp/backend/facade/contracts.py
new file mode 100644
index 000000000000..4a54529aee8c
--- /dev/null
+++ b/products/webmcp/backend/facade/contracts.py
@@ -0,0 +1,35 @@
+"""
+Contract types for webmcp.
+
+Frozen dataclasses that define what this product exposes.
+No Django imports. Used by facade as inputs/outputs.
+"""
+
+from typing import Any
+
+from pydantic.dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class ExecTool:
+ name: str
+ description: str
+ # MCP carries the schema as opaque JSON, and the browser hands it to WebMCP unchanged.
+ input_schema: dict[str, Any]
+
+
+@dataclass(frozen=True)
+class RunExecInput:
+ user_id: int
+ team_id: int
+ command: str
+
+
+@dataclass(frozen=True)
+class ExecResult:
+ content: list[dict[str, Any]]
+ is_error: bool
+
+
+class McpServerError(Exception):
+ """The MCP server could not complete the call."""
diff --git a/products/webmcp/backend/logic/__init__.py b/products/webmcp/backend/logic/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/webmcp/backend/logic/mcp_server.py b/products/webmcp/backend/logic/mcp_server.py
new file mode 100644
index 000000000000..bcf0a6b39b58
--- /dev/null
+++ b/products/webmcp/backend/logic/mcp_server.py
@@ -0,0 +1,129 @@
+from typing import Any
+
+from django.conf import settings
+
+import requests
+
+from posthog.models import User
+
+from ..facade.contracts import ExecResult, ExecTool, McpServerError
+from .tokens import WebMCPTokenIssuer
+
+# The stateless MCP dialect needs no handshake, so each proxied call is one HTTP request.
+PROTOCOL_VERSION = "2026-07-28"
+CLIENT_INFO = {"name": "posthog-webmcp", "version": "1.0.0"}
+EXEC_TOOL_NAME = "exec"
+# Connect, read. The read timeout covers slow tools such as SQL queries.
+REQUEST_TIMEOUT_SECONDS = (5, 120)
+
+
+def get_mcp_server_url() -> str | None:
+ """The MCP server URL that WebMCP can send user tokens to, or None when WebMCP is not available."""
+ url = settings.MCP_SERVER_URL
+ # Every request carries a bearer token for the user, so plain HTTP is for a local MCP server only.
+ if not url or (not url.startswith("https://") and not settings.DEBUG):
+ return None
+ return url
+
+
+class McpServerClient:
+ """Talks to the PostHog MCP server in single-`exec` mode, for one user and team.
+
+ The views that call this client are sync, so each call holds a web worker until the MCP server
+ answers, which can take up to the read timeout. The MCP server runs the tool by calling this
+ API with the minted token, so a slow call holds a second worker for the same time.
+
+ An async view would release the worker while it waits.
+ The larger step is for the browser to call the MCP server directly, which removes this proxy.
+ That is not simple, for these reasons:
+ - The MCP server accepts only bearer tokens. The session cookie belongs to the app origin, so
+ the browser does not send it to the MCP host.
+ - The browser must then hold an access token. Page scripts can read that token, so an XSS
+ gets a token that works outside the session. Here, the token never leaves the server.
+ - The MCP server must allow CORS from every app origin, and each region has its own MCP host.
+ """
+
+ def __init__(self, *, url: str, token: str) -> None:
+ self._url = url
+ self._token = token
+
+ @classmethod
+ def for_user(cls, user: User, team_id: int) -> "McpServerClient":
+ url = get_mcp_server_url()
+ if url is None:
+ raise McpServerError("WebMCP is not available on this instance")
+ return cls(url=url, token=WebMCPTokenIssuer.for_instance().get_or_mint(user, team_id))
+
+ def get_exec_tool(self) -> ExecTool:
+ result = self._request("tools/list", {})
+ for tool in result.get("tools", []):
+ if isinstance(tool, dict) and tool.get("name") == EXEC_TOOL_NAME:
+ return ExecTool(
+ name=EXEC_TOOL_NAME,
+ description=tool.get("description") or "",
+ input_schema=tool.get("inputSchema") or {"type": "object"},
+ )
+ raise McpServerError("The MCP server did not advertise the exec tool")
+
+ def call_exec(self, command: str) -> ExecResult:
+ result = self._request(
+ "tools/call", {"name": EXEC_TOOL_NAME, "arguments": {"command": command}}, name=EXEC_TOOL_NAME
+ )
+ content = result.get("content")
+ return ExecResult(
+ content=[block for block in content if isinstance(block, dict)] if isinstance(content, list) else [],
+ is_error=result.get("isError") is True,
+ )
+
+ def _request(self, method: str, params: dict[str, Any], *, name: str | None = None) -> dict[str, Any]:
+ headers = {
+ "Authorization": f"Bearer {self._token}",
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ "MCP-Protocol-Version": PROTOCOL_VERSION,
+ "Mcp-Method": method,
+ # CLI mode makes the MCP server advertise only the single `exec` tool, which WebMCP registers as its one tool.
+ "x-posthog-mcp-mode": "cli",
+ "x-posthog-mcp-consumer": "webmcp",
+ }
+ if name is not None:
+ headers["Mcp-Name"] = name
+ body = {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": method,
+ "params": {
+ **params,
+ "_meta": {
+ "io.modelcontextprotocol/protocolVersion": PROTOCOL_VERSION,
+ "io.modelcontextprotocol/clientInfo": CLIENT_INFO,
+ "io.modelcontextprotocol/clientCapabilities": {},
+ },
+ },
+ }
+ try:
+ # A redirect can resend the bearer token and the command to a URL nobody configured.
+ response = requests.post(
+ self._url, json=body, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False
+ )
+ except requests.RequestException as error:
+ raise McpServerError(f"Could not reach the MCP server: {error.__class__.__name__}") from error
+
+ if 300 <= response.status_code < 400:
+ raise McpServerError(f"The MCP server returned HTTP {response.status_code}")
+ # Revoking the app deletes its tokens, so get_or_mint never reuses a revoked token and a retry with a
+ # new token cannot fix a 401.
+ if response.status_code == 401:
+ raise McpServerError("The MCP server rejected the access token")
+ try:
+ payload = response.json()
+ except ValueError as error:
+ raise McpServerError(f"The MCP server returned HTTP {response.status_code}") from error
+ if not isinstance(payload, dict):
+ raise McpServerError("The MCP server returned an unexpected response")
+ if error_body := payload.get("error"):
+ message = error_body.get("message") if isinstance(error_body, dict) else None
+ raise McpServerError(message or "The MCP server returned an error")
+ if not response.ok or not isinstance(payload.get("result"), dict):
+ raise McpServerError(f"The MCP server returned HTTP {response.status_code}")
+ return payload["result"]
diff --git a/products/webmcp/backend/logic/tokens.py b/products/webmcp/backend/logic/tokens.py
new file mode 100644
index 000000000000..b29bc5fbb9c1
--- /dev/null
+++ b/products/webmcp/backend/logic/tokens.py
@@ -0,0 +1,62 @@
+from datetime import timedelta
+
+from django.utils import timezone
+
+from posthog.api.oauth.cimd import CIMDFetchError, CIMDValidationError, get_or_create_cimd_application
+from posthog.models import OAuthAccessToken, OAuthApplication, User
+from posthog.models.utils import generate_random_oauth_access_token
+from posthog.scopes import effective_ceiling
+from posthog.temporal.oauth import WEBMCP_APP_CLIENT_ID
+
+from ..facade.contracts import McpServerError
+
+TOKEN_LIFETIME = timedelta(hours=1)
+# A token this close to expiry is not reused, so a slow tool call cannot outlive it.
+TOKEN_REUSE_MARGIN = timedelta(minutes=10)
+
+
+class WebMCPTokenIssuer:
+ """Issues the MCP access tokens that stand in for a browser session.
+
+ The MCP server authenticates bearer tokens only, and the session cookie never leaves the app
+ origin, so the proxy exchanges the session for a short-lived token scoped to one team.
+ """
+
+ def __init__(self, application: OAuthApplication) -> None:
+ self._application = application
+
+ @classmethod
+ def for_instance(cls) -> "WebMCPTokenIssuer":
+ try:
+ return cls(get_or_create_cimd_application(WEBMCP_APP_CLIENT_ID))
+ except (CIMDFetchError, CIMDValidationError) as error:
+ raise McpServerError("Could not load the WebMCP client metadata") from error
+
+ def get_or_mint(self, user: User, team_id: int) -> str:
+ # Reuse keeps one token row per user and team per hour, rather than one per tool call.
+ existing = (
+ OAuthAccessToken.objects.filter(
+ user=user,
+ application=self._application,
+ scoped_teams=[team_id],
+ impersonated_by__isnull=True,
+ expires__gt=timezone.now() + TOKEN_REUSE_MARGIN,
+ )
+ .order_by("-expires")
+ .values_list("token", flat=True)
+ .first()
+ )
+ return existing or self.mint(user, team_id)
+
+ def mint(self, user: User, team_id: int) -> str:
+ token = generate_random_oauth_access_token(None)
+ OAuthAccessToken.objects.create(
+ user=user,
+ application=self._application,
+ token=token,
+ expires=timezone.now() + TOKEN_LIFETIME,
+ # The CIMD document on posthog.com sets what WebMCP can reach, with no deploy here.
+ scope=" ".join(sorted(effective_ceiling(self._application.ceiling_scopes))),
+ scoped_teams=[team_id],
+ )
+ return token
diff --git a/products/webmcp/backend/presentation/__init__.py b/products/webmcp/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/webmcp/backend/presentation/serializers.py b/products/webmcp/backend/presentation/serializers.py
new file mode 100644
index 000000000000..1d9ba422726a
--- /dev/null
+++ b/products/webmcp/backend/presentation/serializers.py
@@ -0,0 +1,46 @@
+"""DRF serializers for webmcp."""
+
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+
+JSON_SCHEMA_OBJECT = {"type": "object", "additionalProperties": True}
+MCP_CONTENT_BLOCK = {
+ "type": "object",
+ "properties": {"type": {"type": "string"}},
+ "required": ["type"],
+ "additionalProperties": True,
+}
+
+
+@extend_schema_field(JSON_SCHEMA_OBJECT)
+class JsonObjectField(serializers.JSONField):
+ pass
+
+
+@extend_schema_field(MCP_CONTENT_BLOCK)
+class McpContentBlockField(serializers.JSONField):
+ pass
+
+
+class WebMCPExecToolSerializer(serializers.Serializer):
+ name = serializers.CharField(help_text="Tool name to register with WebMCP.")
+ description = serializers.CharField(
+ help_text="Tool description from the PostHog MCP server, which tells the agent how to write commands."
+ )
+ input_schema = JsonObjectField(help_text="JSON Schema of the tool input, as the MCP server advertises it.")
+
+
+class WebMCPExecRequestSerializer(serializers.Serializer):
+ command = serializers.CharField(
+ max_length=100_000,
+ trim_whitespace=False,
+ help_text="The exec command to run, for example `search insights` or `call insight-get {...}`.",
+ )
+
+
+class WebMCPExecResultSerializer(serializers.Serializer):
+ content = serializers.ListField(
+ child=McpContentBlockField(),
+ help_text="MCP content blocks the tool returned, such as `{type: 'text', text: '...'}`.",
+ )
+ is_error = serializers.BooleanField(help_text="True when the tool ran and reported a failure.")
diff --git a/products/webmcp/backend/presentation/views.py b/products/webmcp/backend/presentation/views.py
new file mode 100644
index 000000000000..c67fbce617bf
--- /dev/null
+++ b/products/webmcp/backend/presentation/views.py
@@ -0,0 +1,72 @@
+"""
+DRF views for webmcp.
+
+Validate JSON via serializers, call facade methods,
+return serialized responses. No business logic here.
+"""
+
+from typing import cast
+
+from drf_spectacular.utils import OpenApiResponse
+from loginas.utils import is_impersonated_session
+from rest_framework import status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import APIException, PermissionDenied
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.mixins import validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models import User
+
+from ..facade import api, contracts
+from .serializers import WebMCPExecRequestSerializer, WebMCPExecResultSerializer, WebMCPExecToolSerializer
+
+
+class McpServerUnavailable(APIException):
+ status_code = status.HTTP_502_BAD_GATEWAY
+ default_detail = "The PostHog MCP server could not complete the request."
+ default_code = "mcp_server_unavailable"
+
+
+class WebMCPViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ # Session only: WebMCP exists for the logged-in browser, and a token caller can reach the MCP directly.
+ scope_object = "INTERNAL"
+
+ def _check_not_impersonating(self, request: Request) -> None:
+ # A minted token would carry the impersonated user's access past the read-only session rules.
+ if is_impersonated_session(request):
+ raise PermissionDenied("WebMCP is not available in an impersonated session.")
+
+ @validated_request(
+ responses={200: OpenApiResponse(response=WebMCPExecToolSerializer)},
+ summary="Get the exec tool definition to register with WebMCP",
+ )
+ @action(detail=False, methods=["get"], url_path="tool")
+ def tool(self, request: Request, **kwargs) -> Response:
+ self._check_not_impersonating(request)
+ try:
+ tool = api.get_exec_tool(cast(User, request.user).id, self.team_id)
+ except contracts.McpServerError as error:
+ raise McpServerUnavailable(str(error)) from error
+ return Response(WebMCPExecToolSerializer(tool).data)
+
+ @validated_request(
+ request_serializer=WebMCPExecRequestSerializer,
+ responses={200: OpenApiResponse(response=WebMCPExecResultSerializer)},
+ summary="Run an exec command on the PostHog MCP server",
+ )
+ @action(detail=False, methods=["post"], url_path="exec")
+ def exec(self, request: Request, **kwargs) -> Response:
+ self._check_not_impersonating(request)
+ try:
+ result = api.run_exec(
+ contracts.RunExecInput(
+ user_id=cast(User, request.user).id,
+ team_id=self.team_id,
+ command=request.validated_data["command"],
+ )
+ )
+ except contracts.McpServerError as error:
+ raise McpServerUnavailable(str(error)) from error
+ return Response(WebMCPExecResultSerializer(result).data)
diff --git a/products/webmcp/backend/routes.py b/products/webmcp/backend/routes.py
new file mode 100644
index 000000000000..f69920617522
--- /dev/null
+++ b/products/webmcp/backend/routes.py
@@ -0,0 +1,7 @@
+from posthog.api.routing import RouterRegistry
+
+from products.webmcp.backend.presentation.views import WebMCPViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(r"webmcp", WebMCPViewSet, "project_webmcp", ["project_id"])
diff --git a/products/webmcp/backend/tests/__init__.py b/products/webmcp/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/webmcp/backend/tests/test_logic.py b/products/webmcp/backend/tests/test_logic.py
new file mode 100644
index 000000000000..03cfa712e2d2
--- /dev/null
+++ b/products/webmcp/backend/tests/test_logic.py
@@ -0,0 +1,87 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock
+
+from django.test import SimpleTestCase, override_settings
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models import OAuthAccessToken, OAuthApplication, Team, User
+from posthog.temporal.oauth import WEBMCP_APP_CLIENT_ID
+
+from products.webmcp.backend.facade import api
+from products.webmcp.backend.logic.tokens import WebMCPTokenIssuer
+
+
+def create_webmcp_app(scopes: list[str] | None = None) -> OAuthApplication:
+ return OAuthApplication.objects.create(
+ name="PostHog WebMCP",
+ client_id=WEBMCP_APP_CLIENT_ID,
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://us.posthog.com/webmcp/callback",
+ algorithm="RS256",
+ is_cimd_client=True,
+ scopes=scopes or [],
+ )
+
+
+def mcp_response(status_code: int, payload: dict) -> MagicMock:
+ response = MagicMock(status_code=status_code, ok=200 <= status_code < 300)
+ response.json.return_value = payload
+ return response
+
+
+class TestWebMCPTokenIssuer(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.app = create_webmcp_app(scopes=["insight:read", "insight:write"])
+ self.issuer = WebMCPTokenIssuer(self.app)
+
+ def test_reuses_a_live_token_for_the_same_team(self) -> None:
+ first = self.issuer.get_or_mint(self.user, self.team.id)
+
+ assert self.issuer.get_or_mint(self.user, self.team.id) == first
+ token = OAuthAccessToken.objects.get(token=first)
+ assert token.scoped_teams == [self.team.id]
+ assert token.scope == "insight:read insight:write"
+
+ @parameterized.expand(
+ [
+ ("other_team", "other_team", timedelta(hours=1), None),
+ ("near_expiry", "same_team", timedelta(minutes=5), None),
+ ("impersonated", "same_team", timedelta(hours=1), "impersonator"),
+ ]
+ )
+ def test_does_not_reuse_token(self, _name: str, team: str, expires_in: timedelta, impersonator: str | None) -> None:
+ other_team = Team.objects.create(organization=self.organization)
+ existing = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=self.app,
+ token="pha_existing_webmcp_token",
+ expires=timezone.now() + expires_in,
+ scope="insight:read",
+ scoped_teams=[other_team.id if team == "other_team" else self.team.id],
+ impersonated_by=User.objects.create(email="[email protected]") if impersonator else None,
+ )
+
+ minted = self.issuer.get_or_mint(self.user, self.team.id)
+
+ assert minted != existing.token
+ assert OAuthAccessToken.objects.get(token=minted).scoped_teams == [self.team.id]
+
+
+class TestWebMCPAvailability(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("https", "https://mcp.example.com/mcp", False, True),
+ ("plain_http", "http://mcp.example.com/mcp", False, False),
+ ("plain_http_in_debug", "http://localhost:8787/mcp", True, True),
+ ("unset", "", False, False),
+ ]
+ )
+ def test_is_available(self, _name: str, url: str, debug: bool, expected: bool) -> None:
+ with override_settings(MCP_SERVER_URL=url, DEBUG=debug):
+ assert api.is_available() is expected
diff --git a/products/webmcp/backend/tests/test_presentation.py b/products/webmcp/backend/tests/test_presentation.py
new file mode 100644
index 000000000000..e3835ccd09d2
--- /dev/null
+++ b/products/webmcp/backend/tests/test_presentation.py
@@ -0,0 +1,95 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.api.oauth.cimd import CIMDFetchError, CIMDValidationError
+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
+from posthog.models.utils import generate_random_token_personal
+
+from products.webmcp.backend.tests.test_logic import create_webmcp_app, mcp_response
+
+
+@override_settings(MCP_SERVER_URL="https://mcp.example.com/mcp")
+@patch("products.webmcp.backend.logic.mcp_server.requests.post")
+class TestWebMCPViewSet(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # The CIMD lookup refreshes the document from posthog.com, which a test must not reach.
+ patcher = patch(
+ "products.webmcp.backend.logic.tokens.get_or_create_cimd_application", return_value=create_webmcp_app()
+ )
+ self.get_cimd_application = patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def test_exec_forwards_the_command_and_returns_the_tool_result(self, mock_post: MagicMock) -> None:
+ mock_post.return_value = mcp_response(
+ 200,
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "result": {"content": [{"type": "text", "text": "insight-get"}], "isError": False},
+ },
+ )
+
+ response = self.client.post(f"/api/projects/{self.team.id}/webmcp/exec/", {"command": "search insights"})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"content": [{"type": "text", "text": "insight-get"}], "is_error": False}
+ body = mock_post.call_args.kwargs["json"]
+ assert (body["method"], body["params"]["arguments"]) == ("tools/call", {"command": "search insights"})
+
+ def test_exec_reports_an_mcp_error_as_bad_gateway(self, mock_post: MagicMock) -> None:
+ mock_post.return_value = mcp_response(
+ 400, {"jsonrpc": "2.0", "id": 1, "error": {"code": -32020, "message": "Header mismatch"}}
+ )
+
+ response = self.client.post(f"/api/projects/{self.team.id}/webmcp/exec/", {"command": "tools"})
+
+ assert response.status_code == status.HTTP_502_BAD_GATEWAY
+ assert response.json()["detail"] == "Header mismatch"
+
+ @parameterized.expand(
+ [
+ ("cimd_fetch_failed", CIMDFetchError("timed out"), "https://mcp.example.com/mcp"),
+ ("cimd_invalid", CIMDValidationError("missing redirect_uris"), "https://mcp.example.com/mcp"),
+ ("plain_http_url", None, "http://mcp.example.com/mcp"),
+ ]
+ )
+ def test_exec_reports_an_unusable_setup_as_bad_gateway(
+ self, mock_post: MagicMock, _name: str, cimd_error: Exception | None, url: str
+ ) -> None:
+ if cimd_error is not None:
+ self.get_cimd_application.side_effect = cimd_error
+
+ with override_settings(MCP_SERVER_URL=url):
+ response = self.client.post(f"/api/projects/{self.team.id}/webmcp/exec/", {"command": "tools"})
+
+ assert response.status_code == status.HTTP_502_BAD_GATEWAY
+ mock_post.assert_not_called()
+
+ def test_exec_rejects_an_impersonated_session(self, mock_post: MagicMock) -> None:
+ with patch("products.webmcp.backend.presentation.views.is_impersonated_session", return_value=True):
+ response = self.client.post(f"/api/projects/{self.team.id}/webmcp/exec/", {"command": "tools"})
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ mock_post.assert_not_called()
+
+ def test_exec_rejects_a_personal_api_key(self, mock_post: MagicMock) -> None:
+ key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Test", user=self.user, secure_value=hash_key_value(key_value), scopes=["*"]
+ )
+ self.client.logout()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/webmcp/exec/",
+ {"command": "tools"},
+ headers={"authorization": f"Bearer {key_value}"},
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ mock_post.assert_not_called()
diff --git a/products/webmcp/frontend/generated/api.schemas.ts b/products/webmcp/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..d41c90b39a60
--- /dev/null
+++ b/products/webmcp/frontend/generated/api.schemas.ts
@@ -0,0 +1,42 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+export interface WebMCPExecRequestApi {
+ /**
+ * The exec command to run, for example `search insights` or `call insight-get {...}`.
+ * @maxLength 100000
+ */
+ command: string
+}
+
+export type WebMCPExecResultApiContentItem = {
+ type: string
+ [key: string]: unknown
+}
+
+export interface WebMCPExecResultApi {
+ /** MCP content blocks the tool returned, such as `{type: 'text', text: '...'}`. */
+ content: WebMCPExecResultApiContentItem[]
+ /** True when the tool ran and reported a failure. */
+ is_error: boolean
+}
+
+/**
+ * JSON Schema of the tool input, as the MCP server advertises it.
+ */
+export type WebMCPExecToolApiInputSchema = { [key: string]: unknown }
+
+export interface WebMCPExecToolApi {
+ /** Tool name to register with WebMCP. */
+ name: string
+ /** Tool description from the PostHog MCP server, which tells the agent how to write commands. */
+ description: string
+ /** JSON Schema of the tool input, as the MCP server advertises it. */
+ input_schema: WebMCPExecToolApiInputSchema
+}
diff --git a/products/webmcp/frontend/generated/api.ts b/products/webmcp/frontend/generated/api.ts
new file mode 100644
index 000000000000..48e1a548457c
--- /dev/null
+++ b/products/webmcp/frontend/generated/api.ts
@@ -0,0 +1,45 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type { WebMCPExecRequestApi, WebMCPExecResultApi, WebMCPExecToolApi } from './api.schemas'
+
+export const getWebmcpExecCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/webmcp/exec/`
+}
+
+/**
+ * @summary Run an exec command on the PostHog MCP server
+ */
+export const webmcpExecCreate = async (
+ projectId: string,
+ webMCPExecRequestApi: WebMCPExecRequestApi,
+ options?: RequestInit
+): Promise<WebMCPExecResultApi> => {
+ return apiMutator<WebMCPExecResultApi>(getWebmcpExecCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(webMCPExecRequestApi),
+ })
+}
+
+export const getWebmcpToolRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/webmcp/tool/`
+}
+
+/**
+ * @summary Get the exec tool definition to register with WebMCP
+ */
+export const webmcpToolRetrieve = async (projectId: string, options?: RequestInit): Promise<WebMCPExecToolApi> => {
+ return apiMutator<WebMCPExecToolApi>(getWebmcpToolRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/webmcp/frontend/generated/api.zod.ts b/products/webmcp/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..9e46fcde8ee3
--- /dev/null
+++ b/products/webmcp/frontend/generated/api.zod.ts
@@ -0,0 +1,22 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * @summary Run an exec command on the PostHog MCP server
+ */
+export const webmcpExecCreateBodyCommandMax = 100000
+
+export const WebmcpExecCreateBody = /* @__PURE__ */ zod.object({
+ command: zod
+ .string()
+ .max(webmcpExecCreateBodyCommandMax)
+ .describe('The exec command to run, for example `search insights` or `call insight-get {...}`.'),
+})
diff --git a/products/webmcp/frontend/logics/webmcpLogic.test.ts b/products/webmcp/frontend/logics/webmcpLogic.test.ts
new file mode 100644
index 000000000000..90c14e7703c3
--- /dev/null
+++ b/products/webmcp/frontend/logics/webmcpLogic.test.ts
@@ -0,0 +1,104 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { waitFor } from '@testing-library/react'
+
+import { preflightLogic } from 'lib/logic/preflightLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import _preflight from '~/mocks/fixtures/_preflight.json'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import type { TeamType } from '~/types'
+
+import { webmcpLogic } from './webmcpLogic'
+
+interface RegisteredTool {
+ name: string
+ inputSchema?: Record<string, unknown>
+ execute: (input: Record<string, unknown>) => Promise<string>
+}
+
+describe('webmcpLogic', () => {
+ let registerTool: jest.Mock
+ let postedCommands: string[]
+ let toolRequests: number
+
+ beforeEach(() => {
+ registerTool = jest.fn().mockResolvedValue(undefined)
+ postedCommands = []
+ toolRequests = 0
+ Object.defineProperty(document, 'modelContext', { value: { registerTool }, configurable: true })
+
+ useMocks({
+ get: {
+ '/_preflight': () => [200, { ..._preflight, webmcp_available: true }],
+ '/api/projects/:team/webmcp/tool/': () => {
+ toolRequests += 1
+ return [
+ 200,
+ { name: 'exec', description: 'Run PostHog commands', input_schema: { type: 'object' } },
+ ]
+ },
+ },
+ post: {
+ '/api/projects/:team/webmcp/exec/': async ({ request }) => {
+ const { command } = (await request.json()) as { command: string }
+ postedCommands.push(command)
+ return command === 'call broken-tool {}'
+ ? [200, { content: [{ type: 'text', text: 'Tool failed' }], is_error: true }]
+ : [200, { content: [{ type: 'text', text: 'insight-get' }], is_error: false }]
+ },
+ },
+ })
+ })
+
+ afterEach(() => {
+ webmcpLogic.unmount()
+ delete (document as Document & { modelContext?: unknown }).modelContext
+ })
+
+ it('registers the exec tool and forwards each call to the proxy', async () => {
+ initKeaTests()
+ webmcpLogic.mount()
+
+ await waitFor(() => expect(registerTool).toHaveBeenCalled())
+ const tool: RegisteredTool = registerTool.mock.calls[0][0]
+
+ expect(tool.name).toEqual('exec')
+ await expect(tool.execute({ command: 'search insights' })).resolves.toEqual('insight-get')
+ await expect(tool.execute({ command: 'call broken-tool {}' })).rejects.toThrow('Tool failed')
+ expect(postedCommands).toEqual(['search insights', 'call broken-tool {}'])
+ })
+
+ it('retries registration on the next team load after a failed attempt', async () => {
+ registerTool.mockRejectedValueOnce(new Error('Registration failed'))
+ initKeaTests()
+ webmcpLogic.mount()
+ await waitFor(() => expect(registerTool).toHaveBeenCalledTimes(1))
+
+ teamLogic.actions.loadCurrentTeamSuccess(MOCK_DEFAULT_TEAM)
+
+ await waitFor(() => expect(registerTool).toHaveBeenCalledTimes(2))
+ })
+
+ it('registers the tool once the team loads after mount', async () => {
+ initKeaTests(true, null as unknown as TeamType)
+ webmcpLogic.mount()
+ expect(registerTool).not.toHaveBeenCalled()
+
+ teamLogic.actions.loadCurrentTeamSuccess(MOCK_DEFAULT_TEAM)
+
+ await waitFor(() => expect(registerTool).toHaveBeenCalledTimes(1))
+ })
+
+ it('does not ask the proxy for the tool when the instance has no MCP server', async () => {
+ useMocks({ get: { '/_preflight': () => [200, { ..._preflight, webmcp_available: false }] } })
+ initKeaTests()
+ webmcpLogic.mount()
+
+ await waitFor(() => expect(preflightLogic.values.preflight).not.toBeNull())
+
+ expect(toolRequests).toEqual(0)
+ expect(registerTool).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/webmcp/frontend/logics/webmcpLogic.ts b/products/webmcp/frontend/logics/webmcpLogic.ts
new file mode 100644
index 000000000000..7c8c90294230
--- /dev/null
+++ b/products/webmcp/frontend/logics/webmcpLogic.ts
@@ -0,0 +1,164 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path } from 'kea'
+import posthog from 'posthog-js'
+
+import { preflightLogic } from 'lib/logic/preflightLogic'
+import { teamLogic } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import type { PreflightStatus, UserType } from '~/types'
+
+import { webmcpExecCreate, webmcpToolRetrieve } from '../generated/api'
+import type { WebMCPExecResultApi } from '../generated/api.schemas'
+
+interface WebMCPToolAnnotations {
+ readOnlyHint?: boolean
+ untrustedContentHint?: boolean
+ consequentialHint?: boolean
+}
+
+interface WebMCPTool {
+ name: string
+ title?: string
+ description: string
+ inputSchema?: Record<string, unknown>
+ annotations?: WebMCPToolAnnotations
+ execute: (input: Record<string, unknown>, options?: { signal?: AbortSignal }) => Promise<string>
+}
+
+interface ModelContext {
+ // Aborting the signal unregisters the tool.
+ registerTool: (tool: WebMCPTool, options?: { signal?: AbortSignal }) => Promise<void>
+}
+
+export function getModelContext(): ModelContext | null {
+ // Chrome 150 deprecates navigator.modelContext in favor of document.modelContext, so read both.
+ const fromDocument = (document as Document & { modelContext?: ModelContext }).modelContext
+ const fromNavigator = (navigator as Navigator & { modelContext?: ModelContext }).modelContext
+ return fromDocument ?? fromNavigator ?? null
+}
+
+export function formatExecResult(result: WebMCPExecResultApi): string {
+ return result.content
+ .map((block) => (block.type === 'text' && typeof block.text === 'string' ? block.text : JSON.stringify(block)))
+ .join('\n\n')
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface webmcpLogicValues {
+ preflight: PreflightStatus | null // preflightLogic
+ currentTeamId: number | null // teamLogic
+ user: UserType | null // userLogic
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface webmcpLogicActions {
+ loadPreflightSuccess: (
+ preflight: PreflightStatus,
+ payload?: any
+ ) => {
+ payload?: any
+ preflight: PreflightStatus
+ } // preflightLogic
+ loadCurrentTeamSuccess: (
+ currentTeam: null | import('~/types').TeamPublicType,
+ payload?: any
+ ) => {
+ currentTeam: null | import('~/types').TeamPublicType
+ payload?: any
+ } // teamLogic
+ registerTool: () => {
+ value: true
+ }
+}
+
+export type webmcpLogicType = MakeLogicType<webmcpLogicValues, webmcpLogicActions>
+
+export const webmcpLogic = kea<webmcpLogicType>([
+ path(['products', 'webmcp', 'frontend', 'logics', 'webmcpLogic']),
+ connect(() => ({
+ values: [preflightLogic, ['preflight'], teamLogic, ['currentTeamId'], userLogic, ['user']],
+ actions: [preflightLogic, ['loadPreflightSuccess'], teamLogic, ['loadCurrentTeamSuccess']],
+ })),
+ actions({
+ registerTool: true,
+ }),
+ listeners(({ actions, cache, values }) => ({
+ // The preflight and the team can arrive after mount, and the tool needs both.
+ loadPreflightSuccess: () => {
+ actions.registerTool()
+ },
+ loadCurrentTeamSuccess: () => {
+ actions.registerTool()
+ },
+ registerTool: () => {
+ const modelContext = getModelContext()
+ // Without an MCP server every proxy call fails, and the backend refuses impersonated sessions.
+ if (
+ !modelContext ||
+ !values.preflight?.webmcp_available ||
+ values.user?.is_impersonated ||
+ !values.currentTeamId ||
+ cache.toolRegistered
+ ) {
+ return
+ }
+ cache.toolRegistered = true
+ const teamId = values.currentTeamId
+
+ const register = async (signal: AbortSignal): Promise<void> => {
+ const tool = await webmcpToolRetrieve(String(teamId), { signal })
+ if (signal.aborted) {
+ return
+ }
+ await modelContext.registerTool(
+ {
+ name: tool.name,
+ title: 'PostHog',
+ description: tool.description,
+ inputSchema: tool.input_schema,
+ annotations: {
+ // Event and person properties come from end users, so results can carry prompt injection.
+ untrustedContentHint: true,
+ // One tool runs every PostHog command, including the ones that write.
+ consequentialHint: true,
+ },
+ execute: async (input, options) => {
+ const result = await webmcpExecCreate(
+ String(values.currentTeamId ?? teamId),
+ { command: String(input.command ?? '') },
+ { signal: options?.signal }
+ )
+ const text = formatExecResult(result)
+ if (result.is_error) {
+ throw new Error(text)
+ }
+ return text
+ },
+ },
+ { signal }
+ )
+ posthog.capture('webmcp tool registered')
+ }
+
+ cache.disposables.add(
+ () => {
+ const controller = new AbortController()
+ // A failed registration only means no tool, so it must not surface as an app error.
+ // Clearing the flag lets the next team load try again.
+ register(controller.signal).catch(() => {
+ if (!controller.signal.aborted) {
+ cache.toolRegistered = false
+ }
+ })
+ return () => controller.abort()
+ },
+ 'webmcpTool',
+ // Browser agents can drive a tab in the background, so the tool stays registered while hidden.
+ { pauseOnPageHidden: false }
+ )
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.registerTool()
+ }),
+])
diff --git a/products/webmcp/manifest.tsx b/products/webmcp/manifest.tsx
new file mode 100644
index 000000000000..96cf500d17b2
--- /dev/null
+++ b/products/webmcp/manifest.tsx
@@ -0,0 +1,12 @@
+import { ProductManifest } from '../../frontend/src/types'
+
+export const manifest: ProductManifest = {
+ name: 'Webmcp',
+ scenes: {},
+ routes: {},
+ redirects: {},
+ urls: {},
+ fileSystemTypes: {},
+ treeItemsNew: [],
+ treeItemsProducts: [],
+}
diff --git a/products/webmcp/package.json b/products/webmcp/package.json
new file mode 100644
index 000000000000..630fddfdabfa
--- /dev/null
+++ b/products/webmcp/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "@posthog/products-webmcp",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
+ "backend:contract-check": "echo 'Contract files unchanged'"
+ },
+ "dependencies": {
+ "kea": "catalog:",
+ "posthog-js": "catalog:"
+ },
+ "devDependencies": {
+ "@testing-library/react": "*"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "*",
+ "typescript": "catalog:*"
+ }
+}
diff --git a/products/webmcp/product.yaml b/products/webmcp/product.yaml
new file mode 100644
index 000000000000..dd95a02d0625
--- /dev/null
+++ b/products/webmcp/product.yaml
@@ -0,0 +1,4 @@
+name: WebMCP
+owners:
+ - team-context-and-mcp
+ - team-growth
diff --git a/products/webmcp/tsconfig.json b/products/webmcp/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/webmcp/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/products/webmcp/turbo.json b/products/webmcp/turbo.json
new file mode 100644
index 000000000000..2f891fa60904
--- /dev/null
+++ b/products/webmcp/turbo.json
@@ -0,0 +1,16 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": [
+ "backend/facade/**",
+ "backend/presentation/**",
+ "backend/routes.py",
+ "backend/models.py",
+ "backend/migrations/**"
+ ],
+ "outputs": [],
+ "cache": true
+ }
+ }
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8542cb08eb4f..1fbe408a4fb7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -106288,6 +106288,40 @@ export namespace Schemas {
achievements_opt_out: boolean;
}
+ export interface WebMCPExecRequest {
+ /**
+ * The exec command to run, for example `search insights` or `call insight-get {...}`.
+ * @maxLength 100000
+ */
+ command: string;
+ }
+
+ export type WebMCPExecResultContentItem = {
+ type: string;
+ [key: string]: unknown;
+ };
+
+ export interface WebMCPExecResult {
+ /** MCP content blocks the tool returned, such as `{type: 'text', text: '...'}`. */
+ content: WebMCPExecResultContentItem[];
+ /** True when the tool ran and reported a failure. */
+ is_error: boolean;
+ }
+
+ /**
+ * JSON Schema of the tool input, as the MCP server advertises it.
+ */
+ export type WebMCPExecToolInputSchema = { [key: string]: unknown };
+
+ export interface WebMCPExecTool {
+ /** Tool name to register with WebMCP. */
+ name: string;
+ /** Tool description from the PostHog MCP server, which tells the agent how to write commands. */
+ description: string;
+ /** JSON Schema of the tool input, as the MCP server advertises it. */
+ input_schema: WebMCPExecToolInputSchema;
+ }
+
export interface WebhookExternalStatus {
/** Whether the webhook exists on the external service. */
exists: boolean;
diff --git a/services/mcp/src/lib/event-source.ts b/services/mcp/src/lib/event-source.ts
index a77c36606760..08607e1c26b3 100644
--- a/services/mcp/src/lib/event-source.ts
+++ b/services/mcp/src/lib/event-source.ts
@@ -16,6 +16,7 @@ export const EVENT_SOURCE = {
POSTHOG_AI: 'posthog_ai',
POSTHOG_CODE: 'posthog_code',
SELF_DRIVING: 'self_driving',
+ WEBMCP: 'webmcp',
} as const
export type EventSource = (typeof EVENT_SOURCE)[keyof typeof EVENT_SOURCE]
@@ -45,6 +46,10 @@ const SIGNALS_OAUTH_CLIENT_IDS = new Set([
'xMT3Nejjbi4lUdhJLkzmCVJKFsx0JsHXdU0pIjl8',
])
+// Mirrors WEBMCP_APP_CLIENT_ID in `posthog/temporal/oauth.py`. The WebMCP proxy mints its tokens
+// server-side against this CIMD application, and the URL is the same in every region.
+const WEBMCP_OAUTH_CLIENT_ID = 'https://posthog.com/.well-known/oauth/webmcp/client-metadata.json'
+
const FIRST_PARTY_OAUTH_CLIENT_IDS = new Set([
'HCWoE0aRFMYxIxFNTTwkOORn5LBjOt2GVDzwSw5W',
'AIvijgMS0dxKEmr5z6odvRd8Pkh5vts3nPTzgzU9',
@@ -109,6 +114,9 @@ export function resolveEventSource(input: EventSourceInput): EventSource {
if (input.oauthClientId && SIGNALS_OAUTH_CLIENT_IDS.has(input.oauthClientId)) {
return EVENT_SOURCE.SELF_DRIVING
}
+ if (input.oauthClientId === WEBMCP_OAUTH_CLIENT_ID) {
+ return EVENT_SOURCE.WEBMCP
+ }
// Matches Django: the outer caller's user-agent wins over anything the MCP layer says.
if (input.clientUserAgent?.includes(WIZARD_USER_AGENT_FRAGMENT)) {
return EVENT_SOURCE.WIZARD
diff --git a/services/mcp/tests/event-source.test.ts b/services/mcp/tests/event-source.test.ts
index 4c7820271ff0..15abab6ad2b0 100644
--- a/services/mcp/tests/event-source.test.ts
+++ b/services/mcp/tests/event-source.test.ts
@@ -5,7 +5,7 @@ import { EVENT_SOURCE, resolveEventSource } from '@/lib/event-source'
// Every surface this server is allowed to stamp. `test_mcp_server_only_emits_sources_this_enum_knows`
// in `posthog/test/test_event_usage.py` holds the same list against Django's EventSource, so adding
// one here without adding it there fails on that side.
-const SURFACES_THE_API_KNOWS = ['mcp', 'cli', 'wizard', 'slack', 'posthog_ai', 'posthog_code', 'self_driving']
+const SURFACES_THE_API_KNOWS = ['mcp', 'cli', 'wizard', 'slack', 'posthog_ai', 'posthog_code', 'self_driving', 'webmcp']
const SANDBOX_SCOPES = ['insight:read', 'internal_run:read']
const CONSENTED_SCOPES = ['insight:read']
@@ -14,6 +14,7 @@ const CONSENTED_SCOPES = ['insight:read']
const ARRAY_CLIENT_ID = 'DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ'
const POSTHOG_AI_CLIENT_ID = 'DD2ZLG6a2YEUtpPANSzSiIBPuUryYmbndLnKKUy1'
const SIGNALS_CLIENT_ID = 'xMT3Nejjbi4lUdhJLkzmCVJKFsx0JsHXdU0pIjl8'
+const WEBMCP_CLIENT_ID = 'https://posthog.com/.well-known/oauth/webmcp/client-metadata.json'
describe('resolveEventSource', () => {
it.each([
@@ -62,6 +63,11 @@ describe('resolveEventSource', () => {
{ mcpConsumer: 'posthog-code', apiKeyScopes: SANDBOX_SCOPES, oauthClientId: SIGNALS_CLIENT_ID },
EVENT_SOURCE.SELF_DRIVING,
],
+ [
+ 'the WebMCP proxy',
+ { mcpConsumer: 'webmcp', apiKeyScopes: CONSENTED_SCOPES, oauthClientId: WEBMCP_CLIENT_ID },
+ EVENT_SOURCE.WEBMCP,
+ ],
[
'a third-party application declaring a first-party consumer',
{ mcpConsumer: 'slack', apiKeyScopes: CONSENTED_SCOPES, oauthClientId: 'some-third-party-client-id' },
diff --git a/tach.toml b/tach.toml
index b278ac36a7ec..8ae00565ad2b 100644
--- a/tach.toml
+++ b/tach.toml
@@ -151,6 +151,7 @@ depends_on = [
"products.actions",
"products.alerts", "products.warehouse_sources", "products.data_tools", "products.exports", "products.annotations",
"products.security",
+ "products.webmcp",
]
layer = "modules"
@@ -1647,3 +1648,17 @@ expose = [
from = [
"products.today",
]
+
+[[modules]]
+path = "products.webmcp"
+depends_on = ["posthog"]
+layer = "modules"
+
+[[interfaces]]
+expose = [
+ "backend\\.facade.*",
+ "backend\\.presentation\\.views.*",
+]
+from = [
+ "products.webmcp",
+]