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.

fix(canvas): add filtered github reads and safe catalog access (#98199)

Peter Kirkham6a5343c57b69
diff --git a/docs/internal/canvas-connectors.md b/docs/internal/canvas-connectors.md
index 9ad08272654a..ca725da6125a 100644
--- a/docs/internal/canvas-connectors.md
+++ b/docs/internal/canvas-connectors.md
@@ -20,7 +20,7 @@ A canvas with connectors cannot declare shared state. This rule applies to the w
`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.
+The `canvas-connectors-retrieve` MCP tool exposes this catalog to authors. The catalog does not call the upstream tools. Sandbox authors receive only static native tool schemas, with `connected: null`. This response does not read personal connections or MCP installations, even when `mcp_hosts` is set. Viewer calls still include connection status. Sandbox credentials cannot execute connector tools.
## Call a tool
@@ -40,12 +40,53 @@ Results are limited to 256 KiB. Large results become a bounded `preview` with `t
## 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.
+- `github` exposes `list_pull_requests`, `search_pull_requests`, `get_pull_request_snapshot`, `get_pull_request_checks`, `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.
+## GitHub pull request reads
+
+Use `search_pull_requests` for an author's PRs. Do not fetch one repository page and then filter it by author. The search applies filters at GitHub before pagination.
+
+```javascript
+const page = await ph.connectors.call('github', 'search_pull_requests', {
+ repository: 'example/app',
+ author: 'me',
+ state: 'open',
+ page: 1,
+ per_page: 25,
+})
+```
+
+`author: "me"` uses the GitHub user identity stored on the viewer's connection. It does not use the installation account, canvas author, or terminal credentials. A missing identity returns `upstream_error`; reconnect GitHub or supply an explicit login.
+
+Both list and search accept `page`, `per_page` (1–100), `sort` (`created` or `updated`), and `direction` (`asc` or `desc`). Both default to page 1, sorted by creation time descending. List defaults to 100 results; search defaults to 25. Search also accepts `author`, `draft`, and literal `query` text. Search qualifiers in `query` are quoted, not interpreted. `state` is `open`, `closed`, or `all`, and defaults to `open`.
+
+Successful pages return `pull_requests`, `page`, `per_page`, `has_next_page`, and `next_page`. Follow `next_page` with the same filters and page size. A null `next_page` ends the available pages. Search also returns:
+
+- `total_count`: GitHub's reported match count.
+- `incomplete_results`: GitHub could not complete the search. Do not label the result as complete.
+- `search_limit_reached`: More than 1000 matches exist. Narrow the filters to reach results beyond GitHub's search limit.
+
+These fields do not replace the outer `truncated` flag, which reports response-size truncation. Check `status` and `truncated` before reading a page. The tools return selected metadata rather than PR bodies to keep pages small. List results retain `head_branch` and `base_branch`; search results omit these fields. Both preserve `state: "open"` for drafts and expose `draft` separately.
+
+Declare `get_pull_request_snapshot` to fetch CI, approval, mergeability, and `head_sha` for a returned PR:
+
+```javascript
+const status = await ph.connectors.call('github', 'get_pull_request_snapshot', {
+ repository: 'example/app',
+ pr_number: 7,
+})
+```
+
+Snapshot state can be `draft` or `merged`. A null `review_decision` is not approval. Associate each snapshot with its `head_sha`. If a status read fails, keep the PR row and show status as unavailable. Do not replace a failed status read with an empty PR list.
+
+`get_pull_request_checks` accepts the same arguments. It reuses the GitHub client helper that reads all check-run and external commit-status pages. An empty `checks` list is a successful read with no checks. A failed helper returns `upstream_error`, not a successful empty list. The existing issue search and text-only file read contracts do not change.
+
+Connector reads use the host cache, which defaults to 60 seconds. A repeated call can return cached data. A canvas must schedule its own polling; a cache lifetime is not a subscription or a promise of an immediate fresh read.
+
## Host safety
The canvas host asks the viewer before it sends connector calls. Consent is limited to the canvas version, provider, and tool. The prompt explains that the canvas can receive private data and share it through its declared capabilities. A denied call stays blocked until the viewer retries from a user action.
diff --git a/products/canvas/backend/connectors.py b/products/canvas/backend/connectors.py
index 4fcd9135910f..b0775c0f2400 100644
--- a/products/canvas/backend/connectors.py
+++ b/products/canvas/backend/connectors.py
@@ -19,8 +19,10 @@ needs a user gesture and a confirm step in the host.
import json
import base64
from collections.abc import Callable
+from dataclasses import replace
from typing import TYPE_CHECKING, Any
+from django.core.validators import RegexValidator
from django.db import models
import structlog
@@ -131,12 +133,52 @@ class GitHubRepositorySerializer(serializers.Serializer):
return value
-class GitHubListPullRequestsPayloadSerializer(GitHubRepositorySerializer):
+class GitHubPagePayloadSerializer(GitHubRepositorySerializer):
+ page = serializers.IntegerField(min_value=1, default=1, help_text="Page number, starting at 1.")
+ per_page = serializers.IntegerField(
+ min_value=1, max_value=100, default=100, help_text="Results per page, up to 100."
+ )
+ sort = serializers.ChoiceField(
+ choices=["created", "updated"], default="created", help_text="Field used to sort results."
+ )
+ direction = serializers.ChoiceField(choices=["asc", "desc"], default="desc", help_text="Sort direction.")
+
+
+class GitHubListPullRequestsPayloadSerializer(GitHubPagePayloadSerializer):
state = serializers.ChoiceField(
choices=["open", "closed", "all"], default="open", help_text="Which pull requests to list."
)
+class GitHubSearchPullRequestsPayloadSerializer(GitHubListPullRequestsPayloadSerializer):
+ author = serializers.RegexField(
+ r"^[A-Za-z0-9][A-Za-z0-9-]*(?:\[bot\])?$",
+ max_length=100,
+ required=False,
+ help_text="GitHub author login, or 'me' for the connected user's GitHub identity.",
+ )
+ query = serializers.CharField(
+ max_length=256,
+ required=False,
+ help_text="Literal text to search in PR titles and bodies, not search qualifiers.",
+ )
+ draft = serializers.BooleanField(required=False, help_text="Filter to draft or non-draft pull requests.")
+ per_page = serializers.IntegerField(
+ min_value=1, max_value=100, default=25, help_text="Results per page, up to 100."
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ if (attrs["page"] - 1) * attrs["per_page"] >= 1000:
+ raise serializers.ValidationError(
+ {"page": "GitHub search exposes only the first 1000 matches. Narrow the filters."}
+ )
+ return attrs
+
+
+class GitHubPullRequestPayloadSerializer(GitHubRepositorySerializer):
+ pr_number = serializers.IntegerField(min_value=1, help_text="Pull request number within the repository.")
+
+
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.")
@@ -174,7 +216,13 @@ def _github_list_pull_requests(integration: UserIntegration, payload: dict[str,
"GET",
f"/repos/{_github_repo_path(client, payload['repository'])}/pulls",
endpoint="/repos/{owner}/{repo}/pulls",
- params={"state": payload["state"], "per_page": 100},
+ params={
+ "state": payload["state"],
+ "page": payload["page"],
+ "per_page": payload["per_page"],
+ "sort": payload["sort"],
+ "direction": payload["direction"],
+ },
)
if response.status_code != 200:
raise ConnectorToolError(f"GitHub returned HTTP {response.status_code} for the pull request list.")
@@ -196,10 +244,100 @@ def _github_list_pull_requests(integration: UserIntegration, payload: dict[str,
"updated_at": pr["updated_at"],
}
for pr in body
- ]
+ ],
+ "page": payload["page"],
+ "per_page": payload["per_page"],
+ "has_next_page": "next" in response.links,
+ "next_page": payload["page"] + 1 if "next" in response.links else None,
}
+def _github_search_pull_requests(integration: UserIntegration, payload: dict[str, Any]) -> dict[str, Any]:
+ client = _github_client(integration)
+ query = [f"repo:{_github_repo_path(client, payload['repository'])}", "is:pr"]
+ if payload["state"] != "all":
+ query.append(f"is:{payload['state']}")
+ author = payload.get("author")
+ if author == "me":
+ author = client.github_login
+ if not author:
+ raise ConnectorToolError(
+ "The connection has no GitHub user identity. Reconnect GitHub or specify an author."
+ )
+ if author:
+ query.append(f"author:{author}")
+ if "draft" in payload:
+ query.append(f"draft:{str(payload['draft']).lower()}")
+ if payload.get("query"):
+ quoted = payload["query"].replace('"', " ")
+ query.append(f'"{quoted}"')
+ response = client.api_request(
+ "GET",
+ "/search/issues",
+ endpoint="/search/issues",
+ params={
+ "q": " ".join(query),
+ "page": payload["page"],
+ "per_page": payload["per_page"],
+ "sort": payload["sort"],
+ "order": payload["direction"],
+ },
+ )
+ if response.status_code != 200:
+ raise ConnectorToolError(f"GitHub returned HTTP {response.status_code} for the pull request search.")
+ body = response.json()
+ if (
+ not isinstance(body, dict)
+ or not isinstance(body.get("items"), list)
+ or not isinstance(body.get("total_count"), int)
+ ):
+ raise ConnectorToolError("GitHub returned an invalid pull request search.")
+ has_next_page = payload["page"] * payload["per_page"] < min(body["total_count"], 1000)
+ 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"),
+ "created_at": pr["created_at"],
+ "updated_at": pr["updated_at"],
+ }
+ for pr in body["items"]
+ ],
+ "page": payload["page"],
+ "per_page": payload["per_page"],
+ "has_next_page": has_next_page,
+ "next_page": payload["page"] + 1 if has_next_page else None,
+ "total_count": body["total_count"],
+ "incomplete_results": body.get("incomplete_results", True),
+ "search_limit_reached": body["total_count"] > 1000,
+ }
+
+
+def _github_read_result(result: dict[str, Any]) -> dict[str, Any]:
+ if result.get("success") is not True:
+ raise ConnectorToolError(result.get("error") or "GitHub could not read the pull request status.")
+ return {key: value for key, value in result.items() if key != "success"}
+
+
+def _github_get_pull_request_snapshot(integration: UserIntegration, payload: dict[str, Any]) -> dict[str, Any]:
+ client = _github_client(integration)
+ repository = _github_repo_path(client, payload["repository"])
+ return _github_read_result(
+ client.get_pull_request_snapshot(f"https://github.com/{repository}/pull/{payload['pr_number']}")
+ )
+
+
+def _github_get_pull_request_checks(integration: UserIntegration, payload: dict[str, Any]) -> dict[str, Any]:
+ client = _github_client(integration)
+ return _github_read_result(
+ client.get_pull_request_checks(_github_repo_path(client, payload["repository"]), payload["pr_number"])
+ )
+
+
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"])
@@ -270,9 +408,50 @@ NATIVE_CONNECTORS: dict[str, NativeConnector] = {
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."
+ "Arguments `{repository, state?, page?, per_page?, sort?, direction?}` → result "
+ "`{pull_requests: [{number, title, url, state, draft, author, head_branch, base_branch, "
+ "created_at, updated_at}], page, per_page, has_next_page, next_page}`. "
+ "Defaults to open, page 1, 100 results, created descending. "
+ "Use search_pull_requests for author filtering; do not filter one repository page locally."
+ ),
+ ),
+ NativeConnectorTool(
+ name="search_pull_requests",
+ summary="Search a repository's pull requests with author filters and pagination.",
+ payload_serializer=GitHubSearchPullRequestsPayloadSerializer,
+ execute=_github_search_pull_requests,
+ usage=(
+ "Arguments `{repository, author?, state?, draft?, query?, page?, per_page?, sort?, direction?}` "
+ "→ result `{pull_requests: [{number, title, url, state, draft, author, created_at, updated_at}], "
+ "page, per_page, has_next_page, next_page, total_count, incomplete_results, search_limit_reached}`. "
+ "Use author: 'me' for the connected user's identity. Defaults to open, page 1, 25 results, "
+ "created descending. Follow next_page with unchanged filters and per_page. "
+ "GitHub search exposes at most 1000 matches; narrow filters when search_limit_reached. "
+ "incomplete_results means GitHub returned a partial search, not response-size truncation."
+ ),
+ ),
+ NativeConnectorTool(
+ name="get_pull_request_snapshot",
+ summary="Read a pull request's CI, review decision, and head commit.",
+ payload_serializer=GitHubPullRequestPayloadSerializer,
+ execute=_github_get_pull_request_snapshot,
+ usage=(
+ "Arguments `{repository, pr_number}` → result `{number, title, url, state, ci_status, "
+ "review_decision, mergeable, head_sha, head_branch, requested_reviewer_logins, "
+ "author_login, unresolved_threads, updated_at}`. Snapshot state can be draft or merged; "
+ "list/search retain open/closed state and a separate draft boolean. "
+ "A null review_decision is unknown, not approved. Keep the PR visible if this read fails."
+ ),
+ ),
+ NativeConnectorTool(
+ name="get_pull_request_checks",
+ summary="Read check runs and external commit statuses for a pull request.",
+ payload_serializer=GitHubPullRequestPayloadSerializer,
+ execute=_github_get_pull_request_checks,
+ usage=(
+ "Arguments `{repository, pr_number}` → result `{checks: [...]}`. "
+ "Combines all pages of check runs and external commit statuses for the current head. "
+ "An empty checks list means no checks; upstream_error means status is unavailable."
),
),
NativeConnectorTool(
@@ -441,30 +620,69 @@ class ConnectorListing:
provider: str
label: str
kind: ConnectorKind
- connected: bool
+ connected: bool | None
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"
+ return _native_field_schema(tool.payload_serializer())
+
+
+def _native_field_schema(field: serializers.Field) -> dict[str, Any]:
+ schema: dict[str, Any]
+ if isinstance(field, serializers.Serializer):
+ schema = {
+ "type": "object",
+ "properties": {name: _native_field_schema(child) for name, child in field.fields.items()},
+ "required": [name for name, child in field.fields.items() if child.required],
+ }
+ elif isinstance(field, (serializers.ListField, serializers.ListSerializer)):
+ assert field.child is not None
+ schema = {"type": "array", "items": _native_field_schema(field.child)}
+ elif isinstance(field, serializers.DictField):
+ schema = {"type": "object", "additionalProperties": _native_field_schema(field.child)}
+ elif isinstance(field, serializers.BooleanField):
+ schema = {"type": "boolean"}
+ elif isinstance(field, serializers.IntegerField):
+ schema = {"type": "integer"}
+ elif isinstance(field, serializers.FloatField):
+ schema = {"type": "number"}
+ elif isinstance(field, serializers.JSONField) or type(field) is serializers.Field:
+ schema = {}
+ else:
+ schema = {"type": "string"}
+ if isinstance(field, serializers.ChoiceField):
+ schema["enum"] = list(field.choices)
+ if all(isinstance(choice, bool) for choice in field.choices):
+ schema["type"] = "boolean"
+ elif all(isinstance(choice, int) for choice in field.choices):
+ schema["type"] = "integer"
+ for attribute, keyword in (
+ ("min_value", "minimum"),
+ ("max_value", "maximum"),
+ ("min_length", "minItems" if schema.get("type") == "array" else "minLength"),
+ ("max_length", "maxItems" if schema.get("type") == "array" else "maxLength"),
+ ):
+ value = getattr(field, attribute, None)
+ if value is not None:
+ schema[keyword] = value
+ if isinstance(field, serializers.CharField) and not field.allow_blank:
+ schema["minLength"] = max(schema.get("minLength", 0), 1)
+ for validator in field.validators:
+ if isinstance(validator, RegexValidator):
+ regex = validator.regex
+ schema["pattern"] = regex if isinstance(regex, str) else regex.pattern
+ if field.allow_null:
+ if "type" in schema:
+ schema["type"] = [schema["type"], "null"]
+ if "enum" in schema:
+ schema["enum"].append(None)
+ if field.default is not serializers.empty and not callable(field.default):
+ schema["default"] = field.default
+ if field.help_text:
+ schema["description"] = str(field.help_text)
+ return schema
def _mcp_tool_listing(tool: McpConnectorTool) -> ConnectorToolListing:
@@ -477,17 +695,13 @@ def _mcp_tool_listing(tool: McpConnectorTool) -> ConnectorToolListing:
)
-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 = [
+def native_connector_listings() -> list[ConnectorListing]:
+ return [
ConnectorListing(
provider=connector.provider,
label=connector.label,
kind=ConnectorKind.NATIVE,
- connected=_viewer_integration(user_id, connector) is not None,
+ connected=None,
connect_path=_PERSONAL_INTEGRATIONS_PATH,
tools=[
ConnectorToolListing(
@@ -502,6 +716,16 @@ def connector_listings(team_id: int, user_id: int, mcp_hosts: list[str] | None =
)
for connector in sorted(NATIVE_CONNECTORS.values(), key=lambda connector: connector.provider)
]
+
+
+def connector_listings(team_id: int, user_id: int, mcp_hosts: list[str] | None = None) -> list[ConnectorListing]:
+ """Native and MCP tools with the viewer's connection state."""
+ if mcp_hosts is None:
+ mcp_hosts = mcp_store_facade.member_server_hosts(team_id, user_id)
+ listings = [
+ replace(listing, connected=_viewer_integration(user_id, NATIVE_CONNECTORS[listing.provider]) is not None)
+ for listing in native_connector_listings()
+ ]
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(
diff --git a/products/canvas/backend/facade/api.py b/products/canvas/backend/facade/api.py
index 259b8a59edee..69d8fc858eab 100644
--- a/products/canvas/backend/facade/api.py
+++ b/products/canvas/backend/facade/api.py
@@ -5,6 +5,7 @@ from products.canvas.backend.connectors import (
canvas_connectors_enabled as canvas_connectors_enabled,
connector_listings as connector_listings,
mcp_provider_host as mcp_provider_host,
+ native_connector_listings as native_connector_listings,
)
from products.canvas.backend.layout import (
CANVAS_LAYOUT_SCHEMA_VERSION as CANVAS_LAYOUT_SCHEMA_VERSION,
diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.py
index 7beec9f3892a..b3af935143dd 100644
--- a/products/canvas/backend/presentation/serializers.py
+++ b/products/canvas/backend/presentation/serializers.py
@@ -1024,7 +1024,10 @@ class CanvasConnectorSerializer(serializers.Serializer):
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.")
+ connected = serializers.BooleanField(
+ allow_null=True,
+ help_text="True when the caller has a usable connection. Null in the static catalog returned to sandbox authors.",
+ )
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.")
diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.py
index 197be6efd574..2bf0acf848c0 100644
--- a/products/canvas/backend/presentation/views.py
+++ b/products/canvas/backend/presentation/views.py
@@ -36,6 +36,7 @@ from products.canvas.backend.facade.api import (
canvas_connectors_enabled,
connector_listings,
default_layout,
+ native_connector_listings,
seed_home_canvas,
subtract_preexisting_diagnostics,
validate_layout,
@@ -1790,7 +1791,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
],
responses={
200: CanvasConnectorsResponseSerializer,
- 403: OpenApiResponse(description="Connectors are not enabled for this team, or the caller is a sandbox."),
+ 403: OpenApiResponse(description="Connectors are not enabled for this team."),
},
)
@action(methods=["GET"], detail=False, url_path="connectors")
@@ -1798,21 +1799,17 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
"""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.
+ matching capabilities.connectors declarations. Sandbox tokens receive
+ only static native tools, with no connection lookup or MCP installation data.
"""
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)
+ listings = native_connector_listings() if user is None else connector_listings(self.team_id, user.id, mcp_hosts)
return Response(CanvasConnectorsResponseSerializer(instance={"connectors": listings}).data)
@extend_schema(
diff --git a/products/canvas/backend/tests/test_connectors.py b/products/canvas/backend/tests/test_connectors.py
index 16583f677d77..be2cd3768bab 100644
--- a/products/canvas/backend/tests/test_connectors.py
+++ b/products/canvas/backend/tests/test_connectors.py
@@ -6,13 +6,19 @@ from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
from parameterized import parameterized
-from rest_framework import status
+from rest_framework import serializers, 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.connectors import (
+ MAX_RESULT_BYTES,
+ NATIVE_CONNECTORS,
+ ConnectorToolError,
+ _bounded,
+ _native_field_schema,
+)
from products.canvas.backend.models import Canvas
from products.canvas.backend.tests.test_canvas_api import CanvasAPIBaseTest
from products.tasks.backend.models import Task
@@ -35,6 +41,7 @@ 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]
+ response.links = {}
return response
@@ -193,7 +200,8 @@ class TestCanvasConnectors(CanvasAPIBaseTest):
)
Canvas.objects.unscoped().filter(id=canvas_id).update(generation_task_id=task.id)
- response = self._sandbox_client(task.id).post(
+ sandbox_client = self._sandbox_client(task.id)
+ response = sandbox_client.post(
f"/api/projects/{self.team.id}/canvases/{canvas_id}/connectors/call/",
{"provider": "github", "tool": "list_pull_requests", "arguments": {"repository": "app"}},
format="json",
@@ -202,6 +210,72 @@ class TestCanvasConnectors(CanvasAPIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
+ self._connect_github()
+ with (
+ patch("products.canvas.backend.connectors._viewer_integration") as lookup,
+ patch("products.canvas.backend.connectors.mcp_store_facade.member_server_hosts") as hosts,
+ patch("products.canvas.backend.connectors.mcp_store_facade.member_server_tools") as tools,
+ ):
+ catalog = sandbox_client.get(
+ f"/api/projects/{self.team.id}/canvases/connectors/?mcp_hosts=mcp.example.com",
+ HTTP_X_POSTHOG_TASK_ID=str(task.id),
+ )
+ assert catalog.status_code == status.HTTP_200_OK, catalog.json()
+ assert [provider["provider"] for provider in catalog.json()["connectors"]] == ["github"]
+ assert catalog.json()["connectors"][0]["connected"] is None
+ assert "search_pull_requests" in [tool["name"] for tool in catalog.json()["connectors"][0]["tools"]]
+ lookup.assert_not_called()
+ hosts.assert_not_called()
+ tools.assert_not_called()
+
+ @patch("products.canvas.backend.connectors.UserGitHubIntegration.api_request")
+ def test_author_me_uses_each_viewers_identity(self, request: MagicMock) -> None:
+ canvas_id = self._connectors_canvas([{"provider": "github", "tools": ["search_pull_requests"]}])
+ request.return_value = _github_response(payload={"items": [], "total_count": 0, "incomplete_results": False})
+ first = self._connect_github()
+ first.config["github_user"] = {"login": "octocat"}
+ first.save()
+ assert (
+ self._call(canvas_id, tool="search_pull_requests", repository="example/app", author="me").json()["status"]
+ == "ok"
+ )
+ assert "author:octocat" in request.call_args.kwargs["params"]["q"]
+
+ other_user = self._create_user("[email protected]")
+ self.client.force_login(other_user)
+ assert (
+ self._call(canvas_id, tool="search_pull_requests", repository="example/app", author="me").json()["status"]
+ == "not_connected"
+ )
+ assert request.call_count == 1
+ UserIntegration.objects.create(
+ user=other_user,
+ kind="github",
+ integration_id="67890",
+ config={"github_user": {"login": "viewer-two"}},
+ )
+ assert (
+ self._call(canvas_id, tool="search_pull_requests", repository="example/app", author="me").json()["status"]
+ == "ok"
+ )
+ assert "author:viewer-two" in request.call_args.kwargs["params"]["q"]
+
+ @patch("products.canvas.backend.connectors.UserGitHubIntegration.get_pull_request_snapshot")
+ @patch("products.canvas.backend.connectors.UserGitHubIntegration.api_request", return_value=_github_response())
+ def test_failed_status_read_does_not_remove_listed_pr(self, request: MagicMock, snapshot: MagicMock) -> None:
+ canvas_id = self._connectors_canvas(
+ [{"provider": "github", "tools": ["list_pull_requests", "get_pull_request_snapshot"]}]
+ )
+ self._connect_github()
+ snapshot.return_value = {"success": False, "error": "Permission denied"}
+ listed = self._call(canvas_id, repository="example/app").json()
+ assert listed["status"] == "ok"
+ assert listed["result"]["pull_requests"][0]["number"] == 7
+ failed = self._call(canvas_id, tool="get_pull_request_snapshot", repository="example/app", pr_number=7).json()
+ assert failed["status"] == "upstream_error"
+ assert failed["result"] is None
+ assert request.call_count == 1
+
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"]}])
@@ -221,8 +295,11 @@ class TestCanvasConnectors(CanvasAPIBaseTest):
assert github["kind"] == "native"
assert [tool["name"] for tool in github["tools"]] == [
"get_file_contents",
+ "get_pull_request_checks",
+ "get_pull_request_snapshot",
"list_pull_requests",
"search_issues",
+ "search_pull_requests",
]
pulls = next(tool for tool in github["tools"] if tool["name"] == "list_pull_requests")
assert pulls["is_read_only"] is True
@@ -301,3 +378,135 @@ class TestConnectorResultBounds(SimpleTestCase):
result, truncated = _bounded({"data": value * MAX_RESULT_BYTES})
assert truncated
assert len(json.dumps(result).encode("utf-8")) <= MAX_RESULT_BYTES
+
+
+class TestGitHubReadTools(SimpleTestCase):
+ def setUp(self) -> None:
+ client_patch = patch("products.canvas.backend.connectors._github_client")
+ self.github = client_patch.start().return_value
+ self.addCleanup(client_patch.stop)
+
+ def execute(self, tool_name: str, **arguments: Any) -> dict[str, Any]:
+ tool = NATIVE_CONNECTORS["github"].tools[tool_name]
+ payload = tool.payload_serializer(data={"repository": "example/app", **arguments})
+ payload.is_valid(raise_exception=True)
+ return tool.execute(MagicMock(), payload.validated_data)
+
+ def test_author_search_filters_upstream_before_pagination(self) -> None:
+ self.github.github_login = "octocat"
+ self.github.api_request.return_value = _github_response(
+ payload={"items": [_GITHUB_PR], "total_count": 3, "incomplete_results": False}
+ )
+ result = self.execute("search_pull_requests", author="me", page=2, per_page=1)
+ assert self.github.api_request.call_args.kwargs["params"] == {
+ "q": "repo:example/app is:pr is:open author:octocat",
+ "page": 2,
+ "per_page": 1,
+ "sort": "created",
+ "order": "desc",
+ }
+ assert self.github.api_request.call_args.args[1] == "/search/issues"
+ assert result["pull_requests"][0]["author"] == "octocat"
+ assert result["next_page"] == 3
+ assert result["has_next_page"] is True
+ assert result["incomplete_results"] is False
+ assert self.github.api_request.call_count == 1
+
+ def test_me_requires_connected_user_identity(self) -> None:
+ self.github.github_login = None
+ with self.assertRaisesMessage(ConnectorToolError, "identity"):
+ self.execute("search_pull_requests", author="me")
+ self.github.api_request.assert_not_called()
+
+ @parameterized.expand([(False, 0, False), (True, 0, False), (False, 1001, True)])
+ def test_search_reports_incomplete_results_and_search_limit(
+ self, incomplete: bool, total: int, limited: bool
+ ) -> None:
+ self.github.api_request.return_value = _github_response(
+ payload={"items": [], "total_count": total, "incomplete_results": incomplete}
+ )
+ result = self.execute("search_pull_requests", page=10, per_page=100)
+ assert result["next_page"] is None
+ assert result["has_next_page"] is False
+ assert result["incomplete_results"] is incomplete
+ assert result["search_limit_reached"] is limited
+
+ def test_list_pagination_preserves_existing_pr_shape(self) -> None:
+ response = _github_response()
+ response.links = {"next": {"url": "https://api.github.com/repos/example/app/pulls?page=3"}}
+ self.github.api_request.return_value = response
+ result = self.execute("list_pull_requests", page=2, per_page=1)
+ assert result["next_page"] == 3
+ assert result["pull_requests"][0]["state"] == "open"
+ assert result["pull_requests"][0]["draft"] is False
+ assert self.github.api_request.call_args.kwargs["params"]["page"] == 2
+
+ @parameterized.expand([("get_pull_request_snapshot",), ("get_pull_request_checks",)])
+ def test_status_helper_failures_are_not_successful_data(self, tool: str) -> None:
+ getattr(self.github, tool).return_value = {"success": False, "error": "Permission denied"}
+ with self.assertRaisesMessage(ConnectorToolError, "Permission denied"):
+ self.execute(tool, pr_number=7)
+
+ def test_snapshot_preserves_unknown_review_and_head_sha(self) -> None:
+ self.github.get_pull_request_snapshot.return_value = {
+ "success": True,
+ "state": "draft",
+ "review_decision": None,
+ "ci_status": "pending",
+ "head_sha": "abc123",
+ }
+ result = self.execute("get_pull_request_snapshot", pr_number=7)
+ assert result["review_decision"] is None
+ assert result["head_sha"] == "abc123"
+ self.github.get_pull_request_snapshot.assert_called_once_with("https://github.com/example/app/pull/7")
+
+ def test_no_checks_is_a_successful_empty_list(self) -> None:
+ self.github.get_pull_request_checks.return_value = {"success": True, "checks": []}
+ assert self.execute("get_pull_request_checks", pr_number=7) == {"checks": []}
+ self.github.get_pull_request_checks.assert_called_once_with("example/app", 7)
+
+ @parameterized.expand(
+ [
+ ({"author": "octocat repo:other/private"},),
+ ({"page": 0},),
+ ({"page": 11, "per_page": 100},),
+ ({"per_page": 101},),
+ ({"state": "invalid"},),
+ ({"repository": "../private"},),
+ ]
+ )
+ def test_search_rejects_unsafe_or_out_of_range_arguments(self, arguments: dict[str, Any]) -> None:
+ with self.assertRaises(serializers.ValidationError):
+ self.execute("search_pull_requests", **arguments)
+ self.github.api_request.assert_not_called()
+
+ def test_search_text_cannot_override_repository_or_pr_filters(self) -> None:
+ self.github.api_request.return_value = _github_response(
+ payload={"items": [], "total_count": 0, "incomplete_results": False}
+ )
+ self.execute("search_pull_requests", query='" is:issue repo:other/private', draft=True, state="all")
+ assert self.github.api_request.call_args.kwargs["params"]["q"] == (
+ 'repo:example/app is:pr draft:true " is:issue repo:other/private"'
+ )
+
+ def test_catalog_schema_describes_nested_fields_and_constraints(self) -> None:
+ class Reference(serializers.Serializer):
+ number = serializers.IntegerField(min_value=1, max_value=100)
+ branch = serializers.RegexField(r"^[a-z]+$", max_length=20, allow_null=True, default=None)
+
+ class Payload(serializers.Serializer):
+ references = Reference(many=True)
+ labels = serializers.ListField(child=serializers.CharField(max_length=10), max_length=5)
+ options = serializers.DictField(child=serializers.BooleanField())
+
+ schema = _native_field_schema(Payload())
+ reference = schema["properties"]["references"]["items"]
+ assert reference["required"] == ["number"]
+ assert reference["properties"]["number"]["minimum"] == 1
+ assert reference["properties"]["number"]["maximum"] == 100
+ assert reference["properties"]["branch"]["type"] == ["string", "null"]
+ assert reference["properties"]["branch"]["default"] is None
+ assert reference["properties"]["branch"]["pattern"] == "^[a-z]+$"
+ assert schema["properties"]["labels"]["maxItems"] == 5
+ assert schema["properties"]["labels"]["items"]["maxLength"] == 10
+ assert schema["properties"]["options"]["additionalProperties"]["type"] == "boolean"
diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.ts
index 896bcda85f8d..5bc210d61043 100644
--- a/products/canvas/frontend/generated/api.schemas.ts
+++ b/products/canvas/frontend/generated/api.schemas.ts
@@ -1546,8 +1546,11 @@ export interface CanvasConnectorApi {
* * `native` - Native
* * `mcp` - Mcp */
kind: ConnectorKindEnumApi
- /** True when the caller has a usable connection to this provider. */
- connected: boolean
+ /**
+ * True when the caller has a usable connection. Null in the static catalog returned to sandbox authors.
+ * @nullable
+ */
+ connected: boolean | null
/** In-app path where the caller connects this provider. */
connect_path: string
/** Tools the caller's connection exposes, sorted by name. */
diff --git a/products/canvas/frontend/generated/api.ts b/products/canvas/frontend/generated/api.ts
index 95396f745c83..5090a76dbad7 100644
--- a/products/canvas/frontend/generated/api.ts
+++ b/products/canvas/frontend/generated/api.ts
@@ -802,7 +802,8 @@ export const getCanvasesConnectorsRetrieveUrl = (projectId: string, params?: Can
* 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.
+ * matching capabilities.connectors declarations. Sandbox tokens receive
+ * only static native tools, with no connection lookup or MCP installation data.
*/
export const canvasesConnectorsRetrieve = async (
projectId: string,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ed0b2692f204..15ba82f33371 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16275,8 +16275,11 @@ export namespace Schemas {
* * `native` - Native
* * `mcp` - Mcp */
kind: ConnectorKindEnum;
- /** True when the caller has a usable connection to this provider. */
- connected: boolean;
+ /**
+ * True when the caller has a usable connection. Null in the static catalog returned to sandbox authors.
+ * @nullable
+ */
+ connected: boolean | null;
/** In-app path where the caller connects this provider. */
connect_path: string;
/** Tools the caller's connection exposes, sorted by name. */
diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.ts
index 871b5d6239c7..47e16086b26d 100644
--- a/services/mcp/src/generated/canvas/api.ts
+++ b/services/mcp/src/generated/canvas/api.ts
@@ -1505,7 +1505,8 @@ export const CanvasesValidateCreateBody = () => zod
* 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.
+ * matching capabilities.connectors declarations. Sandbox tokens receive
+ * only static native tools, with no connection lookup or MCP installation data.
*/
export const CanvasesConnectorsRetrieveParams = () => zod.object({
project_id: zod