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): connector calls that read third-party data as the viewer (#94560)

Peter Kirkham0ad506286511
diff --git a/docs/internal/canvas-connectors.md b/docs/internal/canvas-connectors.md
new file mode 100644
index 000000000000..1d91c7f4de3e
--- /dev/null
+++ b/docs/internal/canvas-connectors.md
@@ -0,0 +1,55 @@
+# Canvas connectors
+
+Canvases can read third-party data with the current viewer's connection. Calls require the `canvas-connectors` team feature flag. The flag fails closed.
+
+## Declare tools
+
+Declare each provider and tool in the source project's capabilities:
+
+```json
+{
+ "posthog": { "insights": [], "inlineQueries": false, "captureEvents": [], "state": ["user"], "actions": [] },
+ "network": { "origins": [] },
+ "connectors": [{ "provider": "github", "tools": ["list_pull_requests"] }]
+}
+```
+
+A canvas with connectors cannot declare shared state. This rule applies to the whole project, including calls in different files. The call and state endpoints also reject this combination on existing versions.
+
+## Catalog
+
+`GET /api/projects/{project_id}/canvases/connectors/` lists native tools, argument schemas, connection status, and connection paths. The optional `mcp_hosts` query parameter is a comma-separated list of server hosts.
+
+The `canvas-connectors-retrieve` MCP tool exposes this catalog to authors. The catalog does not call the upstream tools.
+
+## Call a tool
+
+`POST /api/projects/{project_id}/canvases/{canvas_id}/connectors/call/` accepts:
+
+```json
+{ "provider": "github", "tool": "list_pull_requests", "arguments": { "repository": "example/app", "state": "open" } }
+```
+
+Scoped credentials need both `canvas:write` and `user:read`. A canvas-only credential cannot spend a personal integration credential. Sandbox credentials cannot call connectors.
+
+The endpoint checks channel access, the feature flag, and the current version's declared provider and tool. It limits requests per viewer and canvas. The activity log records the provider, tool, and outcome, but not arguments or results.
+
+Responses contain `status`, `result`, `detail`, `truncated`, and `connect_path`. Status values are `ok`, `not_connected`, `needs_reauth`, `blocked`, `tool_missing`, `write_blocked`, and `upstream_error`. Invalid arguments return HTTP 400. Access and capability failures return HTTP 403.
+
+Results are limited to 256 KiB. Large results become a bounded `preview` with `truncated: true`. Provider parsing failures return `upstream_error`, not an unhandled exception.
+
+## Providers
+
+- `github` exposes `list_pull_requests`, `search_issues`, and `get_file_contents`. Use `owner/name` to select a repository without ambiguity. A bare name uses the connection's account. Calls try the viewer's connections, newest first, until one can read the repository. Rate-limit failures stop retries.
+- `mcp:<host>` uses the viewer's personal installation, or the team's shared installation if no personal one exists. It never uses a teammate's personal installation. Existing MCP policy, credential checks, and audit rules apply.
+- MCP connector tools must declare `readOnlyHint: true` and start with a recognized read verb: `get`, `list`, `search`, `fetch`, `read`, `find`, `query`, `count`, or `describe`. Write verbs, destructive hints, and an explicit `readOnlyHint: false` block the call. Unknown operations are blocked. An upstream `readOnlyHint: true` alone cannot grant access. These checks cannot prove that an arbitrary upstream tool has no side effects; connect only trusted servers.
+
+When a connection is missing or needs authorization, `connect_path` identifies the settings page. The host must validate the provider before navigation and require a user action.
+
+## Host safety
+
+The canvas host must ask the viewer before it sends connector calls. Consent must be limited to the canvas version, provider, and tool. The prompt must explain that the canvas can receive private data and that declared network access can send it outside PostHog.
+
+Connector caches must be authentication-scoped. Remove them when the viewer, organization, or project changes. Never write connector results into shared canvas state.
+
+Keep the feature flag off until the backend and a host with these checks are deployed. Verify connection failures, cancellation, account changes, and the connector activity log before increasing the rollout.
diff --git a/products/canvas/backend/capabilities.py b/products/canvas/backend/capabilities.py
index 42bd34da9cc7..c4729962859d 100644
--- a/products/canvas/backend/capabilities.py
+++ b/products/canvas/backend/capabilities.py
@@ -10,6 +10,14 @@ structured answer rather than a raw manifest diff.
from dataclasses import dataclass
+@dataclass(frozen=True, kw_only=True)
+class ConnectorGrant:
+ """One provider a manifest lets the canvas call, with the tools it may use."""
+
+ provider: str
+ tools: list[str]
+
+
def _posthog_section(manifest: dict | None) -> dict:
return (manifest or {}).get("posthog") or {}
@@ -28,6 +36,18 @@ def declared_actions(manifest: dict | None) -> set[str]:
return set(_posthog_section(manifest).get("actions") 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]] = {}
+ for entry in (manifest or {}).get("connectors") or []:
+ if not isinstance(entry, dict) or not isinstance(entry.get("provider"), str):
+ continue
+ declared.setdefault(entry["provider"], set()).update(
+ tool for tool in entry.get("tools") or [] if isinstance(tool, str)
+ )
+ return declared
+
+
@dataclass(frozen=True, kw_only=True)
class CapabilityWidening:
"""What `after` declares beyond `before`. Narrowings are not reported here
@@ -41,6 +61,7 @@ class CapabilityWidening:
network_origins_added: list[str]
state_scopes_added: list[str]
actions_added: list[str]
+ connectors_added: list[ConnectorGrant]
@property
def widens(self) -> bool:
@@ -52,6 +73,7 @@ class CapabilityWidening:
or self.network_origins_added
or self.state_scopes_added
or self.actions_added
+ or self.connectors_added
)
@@ -74,4 +96,14 @@ 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 [])),
+ connectors_added=_connectors_added(declared_connectors(before), declared_connectors(after)),
)
+
+
+def _connectors_added(before: dict[str, set[str]], after: dict[str, set[str]]) -> list[ConnectorGrant]:
+ added = []
+ for provider in sorted(after):
+ tools = sorted(after[provider] - before.get(provider, set()))
+ if tools:
+ added.append(ConnectorGrant(provider=provider, tools=tools))
+ return added
diff --git a/products/canvas/backend/connectors.py b/products/canvas/backend/connectors.py
new file mode 100644
index 000000000000..4fcd9135910f
--- /dev/null
+++ b/products/canvas/backend/connectors.py
@@ -0,0 +1,517 @@
+"""Canvas connectors: live third-party data a canvas reads as the viewer (ph.connectors).
+
+A connector call names a provider and a tool. The host forwards
+ph.connectors.call(provider, tool, arguments) to the call endpoint, which
+checks the canvas's declared capabilities and runs the tool with the
+viewer's own connection, never the author's. Two provider families share
+the pipeline:
+
+- Native providers (``github``) run against the viewer's ``UserIntegration``
+ through a registry of hand-written read tools, in the shape of the action
+ registry.
+- MCP providers (``mcp:<host>``) run against the viewer's MCP store
+ installation for that host, through the store's own policy and audit.
+
+Every tool this module exposes is read-only. Writes are a follow-up that
+needs a user gesture and a confirm step in the host.
+"""
+
+import json
+import base64
+from collections.abc import Callable
+from typing import TYPE_CHECKING, Any
+
+from django.db import models
+
+import structlog
+import posthoganalytics
+from rest_framework import serializers
+
+from posthog.dataclasses import frozen
+from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.transport.transport import EgressBudgetExhausted
+from posthog.models.github_integration_base import GitHubIntegrationError
+from posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegration
+
+from products.mcp_store.backend.facade import api as mcp_store_facade
+from products.mcp_store.backend.facade.contracts import ConnectorTool as McpConnectorTool
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+logger = structlog.get_logger(__name__)
+
+# Rollout gate, evaluated per team. Fails closed: connectors stay off when the
+# flag cannot be evaluated, because every call spends the viewer's credential.
+CANVAS_CONNECTORS_FLAG = "canvas-connectors"
+
+MCP_PROVIDER_PREFIX = "mcp:"
+# Results cross the postMessage bridge into the sandbox; a runaway tool result
+# must not be able to stall the host.
+MAX_RESULT_BYTES = 256 * 1024
+_GITHUB_SOURCE = "canvas_connectors"
+_PERSONAL_INTEGRATIONS_PATH = "/settings/user-personal-integrations"
+
+
+class ConnectorCallStatus(models.TextChoices):
+ OK = "ok"
+ NOT_CONNECTED = "not_connected"
+ NEEDS_REAUTH = "needs_reauth"
+ BLOCKED = "blocked"
+ TOOL_MISSING = "tool_missing"
+ WRITE_BLOCKED = "write_blocked"
+ UPSTREAM_ERROR = "upstream_error"
+
+
+class ConnectorKind(models.TextChoices):
+ NATIVE = "native"
+ MCP = "mcp"
+
+
+def canvas_connectors_enabled(team: "Team") -> bool:
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ CANVAS_CONNECTORS_FLAG,
+ str(team.uuid),
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.exception("canvas_connectors_flag_check_failed")
+ return False
+
+
+class ConnectorToolError(Exception):
+ """The upstream service refused or failed the tool call."""
+
+
+@frozen
+class ConnectorCallResult:
+ status: ConnectorCallStatus
+ result: dict[str, Any] | None = None
+ detail: str = ""
+ truncated: bool = False
+ # Where the viewer connects the provider, for the not_connected state.
+ connect_path: str | None = None
+
+
+@frozen
+class NativeConnectorTool:
+ """One read tool of a native provider: what it reads, its payload shape, and its authoring docs."""
+
+ name: str
+ summary: str
+ payload_serializer: type[serializers.Serializer]
+ execute: Callable[[UserIntegration, dict[str, Any]], dict[str, Any]]
+ usage: str
+ read_only: bool = True
+
+
+@frozen
+class NativeConnector:
+ provider: str
+ label: str
+ integration_kind: str
+ tools: dict[str, NativeConnectorTool]
+
+
+class GitHubRepositorySerializer(serializers.Serializer):
+ repository = serializers.RegexField(
+ r"^(?:[A-Za-z0-9._-]+/)?[A-Za-z0-9._-]+$",
+ max_length=200,
+ help_text="Repository as 'owner/name', or 'name' for a repository in the connection's own account.",
+ )
+
+ def validate_repository(self, value: str) -> str:
+ # The regex admits dots, so a dot-only segment would traverse the API path.
+ if any(segment.strip(".") == "" for segment in value.split("/")):
+ raise serializers.ValidationError("Repository segments must not be only dots.")
+ return value
+
+
+class GitHubListPullRequestsPayloadSerializer(GitHubRepositorySerializer):
+ state = serializers.ChoiceField(
+ choices=["open", "closed", "all"], default="open", help_text="Which pull requests to list."
+ )
+
+
+class GitHubSearchIssuesPayloadSerializer(GitHubRepositorySerializer):
+ query = serializers.CharField(max_length=256, help_text="Free text matched against issue titles and bodies.")
+ limit = serializers.IntegerField(min_value=1, max_value=50, default=25, help_text="Maximum issues to return.")
+
+
+class GitHubGetFileContentsPayloadSerializer(GitHubRepositorySerializer):
+ file_path = serializers.CharField(max_length=1024, help_text="Path of the file inside the repository.")
+ ref = serializers.RegexField(
+ r"^[A-Za-z0-9._/-]+$",
+ required=False,
+ allow_null=True,
+ default=None,
+ max_length=256,
+ help_text="Branch, tag, or commit SHA.",
+ )
+
+ def validate_file_path(self, value: str) -> str:
+ segments = value.strip("/").split("/")
+ if any(segment.strip(".") == "" or "?" in segment or "#" in segment for segment in segments):
+ raise serializers.ValidationError("File path segments must be plain names.")
+ return "/".join(segments)
+
+
+def _github_client(integration: UserIntegration) -> UserGitHubIntegration:
+ return UserGitHubIntegration(integration, source=_GITHUB_SOURCE)
+
+
+def _github_repo_path(client: UserGitHubIntegration, repository: str) -> str:
+ return repository if "/" in repository else f"{client.organization()}/{repository}"
+
+
+def _github_list_pull_requests(integration: UserIntegration, payload: dict[str, Any]) -> dict[str, Any]:
+ client = _github_client(integration)
+ response = client.api_request(
+ "GET",
+ f"/repos/{_github_repo_path(client, payload['repository'])}/pulls",
+ endpoint="/repos/{owner}/{repo}/pulls",
+ params={"state": payload["state"], "per_page": 100},
+ )
+ if response.status_code != 200:
+ raise ConnectorToolError(f"GitHub returned HTTP {response.status_code} for the pull request list.")
+ body = response.json()
+ if not isinstance(body, list):
+ raise ConnectorToolError("GitHub returned an invalid pull request list.")
+ return {
+ "pull_requests": [
+ {
+ "number": pr["number"],
+ "title": pr["title"],
+ "url": pr["html_url"],
+ "state": pr["state"],
+ "draft": bool(pr.get("draft")),
+ "author": (pr.get("user") or {}).get("login"),
+ "head_branch": pr["head"]["ref"],
+ "base_branch": pr["base"]["ref"],
+ "created_at": pr["created_at"],
+ "updated_at": pr["updated_at"],
+ }
+ for pr in body
+ ]
+ }
+
+
+def _github_search_issues(integration: UserIntegration, payload: dict[str, Any]) -> dict[str, Any]:
+ client = _github_client(integration)
+ repo_path = _github_repo_path(client, payload["repository"])
+ # Quote the text so search qualifiers in it (repo:, OR) are matched, not interpreted.
+ quoted = payload["query"].replace('"', " ")
+ response = client.api_request(
+ "GET",
+ "/search/issues",
+ endpoint="/search/issues",
+ params={"q": f'repo:{repo_path} is:issue "{quoted}"', "per_page": payload["limit"]},
+ )
+ if response.status_code != 200:
+ raise ConnectorToolError(f"GitHub returned HTTP {response.status_code} for the issue search.")
+ body = response.json()
+ if not isinstance(body, dict) or not isinstance(body.get("items"), list):
+ raise ConnectorToolError("GitHub returned an invalid issue search result.")
+ return {
+ "issues": [
+ {
+ "number": issue["number"],
+ "title": issue["title"],
+ "url": issue["html_url"],
+ "state": issue["state"],
+ "author": (issue.get("user") or {}).get("login"),
+ "labels": [label.get("name") for label in issue.get("labels") or [] if isinstance(label, dict)],
+ "created_at": issue["created_at"],
+ "updated_at": issue["updated_at"],
+ }
+ for issue in body["items"]
+ ]
+ }
+
+
+def _github_get_file_contents(integration: UserIntegration, payload: dict[str, Any]) -> dict[str, Any]:
+ client = _github_client(integration)
+ repo_path = _github_repo_path(client, payload["repository"])
+ ref = payload.get("ref")
+ response = client.api_request(
+ "GET",
+ f"/repos/{repo_path}/contents/{payload['file_path']}",
+ endpoint="/repos/{owner}/{repo}/contents/{path}",
+ params={"ref": ref} if ref else None,
+ )
+ if response.status_code == 404:
+ return {"file": None}
+ if response.status_code != 200:
+ raise ConnectorToolError(f"GitHub returned HTTP {response.status_code} for the file read.")
+ body = response.json()
+ if body.get("encoding") != "base64" or not isinstance(body.get("content"), str):
+ raise ConnectorToolError("GitHub returned a directory or a file too large to read inline.")
+ content = base64.b64decode("".join(body["content"].split()), validate=True).decode("utf-8", errors="replace")
+ return {"file": {"content": content, "sha": body.get("sha"), "size": body.get("size")}}
+
+
+NATIVE_CONNECTORS: dict[str, NativeConnector] = {
+ connector.provider: connector
+ for connector in [
+ NativeConnector(
+ provider="github",
+ label="GitHub",
+ integration_kind=UserIntegration.IntegrationKind.GITHUB,
+ tools={
+ tool.name: tool
+ for tool in [
+ NativeConnectorTool(
+ name="list_pull_requests",
+ summary="List a repository's pull requests.",
+ payload_serializer=GitHubListPullRequestsPayloadSerializer,
+ execute=_github_list_pull_requests,
+ usage=(
+ "Arguments `{repository, state?}` → result `{pull_requests: [{number, title, url, state, "
+ "draft, author, head_branch, base_branch, created_at, updated_at}]}`. `state` is open "
+ "(default), closed, or all. Returns at most 100 pull requests, newest first."
+ ),
+ ),
+ NativeConnectorTool(
+ name="search_issues",
+ summary="Search a repository's issues by text.",
+ payload_serializer=GitHubSearchIssuesPayloadSerializer,
+ execute=_github_search_issues,
+ usage=(
+ "Arguments `{repository, query, limit?}` → result `{issues: [{number, title, url, state, "
+ "...}]}`. The query is matched against titles and bodies; GitHub search syntax in it "
+ "is quoted, not interpreted. `limit` defaults to 25, max 50."
+ ),
+ ),
+ NativeConnectorTool(
+ name="get_file_contents",
+ summary="Read one file from a repository.",
+ payload_serializer=GitHubGetFileContentsPayloadSerializer,
+ execute=_github_get_file_contents,
+ usage=(
+ "Arguments `{repository, file_path, ref?}` → result `{file: {content, sha} | null}`. "
+ "`content` is the decoded text; `file` is null when the path does not exist at `ref` "
+ "(the default branch when omitted)."
+ ),
+ ),
+ ]
+ },
+ ),
+ ]
+}
+
+
+def mcp_provider_host(provider: str) -> str | None:
+ """The server host an ``mcp:<host>`` provider id names, or None for any other id."""
+ if not provider.startswith(MCP_PROVIDER_PREFIX):
+ return None
+ host = provider[len(MCP_PROVIDER_PREFIX) :].strip().lower()
+ return host or None
+
+
+def is_known_provider(provider: str) -> bool:
+ return provider in NATIVE_CONNECTORS or mcp_provider_host(provider) is not None
+
+
+def unregistered_native_tools(provider: str, tools: list[str]) -> list[str]:
+ """Tool names a manifest declares for a native provider that its registry does not have."""
+ connector = NATIVE_CONNECTORS.get(provider)
+ if connector is None:
+ return []
+ return sorted(set(tools) - set(connector.tools))
+
+
+def _viewer_integration(user_id: int, connector: NativeConnector) -> UserIntegration | None:
+ return (
+ UserIntegration.objects.filter(user_id=user_id, kind=connector.integration_kind).order_by("created_at").first()
+ )
+
+
+def _bounded(result: dict[str, Any]) -> tuple[dict[str, Any], bool]:
+ serialized = json.dumps(result, default=str, ensure_ascii=True)
+ if len(serialized.encode("utf-8")) <= MAX_RESULT_BYTES:
+ return result, False
+ preview_limit = (MAX_RESULT_BYTES - len(json.dumps({"preview": ""}))) // 2
+ return {"preview": serialized[:preview_limit]}, True
+
+
+def _call_native_tool(
+ user_id: int, connector: NativeConnector, tool_name: str, arguments: dict[str, Any]
+) -> ConnectorCallResult:
+ tool = connector.tools.get(tool_name)
+ if tool is None:
+ return ConnectorCallResult(
+ status=ConnectorCallStatus.TOOL_MISSING,
+ detail=f'Unknown {connector.label} tool "{tool_name}". Registered tools: {", ".join(sorted(connector.tools))}.',
+ )
+ payload = tool.payload_serializer(data=arguments)
+ payload.is_valid(raise_exception=True)
+ integrations = UserIntegration.objects.filter(user_id=user_id, kind=connector.integration_kind).order_by(
+ "-created_at"
+ )
+ outcome = ConnectorCallResult(
+ status=ConnectorCallStatus.NOT_CONNECTED,
+ detail=f"You have not connected {connector.label}.",
+ connect_path=_PERSONAL_INTEGRATIONS_PATH,
+ )
+ for integration in integrations:
+ try:
+ result = tool.execute(integration, payload.validated_data)
+ except ReauthorizationRequired as error:
+ outcome = ConnectorCallResult(
+ status=ConnectorCallStatus.NEEDS_REAUTH, detail=str(error), connect_path=_PERSONAL_INTEGRATIONS_PATH
+ )
+ continue
+ except (GitHubRateLimitError, EgressBudgetExhausted) as error:
+ return ConnectorCallResult(status=ConnectorCallStatus.UPSTREAM_ERROR, detail=str(error))
+ except (ConnectorToolError, GitHubIntegrationError) as error:
+ outcome = ConnectorCallResult(status=ConnectorCallStatus.UPSTREAM_ERROR, detail=str(error))
+ continue
+ except (ValueError, TypeError, AttributeError, KeyError):
+ return ConnectorCallResult(
+ status=ConnectorCallStatus.UPSTREAM_ERROR, detail="GitHub returned an invalid response."
+ )
+ bounded, truncated = _bounded(result)
+ outcome = ConnectorCallResult(status=ConnectorCallStatus.OK, result=bounded, truncated=truncated)
+ if result != {"file": None}:
+ return outcome
+ return outcome
+
+
+def _call_mcp_tool(
+ team_id: int, user_id: int, host: str, tool_name: str, arguments: dict[str, Any], actor_label: str
+) -> ConnectorCallResult:
+ outcome = mcp_store_facade.call_member_server_tool(
+ team_id, user_id, host, tool_name, arguments, actor_label=actor_label, allow_writes=False
+ )
+ if outcome.status != "ok":
+ return ConnectorCallResult(
+ status=ConnectorCallStatus(outcome.status),
+ detail=outcome.detail,
+ connect_path="/settings/mcp-servers" if outcome.status in ("not_connected", "needs_reauth") else None,
+ )
+ bounded, truncated = _bounded(
+ {
+ "content": list(outcome.content),
+ "structured_content": outcome.structured_content,
+ "is_error": outcome.is_error,
+ }
+ )
+ return ConnectorCallResult(status=ConnectorCallStatus.OK, result=bounded, truncated=truncated)
+
+
+def call_connector_tool(
+ team_id: int,
+ user_id: int,
+ provider: str,
+ tool_name: str,
+ arguments: dict[str, Any],
+ *,
+ actor_label: str = "",
+) -> ConnectorCallResult:
+ """Run one declared connector tool as the viewer. The caller has already
+ checked the canvas's capabilities and the rollout flag."""
+ connector = NATIVE_CONNECTORS.get(provider)
+ if connector is not None:
+ return _call_native_tool(user_id, connector, tool_name, arguments)
+ host = mcp_provider_host(provider)
+ if host is None:
+ return ConnectorCallResult(
+ status=ConnectorCallStatus.TOOL_MISSING,
+ detail=f'Unknown provider "{provider}". Use a native provider ({", ".join(sorted(NATIVE_CONNECTORS))}) '
+ f'or "{MCP_PROVIDER_PREFIX}<server host>".',
+ )
+ return _call_mcp_tool(team_id, user_id, host, tool_name, arguments, actor_label)
+
+
+@frozen
+class ConnectorToolListing:
+ name: str
+ summary: str
+ read_only: bool
+ input_schema: dict[str, Any]
+ usage: str
+
+
+@frozen
+class ConnectorListing:
+ provider: str
+ label: str
+ kind: ConnectorKind
+ connected: bool
+ connect_path: str
+ tools: list[ConnectorToolListing]
+
+
+def _native_tool_schema(tool: NativeConnectorTool) -> dict[str, Any]:
+ properties: dict[str, Any] = {}
+ required: list[str] = []
+ for name, field in tool.payload_serializer().fields.items():
+ entry: dict[str, Any] = {"type": _json_type(field), "description": str(field.help_text or "")}
+ if isinstance(field, serializers.ChoiceField):
+ entry["enum"] = list(field.choices)
+ properties[name] = entry
+ if field.required:
+ required.append(name)
+ return {"type": "object", "properties": properties, "required": required}
+
+
+def _json_type(field: serializers.Field) -> str:
+ if isinstance(field, serializers.IntegerField):
+ return "integer"
+ if isinstance(field, serializers.BooleanField):
+ return "boolean"
+ return "string"
+
+
+def _mcp_tool_listing(tool: McpConnectorTool) -> ConnectorToolListing:
+ return ConnectorToolListing(
+ name=tool.name,
+ summary=tool.description.split("\n", 1)[0][:200],
+ read_only=tool.read_only,
+ input_schema=tool.input_schema,
+ usage=tool.description,
+ )
+
+
+def connector_listings(team_id: int, user_id: int, mcp_hosts: list[str] | None = None) -> list[ConnectorListing]:
+ """Every native provider, plus each requested MCP host (default: every host the
+ viewer has connected), with the viewer's connection state."""
+ if mcp_hosts is None:
+ mcp_hosts = mcp_store_facade.member_server_hosts(team_id, user_id)
+ listings = [
+ ConnectorListing(
+ provider=connector.provider,
+ label=connector.label,
+ kind=ConnectorKind.NATIVE,
+ connected=_viewer_integration(user_id, connector) is not None,
+ connect_path=_PERSONAL_INTEGRATIONS_PATH,
+ tools=[
+ ConnectorToolListing(
+ name=tool.name,
+ summary=tool.summary,
+ read_only=tool.read_only,
+ input_schema=_native_tool_schema(tool),
+ usage=tool.usage,
+ )
+ for tool in sorted(connector.tools.values(), key=lambda tool: tool.name)
+ ],
+ )
+ for connector in sorted(NATIVE_CONNECTORS.values(), key=lambda connector: connector.provider)
+ ]
+ for host in sorted({host.lower() for host in mcp_hosts}):
+ tools = mcp_store_facade.member_server_tools(team_id, user_id, host)
+ listings.append(
+ ConnectorListing(
+ provider=f"{MCP_PROVIDER_PREFIX}{host}",
+ label=host,
+ kind=ConnectorKind.MCP,
+ connected=tools is not None,
+ connect_path="/settings/mcp-servers",
+ tools=[_mcp_tool_listing(tool) for tool in tools or []],
+ )
+ )
+ return listings
diff --git a/products/canvas/backend/facade/api.py b/products/canvas/backend/facade/api.py
index 283f3c855665..259b8a59edee 100644
--- a/products/canvas/backend/facade/api.py
+++ b/products/canvas/backend/facade/api.py
@@ -1,3 +1,11 @@
+from products.canvas.backend.connectors import (
+ ConnectorCallStatus as ConnectorCallStatus,
+ ConnectorKind as ConnectorKind,
+ call_connector_tool as call_connector_tool,
+ canvas_connectors_enabled as canvas_connectors_enabled,
+ connector_listings as connector_listings,
+ mcp_provider_host as mcp_provider_host,
+)
from products.canvas.backend.layout import (
CANVAS_LAYOUT_SCHEMA_VERSION as CANVAS_LAYOUT_SCHEMA_VERSION,
MAX_LAYOUT_PATCH_OPERATIONS as MAX_LAYOUT_PATCH_OPERATIONS,
diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.py
index 1a8375075e9d..acfe137fde59 100644
--- a/products/canvas/backend/presentation/serializers.py
+++ b/products/canvas/backend/presentation/serializers.py
@@ -21,6 +21,8 @@ from products.canvas.backend.facade.api import (
PLACEMENT_ID_RE,
PLACEMENT_STATUSES,
RESERVED_TEMPLATE_IDS,
+ ConnectorCallStatus,
+ ConnectorKind,
)
from products.canvas.backend.models import Canvas, CanvasState
@@ -277,9 +279,38 @@ class CanvasNetworkCapabilitiesSerializer(serializers.Serializer):
origins = serializers.ListField(child=serializers.URLField(max_length=2048), max_length=20)
+class CanvasConnectorDeclarationSerializer(serializers.Serializer):
+ """One provider a canvas may call through ph.connectors, with the tools it may use."""
+
+ provider = serializers.CharField(
+ max_length=300,
+ help_text=(
+ "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' "
+ "(e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store."
+ ),
+ )
+ tools = serializers.ListField(
+ child=serializers.CharField(max_length=200),
+ min_length=1,
+ max_length=64,
+ help_text="Tool names the canvas may call on this provider. Read-only tools only.",
+ )
+
+
class CanvasCapabilitiesSerializer(serializers.Serializer):
posthog = CanvasPostHogCapabilitiesSerializer()
network = CanvasNetworkCapabilitiesSerializer()
+ # Optional so projects published before connectors exist unchanged.
+ connectors = serializers.ListField(
+ child=CanvasConnectorDeclarationSerializer(),
+ required=False,
+ default=list,
+ max_length=20,
+ help_text=(
+ "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. "
+ "Every call runs with the viewer's own connection; declaring one shows it in the promote review."
+ ),
+ )
class CanvasSourceProjectSerializer(serializers.Serializer):
@@ -331,6 +362,7 @@ class CanvasSourceProjectSerializer(serializers.Serializer):
"agentRequests": False,
},
"network": {"origins": []},
+ "connectors": [],
},
help_text=(
"Bounded capabilities frozen into the built artifact. Declare every insight short id the "
@@ -930,6 +962,10 @@ class CanvasCapabilityWideningSerializer(serializers.Serializer):
child=serializers.CharField(),
help_text="Action verbs the draft newly declares it may invoke via ph.actions.",
)
+ connectors_added = CanvasConnectorDeclarationSerializer(
+ many=True,
+ help_text="Connector providers and tools the draft newly declares it may call via ph.connectors.",
+ )
class CanvasActionDefinitionSerializer(serializers.Serializer):
@@ -971,6 +1007,76 @@ class CanvasActionResultSerializer(serializers.Serializer):
)
+class CanvasConnectorToolSerializer(serializers.Serializer):
+ """One tool a connector provider exposes to canvases."""
+
+ name = serializers.CharField(help_text="Tool name, as passed to ph.connectors.call.")
+ summary = serializers.CharField(help_text="One line naming what the tool reads.")
+ is_read_only = serializers.BooleanField(
+ source="read_only", help_text="True when the tool only reads. Canvases may call read-only tools."
+ )
+ input_schema = serializers.DictField(help_text="JSON Schema of the tool's arguments object.")
+ usage = serializers.CharField(help_text="Authoring docs: argument and result shape, limits, and behavior.")
+
+
+class CanvasConnectorSerializer(serializers.Serializer):
+ """One connector provider, with the caller's connection state and the tools it exposes."""
+
+ provider = serializers.CharField(
+ help_text="Provider id to declare and call, e.g. 'github' or 'mcp:mcp.calendly.com'."
+ )
+ display_name = serializers.CharField(source="label", help_text="Display name of the provider.")
+ kind = serializers.ChoiceField(
+ choices=ConnectorKind.choices,
+ help_text="'native' runs through a PostHog personal integration; 'mcp' through an MCP store installation.",
+ )
+ connected = serializers.BooleanField(help_text="True when the caller has a usable connection to this provider.")
+ connect_path = serializers.CharField(help_text="In-app path where the caller connects this provider.")
+ tools = CanvasConnectorToolSerializer(many=True, help_text="Tools the caller's connection exposes, sorted by name.")
+
+
+class CanvasConnectorsResponseSerializer(serializers.Serializer):
+ """The connector catalog: every provider a canvas may declare and call."""
+
+ connectors = CanvasConnectorSerializer(many=True, help_text="Native providers first, then the requested MCP hosts.")
+
+
+class CanvasConnectorCallSerializer(serializers.Serializer):
+ """Payload for calling one connector tool as the viewer."""
+
+ provider = serializers.CharField(max_length=300, help_text="Declared provider id, e.g. 'github'.")
+ tool = serializers.CharField(max_length=200, help_text="Declared tool name, e.g. 'list_pull_requests'.")
+ arguments = serializers.DictField(
+ required=False,
+ default=dict,
+ help_text="Tool arguments, validated against the tool's input schema.",
+ )
+
+
+class CanvasConnectorCallResultSerializer(serializers.Serializer):
+ """Result of one connector call. `status` is 'ok' when `result` holds the tool's output."""
+
+ status = serializers.ChoiceField(
+ choices=ConnectorCallStatus.choices,
+ help_text=(
+ "'ok' carries a result. 'not_connected' and 'needs_reauth' mean the viewer must connect the provider "
+ "at connect_path. 'blocked' is team policy. 'write_blocked' is a tool that may write. "
+ "'upstream_error' is a failure at the provider."
+ ),
+ )
+ result = serializers.DictField(
+ allow_null=True,
+ help_text="Tool output. Native tools return their documented shape; MCP tools return {content, structured_content, is_error}.",
+ )
+ detail = serializers.CharField(allow_blank=True, help_text="Human-readable explanation for a non-ok status.")
+ truncated = serializers.BooleanField(
+ help_text="True when the result exceeded the size cap and was cut to a preview."
+ )
+ connect_path = serializers.CharField(
+ allow_null=True, help_text="In-app path where the viewer can connect the provider, when that would help."
+ )
+
+
class CanvasStateEntrySerializer(serializers.Serializer):
"""One key of a canvas's runtime key-value state (the ph.state store)."""
diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.py
index 8615306be478..e544bec45a1a 100644
--- a/products/canvas/backend/presentation/views.py
+++ b/products/canvas/backend/presentation/views.py
@@ -28,10 +28,13 @@ from posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS
from products.canvas.backend import build_service, error_reports
from products.canvas.backend.actions import CANVAS_ACTIONS, canvas_actions_disabled
-from products.canvas.backend.capabilities import declared_actions, declared_state_scopes
+from products.canvas.backend.capabilities import declared_actions, declared_connectors, declared_state_scopes
from products.canvas.backend.contract import contract_limits
from products.canvas.backend.facade.api import (
apply_layout_ops,
+ call_connector_tool,
+ canvas_connectors_enabled,
+ connector_listings,
default_layout,
seed_home_canvas,
subtract_preexisting_diagnostics,
@@ -49,6 +52,9 @@ from products.canvas.backend.presentation.serializers import (
CanvasBuildSerializer,
CanvasBuildsResponseSerializer,
CanvasCapabilityWideningSerializer,
+ CanvasConnectorCallResultSerializer,
+ CanvasConnectorCallSerializer,
+ CanvasConnectorsResponseSerializer,
CanvasCreateSerializer,
CanvasDraftSerializer,
CanvasErrorReportResultSerializer,
@@ -184,6 +190,11 @@ class CanvasActionInvokeThrottle(CanvasStateWriteThrottle):
rate = "60/min"
+class CanvasConnectorCallThrottle(CanvasStateWriteThrottle):
+ scope = "canvas_connector_call"
+ rate = "120/min"
+
+
class CanvasAccessMixin(TeamAndOrgViewSetMixin):
"""Team, channel, and sandbox visibility rules shared by every canvas-like resource."""
@@ -301,6 +312,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
"validate",
"state",
"layout",
+ "connectors",
]
scope_object_write_actions = [
"create",
@@ -317,6 +329,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
"request_fix",
"set_state",
"invoke_action",
+ "call_connector",
"request_agent",
"publish_layout",
"patch_layout",
@@ -330,6 +343,8 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
return [*super().get_throttles(), CanvasStateWriteThrottle()]
if self.action == "invoke_action":
return [*super().get_throttles(), CanvasActionInvokeThrottle()]
+ if self.action == "call_connector":
+ return [*super().get_throttles(), CanvasConnectorCallThrottle()]
return super().get_throttles()
def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:
@@ -1678,6 +1693,13 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
"""The user whose personal state is read or written."""
return self._request_user()
+ def _connector_actor(self, request: Request) -> User | None:
+ """The viewer whose third-party connections a connector call may use.
+ A sandbox token acts for an agent, not a viewer, so it gets none."""
+ if self._is_sandbox_authenticated(request):
+ return None
+ return self._request_user()
+
@extend_schema(
operation_id="canvases_actions_retrieve",
responses={200: CanvasActionsResponseSerializer},
@@ -1760,6 +1782,122 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
self._report_canvas_action("canvas action invoked", canvas, verb=verb)
return Response(CanvasActionResultSerializer(instance={"verb": verb, "result": result}).data)
+ @extend_schema(
+ operation_id="canvases_connectors_retrieve",
+ parameters=[
+ OpenApiParameter(
+ "mcp_hosts",
+ OpenApiTypes.STR,
+ required=False,
+ description=(
+ "Comma-separated MCP server hosts to include (e.g. 'mcp.calendly.com'). Defaults to every "
+ "server the caller has connected in the MCP store."
+ ),
+ )
+ ],
+ responses={
+ 200: CanvasConnectorsResponseSerializer,
+ 403: OpenApiResponse(description="Connectors are not enabled for this team, or the caller is a sandbox."),
+ },
+ )
+ @action(methods=["GET"], detail=False, url_path="connectors")
+ def connectors(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """List the connector catalog: every provider and tool a canvas may declare, with the caller's connection state.
+
+ Authoring agents read this to write ph.connectors.call sites and the
+ matching capabilities.connectors declarations.
+ """
+ user = self._connector_actor(request)
+ if user is None:
+ return Response(
+ {"detail": "The connector catalog is a viewer surface; sandbox tokens cannot read it."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ if not canvas_connectors_enabled(self.team):
+ return Response(
+ {"detail": "Canvas connectors are not enabled for this team."}, status=status.HTTP_403_FORBIDDEN
+ )
+ raw_hosts = request.query_params.get("mcp_hosts")
+ mcp_hosts = [host.strip() for host in raw_hosts.split(",") if host.strip()] if raw_hosts else None
+ listings = connector_listings(self.team_id, user.id, mcp_hosts)
+ return Response(CanvasConnectorsResponseSerializer(instance={"connectors": listings}).data)
+
+ @extend_schema(
+ operation_id="canvases_connectors_call",
+ request=CanvasConnectorCallSerializer,
+ responses={
+ 200: CanvasConnectorCallResultSerializer,
+ 400: OpenApiResponse(description="The arguments failed the tool's schema."),
+ 403: OpenApiResponse(
+ description="The provider or tool is not declared in the canvas's capabilities, connectors are "
+ "not enabled for the team, or the caller is a sandbox."
+ ),
+ },
+ )
+ @action(methods=["POST"], detail=True, url_path="connectors/call", required_scopes=["canvas:write", "user:read"])
+ def call_connector(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Call one declared connector tool as the viewer.
+
+ The canvas must declare the provider and tool in capabilities.connectors
+ (the reviewed permission boundary); the call runs with the viewer's own
+ connection, so two viewers of the same canvas see their own data.
+ """
+ canvas = self.get_object()
+ user = self._connector_actor(request)
+ if user is None:
+ return Response(
+ {"detail": "Connector calls are made by viewers; sandbox tokens cannot use them."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ if not canvas_connectors_enabled(self.team):
+ return Response(
+ {"detail": "Canvas connectors are not enabled for this team."}, status=status.HTTP_403_FORBIDDEN
+ )
+ payload = CanvasConnectorCallSerializer(data=request.data)
+ payload.is_valid(raise_exception=True)
+ provider = payload.validated_data["provider"]
+ tool = payload.validated_data["tool"]
+ version = canvas.current_source_version
+ declared = declared_connectors(version.capabilities if version else None)
+ if "shared" in declared_state_scopes(version.capabilities if version else None):
+ return Response(
+ {"detail": "Canvases with connectors cannot use shared state."}, status=status.HTTP_403_FORBIDDEN
+ )
+ if tool not in declared.get(provider, set()):
+ return Response(
+ {
+ "detail": f'The canvas does not declare connector tool "{tool}" on "{provider}". '
+ "Add it to capabilities.connectors and publish."
+ },
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ result = call_connector_tool(
+ self.team_id,
+ user.id,
+ provider,
+ tool,
+ payload.validated_data["arguments"],
+ actor_label=user.email or "",
+ )
+ # Every call is audited: the trigger names the tool, the activity log
+ # row names the viewer whose connection it used. Never the arguments.
+ self._log_canvas_activity(
+ canvas,
+ "connector_tool_called",
+ Detail(
+ name=canvas.name,
+ trigger=Trigger(
+ job_type="canvas_connector",
+ job_id=f"{provider}/{tool}",
+ payload={"provider": provider, "tool": tool, "status": str(result.status)},
+ ),
+ ),
+ )
+ self._report_canvas_action(
+ "canvas connector tool called", canvas, provider=provider, tool=tool, status=str(result.status)
+ )
+ return Response(CanvasConnectorCallResultSerializer(instance=result).data)
+
@extend_schema(
operation_id="canvases_state_retrieve",
parameters=[
@@ -1831,6 +1969,10 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
# the canvas's reviewed permission boundary, exactly like insights.
version = canvas.current_source_version
declared = declared_state_scopes(version.capabilities if version else None)
+ if scope == CanvasState.SCOPE_SHARED and declared_connectors(version.capabilities if version else None):
+ return Response(
+ {"detail": "Canvases with connectors cannot use shared state."}, status=status.HTTP_403_FORBIDDEN
+ )
if scope not in declared:
return Response(
{
diff --git a/products/canvas/backend/source.py b/products/canvas/backend/source.py
index e0a8ed981d9b..351f2b7ebd3a 100644
--- a/products/canvas/backend/source.py
+++ b/products/canvas/backend/source.py
@@ -18,6 +18,13 @@ from urllib.parse import urlsplit
import jsonschema
from products.canvas.backend.actions import CANVAS_ACTIONS
+from products.canvas.backend.connectors import (
+ MCP_PROVIDER_PREFIX,
+ NATIVE_CONNECTORS,
+ is_known_provider,
+ mcp_provider_host,
+ unregistered_native_tools,
+)
from products.canvas.backend.contract import (
MAX_COMPONENT_HEIGHT,
MAX_COMPONENT_WIDTH,
@@ -173,6 +180,9 @@ _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_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*[\"']([^\"']+)[\"'])?)?"
+)
_PATH_SEGMENT_RE = re.compile(r"^[A-Za-z0-9._@-]+$")
@@ -377,6 +387,97 @@ def _validate_code_file(path: str, code: str) -> list[dict[str, Any]]:
return diagnostics
+def _validate_connector_declarations(declared: Any) -> list[dict[str, Any]]:
+ """Check capabilities.connectors: known providers, registered native tools, public MCP hosts."""
+ diagnostics: list[dict[str, Any]] = []
+ if not isinstance(declared, list):
+ return [diagnostic("error", "invalid_connector_declaration", "capabilities.connectors must be a list")]
+ for entry in declared:
+ provider = entry.get("provider") if isinstance(entry, dict) else None
+ tools = entry.get("tools") if isinstance(entry, dict) else None
+ if not isinstance(provider, str) or not isinstance(tools, list) or not tools:
+ diagnostics.append(
+ diagnostic(
+ "error",
+ "invalid_connector_declaration",
+ "each capabilities.connectors entry needs a provider and a non-empty list of tool names",
+ )
+ )
+ continue
+ if not is_known_provider(provider):
+ diagnostics.append(
+ diagnostic(
+ "error",
+ "connector_provider_unknown",
+ f'capabilities.connectors names unknown provider "{provider}" — use one of '
+ + ", ".join(sorted(NATIVE_CONNECTORS))
+ + f', or "{MCP_PROVIDER_PREFIX}<server host>" for an MCP store server',
+ )
+ )
+ continue
+ host = mcp_provider_host(provider)
+ if host is not None and canonical_network_origin(f"https://{host}") is None:
+ diagnostics.append(
+ diagnostic(
+ "error",
+ "connector_provider_unknown",
+ f'connector provider "{provider}" must name a public server host, e.g. "mcp:mcp.example.com"',
+ )
+ )
+ continue
+ unregistered = unregistered_native_tools(provider, [tool for tool in tools if isinstance(tool, str)])
+ if unregistered:
+ diagnostics.append(
+ diagnostic(
+ "error",
+ "connector_tool_not_registered",
+ f"capabilities.connectors declares unknown {provider} tools: {', '.join(unregistered)} — "
+ f"registered tools: {', '.join(sorted(NATIVE_CONNECTORS[provider].tools))}",
+ )
+ )
+ return diagnostics
+
+
+def _validate_connector_calls(path: str, code: str, capabilities: dict[str, Any]) -> list[dict[str, Any]]:
+ """Check ph.connectors.call sites against capabilities.connectors."""
+ diagnostics: list[dict[str, Any]] = []
+ declared: dict[str, set[str]] = {}
+ for entry in capabilities.get("connectors") or []:
+ if isinstance(entry, dict) and isinstance(entry.get("provider"), str):
+ declared.setdefault(entry["provider"], set()).update(
+ tool for tool in entry.get("tools") or [] if isinstance(tool, str)
+ )
+ for match in _PH_CONNECTORS_CALL_RE.finditer(code):
+ provider, tool = match.group(1), match.group(2)
+ line = _line_of(code, match.start())
+ if provider is None:
+ if not declared:
+ diagnostics.append(
+ diagnostic(
+ "warning",
+ "capability_missing_connector",
+ "ph.connectors.call() is called with a dynamic provider but capabilities.connectors is "
+ "empty — declare every provider and tool the canvas calls",
+ path=path,
+ line=line,
+ )
+ )
+ continue
+ if provider not in declared or (tool is not None and tool not in declared[provider]):
+ called = f'"{provider}", "{tool}"' if tool is not None else f'"{provider}"'
+ diagnostics.append(
+ diagnostic(
+ "error",
+ "capability_missing_connector",
+ f"ph.connectors.call({called}) requires that provider and tool in capabilities.connectors — "
+ "the host rejects undeclared connector calls at runtime",
+ path=path,
+ line=line,
+ )
+ )
+ return diagnostics
+
+
def _validate_capabilities(path: str, code: str, capabilities: dict[str, Any]) -> list[dict[str, Any]]:
"""Check `ph` bridge calls against the project's declared capabilities."""
diagnostics: list[dict[str, Any]] = []
@@ -709,6 +810,15 @@ def validate_source_project(project: dict[str, Any], *, kind: str = "freeform")
+ ", ".join(sorted(CANVAS_ACTIONS)),
)
)
+ diagnostics.extend(_validate_connector_declarations(capabilities.get("connectors") or []))
+ if capabilities.get("connectors") and "shared" in (capabilities.get("posthog") or {}).get("state", []):
+ diagnostics.append(
+ diagnostic(
+ "error",
+ "connector_results_in_shared_state",
+ "Canvases with connectors cannot declare shared state. Use user-scoped state for connector data.",
+ )
+ )
if len(files) + len(assets) > limits["maxSourceFiles"]:
diagnostics.append(
diagnostic(
@@ -794,5 +904,6 @@ def validate_source_project(project: dict[str, Any], *, kind: str = "freeform")
if path.endswith(_CODE_EXTENSIONS):
diagnostics.extend(_validate_code_file(path, content))
diagnostics.extend(_validate_capabilities(path, content, capabilities))
+ diagnostics.extend(_validate_connector_calls(path, content, capabilities))
return diagnostics
diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.py
index a17fbf45f72e..6c96b912ebd7 100644
--- a/products/canvas/backend/tests/test_canvas_api.py
+++ b/products/canvas/backend/tests/test_canvas_api.py
@@ -1091,6 +1091,7 @@ class TestCanvasActivityLog(CanvasAPIBaseTest):
"agentRequests": False,
},
"network": {"origins": []},
+ "connectors": [],
}
widened_capabilities = {
"posthog": {
@@ -1102,6 +1103,7 @@ class TestCanvasActivityLog(CanvasAPIBaseTest):
"agentRequests": False,
},
"network": {"origins": []},
+ "connectors": [{"provider": "github", "tools": ["list_pull_requests"]}],
}
widened = self._project("export default function C() { return 2 }")
widened["capabilities"] = widened_capabilities
diff --git a/products/canvas/backend/tests/test_capabilities.py b/products/canvas/backend/tests/test_capabilities.py
index 4a97bcd4d754..fcabeaccf54e 100644
--- a/products/canvas/backend/tests/test_capabilities.py
+++ b/products/canvas/backend/tests/test_capabilities.py
@@ -2,7 +2,7 @@ from unittest import TestCase
from parameterized import parameterized
-from products.canvas.backend.capabilities import capability_widening
+from products.canvas.backend.capabilities import ConnectorGrant, capability_widening
BASE = {
"posthog": {
@@ -23,6 +23,10 @@ WIDER = {
"agentRequests": True,
},
"network": {"origins": ["https://api.example.com"]},
+ "connectors": [
+ {"provider": "github", "tools": ["list_pull_requests", "search_issues"]},
+ {"provider": "mcp:mcp.example.com", "tools": ["list_events"]},
+ ],
}
NARROWER = {
"posthog": {"insights": [], "captureEvents": [], "inlineQueries": False, "agentRequests": False},
@@ -52,6 +56,17 @@ 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.connectors_added == [
+ ConnectorGrant(provider="github", tools=["list_pull_requests", "search_issues"]),
+ ConnectorGrant(provider="mcp:mcp.example.com", tools=["list_events"]),
+ ]
+
+ def test_only_new_connector_tools_count_as_widening(self):
+ before = {"connectors": [{"provider": "github", "tools": ["list_pull_requests"]}]}
+ after = {"connectors": [{"provider": "github", "tools": ["search_issues", "list_pull_requests"]}]}
+ widening = capability_widening(before, after)
+ assert widening.connectors_added == [ConnectorGrant(provider="github", tools=["search_issues"])]
+ assert capability_widening(after, before).widens is False
def test_inline_queries_already_enabled_is_not_a_widening(self):
enabled = {"posthog": {"inlineQueries": True}}
diff --git a/products/canvas/backend/tests/test_cloud_builder.py b/products/canvas/backend/tests/test_cloud_builder.py
index 7d9fcd020b5a..b91e4a2172c8 100644
--- a/products/canvas/backend/tests/test_cloud_builder.py
+++ b/products/canvas/backend/tests/test_cloud_builder.py
@@ -301,6 +301,12 @@ class TestCanvasCloudBuilder(SimpleTestCase):
'if (!requests.some((m) => m.payload.hogql === "SELECT 1")) { console.error("pre-connect request was dropped"); process.exit(1); }',
'if (requests.some((m) => m.payload.hogql === "SELECT expired")) { console.error("expired request was still delivered"); process.exit(1); }',
'if (!received.some((m) => m.type === "ready")) { console.error("ready was not posted"); process.exit(1); }',
+ 'Object.defineProperty(globalThis, "navigator", { value: { userActivation: { isActive: false } }, configurable: true });',
+ 'try { window.ph.connectors.connect("github"); throw new Error("connector navigation did not require activation"); } catch (error) { if (!error.message.includes("user action")) throw error; }',
+ 'if (received.some((message) => message.type === "navigate")) throw new Error("connector navigation escaped without activation");',
+ "navigator.userActivation.isActive = true;",
+ 'window.ph.connectors.connect("github");',
+ 'if (!received.some((message) => message.type === "navigate" && message.nav.provider === "github")) throw new Error("connector navigation was not delivered");',
"process.exit(0);",
]
)
diff --git a/products/canvas/backend/tests/test_connectors.py b/products/canvas/backend/tests/test_connectors.py
new file mode 100644
index 000000000000..16583f677d77
--- /dev/null
+++ b/products/canvas/backend/tests/test_connectors.py
@@ -0,0 +1,303 @@
+import json
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.user_integration import UserIntegration
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.canvas.backend.connectors import MAX_RESULT_BYTES, _bounded
+from products.canvas.backend.models import Canvas
+from products.canvas.backend.tests.test_canvas_api import CanvasAPIBaseTest
+from products.tasks.backend.models import Task
+
+_GITHUB_PR = {
+ "number": 7,
+ "title": "feat: thing",
+ "html_url": "https://github.com/example/app/pull/7",
+ "state": "open",
+ "draft": False,
+ "user": {"login": "octocat"},
+ "head": {"ref": "feat"},
+ "base": {"ref": "main"},
+ "created_at": "2026-01-01T00:00:00Z",
+ "updated_at": "2026-01-02T00:00:00Z",
+}
+
+
+def _github_response(status_code: int = 200, payload: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.json.return_value = payload if payload is not None else [_GITHUB_PR]
+ return response
+
+
+class TestCanvasConnectors(CanvasAPIBaseTest):
+ def setUp(self):
+ super().setUp()
+ enabled = patch("products.canvas.backend.presentation.views.canvas_connectors_enabled", return_value=True)
+ enabled.start()
+ self.addCleanup(enabled.stop)
+
+ def _connectors_canvas(self, connectors: list[dict[str, Any]] | None = None) -> str:
+ canvas_id = self._create_canvas()
+ capabilities = {
+ "posthog": {"insights": [], "inlineQueries": False, "captureEvents": [], "state": [], "actions": []},
+ "network": {"origins": []},
+ "connectors": connectors
+ if connectors is not None
+ else [{"provider": "github", "tools": ["list_pull_requests", "search_issues"]}],
+ }
+ response = self._publish(canvas_id, project=self._project(capabilities=capabilities))
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return canvas_id
+
+ def _connect_github(self) -> UserIntegration:
+ return UserIntegration.objects.create(
+ user=self.user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id="12345",
+ config={"installation_id": "12345", "account": {"type": "User", "name": "octocat"}},
+ sensitive_config={"access_token": "ghs_test", "user_access_token": "ghu_test"},
+ )
+
+ def _call(self, canvas_id: str, provider: str = "github", tool: str = "list_pull_requests", **arguments: Any):
+ return self.client.post(
+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/connectors/call/",
+ {"provider": provider, "tool": tool, "arguments": arguments or {"repository": "app"}},
+ format="json",
+ )
+
+ @patch("products.canvas.backend.connectors.UserGitHubIntegration.api_request", return_value=_github_response())
+ def test_declared_github_tool_runs_with_the_viewers_connection_and_is_audited(self, mock_request):
+ canvas_id = self._connectors_canvas()
+ self._connect_github()
+
+ response = self._call(canvas_id, repository="example/app", state="open")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert body["status"] == "ok"
+ assert body["truncated"] is False
+ assert body["result"]["pull_requests"][0] == {
+ "number": 7,
+ "title": "feat: thing",
+ "url": "https://github.com/example/app/pull/7",
+ "state": "open",
+ "draft": False,
+ "author": "octocat",
+ "head_branch": "feat",
+ "base_branch": "main",
+ "created_at": "2026-01-01T00:00:00Z",
+ "updated_at": "2026-01-02T00:00:00Z",
+ }
+ assert mock_request.call_args.args[1] == "/repos/example/app/pulls"
+ entries = self._activity("connector_tool_called")
+ assert len(entries) == 1
+ assert entries[0].detail is not None
+ assert entries[0].detail["trigger"]["payload"] == {
+ "provider": "github",
+ "tool": "list_pull_requests",
+ "status": "ok",
+ }
+
+ @patch("products.canvas.backend.connectors.UserGitHubIntegration.api_request", return_value=_github_response())
+ def test_bare_repository_name_resolves_against_the_connections_account(self, mock_request):
+ canvas_id = self._connectors_canvas()
+ self._connect_github()
+
+ assert self._call(canvas_id, repository="app").status_code == status.HTTP_200_OK
+ assert mock_request.call_args.args[1] == "/repos/octocat/app/pulls"
+
+ def test_viewer_without_a_connection_is_told_where_to_connect(self):
+ canvas_id = self._connectors_canvas()
+
+ response = self._call(canvas_id)
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["status"] == "not_connected"
+ assert body["result"] is None
+ assert body["connect_path"] == "/settings/user-personal-integrations"
+
+ @parameterized.expand(
+ [
+ ("undeclared_tool", "github", "get_file_contents"),
+ ("undeclared_provider", "mcp:mcp.example.com", "list_events"),
+ ]
+ )
+ @patch("products.canvas.backend.connectors.UserGitHubIntegration.api_request")
+ def test_undeclared_calls_are_refused_before_any_upstream_call(self, _name, provider, tool, mock_request):
+ canvas_id = self._connectors_canvas()
+ self._connect_github()
+
+ response = self._call(canvas_id, provider=provider, tool=tool)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ mock_request.assert_not_called()
+ assert self._activity("connector_tool_called") == []
+
+ def test_invalid_arguments_are_rejected_by_the_tools_schema(self):
+ canvas_id = self._connectors_canvas()
+ self._connect_github()
+
+ response = self._call(canvas_id, repository="../evil", state="open")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "repository"
+
+ @parameterized.expand(
+ [
+ ("http_error", "list_pull_requests", 502, {}, None),
+ ("invalid_json", "list_pull_requests", 200, {}, ValueError("invalid JSON")),
+ ("invalid_list", "list_pull_requests", 200, {}, None),
+ ("missing_fields", "list_pull_requests", 200, [{}], None),
+ ("invalid_issues", "search_issues", 200, [], None),
+ ("invalid_file", "get_file_contents", 200, [], None),
+ ("invalid_base64", "get_file_contents", 200, {"encoding": "base64", "content": "!"}, None),
+ ]
+ )
+ @patch("products.canvas.backend.connectors.UserGitHubIntegration.api_request")
+ def test_upstream_failures_surface_as_a_status_not_a_500(self, _name, tool, code, body, error, mock_request):
+ canvas_id = self._connectors_canvas([{"provider": "github", "tools": [tool]}])
+ self._connect_github()
+ mock_request.return_value = _github_response(code, body)
+ mock_request.return_value.json.side_effect = error
+
+ response = self._call(canvas_id, tool=tool, repository="example/app", query="bug", file_path="README.md")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["status"] == "upstream_error"
+
+ def test_disabled_flag_refuses_every_call(self):
+ canvas_id = self._connectors_canvas()
+ self._connect_github()
+ with patch("products.canvas.backend.presentation.views.canvas_connectors_enabled", return_value=False):
+ assert self._call(canvas_id).status_code == status.HTTP_403_FORBIDDEN
+
+ def test_sandbox_tokens_cannot_call_connectors(self):
+ canvas_id = self._connectors_canvas()
+ task = Task.objects.create(
+ team=self.team,
+ channel=self.channel,
+ created_by=self.user,
+ title="Connectors",
+ description="d",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ Canvas.objects.unscoped().filter(id=canvas_id).update(generation_task_id=task.id)
+
+ response = self._sandbox_client(task.id).post(
+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/connectors/call/",
+ {"provider": "github", "tool": "list_pull_requests", "arguments": {"repository": "app"}},
+ format="json",
+ HTTP_X_POSTHOG_TASK_ID=str(task.id),
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_mcp_provider_without_a_connection_points_at_the_mcp_store(self):
+ canvas_id = self._connectors_canvas([{"provider": "mcp:mcp.example.com", "tools": ["list_events"]}])
+
+ response = self._call(canvas_id, provider="mcp:mcp.example.com", tool="list_events", limit=5)
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["status"] == "not_connected"
+ assert body["connect_path"] == "/settings/mcp-servers"
+
+ def test_catalog_lists_native_tools_with_the_callers_connection_state(self):
+ response = self.client.get(f"/api/projects/{self.team.id}/canvases/connectors/")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ github = next(entry for entry in response.json()["connectors"] if entry["provider"] == "github")
+ assert github["connected"] is False
+ assert github["kind"] == "native"
+ assert [tool["name"] for tool in github["tools"]] == [
+ "get_file_contents",
+ "list_pull_requests",
+ "search_issues",
+ ]
+ pulls = next(tool for tool in github["tools"] if tool["name"] == "list_pull_requests")
+ assert pulls["is_read_only"] is True
+ assert pulls["input_schema"]["required"] == ["repository"]
+ assert pulls["input_schema"]["properties"]["state"]["enum"] == ["open", "closed", "all"]
+
+ self._connect_github()
+ response = self.client.get(f"/api/projects/{self.team.id}/canvases/connectors/?mcp_hosts=mcp.example.com")
+ connectors = {entry["provider"]: entry for entry in response.json()["connectors"]}
+ assert connectors["github"]["connected"] is True
+ assert connectors["mcp:mcp.example.com"] == {
+ "provider": "mcp:mcp.example.com",
+ "display_name": "mcp.example.com",
+ "kind": "mcp",
+ "connected": False,
+ "connect_path": "/settings/mcp-servers",
+ "tools": [],
+ }
+
+ @parameterized.expand([("canvas_only", ["canvas:write"], 403), ("user_scope", ["canvas:write", "user:read"], 200)])
+ @patch("products.canvas.backend.connectors.UserGitHubIntegration.api_request", return_value=_github_response())
+ def test_scoped_keys_need_personal_integration_access(self, _name, scopes, expected_status, mock_request):
+ canvas_id = self._connectors_canvas()
+ self._connect_github()
+ raw_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="canvas-connectors", user=self.user, secure_value=hash_key_value(raw_key), scopes=scopes
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {raw_key}")
+ response = self._call(canvas_id)
+ assert response.status_code == expected_status
+ assert mock_request.called is (expected_status == 200)
+
+ @parameterized.expand(
+ [
+ ("list_pull_requests", [_GITHUB_PR]),
+ ("search_issues", {"items": [_GITHUB_PR]}),
+ ("get_file_contents", {"encoding": "base64", "content": "aGk="}),
+ ]
+ )
+ @patch("products.canvas.backend.connectors.UserGitHubIntegration.api_request")
+ def test_retries_another_viewer_connection_when_the_first_cannot_read(self, tool, body, mock_request):
+ canvas_id = self._connectors_canvas([{"provider": "github", "tools": [tool]}])
+ self._connect_github()
+ UserIntegration.objects.create(
+ user=self.user, kind="github", integration_id="67890", config={"account": {"name": "example"}}
+ )
+ mock_request.side_effect = [_github_response(404), _github_response(payload=body)]
+ response = self._call(canvas_id, tool=tool, repository="example/app", query="bug", file_path="README.md")
+ assert response.json()["status"] == "ok"
+ assert mock_request.call_count == 2
+
+ @patch("products.canvas.backend.presentation.views.call_connector_tool")
+ def test_existing_connector_versions_cannot_read_with_shared_state(self, mock_call):
+ canvas_id = self._connectors_canvas()
+ canvas = Canvas.objects.for_team(self.team.id).get(id=canvas_id)
+ version = canvas.current_source_version
+ assert version is not None
+ assert version.capabilities is not None
+ version.capabilities["posthog"]["state"] = ["shared"]
+ version.save(update_fields=["capabilities"])
+ assert self._call(canvas_id).status_code == 403
+ state_response = self.client.post(
+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/set/",
+ {"key": "result", "scope": "shared", "value": "private"},
+ format="json",
+ )
+ assert state_response.status_code == 403
+ mock_call.assert_not_called()
+
+
+class TestConnectorResultBounds(SimpleTestCase):
+ @parameterized.expand([("unicode", "😀"), ("escape", "\\"), ("quotes", '"'), ("control", "\n")])
+ def test_preview_including_json_envelope_stays_within_byte_limit(self, _name: str, value: str) -> None:
+ result, truncated = _bounded({"data": value * MAX_RESULT_BYTES})
+ assert truncated
+ assert len(json.dumps(result).encode("utf-8")) <= MAX_RESULT_BYTES
diff --git a/products/canvas/backend/tests/test_source.py b/products/canvas/backend/tests/test_source.py
index d32011ae87df..88527a88804b 100644
--- a/products/canvas/backend/tests/test_source.py
+++ b/products/canvas/backend/tests/test_source.py
@@ -122,6 +122,59 @@ class TestCanvasSourceAdapter(SimpleTestCase):
project(capabilities={"posthog": {"actions": ["flags.delete"]}, "network": {"origins": []}}),
"action_not_registered",
),
+ (
+ "undeclared_connector_call",
+ project(
+ files={CANVAS_COMPONENT_PATH: CODE + 'ph.connectors.call("github", "list_pull_requests", {});'}
+ ),
+ "capability_missing_connector",
+ ),
+ (
+ # Declaring the provider is not declaring every tool on it.
+ "connector_tool_undeclared_on_declared_provider",
+ project(
+ files={CANVAS_COMPONENT_PATH: CODE + 'ph.connectors.call("github", "search_issues", {});'},
+ capabilities={
+ "posthog": {},
+ "network": {"origins": []},
+ "connectors": [{"provider": "github", "tools": ["list_pull_requests"]}],
+ },
+ ),
+ "capability_missing_connector",
+ ),
+ (
+ "unknown_connector_provider",
+ project(
+ capabilities={
+ "posthog": {},
+ "network": {"origins": []},
+ "connectors": [{"provider": "jira", "tools": ["list_issues"]}],
+ }
+ ),
+ "connector_provider_unknown",
+ ),
+ (
+ "mcp_connector_with_private_host",
+ project(
+ capabilities={
+ "posthog": {},
+ "network": {"origins": []},
+ "connectors": [{"provider": "mcp:localhost", "tools": ["list_events"]}],
+ }
+ ),
+ "connector_provider_unknown",
+ ),
+ (
+ "unregistered_native_connector_tool",
+ project(
+ capabilities={
+ "posthog": {},
+ "network": {"origins": []},
+ "connectors": [{"provider": "github", "tools": ["delete_repository"]}],
+ }
+ ),
+ "connector_tool_not_registered",
+ ),
(
"dynamic_import",
project(files={CANVAS_COMPONENT_PATH: 'const m = await import("https://evil.dev/x.js");'}),
@@ -229,6 +282,23 @@ class TestCanvasSourceAdapter(SimpleTestCase):
candidate = project(files={CANVAS_COMPONENT_PATH: CODE, path: content})
self.assertEqual(validate_source_project(candidate), [])
+ @parameterized.expand([("same_file", True), ("capabilities_only", False)])
+ def test_connectors_cannot_declare_shared_state(self, _name, include_calls):
+ candidate = project(
+ files={
+ CANVAS_COMPONENT_PATH: CODE
+ + ('ph.connectors.call("mcp:mcp.example.com", "list_events", {});' if include_calls else "")
+ },
+ capabilities={
+ "posthog": {"insights": [], "inlineQueries": False, "captureEvents": [], "state": ["shared"]},
+ "network": {"origins": []},
+ "connectors": [{"provider": "mcp:mcp.example.com", "tools": ["list_events"]}],
+ },
+ )
+ diagnostics = validate_source_project(candidate)
+ self.assertTrue(has_errors(diagnostics), diagnostics)
+ self.assertIn("connector_results_in_shared_state", [d["code"] for d in diagnostics])
+
def test_direct_network_calls_warn_but_stay_publishable(self):
candidate = project(files={CANVAS_COMPONENT_PATH: CODE + "fetch(dynamicUrl);"})
diagnostics = validate_source_project(candidate)
diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.ts
index 0cbb5895c5bb..67b1d51e0e60 100644
--- a/products/canvas/frontend/generated/api.schemas.ts
+++ b/products/canvas/frontend/generated/api.schemas.ts
@@ -451,6 +451,86 @@ export interface CanvasBuildActionApi {
build_id: string
}
+/**
+ * Tool arguments, validated against the tool's input schema.
+ */
+export type CanvasConnectorCallApiArguments = { [key: string]: unknown }
+
+/**
+ * Payload for calling one connector tool as the viewer.
+ */
+export interface CanvasConnectorCallApi {
+ /**
+ * Declared provider id, e.g. 'github'.
+ * @maxLength 300
+ */
+ provider: string
+ /**
+ * Declared tool name, e.g. 'list_pull_requests'.
+ * @maxLength 200
+ */
+ tool: string
+ /** Tool arguments, validated against the tool's input schema. */
+ arguments?: CanvasConnectorCallApiArguments
+}
+
+/**
+ * Tool output. Native tools return their documented shape; MCP tools return {content, structured_content, is_error}.
+ * @nullable
+ */
+export type CanvasConnectorCallResultApiResult = { [key: string]: unknown } | null
+
+/**
+ * * `ok` - Ok
+ * * `not_connected` - Not Connected
+ * * `needs_reauth` - Needs Reauth
+ * * `blocked` - Blocked
+ * * `tool_missing` - Tool Missing
+ * * `write_blocked` - Write Blocked
+ * * `upstream_error` - Upstream Error
+ */
+export type ConnectorCallStatusEnumApi = (typeof ConnectorCallStatusEnumApi)[keyof typeof ConnectorCallStatusEnumApi]
+
+export const ConnectorCallStatusEnumApi = {
+ Ok: 'ok',
+ NotConnected: 'not_connected',
+ NeedsReauth: 'needs_reauth',
+ Blocked: 'blocked',
+ ToolMissing: 'tool_missing',
+ WriteBlocked: 'write_blocked',
+ UpstreamError: 'upstream_error',
+} as const
+
+/**
+ * Result of one connector call. `status` is 'ok' when `result` holds the tool's output.
+ */
+export interface CanvasConnectorCallResultApi {
+ /** 'ok' carries a result. 'not_connected' and 'needs_reauth' mean the viewer must connect the provider at connect_path. 'blocked' is team policy. 'write_blocked' is a tool that may write. 'upstream_error' is a failure at the provider.
+ *
+ * * `ok` - Ok
+ * * `not_connected` - Not Connected
+ * * `needs_reauth` - Needs Reauth
+ * * `blocked` - Blocked
+ * * `tool_missing` - Tool Missing
+ * * `write_blocked` - Write Blocked
+ * * `upstream_error` - Upstream Error */
+ status: ConnectorCallStatusEnumApi
+ /**
+ * Tool output. Native tools return their documented shape; MCP tools return {content, structured_content, is_error}.
+ * @nullable
+ */
+ result: CanvasConnectorCallResultApiResult
+ /** Human-readable explanation for a non-ok status. */
+ detail: string
+ /** True when the result exceeded the size cap and was cut to a preview. */
+ truncated: boolean
+ /**
+ * In-app path where the viewer can connect the provider, when that would help.
+ * @nullable
+ */
+ connect_path: string | null
+}
+
/**
* * `base64` - base64
*/
@@ -540,9 +620,32 @@ export interface CanvasNetworkCapabilitiesApi {
origins: string[]
}
+/**
+ * One provider a canvas may call through ph.connectors, with the tools it may use.
+ */
+export interface CanvasConnectorDeclarationApi {
+ /**
+ * Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store.
+ * @maxLength 300
+ */
+ provider: string
+ /**
+ * Tool names the canvas may call on this provider. Read-only tools only.
+ * @minItems 1
+ * @maxItems 64
+ * @items.maxLength 200
+ */
+ tools: string[]
+}
+
export interface CanvasCapabilitiesApi {
posthog: CanvasPostHogCapabilitiesApi
network: CanvasNetworkCapabilitiesApi
+ /**
+ * Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review.
+ * @maxItems 20
+ */
+ connectors?: CanvasConnectorDeclarationApi[]
}
/**
@@ -613,6 +716,8 @@ export interface CanvasCapabilityWideningApi {
state_scopes_added: string[]
/** Action verbs the draft newly declares it may invoke via ph.actions. */
actions_added: string[]
+ /** Connector providers and tools the draft newly declares it may call via ph.connectors. */
+ connectors_added: CanvasConnectorDeclarationApi[]
}
/**
@@ -1399,6 +1504,67 @@ export interface CanvasActionsResponseApi {
actions: CanvasActionDefinitionApi[]
}
+/**
+ * * `native` - Native
+ * * `mcp` - Mcp
+ */
+export type ConnectorKindEnumApi = (typeof ConnectorKindEnumApi)[keyof typeof ConnectorKindEnumApi]
+
+export const ConnectorKindEnumApi = {
+ Native: 'native',
+ Mcp: 'mcp',
+} as const
+
+/**
+ * JSON Schema of the tool's arguments object.
+ */
+export type CanvasConnectorToolApiInputSchema = { [key: string]: unknown }
+
+/**
+ * One tool a connector provider exposes to canvases.
+ */
+export interface CanvasConnectorToolApi {
+ /** Tool name, as passed to ph.connectors.call. */
+ name: string
+ /** One line naming what the tool reads. */
+ summary: string
+ /** True when the tool only reads. Canvases may call read-only tools. */
+ is_read_only: boolean
+ /** JSON Schema of the tool's arguments object. */
+ input_schema: CanvasConnectorToolApiInputSchema
+ /** Authoring docs: argument and result shape, limits, and behavior. */
+ usage: string
+}
+
+/**
+ * One connector provider, with the caller's connection state and the tools it exposes.
+ */
+export interface CanvasConnectorApi {
+ /** Provider id to declare and call, e.g. 'github' or 'mcp:mcp.calendly.com'. */
+ provider: string
+ /** Display name of the provider. */
+ display_name: string
+ /** 'native' runs through a PostHog personal integration; 'mcp' through an MCP store installation.
+ *
+ * * `native` - Native
+ * * `mcp` - Mcp */
+ kind: ConnectorKindEnumApi
+ /** True when the caller has a usable connection to this provider. */
+ connected: boolean
+ /** In-app path where the caller connects this provider. */
+ connect_path: string
+ /** Tools the caller's connection exposes, sorted by name. */
+ tools: CanvasConnectorToolApi[]
+}
+
+/**
+ * The connector catalog: every provider a canvas may declare and call.
+ */
+export interface CanvasConnectorsResponseApi {
+ /** Native providers first, then the requested MCP hosts. */
+ connectors: CanvasConnectorApi[]
+}
+
export type CanvasesListParams = {
/**
* Only return canvases in this channel.
@@ -1486,3 +1652,10 @@ export type CanvasesVersionsRetrieveParams = {
*/
offset?: number
}
+
+export type CanvasesConnectorsRetrieveParams = {
+ /**
+ * Comma-separated MCP server hosts to include (e.g. 'mcp.calendly.com'). Defaults to every server the caller has connected in the MCP store.
+ */
+ mcp_hosts?: string
+}
diff --git a/products/canvas/frontend/generated/api.ts b/products/canvas/frontend/generated/api.ts
index 77a9dcd85447..95396f745c83 100644
--- a/products/canvas/frontend/generated/api.ts
+++ b/products/canvas/frontend/generated/api.ts
@@ -18,6 +18,9 @@ import type {
CanvasBuildActionApi,
CanvasBuildApi,
CanvasBuildsResponseApi,
+ CanvasConnectorCallApi,
+ CanvasConnectorCallResultApi,
+ CanvasConnectorsResponseApi,
CanvasCreateApi,
CanvasErrorReportResultApi,
CanvasFixRequestResultApi,
@@ -42,6 +45,7 @@ import type {
CanvasValidateRequestApi,
CanvasValidateResponseApi,
CanvasesBuildsRetrieveParams,
+ CanvasesConnectorsRetrieveParams,
CanvasesDraftsRetrieveParams,
CanvasesLayoutRetrieveParams,
CanvasesListParams,
@@ -243,6 +247,31 @@ export const canvasesBuildActionCreate = async (
})
}
+export const getCanvasesConnectorsCallUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/canvases/${id}/connectors/call/`
+}
+
+/**
+ * Call one declared connector tool as the viewer.
+ *
+ * The canvas must declare the provider and tool in capabilities.connectors
+ * (the reviewed permission boundary); the call runs with the viewer's own
+ * connection, so two viewers of the same canvas see their own data.
+ */
+export const canvasesConnectorsCall = async (
+ projectId: string,
+ id: string,
+ canvasConnectorCallApi: CanvasConnectorCallApi,
+ options?: RequestInit
+): Promise<CanvasConnectorCallResultApi> => {
+ return apiMutator<CanvasConnectorCallResultApi>(getCanvasesConnectorsCallUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(canvasConnectorCallApi),
+ })
+}
+
export const getCanvasesDraftCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/canvases/${id}/draft/`
}
@@ -753,6 +782,39 @@ export const canvasesActionsRetrieve = async (
})
}
+export const getCanvasesConnectorsRetrieveUrl = (projectId: string, params?: CanvasesConnectorsRetrieveParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/canvases/connectors/?${stringifiedParams}`
+ : `/api/projects/${projectId}/canvases/connectors/`
+}
+
+/**
+ * List the connector catalog: every provider and tool a canvas may declare, with the caller's connection state.
+ *
+ * Authoring agents read this to write ph.connectors.call sites and the
+ * matching capabilities.connectors declarations.
+ */
+export const canvasesConnectorsRetrieve = async (
+ projectId: string,
+ params?: CanvasesConnectorsRetrieveParams,
+ options?: RequestInit
+): Promise<CanvasConnectorsResponseApi> => {
+ return apiMutator<CanvasConnectorsResponseApi>(getCanvasesConnectorsRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getCanvasesHomeCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/canvases/home/`
}
diff --git a/products/canvas/frontend/generated/api.zod.ts b/products/canvas/frontend/generated/api.zod.ts
index 416d1c558907..dff93ca8b0cd 100644
--- a/products/canvas/frontend/generated/api.zod.ts
+++ b/products/canvas/frontend/generated/api.zod.ts
@@ -98,6 +98,34 @@ export const CanvasesBuildActionCreateBody = /* @__PURE__ */ zod.object({
build_id: zod.uuid(),
})
+/**
+ * Call one declared connector tool as the viewer.
+ *
+ * The canvas must declare the provider and tool in capabilities.connectors
+ * (the reviewed permission boundary); the call runs with the viewer's own
+ * connection, so two viewers of the same canvas see their own data.
+ */
+export const canvasesConnectorsCallBodyProviderMax = 300
+
+export const canvasesConnectorsCallBodyToolMax = 200
+
+export const CanvasesConnectorsCallBody = /* @__PURE__ */ zod
+ .object({
+ provider: zod
+ .string()
+ .max(canvasesConnectorsCallBodyProviderMax)
+ .describe("Declared provider id, e.g. 'github'."),
+ tool: zod
+ .string()
+ .max(canvasesConnectorsCallBodyToolMax)
+ .describe("Declared tool name, e.g. 'list_pull_requests'."),
+ arguments: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe("Tool arguments, validated against the tool's input schema."),
+ })
+ .describe('Payload for calling one connector tool as the viewer.')
+
/**
* Stage a complete source project as a draft version and build it, without publishing.
*
@@ -144,6 +172,14 @@ export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemM
export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax = 300
+
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax = 200
+
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax = 64
+
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsMax = 20
+
export const CanvasesDraftCreateBody = /* @__PURE__ */ zod
.object({
project: zod
@@ -291,6 +327,41 @@ export const CanvasesDraftCreateBody = /* @__PURE__ */ zod
)
.max(canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax),
}),
+ connectors: zod
+ .array(
+ zod
+ .object({
+ provider: zod
+ .string()
+ .max(
+ canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax
+ )
+ .describe(
+ "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store."
+ ),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(
+ canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax
+ )
+ )
+ .min(1)
+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax)
+ .describe(
+ 'Tool names the canvas may call on this provider. Read-only tools only.'
+ ),
+ })
+ .describe(
+ 'One provider a canvas may call through ph.connectors, with the tools it may use.'
+ )
+ )
+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsMax)
+ .optional()
+ .describe(
+ "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review."
+ ),
})
.optional()
.describe(
@@ -761,6 +832,14 @@ export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsIte
export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax = 300
+
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax = 200
+
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax = 64
+
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsMax = 20
+
export const canvasesPublishCreateBodyNameMax = 400
export const CanvasesPublishCreateBody = /* @__PURE__ */ zod
@@ -912,6 +991,43 @@ export const CanvasesPublishCreateBody = /* @__PURE__ */ zod
)
.max(canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax),
}),
+ connectors: zod
+ .array(
+ zod
+ .object({
+ provider: zod
+ .string()
+ .max(
+ canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax
+ )
+ .describe(
+ "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store."
+ ),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(
+ canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax
+ )
+ )
+ .min(1)
+ .max(
+ canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax
+ )
+ .describe(
+ 'Tool names the canvas may call on this provider. Read-only tools only.'
+ ),
+ })
+ .describe(
+ 'One provider a canvas may call through ph.connectors, with the tools it may use.'
+ )
+ )
+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsMax)
+ .optional()
+ .describe(
+ "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review."
+ ),
})
.optional()
.describe(
@@ -1078,6 +1194,14 @@ export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsIt
export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax = 300
+
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax = 200
+
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax = 64
+
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsMax = 20
+
export const CanvasesValidateCreateBody = /* @__PURE__ */ zod
.object({
project: zod
@@ -1229,6 +1353,43 @@ export const CanvasesValidateCreateBody = /* @__PURE__ */ zod
)
.max(canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax),
}),
+ connectors: zod
+ .array(
+ zod
+ .object({
+ provider: zod
+ .string()
+ .max(
+ canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax
+ )
+ .describe(
+ "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store."
+ ),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(
+ canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax
+ )
+ )
+ .min(1)
+ .max(
+ canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax
+ )
+ .describe(
+ 'Tool names the canvas may call on this provider. Read-only tools only.'
+ ),
+ })
+ .describe(
+ 'One provider a canvas may call through ph.connectors, with the tools it may use.'
+ )
+ )
+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsMax)
+ .optional()
+ .describe(
+ "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review."
+ ),
})
.optional()
.describe(
diff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yaml
index 7593f692dfb8..8fa1e30da346 100644
--- a/products/canvas/mcp/tools.yaml
+++ b/products/canvas/mcp/tools.yaml
@@ -28,6 +28,24 @@ tools:
param_overrides:
id:
description: ID of the canvas whose builds to read.
+ canvas-connectors-retrieve:
+ operation: canvases_connectors_retrieve
+ enabled: true
+ scopes:
+ - canvas:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List canvas connectors
+ description: >
+ List the connector catalog a canvas can read live third-party data through with `ph.connectors.call`: every
+ native provider (GitHub) and every MCP store server the authenticated user has connected, each with its
+ tools, their argument schemas, and authoring docs. Use this before writing a canvas that shows pull
+ requests, calendar events, issues, or any other data that must stay fresh per viewer, then declare each
+ provider and tool you call in the project's `capabilities.connectors`. Calls run with the VIEWER's own
+ connection at view time, never the author's, so results are never baked into the source. Only read-only
+ tools may be declared. Pass `mcp_hosts` to include a server the user has not connected yet.
canvas-create:
operation: canvases_create
enabled: true
@@ -387,6 +405,9 @@ tools:
canvases-build-action-create:
operation: canvases_build_action_create
enabled: false
+ canvases-connectors-call:
+ operation: canvases_connectors_call
+ enabled: false
canvases-destroy:
operation: canvases_destroy
enabled: false
diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjs
index e8be84318659..b00c83013071 100644
--- a/products/canvas/packages/canvas_builder/build.mjs
+++ b/products/canvas/packages/canvas_builder/build.mjs
@@ -32,7 +32,7 @@ const notebookFrameKeyPrefix = '__posthog_notebook_frame__:'
// event, which fires after the app's module scripts have already run, so any
// ph.* call issued during mount lands before the port exists. Those messages
// queue (bounded, in case the host never connects) and flush on connect.
-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 call=(method,payload)=>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=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"));},30000);pending.set(id,{resolve,reject,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"));};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);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))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,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??{}})}};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)port.postMessage(queued.shift());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 call=(method,payload)=>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=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"));},30000);pending.set(id,{resolve,reject,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"));};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);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))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,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)port.postMessage(queued.shift());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/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.py
index 152ca8f1fb08..5361abfd282b 100644
--- a/products/mcp_store/backend/facade/api.py
+++ b/products/mcp_store/backend/facade/api.py
@@ -4,9 +4,12 @@ Facade API for mcp_store.
This is the ONLY module other apps are allowed to import.
"""
+import json
import uuid
from collections import Counter, defaultdict
from collections.abc import Iterable
+from typing import Any
+from urllib.parse import urlsplit
from django.db.models import Q
@@ -19,7 +22,7 @@ from products.mcp_store.backend.agents import (
get_built_in_agent,
is_builtin_agent_enforcement_enabled,
)
-from products.mcp_store.backend.facade.contracts import ActiveInstallation
+from products.mcp_store.backend.facade.contracts import ActiveInstallation, ConnectorCallOutcome, ConnectorTool
from products.mcp_store.backend.gateway import (
agent_grant_owner_label,
agent_grant_proxy_path,
@@ -27,12 +30,15 @@ from products.mcp_store.backend.gateway import (
reachable_agent_grants,
)
from products.mcp_store.backend.models import (
+ MCPMemberServerRevocation,
MCPServerInstallation,
MCPServerInstallationTool,
MCPServiceAccount,
MCPServiceAccountServerAccess,
)
-from products.mcp_store.backend.policy import GatewayCaller, PolicyContext
+from products.mcp_store.backend.policy import GatewayCaller, PolicyContext, is_read_only_connector_tool
+from products.mcp_store.backend.proxy import record_tool_call_audit, resolve_call_decision, validate_installation_auth
+from products.mcp_store.backend.tools import ToolCallError, ToolsFetchError, call_upstream_tool
# Re-exported for the presentation layer ("presentation must use facade"
# import-linter contract): the single MCP URL policy entry point — shared SSRF
@@ -508,3 +514,159 @@ def resolve_agent_gateway_server_ids(
for installation_id, server_id in installations:
resolved[legacy_ids[installation_id]] = str(server_id)
return resolved
+
+
+def _installation_host(url: str) -> str:
+ return (urlsplit(url).hostname or "").lower()
+
+
+def member_installation_for_host(team_id: int, user_id: int, server_host: str) -> MCPServerInstallation | None:
+ """The member's own enabled connection to the server at ``server_host``,
+ else the team's shared one. A member never rides another member's
+ personal credential."""
+ host = server_host.lower()
+ candidates = (
+ MCPServerInstallation.objects.filter(team_id=team_id, is_enabled=True, url__icontains=host)
+ .filter(Q(user_id=user_id, scope="personal") | Q(scope="shared"))
+ .select_related("gateway_server")
+ .order_by("created_at")
+ )
+ matching = [installation for installation in candidates if _installation_host(installation.url) == host]
+ own = next((installation for installation in matching if installation.scope == "personal"), None)
+ if own is not None:
+ return own
+ return next((installation for installation in matching if installation.scope == "shared"), None)
+
+
+def _connector_tool(tool: MCPServerInstallationTool) -> ConnectorTool:
+ annotations = tool.annotations or {}
+ return ConnectorTool(
+ name=tool.tool_name,
+ description=tool.description or "",
+ input_schema=tool.input_schema or {},
+ read_only=is_read_only_connector_tool(tool.tool_name, annotations),
+ )
+
+
+def member_server_tools(team_id: int, user_id: int, server_host: str) -> list[ConnectorTool] | None:
+ """The tools the member's connection to ``server_host`` exposes, or None
+ when the member has no usable connection to that server."""
+ installation = member_installation_for_host(team_id, user_id, server_host)
+ if installation is None:
+ return None
+ seen: set[str] = set()
+ tools: list[ConnectorTool] = []
+ for tool in installation.tools.filter(removed_at__isnull=True).order_by("tool_name", "-last_seen_at", "-id"):
+ if tool.tool_name in seen:
+ continue
+ seen.add(tool.tool_name)
+ tools.append(_connector_tool(tool))
+ return tools
+
+
+def _member_access_outcome(
+ installation: MCPServerInstallation, team_id: int, user_id: int
+) -> ConnectorCallOutcome | None:
+ """The gates the member proxy applies before any call: the admin kill
+ switch, per-member revocation, and credential health."""
+ gateway_server = installation.gateway_server
+ if gateway_server is not None:
+ if not gateway_server.is_team_enabled:
+ return ConnectorCallOutcome(status="blocked", detail="This server is turned off for the team.")
+ if (
+ MCPMemberServerRevocation.objects.for_team(team_id)
+ .filter(gateway_server=gateway_server, user_id=user_id)
+ .exists()
+ ):
+ return ConnectorCallOutcome(status="blocked", detail="An admin turned this server off for you.")
+ ok, error_response = validate_installation_auth(installation)
+ if ok or error_response is None:
+ return None
+ detail = json.loads(error_response.content).get("error", "The connection cannot be used.")
+ if error_response.status_code == 401:
+ return ConnectorCallOutcome(status="needs_reauth", detail=detail)
+ return ConnectorCallOutcome(status="blocked", detail=detail)
+
+
+def call_member_server_tool(
+ team_id: int,
+ user_id: int,
+ server_host: str,
+ tool_name: str,
+ arguments: dict[str, Any],
+ *,
+ actor_label: str = "",
+ allow_writes: bool = True,
+) -> ConnectorCallOutcome:
+ """Call one tool on the server at ``server_host`` with the member's own
+ connection (or the team's shared one). Runs the same policy resolution
+ and audit as the member proxy, so a canvas cannot reach a tool the member
+ could not call from the MCP settings page."""
+ installation = member_installation_for_host(team_id, user_id, server_host)
+ if installation is None:
+ return ConnectorCallOutcome(status="not_connected", detail=f"You have not connected {server_host}.")
+ access_outcome = _member_access_outcome(installation, team_id, user_id)
+ if access_outcome is not None:
+ return access_outcome
+
+ tool = installation.tools.filter(tool_name=tool_name).order_by("-last_seen_at", "-id").first()
+ if tool is None:
+ return ConnectorCallOutcome(
+ status="tool_missing", detail=f"Tool '{tool_name}' is not registered for this connection."
+ )
+ if not allow_writes and not _connector_tool(tool).read_only:
+ return ConnectorCallOutcome(
+ status="write_blocked", detail=f"Tool '{tool_name}' may write; only reads are allowed."
+ )
+
+ gateway_server = installation.gateway_server
+ caller = GatewayCaller(kind="member", user_id=user_id)
+ policy_context = (
+ PolicyContext(team_id=team_id, caller=caller, gateway_server=gateway_server, installation=installation)
+ if gateway_server is not None
+ else None
+ )
+ decision, block_reason = resolve_call_decision(tool, policy_context)
+ if gateway_server is not None:
+ record_tool_call_audit(installation, gateway_server, caller, actor_label, tool_name, decision)
+ if block_reason == "removed":
+ return ConnectorCallOutcome(status="tool_missing", detail=f"Tool '{tool_name}' is no longer available.")
+ if block_reason == "needs_approval":
+ return ConnectorCallOutcome(
+ status="blocked", detail=f"Tool '{tool_name}' needs your approval in Settings → MCP servers."
+ )
+ if block_reason is not None:
+ return ConnectorCallOutcome(status="blocked", detail=f"Tool '{tool_name}' is turned off by team policy.")
+
+ try:
+ result = call_upstream_tool(installation, tool_name, arguments)
+ except (ToolCallError, ToolsFetchError) as exc:
+ logger.warning(
+ "mcp_store member tool call failed",
+ team_id=team_id,
+ installation_id=str(installation.id),
+ tool_name=tool_name,
+ error=str(exc),
+ )
+ return ConnectorCallOutcome(status="upstream_error", detail=f"The server could not run '{tool_name}': {exc}")
+
+ # The upstream server is untrusted input: a malformed `content` degrades
+ # to no blocks instead of raising.
+ content = result.get("content")
+ blocks = tuple(block for block in content if isinstance(block, dict)) if isinstance(content, list) else ()
+ return ConnectorCallOutcome(
+ status="ok",
+ content=blocks,
+ structured_content=result.get("structuredContent"),
+ is_error=bool(result.get("isError")),
+ )
+
+
+def member_server_hosts(team_id: int, user_id: int) -> list[str]:
+ """Hosts of every enabled server the member can call: their own connections and the team's shared ones."""
+ urls = (
+ MCPServerInstallation.objects.filter(team_id=team_id, is_enabled=True)
+ .filter(Q(user_id=user_id, scope="personal") | Q(scope="shared"))
+ .values_list("url", flat=True)
+ )
+ return sorted({host for url in urls if (host := _installation_host(url))})
diff --git a/products/mcp_store/backend/facade/contracts.py b/products/mcp_store/backend/facade/contracts.py
index eefeb9fe1be1..ae8ffbe298d1 100644
--- a/products/mcp_store/backend/facade/contracts.py
+++ b/products/mcp_store/backend/facade/contracts.py
@@ -6,6 +6,34 @@ exposes to the rest of the codebase. No Django imports.
"""
from dataclasses import dataclass, field
+from typing import Any, Literal
+
+
+@dataclass(frozen=True)
+class ConnectorTool:
+ """One tool a connected MCP server exposes to a member."""
+
+ name: str
+ description: str
+ input_schema: dict[str, Any]
+ # False when the server marks the tool destructive or its name reads as a write.
+ read_only: bool
+
+
+ConnectorCallStatus = Literal[
+ "ok", "not_connected", "needs_reauth", "blocked", "tool_missing", "write_blocked", "upstream_error"
+]
+
+
+@dataclass(frozen=True)
+class ConnectorCallOutcome:
+ """Result of one tool call made with a member's own connection."""
+
+ status: ConnectorCallStatus
+ content: tuple[dict[str, Any], ...] = ()
+ structured_content: Any = None
+ is_error: bool = False
+ detail: str = ""
@dataclass(frozen=True)
diff --git a/products/mcp_store/backend/policy.py b/products/mcp_store/backend/policy.py
index 2d4b346cf386..bfa451c8a3b3 100644
--- a/products/mcp_store/backend/policy.py
+++ b/products/mcp_store/backend/policy.py
@@ -140,6 +140,50 @@ def is_destructive_tool(tool_name: str, annotations: dict[str, Any] | None = Non
return bool(_word_tokens(tool_name) & _DESTRUCTIVE_TOKENS)
+_CONNECTOR_READ_VERBS = frozenset({"get", "list", "search", "fetch", "read", "find", "query", "count", "describe"})
+_CONNECTOR_WRITE_VERBS = frozenset(
+ {
+ "create",
+ "update",
+ "send",
+ "write",
+ "set",
+ "add",
+ "append",
+ "edit",
+ "put",
+ "post",
+ "patch",
+ "upload",
+ "publish",
+ "submit",
+ "merge",
+ "assign",
+ "invite",
+ "install",
+ "execute",
+ "invoke",
+ "insert",
+ "upsert",
+ "replace",
+ "and",
+ "or",
+ "then",
+ }
+)
+
+
+def is_read_only_connector_tool(tool_name: str, annotations: dict[str, Any] | None = None) -> bool:
+ tokens = [token for token in _WORD_SPLIT.split(_CAMEL_CASE_BOUNDARY.sub(" ", tool_name).lower()) if token]
+ return bool(
+ tokens
+ and tokens[0] in _CONNECTOR_READ_VERBS
+ and not set(tokens) & _CONNECTOR_WRITE_VERBS
+ and not is_destructive_tool(tool_name, annotations)
+ and (annotations or {}).get("readOnlyHint") is True
+ )
+
+
def member_preset_team_state(preset: str, tool_name: str, annotations: dict[str, Any] | None = None) -> str | None:
"""The default state a policy preset implies for a tool, or None when the
preset is unset and imposes nothing."""
diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.py
index 8ba09b1db38f..88670a2593a2 100644
--- a/products/mcp_store/backend/test/test_facade.py
+++ b/products/mcp_store/backend/test/test_facade.py
@@ -1,6 +1,8 @@
from posthog.test.base import BaseTest
from unittest.mock import patch
+from django.utils import timezone
+
from parameterized import parameterized
from posthog.models import User
@@ -12,9 +14,11 @@ from products.mcp_store.backend.agents import (
resolve_gateway_agent_token,
)
from products.mcp_store.backend.facade.api import (
+ call_member_server_tool,
get_active_installations,
get_installations_for_sandbox,
get_sandbox_mcp_server_names,
+ member_server_tools,
resolve_agent_gateway_server_ids,
)
from products.mcp_store.backend.facade.contracts import ActiveInstallation
@@ -22,6 +26,7 @@ from products.mcp_store.backend.models import (
MCPGatewayServer,
MCPMemberServerRevocation,
MCPServerInstallation,
+ MCPServerInstallationTool,
MCPServerTemplate,
MCPServiceAccount,
MCPServiceAccountServerAccess,
@@ -904,3 +909,109 @@ class TestGetInstallationsForSandbox(BaseTest):
results = get_installations_for_sandbox(self.team.id, user_id=self.user.id, include_personal=include_personal)
assert (len(results) == 1) == expected_included
+
+
+class TestCallMemberServerTool(BaseTest):
+ HOST = "mcp.example.com"
+
+ def _installation(self, **kwargs) -> MCPServerInstallation:
+ defaults: dict = {
+ "team": self.team,
+ "user": self.user,
+ "url": f"https://{self.HOST}/mcp",
+ "auth_type": "api_key",
+ "sensitive_configuration": {"api_key": "sk-test"},
+ }
+ defaults.update(kwargs)
+ return MCPServerInstallation.objects.create(**defaults)
+
+ def _tool(self, installation: MCPServerInstallation, name: str = "list_events", **kwargs) -> None:
+ kwargs.setdefault("annotations", {"readOnlyHint": True})
+ MCPServerInstallationTool.objects.create(
+ installation=installation,
+ tool_name=name,
+ approval_state="approved",
+ last_seen_at=timezone.now(),
+ **kwargs,
+ )
+
+ def _call(self, name: str = "list_events", **kwargs):
+ return call_member_server_tool(self.team.id, self.user.id, self.HOST, name, {"limit": 5}, **kwargs)
+
+ @patch(
+ "products.mcp_store.backend.facade.api.call_upstream_tool",
+ return_value={"content": [{"type": "text", "text": "3 events"}], "isError": False},
+ )
+ def test_prefers_the_members_own_connection_over_a_shared_one(self, mock_call) -> None:
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ shared = self._installation(user=other_user, scope="shared")
+ own = self._installation()
+ self._tool(shared)
+ self._tool(own)
+
+ outcome = self._call()
+
+ assert outcome.status == "ok"
+ assert outcome.content == ({"type": "text", "text": "3 events"},)
+ assert mock_call.call_args.args[0].id == own.id
+
+ @patch("products.mcp_store.backend.facade.api.call_upstream_tool", return_value={"content": []})
+ def test_falls_back_to_the_teams_shared_connection(self, mock_call) -> None:
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ shared = self._installation(user=other_user, scope="shared")
+ self._installation(user=other_user, url="https://mcp.example.com.evil.test/mcp")
+ self._tool(shared)
+
+ assert self._call().status == "ok"
+ assert mock_call.call_args.args[0].id == shared.id
+
+ @patch("products.mcp_store.backend.facade.api.call_upstream_tool")
+ def test_never_borrows_a_teammates_personal_connection(self, mock_call) -> None:
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ self._tool(self._installation(user=other_user))
+
+ assert self._call().status == "not_connected"
+ mock_call.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("destructive_name", "delete_event", {}, False, "write_blocked"),
+ ("read_only_hint_cannot_clear_name", "delete_event", {"readOnlyHint": True}, False, "write_blocked"),
+ (
+ "destructive_hint",
+ "list_events",
+ {"readOnlyHint": True, "destructiveHint": True},
+ False,
+ "write_blocked",
+ ),
+ ("create", "create_issue", {"readOnlyHint": True}, False, "write_blocked"),
+ ("update", "update_event", {"readOnlyHint": True}, False, "write_blocked"),
+ ("send", "send_message", {"readOnlyHint": True}, False, "write_blocked"),
+ ("unknown", "process_event", {"readOnlyHint": True}, False, "write_blocked"),
+ ("mixed", "getOrCreateEvent", {"readOnlyHint": True}, False, "write_blocked"),
+ ("missing_hint", "list_events", {}, False, "write_blocked"),
+ ("read_name_marked_write", "list_events", {"readOnlyHint": False}, False, "write_blocked"),
+ ("writes_allowed", "delete_event", {}, True, "ok"),
+ ]
+ )
+ @patch("products.mcp_store.backend.facade.api.call_upstream_tool", return_value={"content": []})
+ def test_allow_writes_gates_tools_that_may_write(
+ self, _name, tool_name, annotations, allow_writes, expected_status, mock_call
+ ) -> None:
+ self._tool(self._installation(), name=tool_name, annotations=annotations)
+
+ assert self._call(tool_name, allow_writes=allow_writes).status == expected_status
+ assert mock_call.called is (expected_status == "ok")
+ tools = member_server_tools(self.team.id, self.user.id, self.HOST)
+ assert tools is not None
+ assert tools[0].read_only is False
+
+ @patch("products.mcp_store.backend.facade.api.call_upstream_tool")
+ def test_disabled_gateway_server_blocks_without_calling_upstream(self, mock_call) -> None:
+ server = MCPGatewayServer.objects.for_team(self.team.id).create(
+ team=self.team, name="Example", url=f"https://{self.HOST}/mcp", is_team_enabled=False
+ )
+ self._tool(self._installation(gateway_server=server))
+
+ assert self._call().status == "blocked"
+ mock_call.assert_not_called()
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 1d492507b26a..56ec1e7f7873 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1128,6 +1128,20 @@
"readOnlyHint": true
}
},
+ "canvas-connectors-retrieve": {
+ "description": "List the connector catalog a canvas can read live third-party data through with `ph.connectors.call`: every native provider (GitHub) and every MCP store server the authenticated user has connected, each with its tools, their argument schemas, and authoring docs. Use this before writing a canvas that shows pull requests, calendar events, issues, or any other data that must stay fresh per viewer, then declare each provider and tool you call in the project's `capabilities.connectors`. Calls run with the VIEWER's own connection at view time, never the author's, so results are never baked into the source. Only read-only tools may be declared. Pass `mcp_hosts` to include a server the user has not connected yet.",
+ "category": "Canvas",
+ "feature": "canvas",
+ "summary": "List canvas connectors",
+ "title": "List canvas connectors",
+ "required_scopes": ["canvas:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"canvas-create": {
"description": "Create a new, empty canvas in a channel. Returns the canvas's id and (null) `current_version_id`; give it source by publishing a project with canvas-publish-create. Only create a canvas when no existing one is the intended target — list them with canvas-list first. The response's `url` is the canvas's only valid link — share it verbatim when pointing the user at the canvas; never construct a canvas URL yourself.",
"category": "Canvas",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 71309ac98c64..8d1db210b862 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1143,6 +1143,20 @@
"readOnlyHint": true
}
},
+ "canvas-connectors-retrieve": {
+ "description": "List the connector catalog a canvas can read live third-party data through with `ph.connectors.call`: every native provider (GitHub) and every MCP store server the authenticated user has connected, each with its tools, their argument schemas, and authoring docs. Use this before writing a canvas that shows pull requests, calendar events, issues, or any other data that must stay fresh per viewer, then declare each provider and tool you call in the project's `capabilities.connectors`. Calls run with the VIEWER's own connection at view time, never the author's, so results are never baked into the source. Only read-only tools may be declared. Pass `mcp_hosts` to include a server the user has not connected yet.",
+ "category": "Canvas",
+ "feature": "canvas",
+ "summary": "List canvas connectors",
+ "title": "List canvas connectors",
+ "required_scopes": ["canvas:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"canvas-create": {
"description": "Create a new, empty canvas in a channel. Returns the canvas's id and (null) `current_version_id`; give it source by publishing a project with canvas-publish-create. Only create a canvas when no existing one is the intended target — list them with canvas-list first. The response's `url` is the canvas's only valid link — share it verbatim when pointing the user at the canvas; never construct a canvas URL yourself.",
"category": "Canvas",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c6878b7f1862..db0a766485c1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -15816,9 +15816,32 @@ export namespace Schemas {
origins: string[];
}
+ /**
+ * One provider a canvas may call through ph.connectors, with the tools it may use.
+ */
+ export interface CanvasConnectorDeclaration {
+ /**
+ * Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store.
+ * @maxLength 300
+ */
+ provider: string;
+ /**
+ * Tool names the canvas may call on this provider. Read-only tools only.
+ * @minItems 1
+ * @maxItems 64
+ * @items.maxLength 200
+ */
+ tools: string[];
+ }
+
export interface CanvasCapabilities {
posthog: CanvasPostHogCapabilities;
network: CanvasNetworkCapabilities;
+ /**
+ * Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review.
+ * @maxItems 20
+ */
+ connectors?: CanvasConnectorDeclaration[];
}
/**
@@ -15842,6 +15865,151 @@ export namespace Schemas {
state_scopes_added: string[];
/** Action verbs the draft newly declares it may invoke via ph.actions. */
actions_added: string[];
+ /** Connector providers and tools the draft newly declares it may call via ph.connectors. */
+ connectors_added: CanvasConnectorDeclaration[];
+ }
+
+ /**
+ * * `native` - Native
+ * * `mcp` - Mcp
+ */
+ export type ConnectorKindEnum = typeof ConnectorKindEnum[keyof typeof ConnectorKindEnum];
+
+
+ export const ConnectorKindEnum = {
+ Native: 'native',
+ Mcp: 'mcp',
+ } as const;
+
+ /**
+ * JSON Schema of the tool's arguments object.
+ */
+ export type CanvasConnectorToolInputSchema = { [key: string]: unknown };
+
+ /**
+ * One tool a connector provider exposes to canvases.
+ */
+ export interface CanvasConnectorTool {
+ /** Tool name, as passed to ph.connectors.call. */
+ name: string;
+ /** One line naming what the tool reads. */
+ summary: string;
+ /** True when the tool only reads. Canvases may call read-only tools. */
+ is_read_only: boolean;
+ /** JSON Schema of the tool's arguments object. */
+ input_schema: CanvasConnectorToolInputSchema;
+ /** Authoring docs: argument and result shape, limits, and behavior. */
+ usage: string;
+ }
+
+ /**
+ * One connector provider, with the caller's connection state and the tools it exposes.
+ */
+ export interface CanvasConnector {
+ /** Provider id to declare and call, e.g. 'github' or 'mcp:mcp.calendly.com'. */
+ provider: string;
+ /** Display name of the provider. */
+ display_name: string;
+ /** 'native' runs through a PostHog personal integration; 'mcp' through an MCP store installation.
+ *
+ * * `native` - Native
+ * * `mcp` - Mcp */
+ kind: ConnectorKindEnum;
+ /** True when the caller has a usable connection to this provider. */
+ connected: boolean;
+ /** In-app path where the caller connects this provider. */
+ connect_path: string;
+ /** Tools the caller's connection exposes, sorted by name. */
+ tools: CanvasConnectorTool[];
+ }
+
+ /**
+ * Tool arguments, validated against the tool's input schema.
+ */
+ export type CanvasConnectorCallArguments = { [key: string]: unknown };
+
+ /**
+ * Payload for calling one connector tool as the viewer.
+ */
+ export interface CanvasConnectorCall {
+ /**
+ * Declared provider id, e.g. 'github'.
+ * @maxLength 300
+ */
+ provider: string;
+ /**
+ * Declared tool name, e.g. 'list_pull_requests'.
+ * @maxLength 200
+ */
+ tool: string;
+ /** Tool arguments, validated against the tool's input schema. */
+ arguments?: CanvasConnectorCallArguments;
+ }
+
+ /**
+ * Tool output. Native tools return their documented shape; MCP tools return {content, structured_content, is_error}.
+ * @nullable
+ */
+ export type CanvasConnectorCallResultResult = { [key: string]: unknown } | null;
+
+ /**
+ * * `ok` - Ok
+ * * `not_connected` - Not Connected
+ * * `needs_reauth` - Needs Reauth
+ * * `blocked` - Blocked
+ * * `tool_missing` - Tool Missing
+ * * `write_blocked` - Write Blocked
+ * * `upstream_error` - Upstream Error
+ */
+ export type ConnectorCallStatusEnum = typeof ConnectorCallStatusEnum[keyof typeof ConnectorCallStatusEnum];
+
+
+ export const ConnectorCallStatusEnum = {
+ Ok: 'ok',
+ NotConnected: 'not_connected',
+ NeedsReauth: 'needs_reauth',
+ Blocked: 'blocked',
+ ToolMissing: 'tool_missing',
+ WriteBlocked: 'write_blocked',
+ UpstreamError: 'upstream_error',
+ } as const;
+
+ /**
+ * Result of one connector call. `status` is 'ok' when `result` holds the tool's output.
+ */
+ export interface CanvasConnectorCallResult {
+ /** 'ok' carries a result. 'not_connected' and 'needs_reauth' mean the viewer must connect the provider at connect_path. 'blocked' is team policy. 'write_blocked' is a tool that may write. 'upstream_error' is a failure at the provider.
+ *
+ * * `ok` - Ok
+ * * `not_connected` - Not Connected
+ * * `needs_reauth` - Needs Reauth
+ * * `blocked` - Blocked
+ * * `tool_missing` - Tool Missing
+ * * `write_blocked` - Write Blocked
+ * * `upstream_error` - Upstream Error */
+ status: ConnectorCallStatusEnum;
+ /**
+ * Tool output. Native tools return their documented shape; MCP tools return {content, structured_content, is_error}.
+ * @nullable
+ */
+ result: CanvasConnectorCallResultResult;
+ /** Human-readable explanation for a non-ok status. */
+ detail: string;
+ /** True when the result exceeded the size cap and was cut to a preview. */
+ truncated: boolean;
+ /**
+ * In-app path where the viewer can connect the provider, when that would help.
+ * @nullable
+ */
+ connect_path: string | null;
+ }
+
+ /**
+ * The connector catalog: every provider a canvas may declare and call.
+ */
+ export interface CanvasConnectorsResponse {
+ /** Native providers first, then the requested MCP hosts. */
+ connectors: CanvasConnector[];
}
/**
@@ -93607,6 +93775,13 @@ export namespace Schemas {
offset?: number;
};
+ export type CanvasesConnectorsRetrieveParams = {
+ /**
+ * Comma-separated MCP server hosts to include (e.g. 'mcp.calendly.com'). Defaults to every server the caller has connected in the MCP store.
+ */
+ mcp_hosts?: string;
+ };
+
export type ChangeRequestsListParams = {
action_key?: string;
/**
diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.ts
index 9d5cafdd6ed4..ded91b2f79c7 100644
--- a/services/mcp/src/generated/canvas/api.ts
+++ b/services/mcp/src/generated/canvas/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 17 enabled ops
+ * PostHog API - MCP 18 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -188,6 +188,14 @@ export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemM
export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax = 300
+
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax = 200
+
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax = 64
+
+export const canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsMax = 20
+
export const CanvasesDraftCreateBody = () => zod
.object({
project: zod
@@ -335,6 +343,41 @@ export const CanvasesDraftCreateBody = () => zod
)
.max(canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax),
}),
+ connectors: zod
+ .array(
+ zod
+ .object({
+ provider: zod
+ .string()
+ .max(
+ canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax
+ )
+ .describe(
+ "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store."
+ ),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(
+ canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax
+ )
+ )
+ .min(1)
+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax)
+ .describe(
+ 'Tool names the canvas may call on this provider. Read-only tools only.'
+ ),
+ })
+ .describe(
+ 'One provider a canvas may call through ph.connectors, with the tools it may use.'
+ )
+ )
+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOneConnectorsMax)
+ .optional()
+ .describe(
+ "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review."
+ ),
})
.optional()
.describe(
@@ -894,6 +937,14 @@ export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsIte
export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax = 300
+
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax = 200
+
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax = 64
+
+export const canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsMax = 20
+
export const canvasesPublishCreateBodyNameMax = 400
export const CanvasesPublishCreateBody = () => zod
@@ -1045,6 +1096,43 @@ export const CanvasesPublishCreateBody = () => zod
)
.max(canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax),
}),
+ connectors: zod
+ .array(
+ zod
+ .object({
+ provider: zod
+ .string()
+ .max(
+ canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax
+ )
+ .describe(
+ "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store."
+ ),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(
+ canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax
+ )
+ )
+ .min(1)
+ .max(
+ canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax
+ )
+ .describe(
+ 'Tool names the canvas may call on this provider. Read-only tools only.'
+ ),
+ })
+ .describe(
+ 'One provider a canvas may call through ph.connectors, with the tools it may use.'
+ )
+ )
+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOneConnectorsMax)
+ .optional()
+ .describe(
+ "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review."
+ ),
})
.optional()
.describe(
@@ -1207,6 +1295,14 @@ export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsIt
export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax = 300
+
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax = 200
+
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax = 64
+
+export const canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsMax = 20
+
export const CanvasesValidateCreateBody = () => zod
.object({
project: zod
@@ -1358,6 +1454,43 @@ export const CanvasesValidateCreateBody = () => zod
)
.max(canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax),
}),
+ connectors: zod
+ .array(
+ zod
+ .object({
+ provider: zod
+ .string()
+ .max(
+ canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemProviderMax
+ )
+ .describe(
+ "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store."
+ ),
+ tools: zod
+ .array(
+ zod
+ .string()
+ .max(
+ canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsItemMax
+ )
+ )
+ .min(1)
+ .max(
+ canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsItemToolsMax
+ )
+ .describe(
+ 'Tool names the canvas may call on this provider. Read-only tools only.'
+ ),
+ })
+ .describe(
+ 'One provider a canvas may call through ph.connectors, with the tools it may use.'
+ )
+ )
+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOneConnectorsMax)
+ .optional()
+ .describe(
+ "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review."
+ ),
})
.optional()
.describe(
@@ -1368,3 +1501,26 @@ export const CanvasesValidateCreateBody = () => zod
.describe('The candidate source project to validate.'),
})
.describe('Payload for validating a candidate source project without publishing it.')
+
+/**
+ * List the connector catalog: every provider and tool a canvas may declare, with the caller's connection state.
+ *
+ * Authoring agents read this to write ph.connectors.call sites and the
+ * matching capabilities.connectors declarations.
+ */
+export const CanvasesConnectorsRetrieveParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const CanvasesConnectorsRetrieveQueryParams = () => zod.object({
+ mcp_hosts: zod
+ .string()
+ .optional()
+ .describe(
+ "Comma-separated MCP server hosts to include (e.g. 'mcp.calendly.com'). Defaults to every server the caller has connected in the MCP store."
+ ),
+})
diff --git a/services/mcp/src/tools/generated/canvas.ts b/services/mcp/src/tools/generated/canvas.ts
index f85628e6f997..1f7079456474 100644
--- a/services/mcp/src/tools/generated/canvas.ts
+++ b/services/mcp/src/tools/generated/canvas.ts
@@ -32,6 +32,30 @@ const canvasBuildsRetrieve = (): ToolBase<
},
})
+const CanvasConnectorsRetrieveSchema = () => {
+ const CanvasesConnectorsRetrieveQueryParams = orvalSchemas.CanvasesConnectorsRetrieveQueryParams()
+ return CanvasesConnectorsRetrieveQueryParams
+}
+
+const canvasConnectorsRetrieve = (): ToolBase<
+ ReturnType<typeof CanvasConnectorsRetrieveSchema>,
+ Schemas.CanvasConnectorsResponse
+> => ({
+ name: 'canvas-connectors-retrieve',
+ schema: CanvasConnectorsRetrieveSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof CanvasConnectorsRetrieveSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.CanvasConnectorsResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/canvases/connectors/`,
+ query: {
+ mcp_hosts: params.mcp_hosts,
+ },
+ })
+ return result
+ },
+})
+
const CanvasCreateSchema = () => {
const CanvasesCreateBody = orvalSchemas.CanvasesCreateBody()
return CanvasesCreateBody.extend({
@@ -559,6 +583,7 @@ const canvasValidateCreate = (): ToolBase<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'canvas-builds-retrieve': canvasBuildsRetrieve,
+ 'canvas-connectors-retrieve': canvasConnectorsRetrieve,
'canvas-create': canvasCreate,
'canvas-draft-create': canvasDraftCreate,
'canvas-drafts-retrieve': canvasDraftsRetrieve,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-connectors-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-connectors-retrieve.json
new file mode 100644
index 000000000000..574fbe1823d4
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-connectors-retrieve.json
@@ -0,0 +1,10 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "mcp_hosts": {
+ "description": "Comma-separated MCP server hosts to include (e.g. 'mcp.calendly.com'). Defaults to every server the caller has connected in the MCP store.",
+ "type": "string"
+ }
+ },
+ "type": "object"
+}
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 9bd7463c0bf1..8435b8e0c662 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
@@ -53,6 +53,33 @@
"capabilities": {
"description": "Bounded capabilities frozen into the built artifact. Declare every insight short id the canvas loads, every event it captures, and inlineQueries when it runs ad-hoc HogQL — the host enforces these at runtime and validation rejects undeclared `ph` calls. Network origins must be exact HTTPS origins. Data fetched by canvas code can be sent to those origins.",
"properties": {
+ "connectors": {
+ "description": "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review.",
+ "items": {
+ "description": "One provider a canvas may call through ph.connectors, with the tools it may use.",
+ "properties": {
+ "provider": {
+ "description": "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store.",
+ "maxLength": 300,
+ "type": "string"
+ },
+ "tools": {
+ "description": "Tool names the canvas may call on this provider. Read-only tools only.",
+ "items": {
+ "maxLength": 200,
+ "type": "string"
+ },
+ "maxItems": 64,
+ "minItems": 1,
+ "type": "array"
+ }
+ },
+ "required": ["provider", "tools"],
+ "type": "object"
+ },
+ "maxItems": 20,
+ "type": "array"
+ },
"network": {
"properties": {
"origins": {
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 fd3433715134..0a5855faf54b 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
@@ -69,6 +69,33 @@
"capabilities": {
"description": "Bounded capabilities frozen into the built artifact. Declare every insight short id the canvas loads, every event it captures, and inlineQueries when it runs ad-hoc HogQL — the host enforces these at runtime and validation rejects undeclared `ph` calls. Network origins must be exact HTTPS origins. Data fetched by canvas code can be sent to those origins.",
"properties": {
+ "connectors": {
+ "description": "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review.",
+ "items": {
+ "description": "One provider a canvas may call through ph.connectors, with the tools it may use.",
+ "properties": {
+ "provider": {
+ "description": "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store.",
+ "maxLength": 300,
+ "type": "string"
+ },
+ "tools": {
+ "description": "Tool names the canvas may call on this provider. Read-only tools only.",
+ "items": {
+ "maxLength": 200,
+ "type": "string"
+ },
+ "maxItems": 64,
+ "minItems": 1,
+ "type": "array"
+ }
+ },
+ "required": ["provider", "tools"],
+ "type": "object"
+ },
+ "maxItems": 20,
+ "type": "array"
+ },
"network": {
"properties": {
"origins": {
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 2d43fec6a3b1..c8455eb97dce 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
@@ -53,6 +53,33 @@
"capabilities": {
"description": "Bounded capabilities frozen into the built artifact. Declare every insight short id the canvas loads, every event it captures, and inlineQueries when it runs ad-hoc HogQL — the host enforces these at runtime and validation rejects undeclared `ph` calls. Network origins must be exact HTTPS origins. Data fetched by canvas code can be sent to those origins.",
"properties": {
+ "connectors": {
+ "description": "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review.",
+ "items": {
+ "description": "One provider a canvas may call through ph.connectors, with the tools it may use.",
+ "properties": {
+ "provider": {
+ "description": "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store.",
+ "maxLength": 300,
+ "type": "string"
+ },
+ "tools": {
+ "description": "Tool names the canvas may call on this provider. Read-only tools only.",
+ "items": {
+ "maxLength": 200,
+ "type": "string"
+ },
+ "maxItems": 64,
+ "minItems": 1,
+ "type": "array"
+ }
+ },
+ "required": ["provider", "tools"],
+ "type": "object"
+ },
+ "maxItems": 20,
+ "type": "array"
+ },
"network": {
"properties": {
"origins": {
diff --git a/tach.toml b/tach.toml
index 896f4486c86a..6a4d41b3c434 100644
--- a/tach.toml
+++ b/tach.toml
@@ -914,6 +914,8 @@ depends_on = [
"products.tasks",
# The annotations.create action verb (via the annotations facade).
"products.annotations",
+ # MCP connector calls made with the viewer's own installation (via the mcp_store facade).
+ "products.mcp_store",
]
layer = "modules"