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(canvas): run allowlisted posthog mcp tools from canvases (#123064)

Harley Alexanderd05f072f8301
diff --git a/posthog/mcp_tool_definitions.py b/posthog/mcp_tool_definitions.py
index b1a264310efb..df4251d45981 100644
--- a/posthog/mcp_tool_definitions.py
+++ b/posthog/mcp_tool_definitions.py
@@ -59,6 +59,7 @@ class McpToolDefinition:
feature: str
required_scopes: tuple[str, ...]
read_only: bool
+ destructive: bool
requires_ai_consent: bool
# The flag gate, exactly as services/mcp/src/tools/toolDefinitions.ts reads it. The gate
# resolves per project, so a caller that needs the served catalogue for one project
@@ -93,6 +94,7 @@ def _definition_from_json(name: str, raw: Mapping[str, Any]) -> McpToolDefinitio
feature=raw["feature"],
required_scopes=tuple(raw.get("required_scopes") or ()),
read_only=bool(raw["annotations"]["readOnlyHint"]),
+ destructive=bool(raw["annotations"].get("destructiveHint", False)),
requires_ai_consent=bool(raw.get("requires_ai_consent", False)),
feature_flag=raw.get("feature_flag"),
feature_flag_behavior=raw.get("feature_flag_behavior"),
diff --git a/products/canvas/backend/capabilities.py b/products/canvas/backend/capabilities.py
index c4729962859d..022c9892a50a 100644
--- a/products/canvas/backend/capabilities.py
+++ b/products/canvas/backend/capabilities.py
@@ -36,6 +36,11 @@ def declared_actions(manifest: dict | None) -> set[str]:
return set(_posthog_section(manifest).get("actions") or [])
+def declared_tools(manifest: dict | None) -> set[str]:
+ """The PostHog MCP tools a capabilities manifest declares for ph.tools."""
+ return set(_posthog_section(manifest).get("tools") or [])
+
+
def declared_connectors(manifest: dict | None) -> dict[str, set[str]]:
"""The ph.connectors tools a capabilities manifest declares, keyed by provider."""
declared: dict[str, set[str]] = {}
@@ -61,6 +66,7 @@ class CapabilityWidening:
network_origins_added: list[str]
state_scopes_added: list[str]
actions_added: list[str]
+ tools_added: list[str]
connectors_added: list[ConnectorGrant]
@property
@@ -73,6 +79,7 @@ class CapabilityWidening:
or self.network_origins_added
or self.state_scopes_added
or self.actions_added
+ or self.tools_added
or self.connectors_added
)
@@ -96,6 +103,7 @@ def capability_widening(before: dict | None, after: dict | None) -> CapabilityWi
network_origins_added=sorted(set(_network_origins(after)) - set(_network_origins(before))),
state_scopes_added=sorted(set(after_ph.get("state") or []) - set(before_ph.get("state") or [])),
actions_added=sorted(set(after_ph.get("actions") or []) - set(before_ph.get("actions") or [])),
+ tools_added=sorted(declared_tools(after) - declared_tools(before)),
connectors_added=_connectors_added(declared_connectors(before), declared_connectors(after)),
)
diff --git a/products/canvas/backend/facade/api.py b/products/canvas/backend/facade/api.py
index 10a5ac0c6e74..938e09efd8bd 100644
--- a/products/canvas/backend/facade/api.py
+++ b/products/canvas/backend/facade/api.py
@@ -59,15 +59,19 @@ from products.canvas.backend.logic.runtime import (
action_required_scopes as action_required_scopes,
action_starts_cloud_run as action_starts_cloud_run,
call_connector as call_connector,
+ call_tool as call_tool,
execute_action as execute_action,
list_actions as list_actions,
+ list_tools as list_tools,
prepare_agent_request as prepare_agent_request,
prepare_fix_request as prepare_fix_request,
read_state as read_state,
read_state_value as read_state_value,
report_error as report_error,
set_state as set_state,
+ tool_required_scopes as tool_required_scopes,
validate_action as validate_action,
+ validate_tool as validate_tool,
)
from products.canvas.backend.logic.sources import (
build_action as build_action,
@@ -87,6 +91,7 @@ from products.canvas.backend.logic.sources import (
revert as revert,
wait_for_build as wait_for_build,
)
+from products.canvas.backend.mcp_tools import canvas_mcp_tools_enabled as canvas_mcp_tools_enabled
from products.canvas.backend.source import (
has_errors as has_errors,
validate_source_project as validate_source_project,
diff --git a/products/canvas/backend/facade/contracts.py b/products/canvas/backend/facade/contracts.py
index 60792e4e7d5d..f4820d886141 100644
--- a/products/canvas/backend/facade/contracts.py
+++ b/products/canvas/backend/facade/contracts.py
@@ -270,6 +270,7 @@ class CanvasCapabilityWidening:
network_origins_added: list[str]
state_scopes_added: list[str]
actions_added: list[str]
+ tools_added: list[str]
connectors_added: list[dict[str, Any]]
diff --git a/products/canvas/backend/logic/records.py b/products/canvas/backend/logic/records.py
index 47dee8fc062b..86bca414ff51 100644
--- a/products/canvas/backend/logic/records.py
+++ b/products/canvas/backend/logic/records.py
@@ -110,6 +110,7 @@ def widening_record(widening: CapabilityWidening) -> CanvasCapabilityWidening:
network_origins_added=widening.network_origins_added,
state_scopes_added=widening.state_scopes_added,
actions_added=widening.actions_added,
+ tools_added=widening.tools_added,
connectors_added=[{"provider": grant.provider, "tools": grant.tools} for grant in widening.connectors_added],
)
diff --git a/products/canvas/backend/logic/runtime.py b/products/canvas/backend/logic/runtime.py
index 7a1645dddb59..05be521791db 100644
--- a/products/canvas/backend/logic/runtime.py
+++ b/products/canvas/backend/logic/runtime.py
@@ -11,7 +11,12 @@ from rest_framework import status
from products.canvas.backend import error_reports
from products.canvas.backend.actions import CANVAS_ACTIONS, CanvasActionDenied
-from products.canvas.backend.capabilities import declared_actions, declared_connectors, declared_state_scopes
+from products.canvas.backend.capabilities import (
+ declared_actions,
+ declared_connectors,
+ declared_state_scopes,
+ declared_tools,
+)
from products.canvas.backend.connectors import ConnectorCallResult, call_connector_tool
from products.canvas.backend.contract import contract_limits
from products.canvas.backend.facade.contracts import (
@@ -25,6 +30,13 @@ from products.canvas.backend.facade.contracts import (
)
from products.canvas.backend.logic.canvases import canvas_row
from products.canvas.backend.logic.records import state_entry_record
+from products.canvas.backend.mcp_tools import (
+ CANVAS_MCP_TOOL_ALLOWLIST,
+ CanvasMcpToolError,
+ call_canvas_mcp_tool,
+ canvas_mcp_tool,
+ canvas_mcp_tools,
+)
from products.canvas.backend.models import Canvas, CanvasBuild, CanvasState
from products.canvas.backend.state_reads import CanvasStateReader
@@ -139,6 +151,57 @@ def execute_action(team_id: int, user_id: int, canvas_id: UUID, verb: str, paylo
raise CanvasRequestRejected(error.response.status_code, str(body.get("detail", "")), body=body) from error
+def list_tools() -> list[dict[str, Any]]:
+ return [
+ {
+ "name": tool.name,
+ "title": tool.title,
+ "summary": tool.summary,
+ "read_only": tool.read_only,
+ "destructive": tool.destructive,
+ }
+ for tool in canvas_mcp_tools()
+ ]
+
+
+def tool_required_scopes(tool: str) -> list[str] | None:
+ """The API scopes a scoped credential needs to run `tool`, or None for a tool canvases may not run."""
+ definition = canvas_mcp_tool(tool)
+ if definition is None:
+ return None
+ # A read-only tool needs only read access to the canvas, so a viewer-level member can load a board.
+ return ["canvas:read" if definition.read_only else "canvas:write", *definition.required_scopes]
+
+
+def validate_tool(capabilities: dict[str, Any] | None, tool: str) -> None:
+ """Raise CanvasRequestRejected unless canvases may run `tool` and this canvas declares it."""
+ if canvas_mcp_tool(tool) is None:
+ raise CanvasRequestRejected(
+ status.HTTP_400_BAD_REQUEST,
+ f'Canvases cannot run the tool "{tool}". Allowed tools: {", ".join(sorted(CANVAS_MCP_TOOL_ALLOWLIST))}.',
+ )
+ if tool not in declared_tools(capabilities):
+ raise CanvasRequestRejected(
+ status.HTTP_403_FORBIDDEN,
+ f'The canvas does not declare the tool "{tool}". Add it to capabilities.posthog.tools and publish.',
+ )
+
+
+def call_tool(team_id: int, user_id: int, tool: str, arguments: dict[str, Any]) -> dict[str, Any]:
+ """Run a validated tool as the viewer. Raises CanvasRequestRejected when the tool fails."""
+ try:
+ return call_canvas_mcp_tool(team_id, user_id, tool, arguments).result
+ except CanvasMcpToolError as error:
+ status_code: int
+ if error.outcome_unknown:
+ status_code = status.HTTP_504_GATEWAY_TIMEOUT
+ elif error.server_unavailable:
+ status_code = status.HTTP_502_BAD_GATEWAY
+ else:
+ status_code = status.HTTP_400_BAD_REQUEST
+ raise CanvasRequestRejected(status_code, str(error)) from error
+
+
def call_connector(
team_id: int,
user_id: int,
diff --git a/products/canvas/backend/mcp_tools.py b/products/canvas/backend/mcp_tools.py
new file mode 100644
index 000000000000..0ebab22f6b85
--- /dev/null
+++ b/products/canvas/backend/mcp_tools.py
@@ -0,0 +1,114 @@
+"""Canvas MCP tools: PostHog MCP tools a canvas may call as the viewer (ph.tools).
+
+The tool runs on the PostHog MCP server with a short-lived token minted for
+the viewer, so the canvas reuses the tool's own input handling, the viewer's
+permissions, approval policies and activity logging. A new capability is one
+line in the allowlist, not a new action verb.
+
+A canvas reads with ph.tools.read, which takes read-only tools only, and
+writes with ph.tools.call, which the host runs from a click and confirms
+with the viewer first.
+"""
+
+from typing import Any
+from uuid import UUID
+
+import structlog
+import posthoganalytics
+
+from posthog.dataclasses import frozen
+from posthog.mcp_tool_definitions import McpToolDefinition, get_mcp_tool_definitions
+
+from products.webmcp.backend.facade import api as webmcp_facade
+from products.webmcp.backend.facade.contracts import CallToolInput, McpServerError, McpServerTimeout
+
+logger = structlog.get_logger(__name__)
+
+# Rollout gate, evaluated per team. Fails closed because every call acts with the viewer's permissions.
+CANVAS_MCP_TOOLS_FLAG = "canvas-mcp-tools"
+
+# The tools a canvas may declare. Every entry must be a catalogued MCP tool; a
+# test checks that. Add a tool here only when one call to it is safe to run
+# from a button, because the viewer confirms a single call, not a sequence.
+CANVAS_MCP_TOOL_ALLOWLIST: frozenset[str] = frozenset(
+ {
+ "feature-flag-get-all",
+ "feature-flag-get-definition",
+ "feature-flag-enable",
+ "feature-flag-disable",
+ "feature-flag-set-release-condition-rollout",
+ }
+)
+
+
+class CanvasMcpToolError(Exception):
+ """The tool ran and failed, or the MCP server could not run it. The message is safe to show the viewer."""
+
+ def __init__(self, message: str, *, server_unavailable: bool = False, outcome_unknown: bool = False) -> None:
+ super().__init__(message)
+ self.server_unavailable = server_unavailable
+ # A write timed out after the server received it, so it can still apply.
+ self.outcome_unknown = outcome_unknown
+
+
+@frozen
+class CanvasMcpToolResult:
+ result: dict[str, Any]
+
+
+def canvas_mcp_tools_enabled(team_uuid: UUID | str) -> bool:
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ CANVAS_MCP_TOOLS_FLAG,
+ str(team_uuid),
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.exception("canvas_mcp_tools_flag_check_failed")
+ return False
+
+
+def canvas_mcp_tool(name: str) -> McpToolDefinition | None:
+ """The tool's catalogue entry when canvases may call it, else None."""
+ if name not in CANVAS_MCP_TOOL_ALLOWLIST:
+ return None
+ return get_mcp_tool_definitions().get(name)
+
+
+def canvas_mcp_tools() -> list[McpToolDefinition]:
+ definitions = get_mcp_tool_definitions()
+ return [definitions[name] for name in sorted(CANVAS_MCP_TOOL_ALLOWLIST) if name in definitions]
+
+
+def call_canvas_mcp_tool(team_id: int, user_id: int, tool: str, arguments: dict[str, Any]) -> CanvasMcpToolResult:
+ """Run one allowlisted tool as the viewer. Raises CanvasMcpToolError when it fails."""
+ try:
+ outcome = webmcp_facade.call_tool(
+ CallToolInput(user_id=user_id, team_id=team_id, tool=tool, arguments=arguments)
+ )
+ except McpServerTimeout as error:
+ definition = canvas_mcp_tool(tool)
+ if definition is not None and not definition.read_only:
+ logger.warning("canvas_mcp_tool_write_timed_out", tool=tool)
+ raise CanvasMcpToolError(
+ "The tool did not answer in time, and the change can still apply. "
+ "Load the current state before you try again.",
+ outcome_unknown=True,
+ ) from error
+ logger.warning("canvas_mcp_tool_server_error", tool=tool, error=str(error))
+ raise CanvasMcpToolError(
+ "The PostHog MCP server could not run this tool. Try again.", server_unavailable=True
+ ) from error
+ except McpServerError as error:
+ logger.warning("canvas_mcp_tool_server_error", tool=tool, error=str(error))
+ raise CanvasMcpToolError(
+ "The PostHog MCP server could not run this tool. Try again.", server_unavailable=True
+ ) from error
+ if outcome.is_error:
+ raise CanvasMcpToolError(outcome.text or f'The tool "{tool}" failed.')
+ if outcome.structured_content is None:
+ raise CanvasMcpToolError(f'The tool "{tool}" returned no JSON result.')
+ return CanvasMcpToolResult(result=outcome.structured_content)
diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.py
index c82ecdea3e92..4295e9aa6aa7 100644
--- a/products/canvas/backend/presentation/serializers.py
+++ b/products/canvas/backend/presentation/serializers.py
@@ -254,6 +254,18 @@ class CanvasPostHogCapabilitiesSerializer(serializers.Serializer):
"'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."
),
)
+ # Optional so projects published before ph.tools exist unchanged.
+ tools = serializers.ListField(
+ child=serializers.CharField(max_length=200),
+ required=False,
+ default=list,
+ max_length=32,
+ help_text=(
+ "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', "
+ "'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the "
+ "promote review."
+ ),
+ )
agentRequests = serializers.BooleanField(required=False, default=False)
@@ -341,6 +353,7 @@ class CanvasSourceProjectSerializer(serializers.Serializer):
"captureEvents": [],
"state": [],
"actions": [],
+ "tools": [],
"agentRequests": False,
},
"network": {"origins": []},
@@ -1123,6 +1136,10 @@ class CanvasCapabilityWideningSerializer(serializers.Serializer):
child=serializers.CharField(),
help_text="Action verbs the draft newly declares it may invoke via ph.actions.",
)
+ tools_added = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="PostHog MCP tools the draft newly declares it may run via ph.tools.",
+ )
connectors_added = CanvasConnectorDeclarationSerializer(
many=True,
help_text="Connector providers and tools the draft newly declares it may call via ph.connectors.",
@@ -1142,16 +1159,40 @@ class CanvasActionDefinitionSerializer(serializers.Serializer):
)
+class CanvasToolDefinitionSerializer(serializers.Serializer):
+ """One PostHog MCP tool a canvas may declare, as the host renders it before running it."""
+
+ name = serializers.CharField(help_text="MCP tool name, e.g. 'feature-flag-enable'.")
+ title = serializers.CharField(help_text="Human-readable tool title.")
+ summary = serializers.CharField(help_text="One line naming what the tool does.")
+ # The name shadows Field.read_only for mypy only: DRF moves declared fields off the class.
+ read_only = serializers.BooleanField( # type: ignore[assignment]
+ help_text="True when the tool only reads. A canvas runs read-only tools with ph.tools.read, others with "
+ "ph.tools.call."
+ )
+ destructive = serializers.BooleanField(
+ help_text="True when the tool deletes or overwrites something; the host warns the viewer before it runs."
+ )
+
+
class CanvasActionsResponseSerializer(serializers.Serializer):
- """The action registry: every verb a canvas may declare and invoke."""
+ """The action registry: every verb and PostHog MCP tool a canvas may declare and invoke."""
actions = CanvasActionDefinitionSerializer(many=True, help_text="Registered verbs, sorted by name.")
+ tools = CanvasToolDefinitionSerializer(
+ many=True,
+ help_text="PostHog MCP tools a canvas may declare in capabilities.posthog.tools, sorted by name. Read each "
+ "tool's input schema with the MCP `info` command.",
+ )
class CanvasActionInvokeSerializer(serializers.Serializer):
"""Payload for invoking one action verb."""
- verb = serializers.CharField(max_length=64, help_text="Registered verb to invoke, e.g. 'tasks.create'.")
+ # Untrimmed, so the scope check and the dispatch read the same verb.
+ verb = serializers.CharField(
+ max_length=64, trim_whitespace=False, help_text="Registered verb to invoke, e.g. 'tasks.create'."
+ )
payload = serializers.DictField(
required=False,
default=dict,
@@ -1168,6 +1209,27 @@ class CanvasActionResultSerializer(serializers.Serializer):
)
+class CanvasToolInvokeSerializer(serializers.Serializer):
+ """Payload for running one PostHog MCP tool."""
+
+ # Untrimmed, so the scope check and the dispatch read the same name.
+ tool = serializers.CharField(
+ max_length=200, trim_whitespace=False, help_text="MCP tool to run, e.g. 'feature-flag-enable'."
+ )
+ arguments = serializers.DictField(
+ required=False,
+ default=dict,
+ help_text="The tool's input, exactly as an MCP client passes it.",
+ )
+
+
+class CanvasToolResultSerializer(serializers.Serializer):
+ """Result of one PostHog MCP tool run."""
+
+ tool = serializers.CharField(help_text="The tool that ran.")
+ result = serializers.DictField(help_text="The tool's JSON result.")
+
+
class CanvasConnectorToolSerializer(serializers.Serializer):
"""One tool a connector provider exposes to canvases."""
diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.py
index b3b8eb06b240..853208d2feb5 100644
--- a/products/canvas/backend/presentation/views.py
+++ b/products/canvas/backend/presentation/views.py
@@ -107,6 +107,8 @@ from products.canvas.backend.presentation.serializers import (
CanvasStateValueQuerySerializer,
CanvasStateValueResponseSerializer,
CanvasSummarySerializer,
+ CanvasToolInvokeSerializer,
+ CanvasToolResultSerializer,
CanvasUpdateSerializer,
CanvasValidateRequestSerializer,
CanvasValidateResponseSerializer,
@@ -272,6 +274,13 @@ class CanvasActionInvokeThrottle(CanvasStateWriteThrottle):
rate = "60/min"
+class CanvasToolInvokeThrottle(CanvasStateWriteThrottle):
+ """Shares the action ceiling: a tool call is a real PostHog read or write as the viewer."""
+
+ scope = "canvas_tool_invoke"
+ rate = "60/min"
+
+
class CanvasConnectorCallThrottle(CanvasStateWriteThrottle):
scope = "canvas_connector_call"
rate = "120/min"
@@ -378,6 +387,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
"request_fix",
"set_state",
"invoke_action",
+ "invoke_tool",
"call_connector",
"request_agent",
"publish_layout",
@@ -392,6 +402,8 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
return [*super().get_throttles(), CanvasStateWriteThrottle()]
if self.action == "invoke_action":
return [*super().get_throttles(), CanvasActionInvokeThrottle()]
+ if self.action == "invoke_tool":
+ return [*super().get_throttles(), CanvasToolInvokeThrottle()]
if self.action == "call_connector":
return [*super().get_throttles(), CanvasConnectorCallThrottle()]
return super().get_throttles()
@@ -400,7 +412,11 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
# Invoking a verb writes the target resource, so a scoped credential
# must hold that resource's scope — canvas:write alone is not consent
# to create tasks or annotations.
- if getattr(view, "action", None) != "invoke_action":
+ action = getattr(view, "action", None)
+ if action == "invoke_tool":
+ tool = request.data.get("tool") if isinstance(request.data, dict) else None
+ return canvas_api.tool_required_scopes(tool) if isinstance(tool, str) else None
+ if action != "invoke_action":
return None
verb = request.data.get("verb") if isinstance(request.data, dict) else None
return canvas_api.action_required_scopes(verb) if isinstance(verb, str) else None
@@ -1791,8 +1807,12 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
)
@action(methods=["GET"], detail=False, url_path="actions")
def actions(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- """List the action registry: every verb a canvas may declare and invoke."""
- return Response(CanvasActionsResponseSerializer(instance={"actions": canvas_api.list_actions()}).data)
+ """List the action registry: every verb and PostHog MCP tool a canvas may declare and invoke."""
+ return Response(
+ CanvasActionsResponseSerializer(
+ instance={"actions": canvas_api.list_actions(), "tools": canvas_api.list_tools()}
+ ).data
+ )
@extend_schema(
operation_id="canvases_actions_invoke",
@@ -1852,6 +1872,74 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.GenericViewSet):
self._report_canvas_action("canvas action invoked", canvas, verb=verb)
return Response(CanvasActionResultSerializer(instance={"verb": verb, "result": result}).data)
+ @extend_schema(
+ operation_id="canvases_tools_invoke",
+ request=CanvasToolInvokeSerializer,
+ responses={
+ 200: CanvasToolResultSerializer,
+ 400: OpenApiResponse(
+ description="Canvases cannot run the tool, or the tool ran and failed. `detail` holds the tool's error."
+ ),
+ 403: OpenApiResponse(
+ description="The tool is not declared in the canvas's capabilities, canvas tools are off for the team, "
+ "or the caller is a sandbox or an impersonated session."
+ ),
+ 502: OpenApiResponse(description="The PostHog MCP server could not run the tool."),
+ 504: OpenApiResponse(
+ description="A tool that changes data did not answer in time. The change can still apply."
+ ),
+ },
+ )
+ @action(methods=["POST"], detail=True, url_path="tools/invoke")
+ def invoke_tool(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Run one PostHog MCP tool as the viewer.
+
+ The canvas must declare the tool in capabilities.posthog.tools. The
+ tool runs on the MCP server with a token minted for the viewer, so it
+ has the viewer's own permissions, exactly as if they called it from
+ an MCP client.
+ """
+ canvas = self._canvas()
+ user = self._state_actor(request)
+ # A sandbox token authenticates as its user, so the user check alone lets an agent through.
+ if user is None or self._is_sandbox_authenticated(request):
+ return Response(
+ {"detail": "Canvas tools are run by viewers; sandbox tokens cannot use them."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ # A minted token would carry the impersonated user's access past the read-only session rules.
+ if is_impersonated(request):
+ return Response(
+ {"detail": "Canvas tools are not available in an impersonated session."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ if canvas_actions_disabled(self.team.uuid) or not canvas_api.canvas_mcp_tools_enabled(self.team.uuid):
+ return Response(
+ {"detail": "Canvas tools are not enabled for this team."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ payload = CanvasToolInvokeSerializer(data=request.data)
+ payload.is_valid(raise_exception=True)
+ tool = payload.validated_data["tool"]
+ try:
+ canvas_api.validate_tool(canvas.head_capabilities, tool)
+ result = canvas_api.call_tool(self.team_id, user.id, tool, payload.validated_data["arguments"])
+ except CanvasRequestRejected as rejection:
+ self._report_canvas_action(
+ "canvas tool invoked", canvas, tool=tool, succeeded=False, status_code=rejection.status_code
+ )
+ return Response(rejection.body, status=rejection.status_code)
+ self._log_canvas_activity(
+ canvas,
+ "tool_invoked",
+ Detail(
+ name=canvas.name,
+ trigger=Trigger(job_type="canvas_tool", job_id=tool, payload={"tool": tool}),
+ ),
+ )
+ self._report_canvas_action("canvas tool invoked", canvas, tool=tool, succeeded=True, status_code=200)
+ return Response(CanvasToolResultSerializer(instance={"tool": tool, "result": result}).data)
+
@extend_schema(
operation_id="canvases_connectors_retrieve",
parameters=[
diff --git a/products/canvas/backend/source.py b/products/canvas/backend/source.py
index 7aa68790b0d0..80ebc3b67191 100644
--- a/products/canvas/backend/source.py
+++ b/products/canvas/backend/source.py
@@ -34,6 +34,7 @@ from products.canvas.backend.contract import (
contract_limits,
platform_dependencies,
)
+from products.canvas.backend.mcp_tools import CANVAS_MCP_TOOL_ALLOWLIST, canvas_mcp_tool
CANVAS_SOURCE_SCHEMA_VERSION = 1
CANVAS_ENTRY_HTML = "index.html"
@@ -179,6 +180,7 @@ _PH_STATE_RE = re.compile(r"\bph\s*\.\s*state\s*\.")
_PH_STATE_CALL_RE = re.compile(r"\bph\s*\.\s*state\s*\.\s*(get|set|list)\s*\(")
_STATE_SCOPE_LITERAL_RE = re.compile(r"\bscope\s*:\s*[\"']([^\"']+)[\"']")
_PH_ACTIONS_RE = re.compile(r"\bph\s*\.\s*actions\s*\.\s*invoke\s*\(\s*(?:[\"']([^\"']+)[\"'])?")
+_PH_TOOLS_RE = re.compile(r"\bph\s*\.\s*tools\s*\.\s*(read|call)\s*\(\s*(?:[\"']([^\"']+)[\"'])?")
_PH_AGENT_REQUEST_RE = re.compile(r"\bph\s*\.\s*agent\s*\.\s*request\s*\(")
_PH_CONNECTORS_CALL_RE = re.compile(
r"\bph\s*\.\s*connectors\s*\.\s*call\s*\(\s*(?:[\"']([^\"']+)[\"']\s*(?:,\s*[\"']([^\"']+)[\"'])?)?"
@@ -529,6 +531,33 @@ def _validate_capabilities(path: str, code: str, capabilities: dict[str, Any]) -
)
)
+ declared_tool_names = set(posthog_capabilities.get("tools") or [])
+ for match in _PH_TOOLS_RE.finditer(code):
+ method, tool = match.group(1), match.group(2)
+ line = _line_of(code, match.start())
+ if tool is not None and tool not in declared_tool_names:
+ diagnostics.append(
+ diagnostic(
+ "error",
+ "capability_missing_tool",
+ f'ph.tools.{method}("{tool}") requires "{tool}" in capabilities.posthog.tools. '
+ "The host rejects undeclared tools at runtime.",
+ path=path,
+ line=line,
+ )
+ )
+ elif tool is None and not declared_tool_names:
+ diagnostics.append(
+ diagnostic(
+ "warning",
+ "capability_missing_tool",
+ f"ph.tools.{method}() is called with a dynamic tool name but capabilities.posthog.tools is "
+ "empty. Declare every tool the canvas runs.",
+ path=path,
+ line=line,
+ )
+ )
+
for match in _PH_LOAD_INSIGHT_RE.finditer(code):
short_id = match.group(1)
line = _line_of(code, match.start())
@@ -780,6 +809,21 @@ def validate_source_project(project: dict[str, Any], *, kind: str = "freeform")
+ ", ".join(sorted(CANVAS_ACTIONS)),
)
)
+ declared_tools = (capabilities.get("posthog") or {}).get("tools") or []
+ disallowed_tools = sorted(
+ {str(tool) for tool in declared_tools if not isinstance(tool, str) or canvas_mcp_tool(tool) is None}
+ )
+ if disallowed_tools:
+ diagnostics.append(
+ diagnostic(
+ "error",
+ "tool_not_allowed",
+ "capabilities.posthog.tools declares tools canvases cannot run: "
+ + ", ".join(disallowed_tools)
+ + ". Allowed tools: "
+ + ", ".join(sorted(CANVAS_MCP_TOOL_ALLOWLIST)),
+ )
+ )
diagnostics.extend(_validate_connector_declarations(capabilities.get("connectors") or []))
if capabilities.get("connectors") and "shared" in (capabilities.get("posthog") or {}).get("state", []):
diagnostics.append(
diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.py
index 86a1d42d8f80..3b2bbcdf8fc5 100644
--- a/products/canvas/backend/tests/test_canvas_api.py
+++ b/products/canvas/backend/tests/test_canvas_api.py
@@ -34,12 +34,14 @@ from products.annotations.backend.models.annotation import Annotation
from products.canvas.backend import build_service
from products.canvas.backend.actions import CANVAS_ACTIONS, TaskCreatePayloadSerializer
from products.canvas.backend.facade import access as canvas_facade
+from products.canvas.backend.mcp_tools import CANVAS_MCP_TOOL_ALLOWLIST
from products.canvas.backend.models import Canvas, CanvasBuild, CanvasSourceVersion
from products.canvas.backend.source import synthetic_source_project
from products.tasks.backend.facade.access import DesktopAccessDecision
from products.tasks.backend.facade.ai_run_defaults import update_team_ai_run_preferences, update_user_ai_run_preferences
from products.tasks.backend.facade.contracts import ComputeQuotaDenialReason
from products.tasks.backend.models import Channel, Task, TaskRun, TaskThreadMessage
+from products.webmcp.backend.facade.contracts import CallToolInput, McpServerError, McpServerTimeout, ToolCallResult
from products.workflows.backend.facade.api import get_workflow_summary
from products.workflows.backend.facade.testing import create_workflow_for_test
@@ -105,7 +107,9 @@ class CanvasAPIBaseTest(APIBaseTest):
assert entry.detail is not None
return entry.detail["changes"]
- def _sandbox_client(self, task_id: UUID, *, user: User | None = None) -> APIClient:
+ def _sandbox_client(
+ self, task_id: UUID, *, user: User | None = None, scope: str = "canvas:read canvas:write task:read"
+ ) -> APIClient:
actor = user or self.user
application = OAuthApplication.objects.create(
name="Canvas sandbox",
@@ -122,7 +126,7 @@ class CanvasAPIBaseTest(APIBaseTest):
application=application,
token=f"pha_canvas_{uuid4().hex}",
expires=timezone.now() + timedelta(hours=1),
- scope="canvas:read canvas:write task:read",
+ scope=scope,
scoped_teams=[self.team.id],
sandbox_task_id=task_id,
)
@@ -1357,6 +1361,7 @@ class TestCanvasActivityLog(CanvasAPIBaseTest):
"captureEvents": [],
"state": [],
"actions": [],
+ "tools": [],
"agentRequests": False,
},
"network": {"origins": []},
@@ -1369,6 +1374,7 @@ class TestCanvasActivityLog(CanvasAPIBaseTest):
"captureEvents": [],
"state": [],
"actions": [],
+ "tools": [],
"agentRequests": False,
},
"network": {"origins": []},
@@ -2393,10 +2399,12 @@ class TestCanvasActions(CanvasAPIBaseTest):
("cloud_canvas_scope_only", "tasks.create_and_run", ["canvas:write"], status.HTTP_403_FORBIDDEN),
("workflow_canvas_scope_only", "workflows.pause", ["canvas:write"], status.HTTP_403_FORBIDDEN),
("workflow_scope_held", "workflows.pause", ["canvas:write", "hog_flow:write"], status.HTTP_200_OK),
+ # A padded verb must not slip past the scope check and run once trimmed.
+ ("padded_verb", " tasks.create ", ["canvas:write"], status.HTTP_400_BAD_REQUEST),
]
)
def test_scoped_keys_need_the_verbs_target_scope(self, _name, verb, scopes, expected_status):
- canvas_id = self._actions_canvas(verbs=(verb,))
+ canvas_id = self._actions_canvas(verbs=(verb.strip(),))
raw_key = generate_random_token_personal()
PersonalAPIKey.objects.create(
label="canvas-actions", user=self.user, secure_value=hash_key_value(raw_key), scopes=scopes
@@ -2529,6 +2537,9 @@ class TestCanvasActions(CanvasAPIBaseTest):
assert set(rows) == set(CANVAS_ACTIONS)
for row in rows.values():
assert row["usage"].strip(), f"verb {row['verb']} shipped without usage docs"
+ # A renamed or removed MCP tool drops out of the catalogue, so a canvas
+ # that declares it would fail at runtime with no build-time warning.
+ assert {row["name"] for row in response.json()["tools"]} == CANVAS_MCP_TOOL_ALLOWLIST
def test_tasks_create_files_a_task_in_the_canvas_channel_as_the_viewer(self):
canvas_id = self._actions_canvas()
@@ -2745,6 +2756,171 @@ class TestCanvasActions(CanvasAPIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
+class TestCanvasTools(CanvasAPIBaseTest):
+ def setUp(self):
+ super().setUp()
+ enabled = patch(
+ "products.canvas.backend.presentation.views.canvas_api.canvas_mcp_tools_enabled", return_value=True
+ )
+ self.enabled = enabled.start()
+ self.addCleanup(enabled.stop)
+ call_tool = patch(
+ "products.canvas.backend.mcp_tools.webmcp_facade.call_tool",
+ return_value=ToolCallResult(structured_content={"id": 7, "active": True}, text="", is_error=False),
+ )
+ self.call_tool = call_tool.start()
+ self.addCleanup(call_tool.stop)
+
+ def _tools_canvas(self, tools: tuple[str, ...] = ("feature-flag-enable",)) -> str:
+ canvas_id = self._create_canvas()
+ capabilities = {
+ "posthog": {"insights": [], "inlineQueries": False, "captureEvents": [], "state": [], "tools": list(tools)},
+ "network": {"origins": []},
+ }
+ response = self._publish(canvas_id, project=self._project(capabilities=capabilities))
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return canvas_id
+
+ def _invoke(self, canvas_id: str, tool: str, arguments: dict[str, Any], **extra: Any):
+ return self.client.post(
+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/tools/invoke/",
+ {"tool": tool, "arguments": arguments},
+ format="json",
+ **extra,
+ )
+
+ def test_runs_a_declared_tool_as_the_viewer(self):
+ canvas_id = self._tools_canvas()
+
+ response = self._invoke(canvas_id, "feature-flag-enable", {"id": 7})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"tool": "feature-flag-enable", "result": {"id": 7, "active": True}}
+ self.call_tool.assert_called_once_with(
+ CallToolInput(user_id=self.user.id, team_id=self.team.id, tool="feature-flag-enable", arguments={"id": 7})
+ )
+ [entry] = self._activity("tool_invoked")
+ assert entry.detail is not None
+ assert entry.detail["trigger"]["job_id"] == "feature-flag-enable"
+
+ @parameterized.expand(
+ [
+ ("undeclared", "feature-flag-disable", {}, status.HTTP_403_FORBIDDEN),
+ ("not_allowlisted", "feature-flags-bulk-delete-create", {}, status.HTTP_400_BAD_REQUEST),
+ ("rollout_flag_off", "feature-flag-enable", {"enabled": False}, status.HTTP_403_FORBIDDEN),
+ ("kill_switch", "feature-flag-enable", {"kill_switch": True}, status.HTTP_403_FORBIDDEN),
+ ("impersonated", "feature-flag-enable", {"impersonated": True}, status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_refuses_before_reaching_the_mcp_server(self, _name, tool, gates, expected_status):
+ canvas_id = self._tools_canvas()
+ self.enabled.return_value = gates.get("enabled", True)
+
+ with (
+ patch(
+ "products.canvas.backend.presentation.views.canvas_actions_disabled",
+ return_value=gates.get("kill_switch", False),
+ ),
+ patch(
+ "products.canvas.backend.presentation.views.is_impersonated",
+ return_value=gates.get("impersonated", False),
+ ),
+ ):
+ response = self._invoke(canvas_id, tool, {"id": 7})
+
+ assert response.status_code == expected_status, response.json()
+ self.call_tool.assert_not_called()
+
+ def test_refuses_a_sandbox_token_that_holds_the_tool_scopes(self):
+ canvas_id = self._tools_canvas()
+ bound_task = Task.objects.create(
+ team=self.team,
+ channel=self.channel,
+ created_by=self.user,
+ title="Bound",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ client = self._sandbox_client(bound_task.id, scope="canvas:read canvas:write feature_flag:write")
+
+ response = client.post(
+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/tools/invoke/",
+ {"tool": "feature-flag-enable", "arguments": {"id": 7}},
+ format="json",
+ HTTP_X_POSTHOG_TASK_ID=str(bound_task.id),
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ assert response.json()["detail"] == "Canvas tools are run by viewers; sandbox tokens cannot use them."
+ self.call_tool.assert_not_called()
+
+ @parameterized.expand(
+ [
+ (
+ "tool_error",
+ ToolCallResult(structured_content=None, text="Error: version conflict", is_error=True),
+ status.HTTP_400_BAD_REQUEST,
+ "Error: version conflict",
+ ),
+ (
+ "server_unreachable",
+ McpServerError("Could not reach the MCP server: ConnectionError"),
+ status.HTTP_502_BAD_GATEWAY,
+ "The PostHog MCP server could not run this tool. Try again.",
+ ),
+ (
+ # The server can still apply the write, so the viewer must not retry blind.
+ "write_timed_out",
+ McpServerTimeout("The MCP server did not answer in time"),
+ status.HTTP_504_GATEWAY_TIMEOUT,
+ "The tool did not answer in time, and the change can still apply. "
+ "Load the current state before you try again.",
+ ),
+ ]
+ )
+ def test_reports_a_failed_tool_to_the_canvas(self, _name, outcome, expected_status, expected_detail):
+ canvas_id = self._tools_canvas()
+ if isinstance(outcome, Exception):
+ self.call_tool.side_effect = outcome
+ else:
+ self.call_tool.return_value = outcome
+
+ response = self._invoke(canvas_id, "feature-flag-enable", {"id": 7})
+
+ assert response.status_code == expected_status
+ assert response.json()["detail"] == expected_detail
+ assert self._activity("tool_invoked") == []
+
+ @parameterized.expand(
+ [
+ # canvas:write alone is not consent to change feature flags.
+ ("canvas_scope_only", "feature-flag-enable", ["canvas:write"], status.HTTP_403_FORBIDDEN),
+ ("target_scope_held", "feature-flag-enable", ["canvas:write", "feature_flag:write"], status.HTTP_200_OK),
+ # A padded name must not slip past the scope check and run once trimmed.
+ ("padded_tool_name", " feature-flag-enable ", ["canvas:write"], status.HTTP_400_BAD_REQUEST),
+ # A board viewer reads flags without write access to the canvas.
+ (
+ "read_tool_read_scopes",
+ "feature-flag-get-definition",
+ ["canvas:read", "feature_flag:read"],
+ status.HTTP_200_OK,
+ ),
+ ]
+ )
+ def test_scoped_keys_need_the_tools_scope(self, _name, tool, scopes, expected_status):
+ canvas_id = self._tools_canvas(("feature-flag-enable", "feature-flag-get-definition"))
+ raw_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="canvas-tools", user=self.user, secure_value=hash_key_value(raw_key), scopes=scopes
+ )
+ self.client.logout()
+
+ response = self._invoke(canvas_id, tool, {"id": 7}, HTTP_AUTHORIZATION=f"Bearer {raw_key}")
+
+ assert response.status_code == expected_status, response.json()
+ assert self.call_tool.called is (expected_status == status.HTTP_200_OK)
+
+
class TestTaskCreatePayloadSerializer(SimpleTestCase):
def test_title_over_the_task_store_limit_is_rejected(self):
# The task store caps title at 255; a longer value would reach Postgres
diff --git a/products/canvas/backend/tests/test_capabilities.py b/products/canvas/backend/tests/test_capabilities.py
index fcabeaccf54e..6b59bcc0d437 100644
--- a/products/canvas/backend/tests/test_capabilities.py
+++ b/products/canvas/backend/tests/test_capabilities.py
@@ -20,6 +20,7 @@ WIDER = {
"inlineQueries": True,
"state": ["user"],
"actions": ["tasks.create"],
+ "tools": ["feature-flag-enable"],
"agentRequests": True,
},
"network": {"origins": ["https://api.example.com"]},
@@ -56,6 +57,7 @@ class TestCapabilityWidening(TestCase):
assert widening.network_origins_added == ["https://api.example.com"]
assert widening.state_scopes_added == ["user"]
assert widening.actions_added == ["tasks.create"]
+ assert widening.tools_added == ["feature-flag-enable"]
assert widening.connectors_added == [
ConnectorGrant(provider="github", tools=["list_pull_requests", "search_issues"]),
ConnectorGrant(provider="mcp:mcp.example.com", tools=["list_events"]),
diff --git a/products/canvas/backend/tests/test_source.py b/products/canvas/backend/tests/test_source.py
index 88527a88804b..173db713cfc8 100644
--- a/products/canvas/backend/tests/test_source.py
+++ b/products/canvas/backend/tests/test_source.py
@@ -122,6 +122,22 @@ class TestCanvasSourceAdapter(SimpleTestCase):
project(capabilities={"posthog": {"actions": ["flags.delete"]}, "network": {"origins": []}}),
"action_not_registered",
),
+ (
+ "undeclared_tool_call",
+ project(files={CANVAS_COMPONENT_PATH: CODE + 'ph.tools.call("feature-flag-enable", { id: 1 });'}),
+ "capability_missing_tool",
+ ),
+ (
+ # Only allowlisted tools may be declared, so a canvas cannot reach a bulk delete.
+ "disallowed_declared_tool",
+ project(
+ capabilities={
+ "posthog": {"tools": ["feature-flags-bulk-delete-create"]},
+ "network": {"origins": []},
+ }
+ ),
+ "tool_not_allowed",
+ ),
(
"undeclared_connector_call",
project(
diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.ts
index af3e3f917ef2..fababe3aee4e 100644
--- a/products/canvas/frontend/generated/api.schemas.ts
+++ b/products/canvas/frontend/generated/api.schemas.ts
@@ -736,6 +736,12 @@ export interface CanvasPostHogCapabilitiesApi {
* @items.maxLength 64
*/
actions?: string[]
+ /**
+ * PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review.
+ * @maxItems 32
+ * @items.maxLength 200
+ */
+ tools?: string[]
agentRequests?: boolean
}
@@ -843,6 +849,8 @@ export interface CanvasCapabilityWideningApi {
state_scopes_added: string[]
/** Action verbs the draft newly declares it may invoke via ph.actions. */
actions_added: string[]
+ /** PostHog MCP tools the draft newly declares it may run via ph.tools. */
+ tools_added: string[]
/** Connector providers and tools the draft newly declares it may call via ph.connectors. */
connectors_added: CanvasConnectorDeclarationApi[]
}
@@ -1662,6 +1670,39 @@ export interface CanvasStateValueResponseApi {
complete: boolean
}
+/**
+ * The tool's input, exactly as an MCP client passes it.
+ */
+export type CanvasToolInvokeApiArguments = { [key: string]: unknown }
+
+/**
+ * Payload for running one PostHog MCP tool.
+ */
+export interface CanvasToolInvokeApi {
+ /**
+ * MCP tool to run, e.g. 'feature-flag-enable'.
+ * @maxLength 200
+ */
+ tool: string
+ /** The tool's input, exactly as an MCP client passes it. */
+ arguments?: CanvasToolInvokeApiArguments
+}
+
+/**
+ * The tool's JSON result.
+ */
+export type CanvasToolResultApiResult = { [key: string]: unknown }
+
+/**
+ * Result of one PostHog MCP tool run.
+ */
+export interface CanvasToolResultApi {
+ /** The tool that ran. */
+ tool: string
+ /** The tool's JSON result. */
+ result: CanvasToolResultApiResult
+}
+
/**
* Payload for validating a candidate source project without publishing it.
*/
@@ -1766,11 +1807,29 @@ export interface CanvasActionDefinitionApi {
}
/**
- * The action registry: every verb a canvas may declare and invoke.
+ * One PostHog MCP tool a canvas may declare, as the host renders it before running it.
+ */
+export interface CanvasToolDefinitionApi {
+ /** MCP tool name, e.g. 'feature-flag-enable'. */
+ name: string
+ /** Human-readable tool title. */
+ title: string
+ /** One line naming what the tool does. */
+ summary: string
+ /** True when the tool only reads. A canvas runs read-only tools with ph.tools.read, others with ph.tools.call. */
+ read_only: boolean
+ /** True when the tool deletes or overwrites something; the host warns the viewer before it runs. */
+ destructive: boolean
+}
+
+/**
+ * The action registry: every verb and PostHog MCP tool a canvas may declare and invoke.
*/
export interface CanvasActionsResponseApi {
/** Registered verbs, sorted by name. */
actions: CanvasActionDefinitionApi[]
+ /** PostHog MCP tools a canvas may declare in capabilities.posthog.tools, sorted by name. Read each tool's input schema with the MCP `info` command. */
+ tools: CanvasToolDefinitionApi[]
}
/**
diff --git a/products/canvas/frontend/generated/api.ts b/products/canvas/frontend/generated/api.ts
index fc1a8f11aa64..f4f17cad8aca 100644
--- a/products/canvas/frontend/generated/api.ts
+++ b/products/canvas/frontend/generated/api.ts
@@ -46,6 +46,8 @@ import type {
CanvasStateResponseApi,
CanvasStateSetApi,
CanvasStateValueResponseApi,
+ CanvasToolInvokeApi,
+ CanvasToolResultApi,
CanvasValidateRequestApi,
CanvasValidateResponseApi,
CanvasViewResponseApi,
@@ -805,6 +807,32 @@ export const canvasesStateValueRetrieve = async (
})
}
+export const getCanvasesToolsInvokeUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/canvases/${id}/tools/invoke/`
+}
+
+/**
+ * Run one PostHog MCP tool as the viewer.
+ *
+ * The canvas must declare the tool in capabilities.posthog.tools. The
+ * tool runs on the MCP server with a token minted for the viewer, so it
+ * has the viewer's own permissions, exactly as if they called it from
+ * an MCP client.
+ */
+export const canvasesToolsInvoke = async (
+ projectId: string,
+ id: string,
+ canvasToolInvokeApi: CanvasToolInvokeApi,
+ options?: RequestInit
+): Promise<CanvasToolResultApi> => {
+ return apiMutator<CanvasToolResultApi>(getCanvasesToolsInvokeUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(canvasToolInvokeApi),
+ })
+}
+
export const getCanvasesValidateCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/canvases/${id}/validate/`
}
@@ -893,7 +921,7 @@ export const getCanvasesActionsRetrieveUrl = (projectId: string) => {
}
/**
- * List the action registry: every verb a canvas may declare and invoke.
+ * List the action registry: every verb and PostHog MCP tool a canvas may declare and invoke.
*/
export const canvasesActionsRetrieve = async (
projectId: string,
diff --git a/products/canvas/frontend/generated/api.zod.ts b/products/canvas/frontend/generated/api.zod.ts
index 895e1ed76a14..3b80eb771698 100644
--- a/products/canvas/frontend/generated/api.zod.ts
+++ b/products/canvas/frontend/generated/api.zod.ts
@@ -175,6 +175,10 @@ export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsItemM
export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax = 200
+
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogToolsMax = 32
+
export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = false
export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048
@@ -324,6 +328,17 @@ export const CanvasesDraftCreateBody = /* @__PURE__ */ zod
.describe(
"Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."
),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax)
+ )
+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogToolsMax)
+ .optional()
+ .describe(
+ "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review."
+ ),
agentRequests: zod
.boolean()
.default(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault),
@@ -409,6 +424,10 @@ export const canvasesEditCreateBodyCapabilitiesOnePosthogActionsItemMax = 64
export const canvasesEditCreateBodyCapabilitiesOnePosthogActionsMax = 32
+export const canvasesEditCreateBodyCapabilitiesOnePosthogToolsItemMax = 200
+
+export const canvasesEditCreateBodyCapabilitiesOnePosthogToolsMax = 32
+
export const canvasesEditCreateBodyCapabilitiesOnePosthogAgentRequestsDefault = false
export const canvasesEditCreateBodyCapabilitiesOneNetworkOriginsItemMax = 2048
@@ -496,6 +515,13 @@ export const CanvasesEditCreateBody = /* @__PURE__ */ zod
.describe(
"Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."
),
+ tools: zod
+ .array(zod.string().max(canvasesEditCreateBodyCapabilitiesOnePosthogToolsItemMax))
+ .max(canvasesEditCreateBodyCapabilitiesOnePosthogToolsMax)
+ .optional()
+ .describe(
+ "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review."
+ ),
agentRequests: zod
.boolean()
.default(canvasesEditCreateBodyCapabilitiesOnePosthogAgentRequestsDefault),
@@ -959,6 +985,10 @@ export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsIte
export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax = 200
+
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogToolsMax = 32
+
export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = false
export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048
@@ -1110,6 +1140,17 @@ export const CanvasesPublishCreateBody = /* @__PURE__ */ zod
.describe(
"Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."
),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax)
+ )
+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogToolsMax)
+ .optional()
+ .describe(
+ "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review."
+ ),
agentRequests: zod
.boolean()
.default(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault),
@@ -1287,6 +1328,26 @@ export const CanvasesStateSetBody = /* @__PURE__ */ zod
})
.describe("Payload for writing (or deleting) one key of a canvas's runtime state.")
+/**
+ * Run one PostHog MCP tool as the viewer.
+ *
+ * The canvas must declare the tool in capabilities.posthog.tools. The
+ * tool runs on the MCP server with a token minted for the viewer, so it
+ * has the viewer's own permissions, exactly as if they called it from
+ * an MCP client.
+ */
+export const canvasesToolsInvokeBodyToolMax = 200
+
+export const CanvasesToolsInvokeBody = /* @__PURE__ */ zod
+ .object({
+ tool: zod.string().max(canvasesToolsInvokeBodyToolMax).describe("MCP tool to run, e.g. 'feature-flag-enable'."),
+ arguments: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe("The tool's input, exactly as an MCP client passes it."),
+ })
+ .describe('Payload for running one PostHog MCP tool.')
+
/**
* Validate a candidate source project without publishing it. Side-effect free.
*/
@@ -1321,6 +1382,10 @@ export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsIt
export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax = 200
+
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogToolsMax = 32
+
export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = false
export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048
@@ -1470,6 +1535,17 @@ export const CanvasesValidateCreateBody = /* @__PURE__ */ zod
.describe(
"Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."
),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax)
+ )
+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogToolsMax)
+ .optional()
+ .describe(
+ "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review."
+ ),
agentRequests: zod
.boolean()
.default(
diff --git a/products/canvas/frontend/host/canvasCapabilities.test.ts b/products/canvas/frontend/host/canvasCapabilities.test.ts
index 7c7fb35d6315..89a49d554f4e 100644
--- a/products/canvas/frontend/host/canvasCapabilities.test.ts
+++ b/products/canvas/frontend/host/canvasCapabilities.test.ts
@@ -8,6 +8,7 @@ const capabilities: CanvasCapabilitiesApi = {
captureEvents: ['canvas clicked'],
state: ['user'],
actions: ['annotations.create'],
+ tools: ['feature-flag-enable'],
agentRequests: false,
},
network: { origins: [] },
@@ -26,6 +27,8 @@ describe('assertCanvasCapability', () => {
['stateList', {}, 'State scope "any" is not allowed by this canvas'],
['actionInvoke', { verb: 'annotations.create' }, null],
['actionInvoke', { verb: 'flags.delete' }, 'Action "flags.delete" is not allowed by this canvas'],
+ ['toolCall', { tool: 'feature-flag-enable' }, null],
+ ['toolRead', { tool: 'feature-flag-disable' }, 'Tool "feature-flag-disable" is not allowed by this canvas'],
['agentRequest', { prompt: 'x' }, 'Agent requests are not allowed by this canvas'],
['connectorCall', { provider: 'github', tool: 'list_pull_requests' }, null],
[
diff --git a/products/canvas/frontend/host/canvasCapabilities.ts b/products/canvas/frontend/host/canvasCapabilities.ts
index a18b2c2d2858..6b359289e79d 100644
--- a/products/canvas/frontend/host/canvasCapabilities.ts
+++ b/products/canvas/frontend/host/canvasCapabilities.ts
@@ -54,6 +54,14 @@ export function assertCanvasCapability(
}
return
}
+ case 'toolRead':
+ case 'toolCall': {
+ const tool = input.tool
+ if (typeof tool !== 'string' || !(capabilities.posthog.tools ?? []).includes(tool)) {
+ throw new Error(`Tool "${typeof tool === 'string' ? tool : ''}" is not allowed by this canvas`)
+ }
+ return
+ }
case 'agentRequest':
if (!capabilities.posthog.agentRequests) {
throw new Error('Agent requests are not allowed by this canvas')
diff --git a/products/canvas/frontend/host/canvasDataBridge.test.ts b/products/canvas/frontend/host/canvasDataBridge.test.ts
index 069cb68fb8bb..a134b2008af4 100644
--- a/products/canvas/frontend/host/canvasDataBridge.test.ts
+++ b/products/canvas/frontend/host/canvasDataBridge.test.ts
@@ -1,6 +1,6 @@
import api from 'lib/api'
-import { canvasesActionsInvoke, canvasesActionsRetrieve } from '../generated/api'
+import { canvasesActionsInvoke, canvasesActionsRetrieve, canvasesToolsInvoke } from '../generated/api'
import { CanvasDataBridge } from './canvasDataBridge'
jest.mock('../generated/api')
@@ -85,7 +85,7 @@ describe('CanvasDataBridge action confirmation', () => {
description: 'Check the example chart.',
idempotency_key: 'one',
}
- jest.mocked(canvasesActionsRetrieve).mockResolvedValue({ actions: [action] })
+ jest.mocked(canvasesActionsRetrieve).mockResolvedValue({ actions: [action], tools: [] })
jest.mocked(canvasesActionsInvoke)
.mockReset()
.mockResolvedValue({ verb: action.verb, result: { task_id: 'task-1' } })
@@ -119,4 +119,53 @@ describe('CanvasDataBridge action confirmation', () => {
}
expect(confirmAction).toHaveBeenCalledWith({ action, payload })
})
+
+ const writeTool = {
+ name: 'feature-flag-enable',
+ title: 'Enable feature flag',
+ summary: 'Enable feature flag',
+ read_only: false,
+ destructive: false,
+ }
+ const readTool = { ...writeTool, name: 'feature-flag-get-definition', read_only: true }
+
+ test.each([
+ // A canvas must not change data from a load or render, so reads take read-only tools only.
+ { method: 'toolRead', tool: writeTool, allowed: true, error: 'changes data' },
+ { method: 'toolCall', tool: writeTool, allowed: false, error: 'Canvas tool call canceled' },
+ { method: 'toolCall', tool: writeTool, allowed: true, error: null },
+ { method: 'toolRead', tool: readTool, allowed: false, error: null },
+ ])('$method of $tool.name with approval $allowed', async ({ method, tool, allowed, error }) => {
+ jest.mocked(canvasesActionsRetrieve).mockResolvedValue({ actions: [], tools: [writeTool, readTool] })
+ jest.mocked(canvasesToolsInvoke)
+ .mockReset()
+ .mockResolvedValue({ tool: tool.name, result: { id: 7 } })
+ const confirmAction = jest.fn(async () => allowed)
+ const bridge = new CanvasDataBridge(
+ () => ({
+ projectId: '1',
+ canvasId: 'canvas-1',
+ sourceVersionId: 'v1',
+ captureToken: null,
+ distinctId: null,
+ }),
+ {
+ confirmAction,
+ confirmAgentRequest: jest.fn(),
+ requestConnectorPermission: jest.fn(),
+ hasUserActivation: () => true,
+ }
+ )
+
+ const result = bridge.handle(method, { tool: tool.name, arguments: { id: 7 } })
+
+ if (error) {
+ await expect(result).rejects.toThrow(error)
+ expect(canvasesToolsInvoke).not.toHaveBeenCalled()
+ } else {
+ await expect(result).resolves.toEqual({ id: 7 })
+ expect(canvasesToolsInvoke).toHaveBeenCalledWith('1', 'canvas-1', { tool: tool.name, arguments: { id: 7 } })
+ }
+ expect(confirmAction).toHaveBeenCalledTimes(method === 'toolCall' && !tool.read_only ? 1 : 0)
+ })
})
diff --git a/products/canvas/frontend/host/canvasDataBridge.ts b/products/canvas/frontend/host/canvasDataBridge.ts
index d7faffa35bc7..b760ce838df5 100644
--- a/products/canvas/frontend/host/canvasDataBridge.ts
+++ b/products/canvas/frontend/host/canvasDataBridge.ts
@@ -13,9 +13,11 @@ import {
canvasesRequestAgentCreate,
canvasesStateRetrieve,
canvasesStateSet,
+ canvasesToolsInvoke,
} from '../generated/api'
import type {
CanvasActionDefinitionApi,
+ CanvasToolDefinitionApi,
CanvasConnectorCallResultApi,
CanvasStateEntryApi,
} from '../generated/api.schemas'
@@ -163,6 +165,7 @@ function assertVariablesApplied(
export class CanvasDataBridge {
private readonly cache = new CanvasReadCache()
private readonly connectorConsent = new Map<string, boolean>()
+ private toolRegistry: Promise<CanvasToolDefinitionApi[]> | null = null
constructor(
private readonly context: () => CanvasDataBridgeContext,
@@ -186,6 +189,10 @@ export class CanvasDataBridge {
return this.stateList(input)
case 'actionInvoke':
return this.actionInvoke(input)
+ case 'toolRead':
+ return this.toolInvoke(input, false)
+ case 'toolCall':
+ return this.toolInvoke(input, true)
case 'agentRequest':
return this.agentRequest(payload)
case 'connectorCall':
@@ -371,6 +378,49 @@ export class CanvasDataBridge {
})
}
+ // ph.tools.read runs without a click, so it takes read-only tools only. ph.tools.call
+ // comes from a click, and the viewer confirms every tool that is not read-only.
+ private async toolInvoke(input: Record<string, unknown>, fromGesture: boolean): Promise<unknown> {
+ const name = input.tool
+ if (typeof name !== 'string' || !name) {
+ throw new Error('ph.tools requires a tool name')
+ }
+ const { projectId, canvasId } = this.context()
+ const tool = (await this.tools(projectId)).find((entry) => entry.name === name)
+ if (!tool) {
+ throw new Error(`Canvases cannot run the tool "${name}"`)
+ }
+ if (!fromGesture && !tool.read_only) {
+ throw new Error(`"${name}" changes data. Run it with ph.tools.call from a click.`)
+ }
+ const args = (input.arguments as Record<string, unknown> | undefined) ?? {}
+ if (
+ !tool.read_only &&
+ !(await this.prompts.confirmAction({
+ action: { verb: tool.name, summary: tool.summary, destructive: tool.destructive, usage: '' },
+ payload: args,
+ }))
+ ) {
+ throw new Error('Canvas tool call canceled')
+ }
+ const { result } = await canvasesToolsInvoke(projectId, canvasId, { tool: name, arguments: args })
+ return result
+ }
+
+ // The allowlist changes only with a deploy, so a board that reads many flags on load fetches it once.
+ private tools(projectId: string): Promise<CanvasToolDefinitionApi[]> {
+ if (!this.toolRegistry) {
+ this.toolRegistry = canvasesActionsRetrieve(projectId).then(
+ ({ tools }) => tools,
+ (error) => {
+ this.toolRegistry = null
+ throw error
+ }
+ )
+ }
+ return this.toolRegistry
+ }
+
private async agentRequest(payload: unknown): Promise<{ requestOutcome: string; taskId: string }> {
const { prompt } = canvasAgentRequestInputSchema.parse(payload)
if (!(await this.prompts.confirmAgentRequest(prompt))) {
diff --git a/products/canvas/frontend/host/canvasHostMessageRouter.test.ts b/products/canvas/frontend/host/canvasHostMessageRouter.test.ts
index f1deef3738e9..25691299ee42 100644
--- a/products/canvas/frontend/host/canvasHostMessageRouter.test.ts
+++ b/products/canvas/frontend/host/canvasHostMessageRouter.test.ts
@@ -45,7 +45,9 @@ describe('createCanvasHostMessageRouter', () => {
test.each([
['actionInvoke', false, 'Canvas actions require a user action'],
['agentRequest', false, 'Agent requests require a user action'],
+ ['toolCall', false, 'Canvas actions require a user action'],
['actionInvoke', true, null],
+ ['toolRead', false, null],
['agentRequest', true, null],
['query', false, null],
])('%s with user activation %s is rejected with %s', async (method, activated, error) => {
diff --git a/products/canvas/frontend/host/canvasHostMessageRouter.ts b/products/canvas/frontend/host/canvasHostMessageRouter.ts
index d3631f492b7a..6a0570e6ec88 100644
--- a/products/canvas/frontend/host/canvasHostMessageRouter.ts
+++ b/products/canvas/frontend/host/canvasHostMessageRouter.ts
@@ -48,10 +48,10 @@ const REPLAYABLE_SHORTCUT_KEYS = new Set([
])
// These write or start work, so the canvas must not fire them just by loading.
-const GESTURE_GATED_METHODS = new Set(['actionInvoke', 'agentRequest'])
+const GESTURE_GATED_METHODS = new Set(['actionInvoke', 'toolCall', 'agentRequest'])
const GESTURE_GATED_NAV_TARGETS = new Set<CanvasNavIntent['target']>(['connect', 'compose-task', 'new-task'])
// Approval dialogs can stay open longer than the I/O timeout, so these wait unbounded.
-const UNTIMED_METHODS = new Set(['agentRequest', 'actionInvoke', 'connectorCall'])
+const UNTIMED_METHODS = new Set(['agentRequest', 'actionInvoke', 'toolCall', 'connectorCall'])
function isBoundedPayload(payload: unknown): boolean {
try {
diff --git a/products/canvas/frontend/host/canvasProtocol.ts b/products/canvas/frontend/host/canvasProtocol.ts
index b6925dd34977..2e7861bd95bf 100644
--- a/products/canvas/frontend/host/canvasProtocol.ts
+++ b/products/canvas/frontend/host/canvasProtocol.ts
@@ -89,6 +89,8 @@ export const CANVAS_DATA_METHODS = [
'stateSet',
'stateList',
'actionInvoke',
+ 'toolRead',
+ 'toolCall',
'agentRequest',
'connectorCall',
] as const
diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjs
index 6b055ae23148..08e4a23bf782 100644
--- a/products/canvas/packages/canvas_builder/build.mjs
+++ b/products/canvas/packages/canvas_builder/build.mjs
@@ -37,7 +37,7 @@ const notebookFrameKeyPrefix = '__posthog_notebook_frame__:'
// The timer restarts when the port connects, so a slow iframe load does not
// use up a request's budget. From then on, calls that wait on the viewer's
// approval get no timer, as on the host.
-const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const waitsOnViewer=(method)=>method==="connectorCall"||method==="actionInvoke"||method==="agentRequest";const arm=(id,method,reject)=>port&&waitsOnViewer(method)?undefined:setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},120000);const maxRetries=2,retryBaseDelay=1000;const call=(method,payload,attempt=0)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=arm(id,method,reject);const fail=(error,retryable)=>{if(!retryable||attempt>=maxRetries){reject(error);return}setTimeout(()=>call(method,payload,attempt+1).then(resolve,reject),retryBaseDelay*Math.pow(2,attempt)*(0.5+Math.random()))};pending.set(id,{method,resolve,reject:fail,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};const fragmentParams=new URLSearchParams(location.hash.slice(1));applyTheme(fragmentParams.get("theme"));let config={};try{const rawConfig=fragmentParams.get("config");if(rawConfig)config=Object.freeze(JSON.parse(rawConfig))}catch{config={}};const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"),event.data.retryable===true);};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);const github=url.hostname==="github.com"&&!url.username&&!url.password&&!url.port&&!url.search&&new RegExp("^/[a-z0-9-]+/[a-z0-9_.-]+/pull/[1-9][0-9]*(/(files|commits|checks))?/?$","i").test(url.pathname);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")||github))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={config,loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange,variables:options?.variables,refresh:options?.refresh}),query:(query,params,options)=>call("query",typeof query==="string"?{hogql:query,params:params??{},refresh:options?.refresh}:{query,params:params??{},refresh:options?.refresh}),capture,openExternal,navigate:{toTask:(taskId)=>post({type:"navigate",nav:{target:"task",taskId}}),toNewTask:(options)=>{if(!navigator.userActivation?.isActive)throw new Error("Opening a task requires a user action");post({type:"navigate",nav:{target:options?"compose-task":"new-task",prompt:options?.prompt,repository:options?.repository}})},toCanvas:(dashboardId)=>post({type:"navigate",nav:{target:"canvas",dashboardId}}),toNewCanvas:()=>post({type:"navigate",nav:{target:"new-canvas"}})},agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})},connectors:{call:(provider,tool,args,options)=>call("connectorCall",{provider,tool,arguments:args??{},refresh:options?.refresh}),connect:(provider)=>{if(!navigator.userActivation?.isActive)throw new Error("Connecting a provider requires a user action");post({type:"navigate",nav:{target:"connect",provider}})}}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length){const message=queued.shift();const request=message.type==="data-request"&&pending.get(message.id);if(request){clearTimeout(request.timer);request.timer=arm(message.id,request.method,request.reject)}port.postMessage(message)}if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));const cspSeen=new Set();addEventListener("securitypolicyviolation",(event)=>{const directive=event.effectiveDirective||"unknown";if(cspSeen.has(directive))return;cspSeen.add(directive);post({type:"error",message:"SecurityPolicyViolationError: "+directive})});addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`
+const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const waitsOnViewer=(method)=>method==="connectorCall"||method==="actionInvoke"||method==="toolCall"||method==="agentRequest";const arm=(id,method,reject)=>port&&waitsOnViewer(method)?undefined:setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},120000);const maxRetries=2,retryBaseDelay=1000;const call=(method,payload,attempt=0)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="toolCall"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=arm(id,method,reject);const fail=(error,retryable)=>{if(!retryable||attempt>=maxRetries){reject(error);return}setTimeout(()=>call(method,payload,attempt+1).then(resolve,reject),retryBaseDelay*Math.pow(2,attempt)*(0.5+Math.random()))};pending.set(id,{method,resolve,reject:fail,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};const fragmentParams=new URLSearchParams(location.hash.slice(1));applyTheme(fragmentParams.get("theme"));let config={};try{const rawConfig=fragmentParams.get("config");if(rawConfig)config=Object.freeze(JSON.parse(rawConfig))}catch{config={}};const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"),event.data.retryable===true);};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);const github=url.hostname==="github.com"&&!url.username&&!url.password&&!url.port&&!url.search&&new RegExp("^/[a-z0-9-]+/[a-z0-9_.-]+/pull/[1-9][0-9]*(/(files|commits|checks))?/?$","i").test(url.pathname);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")||github))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={config,loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange,variables:options?.variables,refresh:options?.refresh}),query:(query,params,options)=>call("query",typeof query==="string"?{hogql:query,params:params??{},refresh:options?.refresh}:{query,params:params??{},refresh:options?.refresh}),capture,openExternal,navigate:{toTask:(taskId)=>post({type:"navigate",nav:{target:"task",taskId}}),toNewTask:(options)=>{if(!navigator.userActivation?.isActive)throw new Error("Opening a task requires a user action");post({type:"navigate",nav:{target:options?"compose-task":"new-task",prompt:options?.prompt,repository:options?.repository}})},toCanvas:(dashboardId)=>post({type:"navigate",nav:{target:"canvas",dashboardId}}),toNewCanvas:()=>post({type:"navigate",nav:{target:"new-canvas"}})},agent:{request:(prompt)=>call("agentRequest",{prompt})},state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})},tools:{read:(tool,args)=>call("toolRead",{tool,arguments:args??{}}),call:(tool,args)=>call("toolCall",{tool,arguments:args??{}})},connectors:{call:(provider,tool,args,options)=>call("connectorCall",{provider,tool,arguments:args??{},refresh:options?.refresh}),connect:(provider)=>{if(!navigator.userActivation?.isActive)throw new Error("Connecting a provider requires a user action");post({type:"navigate",nav:{target:"connect",provider}})}}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length){const message=queued.shift();const request=message.type==="data-request"&&pending.get(message.id);if(request){clearTimeout(request.timer);request.timer=arm(message.id,request.method,request.reject)}port.postMessage(message)}if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));const cspSeen=new Set();addEventListener("securitypolicyviolation",(event)=>{const directive=event.effectiveDirective||"unknown";if(cspSeen.has(directive))return;cspSeen.add(directive);post({type:"error",message:"SecurityPolicyViolationError: "+directive})});addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`
// Notebook source remains arbitrary JavaScript, and its separate AI review is advisory.
// The cross-origin sandbox, CSP, host authorization, and frame allow-list are
// load-bearing controls. Navigation interception is defense in depth: the Navigation
diff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.md
index 187549bacbc2..0ddff578de69 100644
--- a/products/canvas/skills/building-canvases/SKILL.md
+++ b/products/canvas/skills/building-canvases/SKILL.md
@@ -214,6 +214,11 @@ That field is the only valid link to a canvas — never construct one yourself;
`canvases-actions-retrieve` tool and follow each verb's `usage` (payload/result shape,
behavior, and the confirmation copy it warrants) before wiring it.
+- **`ph.tools.read(tool, args)` and `ph.tools.call(tool, args)`**: run an allowlisted PostHog
+ MCP tool as the viewer, for example to read a feature flag and change its rollout. Declare every
+ tool in `capabilities.posthog.tools`. `read` takes read-only tools; `call` changes data, so wire
+ it to a click, and the host asks the viewer to confirm. See `querying-canvas-data` for the
+ allowlist and the version handling that flag writes need.
- **`ph.connectors.call(provider, tool, args)`** — read live third-party data (GitHub, or any
MCP store server) with the VIEWER's own connection at view time. Never call GitHub, Calendly,
or another service yourself and paste the result into the source: that snapshot is stale on
diff --git a/products/canvas/skills/building-react-quill-canvases/SKILL.md b/products/canvas/skills/building-react-quill-canvases/SKILL.md
index bd60df38026e..fd7b9630e368 100644
--- a/products/canvas/skills/building-react-quill-canvases/SKILL.md
+++ b/products/canvas/skills/building-react-quill-canvases/SKILL.md
@@ -174,8 +174,9 @@ when the window changes — see the `querying-canvas-data` skill for feeding it
## State and actions
Persisting values across reloads (`ph.state`, with user/shared scopes) and writing into PostHog
-from a button (`ph.actions.invoke`, e.g. filing a task or an annotation) have their own API
-contracts, capability declarations, and gesture rules — read the "Runtime memory" and "PostHog
-writes" sections of the `querying-canvas-data` skill before using either. Wire actions to a
+from a button (`ph.actions.invoke`, e.g. filing a task or an annotation, or `ph.tools.call`, e.g.
+changing a feature flag rollout) have their own API contracts, capability declarations, and
+gesture rules — read the "Runtime memory", "PostHog writes" and "PostHog MCP tools" sections of
+the `querying-canvas-data` skill before using them. Wire actions to a
`Button` `onClick` that disables itself while the call is in flight, and render the returned
error (they are real PostHog writes, throttled server-side).
diff --git a/products/canvas/skills/querying-canvas-data/SKILL.md b/products/canvas/skills/querying-canvas-data/SKILL.md
index 2272157ece76..c63c2f538026 100644
--- a/products/canvas/skills/querying-canvas-data/SKILL.md
+++ b/products/canvas/skills/querying-canvas-data/SKILL.md
@@ -260,6 +260,35 @@ canvas) differ in payload shape, auth, and behavior. Invoking looks like:
const { result } = await ph.actions.invoke('tasks.create', { title, description })
```
+## PostHog MCP tools — ph.tools
+
+`ph.tools` runs a PostHog MCP tool as the viewer, with the viewer's own permissions. The tool runs
+on the PostHog MCP server, so its input is the same input you pass when you call that tool
+yourself. Use it when a board needs a control that a PostHog MCP tool already covers, such as
+the rollout of a feature flag.
+
+- Declare every tool in `capabilities.posthog.tools`. Only an allowlist of tools is available to
+ canvases. The `tools` list of the `canvases-actions-retrieve` tool names them, with
+ `read_only` and `destructive` for each one. Read a tool's input schema with `info <tool>`.
+- `ph.tools.read(tool, args)` takes read-only tools only. It can run on load or render.
+- `ph.tools.call(tool, args)` changes data. Call it only from a click. The host shows the viewer
+ the tool and its arguments and asks them to confirm, and it rejects calls made on load or render.
+- Both return the tool's JSON result, and throw with the tool's error message when it fails.
+ Render that message, and disable the button while the call is in flight.
+
+A feature flag write needs the flag's current `version`. Read it, write with it, and keep the
+version the write returns. On a version conflict, read the flag again before the next write:
+
+```tsx
+const flag = await ph.tools.read('feature-flag-get-definition', { id: flagId })
+const updated = await ph.tools.call('feature-flag-set-release-condition-rollout', {
+ id: flagId,
+ condition_index: 0,
+ rollout_percentage: 25,
+ version: flag.version,
+})
+```
+
## Live third-party data — ph.connectors
`ph.connectors.call(provider, tool, args, { refresh? })` reads data from a third-party service
diff --git a/products/webmcp/backend/facade/api.py b/products/webmcp/backend/facade/api.py
index 454250d9ec02..c2bbe162f1ea 100644
--- a/products/webmcp/backend/facade/api.py
+++ b/products/webmcp/backend/facade/api.py
@@ -24,3 +24,10 @@ def get_exec_tool(user_id: int, team_id: int) -> contracts.ExecTool:
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)
+
+
+def call_tool(input: contracts.CallToolInput) -> contracts.ToolCallResult:
+ """Call one MCP tool by name as the user and return its JSON result."""
+ return McpServerClient.for_user(User.objects.get(id=input.user_id), input.team_id).call_tool(
+ input.tool, input.arguments
+ )
diff --git a/products/webmcp/backend/facade/contracts.py b/products/webmcp/backend/facade/contracts.py
index 4a54529aee8c..e6711a1c10ea 100644
--- a/products/webmcp/backend/facade/contracts.py
+++ b/products/webmcp/backend/facade/contracts.py
@@ -31,5 +31,26 @@ class ExecResult:
is_error: bool
+@dataclass(frozen=True)
+class CallToolInput:
+ user_id: int
+ team_id: int
+ tool: str
+ arguments: dict[str, Any]
+
+
+@dataclass(frozen=True)
+class ToolCallResult:
+ # The tool's JSON result. None when the tool failed or its result is not a JSON object.
+ structured_content: dict[str, Any] | None
+ # The text blocks of the result, joined. A failed tool puts its error message here.
+ text: str
+ is_error: bool
+
+
class McpServerError(Exception):
"""The MCP server could not complete the call."""
+
+
+class McpServerTimeout(McpServerError):
+ """The MCP server received the call and did not answer in time. The call can still complete."""
diff --git a/products/webmcp/backend/logic/mcp_server.py b/products/webmcp/backend/logic/mcp_server.py
index bcf0a6b39b58..9a485bf0ac6e 100644
--- a/products/webmcp/backend/logic/mcp_server.py
+++ b/products/webmcp/backend/logic/mcp_server.py
@@ -1,3 +1,5 @@
+import re
+import json
from typing import Any
from django.conf import settings
@@ -6,7 +8,7 @@ import requests
from posthog.models import User
-from ..facade.contracts import ExecResult, ExecTool, McpServerError
+from ..facade.contracts import ExecResult, ExecTool, McpServerError, McpServerTimeout, ToolCallResult
from .tokens import WebMCPTokenIssuer
# The stateless MCP dialect needs no handshake, so each proxied call is one HTTP request.
@@ -15,6 +17,10 @@ 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)
+# A direct tool call backs a button a person is waiting on, so it gives up long before a slow query would.
+TOOL_CALL_TIMEOUT_SECONDS = (5, 30)
+# A tool name goes into an exec command line, so it must not carry spaces, flags or a second command.
+TOOL_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
def get_mcp_server_url() -> str | None:
@@ -65,9 +71,12 @@ class McpServerClient:
)
raise McpServerError("The MCP server did not advertise the exec tool")
- def call_exec(self, command: str) -> ExecResult:
+ def call_exec(self, command: str, *, timeout: tuple[int, int] = REQUEST_TIMEOUT_SECONDS) -> ExecResult:
result = self._request(
- "tools/call", {"name": EXEC_TOOL_NAME, "arguments": {"command": command}}, name=EXEC_TOOL_NAME
+ "tools/call",
+ {"name": EXEC_TOOL_NAME, "arguments": {"command": command}},
+ name=EXEC_TOOL_NAME,
+ timeout=timeout,
)
content = result.get("content")
return ExecResult(
@@ -75,7 +84,36 @@ class McpServerClient:
is_error=result.get("isError") is True,
)
- def _request(self, method: str, params: dict[str, Any], *, name: str | None = None) -> dict[str, Any]:
+ def call_tool(self, tool: str, arguments: dict[str, Any]) -> ToolCallResult:
+ if not TOOL_NAME_RE.match(tool):
+ raise McpServerError(f'"{tool}" is not a valid tool name')
+ # `--json` returns the handler's result as JSON for every tool. Without it most tools answer
+ # with formatted text, and only tools with a UI app set structuredContent. The caller
+ # confirms the call with the user, so `--confirm` lets a destructive tool run.
+ command = f"call --json --confirm {tool} {json.dumps(arguments, separators=(',', ':'))}"
+ result = self.call_exec(command, timeout=TOOL_CALL_TIMEOUT_SECONDS)
+ # The first block is the tool's output. Exec can append blocks with session metadata after it.
+ text = next((block["text"] for block in result.content if isinstance(block.get("text"), str)), "")
+ structured: Any = None
+ if not result.is_error:
+ try:
+ structured = json.loads(text)
+ except ValueError:
+ structured = None
+ return ToolCallResult(
+ structured_content=structured if isinstance(structured, dict) else None,
+ text=text,
+ is_error=result.is_error,
+ )
+
+ def _request(
+ self,
+ method: str,
+ params: dict[str, Any],
+ *,
+ name: str | None = None,
+ timeout: tuple[int, int] = REQUEST_TIMEOUT_SECONDS,
+ ) -> dict[str, Any]:
headers = {
"Authorization": f"Bearer {self._token}",
"Content-Type": "application/json",
@@ -103,9 +141,10 @@ class McpServerClient:
}
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
- )
+ response = requests.post(self._url, json=body, headers=headers, timeout=timeout, allow_redirects=False)
+ except requests.ReadTimeout as error:
+ # The server has the request, so it can still finish the call after this client gives up.
+ raise McpServerTimeout("The MCP server did not answer in time") from error
except requests.RequestException as error:
raise McpServerError(f"Could not reach the MCP server: {error.__class__.__name__}") from error
diff --git a/products/webmcp/backend/tests/test_logic.py b/products/webmcp/backend/tests/test_logic.py
index 03cfa712e2d2..bed6763f2bbd 100644
--- a/products/webmcp/backend/tests/test_logic.py
+++ b/products/webmcp/backend/tests/test_logic.py
@@ -1,17 +1,19 @@
from datetime import timedelta
from posthog.test.base import BaseTest
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
from django.utils import timezone
+import requests
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.facade.contracts import CallToolInput, McpServerError, McpServerTimeout, ToolCallResult
from products.webmcp.backend.logic.tokens import WebMCPTokenIssuer
@@ -85,3 +87,88 @@ class TestWebMCPAvailability(SimpleTestCase):
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
+
+
+@override_settings(MCP_SERVER_URL="https://mcp.example.com/mcp")
+@patch("products.webmcp.backend.logic.mcp_server.requests.post")
+class TestWebMCPCallTool(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ patcher = patch(
+ "products.webmcp.backend.logic.tokens.get_or_create_cimd_application", return_value=create_webmcp_app()
+ )
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ @parameterized.expand(
+ [
+ (
+ # Exec appends a session metadata block, which must not read as the tool's result.
+ "json_result",
+ {
+ "content": [
+ {"type": "text", "text": '{"id":7,"active":true}'},
+ {"type": "text", "text": '{"conversation_id":"c-1"}'},
+ ]
+ },
+ ToolCallResult(
+ structured_content={"id": 7, "active": True}, text='{"id":7,"active":true}', is_error=False
+ ),
+ ),
+ (
+ "tool_error",
+ {
+ "content": [{"type": "text", "text": "Error: [feature-flag-enable]: version conflict"}],
+ "isError": True,
+ },
+ ToolCallResult(
+ structured_content=None, text="Error: [feature-flag-enable]: version conflict", is_error=True
+ ),
+ ),
+ ]
+ )
+ def test_calls_the_named_tool_through_exec(
+ self, mock_post: MagicMock, _name: str, result: dict, expected: ToolCallResult
+ ) -> None:
+ mock_post.return_value = mcp_response(200, {"jsonrpc": "2.0", "id": 1, "result": result})
+
+ outcome = api.call_tool(
+ CallToolInput(user_id=self.user.id, team_id=self.team.id, tool="feature-flag-enable", arguments={"id": 7})
+ )
+
+ assert outcome == expected
+ # Without --json most tools answer with formatted text that the caller cannot parse.
+ assert mock_post.call_args.kwargs["json"]["params"]["arguments"] == {
+ "command": 'call --json --confirm feature-flag-enable {"id":7}'
+ }
+
+ def test_refuses_a_tool_name_that_would_change_the_command(self, mock_post: MagicMock) -> None:
+ with self.assertRaises(McpServerError):
+ api.call_tool(
+ CallToolInput(
+ user_id=self.user.id, team_id=self.team.id, tool="feature-flags-list\ncall x", arguments={}
+ )
+ )
+
+ mock_post.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("read_timeout", requests.ReadTimeout(), McpServerTimeout),
+ # A connect timeout never reached the server, so the call is safe to retry.
+ ("connect_timeout", requests.ConnectTimeout(), McpServerError),
+ ]
+ )
+ def test_only_a_read_timeout_leaves_the_outcome_unknown(
+ self, mock_post: MagicMock, _name: str, error: Exception, expected: type[McpServerError]
+ ) -> None:
+ mock_post.side_effect = error
+
+ with self.assertRaises(McpServerError) as raised:
+ api.call_tool(
+ CallToolInput(
+ user_id=self.user.id, team_id=self.team.id, tool="feature-flag-enable", arguments={"id": 7}
+ )
+ )
+
+ assert type(raised.exception) is expected
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 80e883ec16df..8467b4e963ea 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21427,11 +21427,29 @@ export namespace Schemas {
}
/**
- * The action registry: every verb a canvas may declare and invoke.
+ * One PostHog MCP tool a canvas may declare, as the host renders it before running it.
+ */
+ export interface CanvasToolDefinition {
+ /** MCP tool name, e.g. 'feature-flag-enable'. */
+ name: string;
+ /** Human-readable tool title. */
+ title: string;
+ /** One line naming what the tool does. */
+ summary: string;
+ /** True when the tool only reads. A canvas runs read-only tools with ph.tools.read, others with ph.tools.call. */
+ read_only: boolean;
+ /** True when the tool deletes or overwrites something; the host warns the viewer before it runs. */
+ destructive: boolean;
+ }
+
+ /**
+ * The action registry: every verb and PostHog MCP tool a canvas may declare and invoke.
*/
export interface CanvasActionsResponse {
/** Registered verbs, sorted by name. */
actions: CanvasActionDefinition[];
+ /** PostHog MCP tools a canvas may declare in capabilities.posthog.tools, sorted by name. Read each tool's input schema with the MCP `info` command. */
+ tools: CanvasToolDefinition[];
}
/**
@@ -21699,6 +21717,12 @@ export namespace Schemas {
* @items.maxLength 64
*/
actions?: string[];
+ /**
+ * PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review.
+ * @maxItems 32
+ * @items.maxLength 200
+ */
+ tools?: string[];
agentRequests?: boolean;
}
@@ -21759,6 +21783,8 @@ export namespace Schemas {
state_scopes_added: string[];
/** Action verbs the draft newly declares it may invoke via ph.actions. */
actions_added: string[];
+ /** PostHog MCP tools the draft newly declares it may run via ph.tools. */
+ tools_added: string[];
/** Connector providers and tools the draft newly declares it may call via ph.connectors. */
connectors_added: CanvasConnectorDeclaration[];
}
@@ -22937,6 +22963,39 @@ export namespace Schemas {
complete: boolean;
}
+ /**
+ * The tool's input, exactly as an MCP client passes it.
+ */
+ export type CanvasToolInvokeArguments = { [key: string]: unknown };
+
+ /**
+ * Payload for running one PostHog MCP tool.
+ */
+ export interface CanvasToolInvoke {
+ /**
+ * MCP tool to run, e.g. 'feature-flag-enable'.
+ * @maxLength 200
+ */
+ tool: string;
+ /** The tool's input, exactly as an MCP client passes it. */
+ arguments?: CanvasToolInvokeArguments;
+ }
+
+ /**
+ * The tool's JSON result.
+ */
+ export type CanvasToolResultResult = { [key: string]: unknown };
+
+ /**
+ * Result of one PostHog MCP tool run.
+ */
+ export interface CanvasToolResult {
+ /** The tool that ran. */
+ tool: string;
+ /** The tool's JSON result. */
+ result: CanvasToolResultResult;
+ }
+
/**
* Payload for validating a candidate source project without publishing it.
*/
diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.ts
index 77c21228123e..8ef1fd0a8917 100644
--- a/services/mcp/src/generated/canvas/api.ts
+++ b/services/mcp/src/generated/canvas/api.ts
@@ -278,6 +278,10 @@ export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsItemM
export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax = 200
+
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogToolsMax = 32
+
export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = false
export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048
@@ -427,6 +431,17 @@ export const CanvasesDraftCreateBody = () => zod
.describe(
"Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."
),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax)
+ )
+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogToolsMax)
+ .optional()
+ .describe(
+ "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review."
+ ),
agentRequests: zod
.boolean()
.default(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault),
@@ -536,6 +551,10 @@ export const canvasesEditCreateBodyCapabilitiesOnePosthogActionsItemMax = 64
export const canvasesEditCreateBodyCapabilitiesOnePosthogActionsMax = 32
+export const canvasesEditCreateBodyCapabilitiesOnePosthogToolsItemMax = 200
+
+export const canvasesEditCreateBodyCapabilitiesOnePosthogToolsMax = 32
+
export const canvasesEditCreateBodyCapabilitiesOnePosthogAgentRequestsDefault = false
export const canvasesEditCreateBodyCapabilitiesOneNetworkOriginsItemMax = 2048
@@ -623,6 +642,13 @@ export const CanvasesEditCreateBody = () => zod
.describe(
"Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."
),
+ tools: zod
+ .array(zod.string().max(canvasesEditCreateBodyCapabilitiesOnePosthogToolsItemMax))
+ .max(canvasesEditCreateBodyCapabilitiesOnePosthogToolsMax)
+ .optional()
+ .describe(
+ "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review."
+ ),
agentRequests: zod
.boolean()
.default(canvasesEditCreateBodyCapabilitiesOnePosthogAgentRequestsDefault),
@@ -1152,6 +1178,10 @@ export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsIte
export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax = 200
+
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogToolsMax = 32
+
export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = false
export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048
@@ -1303,6 +1333,17 @@ export const CanvasesPublishCreateBody = () => zod
.describe(
"Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."
),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax)
+ )
+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogToolsMax)
+ .optional()
+ .describe(
+ "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review."
+ ),
agentRequests: zod
.boolean()
.default(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault),
@@ -1607,6 +1648,10 @@ export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsIt
export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax = 200
+
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogToolsMax = 32
+
export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogAgentRequestsDefault = false
export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048
@@ -1756,6 +1801,17 @@ export const CanvasesValidateCreateBody = () => zod
.describe(
"Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."
),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogToolsItemMax)
+ )
+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogToolsMax)
+ .optional()
+ .describe(
+ "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review."
+ ),
agentRequests: zod
.boolean()
.default(
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json
index 8435b8e0c662..8e8e08b4a30f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json
@@ -138,6 +138,15 @@
},
"maxItems": 2,
"type": "array"
+ },
+ "tools": {
+ "description": "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review.",
+ "items": {
+ "maxLength": 200,
+ "type": "string"
+ },
+ "maxItems": 32,
+ "type": "array"
}
},
"required": ["insights", "inlineQueries", "captureEvents"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-edit-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-edit-create.json
index fd4422ad9af2..8488c31bcf7b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-edit-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-edit-create.json
@@ -89,6 +89,15 @@
},
"maxItems": 2,
"type": "array"
+ },
+ "tools": {
+ "description": "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review.",
+ "items": {
+ "maxLength": 200,
+ "type": "string"
+ },
+ "maxItems": 32,
+ "type": "array"
}
},
"required": ["insights", "inlineQueries", "captureEvents"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.json
index 0a5855faf54b..cb3b2e7bc01b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.json
@@ -154,6 +154,15 @@
},
"maxItems": 2,
"type": "array"
+ },
+ "tools": {
+ "description": "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review.",
+ "items": {
+ "maxLength": 200,
+ "type": "string"
+ },
+ "maxItems": 32,
+ "type": "array"
}
},
"required": ["insights", "inlineQueries", "captureEvents"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.json
index c8455eb97dce..9c373a453e9f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.json
@@ -138,6 +138,15 @@
},
"maxItems": 2,
"type": "array"
+ },
+ "tools": {
+ "description": "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', 'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the promote review.",
+ "items": {
+ "maxLength": 200,
+ "type": "string"
+ },
+ "maxItems": 32,
+ "type": "array"
}
},
"required": ["insights", "inlineQueries", "captureEvents"],
diff --git a/tach.toml b/tach.toml
index fd2c03a313c0..7d2fb0a59792 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1080,6 +1080,8 @@ depends_on = [
"products.annotations",
# MCP connector calls made with the viewer's own installation (via the mcp_store facade).
"products.mcp_store",
+ # ph.tools calls run on the PostHog MCP server as the viewer (via the webmcp facade).
+ "products.webmcp",
# Object access checks on canvases served as contracts (via the access_control facade).
"products.access_control",
]