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(signals): serve a read-only MCP tool catalogue for scouts (#106650)

posthog[bot]421700df6199
diff --git a/posthog/api/oauth/mcp_resource_scopes.py b/posthog/api/oauth/mcp_resource_scopes.py
index 487c8b65def4..3f2cf7be4e34 100644
--- a/posthog/api/oauth/mcp_resource_scopes.py
+++ b/posthog/api/oauth/mcp_resource_scopes.py
@@ -1,31 +1,16 @@
from __future__ import annotations
-import os
-import json
-from functools import lru_cache
from typing import TypedDict
from urllib.parse import urlparse
import structlog
from posthog.cloud_utils import is_dev_mode
+from posthog.mcp_tool_definitions import mcp_tool_required_scopes
from posthog.scopes import get_oauth_scopes_supported
-from posthog.settings.base_variables import BASE_DIR
logger = structlog.get_logger(__name__)
-# The MCP server builds its RFC 9728 `scopes_supported` from these same committed
-# artifacts (services/mcp/src/tools/toolDefinitions.ts merges both). Deriving the
-# consent list from them here keeps the authorization server's promise sourced from
-# its own state instead of a runtime fetch to the resource server. Both files are
-# needed: hand-written tools (e.g. read-data-schema) live in tool-definitions.json
-# and are the only users of some scopes, so reading the generated file alone drops
-# their scopes from the consent default.
-_TOOL_DEFINITIONS_PATHS = (
- os.path.join(BASE_DIR, "services", "mcp", "schema", "tool-definitions.json"),
- os.path.join(BASE_DIR, "services", "mcp", "schema", "generated-tool-definitions.json"),
-)
-
# Keep in sync with services/mcp/src/lib/routing.ts regional MCP hostnames.
PRODUCTION_MCP_HOSTS = frozenset(
{
@@ -62,28 +47,17 @@ def is_trusted_posthog_mcp_resource(resource_url: str) -> bool:
return False
-@lru_cache(maxsize=1)
-def _tool_required_scopes() -> frozenset[str]:
- # Keyed merge, later files winning — same precedence as the MCP server's
- # getToolDefinitions() ({ ...handwritten, ...generated }), so a hand-written
- # tool overridden by a generated one doesn't leak its scopes into consent.
- merged: dict[str, dict] = {}
- for path in _TOOL_DEFINITIONS_PATHS:
- with open(path) as definitions_file:
- merged.update(json.load(definitions_file))
-
- return frozenset(scope for definition in merged.values() for scope in (definition.get("required_scopes") or []))
-
-
def mcp_advertised_scopes() -> list[str]:
"""The scopes an MCP client gets when it omits `scope` on `/oauth/authorize`.
Mirrors the MCP server's `getAdvertisedOAuthScopes()`: every identity scope
(no `:`) plus the resource scopes some tool actually requires, both drawn from
the authorization server's own supported set so nothing advertised is later
- rejected at `/authorize`.
+ rejected at `/authorize`. Both sides read the same committed definition files, so
+ the authorization server's promise stays sourced from its own state instead of a
+ runtime fetch to the resource server.
"""
- required = _tool_required_scopes()
+ required = mcp_tool_required_scopes()
return [scope for scope in get_oauth_scopes_supported() if ":" not in scope or scope in required]
diff --git a/posthog/api/oauth/test_mcp_resource_scopes.py b/posthog/api/oauth/test_mcp_resource_scopes.py
index 1430eec0fa3f..55a75f117014 100644
--- a/posthog/api/oauth/test_mcp_resource_scopes.py
+++ b/posthog/api/oauth/test_mcp_resource_scopes.py
@@ -1,17 +1,13 @@
-import os
-import json
-import tempfile
-
from unittest.mock import patch
from django.test import SimpleTestCase, override_settings
from posthog.api.oauth.mcp_resource_scopes import (
- _tool_required_scopes,
build_oauth_mcp_consent_context,
is_trusted_posthog_mcp_resource,
mcp_advertised_scopes,
)
+from posthog.mcp_tool_definitions import mcp_tool_required_scopes
class TestMcpResourceScopes(SimpleTestCase):
@@ -42,7 +38,7 @@ class TestMcpResourceScopes(SimpleTestCase):
return_value=["openid", "profile", "notebook:read", "notebook:write", "webhook:write"],
)
@patch(
- "posthog.api.oauth.mcp_resource_scopes._tool_required_scopes",
+ "posthog.api.oauth.mcp_resource_scopes.mcp_tool_required_scopes",
return_value=frozenset({"notebook:read", "notebook:write"}),
)
def test_advertised_scopes_keeps_identity_and_tool_required_only(self, _mock_required, _mock_supported):
@@ -57,7 +53,7 @@ class TestMcpResourceScopes(SimpleTestCase):
# Guards the cross-service artifact paths and shape: if the files under
# services/mcp/schema/ move or change structure, this fails loudly
# instead of silently advertising nothing.
- _tool_required_scopes.cache_clear()
+ mcp_tool_required_scopes.cache_clear()
scopes = mcp_advertised_scopes()
self.assertIn("openid", scopes)
self.assertIn("notebook:read", scopes)
@@ -68,29 +64,6 @@ class TestMcpResourceScopes(SimpleTestCase):
self.assertIn("property_definition:read", scopes)
self.assertGreater(len(scopes), 50)
- def test_tool_required_scopes_merges_by_tool_name_with_generated_winning(self):
- # A hand-written tool overridden by a generated one must not leak its
- # scopes: the MCP server's getToolDefinitions() keyed merge drops the
- # overridden definition, so a per-file scope union would advertise
- # consent scopes no active tool requires.
- with tempfile.TemporaryDirectory() as tmp_dir:
- handwritten = os.path.join(tmp_dir, "handwritten.json")
- generated = os.path.join(tmp_dir, "generated.json")
- with open(handwritten, "w") as f:
- json.dump({"tool": {"required_scopes": ["overridden:read"]}}, f)
- with open(generated, "w") as f:
- json.dump({"tool": {"required_scopes": ["active:read"]}}, f)
-
- with patch(
- "posthog.api.oauth.mcp_resource_scopes._TOOL_DEFINITIONS_PATHS",
- (handwritten, generated),
- ):
- _tool_required_scopes.cache_clear()
- try:
- self.assertEqual(_tool_required_scopes(), frozenset({"active:read"}))
- finally:
- _tool_required_scopes.cache_clear()
-
def test_build_oauth_mcp_consent_context_success(self):
context = build_oauth_mcp_consent_context("https://mcp.posthog.com/mcp")
diff --git a/posthog/mcp_tool_definitions.py b/posthog/mcp_tool_definitions.py
new file mode 100644
index 000000000000..330eb0f24dfb
--- /dev/null
+++ b/posthog/mcp_tool_definitions.py
@@ -0,0 +1,110 @@
+"""Read the committed MCP tool catalogue.
+
+`services/mcp/schema/` holds the tool definitions the MCP server advertises: the
+hand-written tools in `tool-definitions.json` and the code-generated ones in
+`generated-tool-definitions.json`. Both files ship in this repository, so any Django
+process can answer what tools exist without a runtime call to the resource server.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Mapping
+from functools import lru_cache
+from pathlib import Path
+from types import MappingProxyType
+from typing import Any, Literal
+
+from posthog.dataclasses import frozen
+from posthog.settings.base_variables import BASE_DIR
+
+_SCHEMA_DIR = Path(BASE_DIR) / "services" / "mcp" / "schema"
+
+# Hand-written first, generated second, so the generated definition wins on the seven names
+# both files hold. This is the precedence `getToolDefinitions()` in
+# services/mcp/src/tools/toolDefinitions.ts merges with, and a catalogue built the other way
+# round would describe a tool the server does not serve. Both files are needed: some tools
+# exist only as hand-written ones (for example read-data-schema), and they are the only users
+# of some scopes.
+_TOOL_DEFINITION_PATHS = (
+ _SCHEMA_DIR / "tool-definitions.json",
+ _SCHEMA_DIR / "generated-tool-definitions.json",
+)
+
+FeatureFlagBehavior = Literal["enable", "disable"]
+
+
+@frozen
+class McpToolDefinition:
+ """One entry of the MCP tool catalogue.
+
+ The fields mirror `ToolDefinitionSchema` in services/mcp/src/tools/toolDefinitions.ts.
+ `description` runs to several kilobytes on the query tools, so a caller that lists the
+ whole catalogue reads `summary` instead.
+ """
+
+ name: str
+ title: str
+ summary: str
+ description: str
+ category: str
+ feature: str
+ required_scopes: tuple[str, ...]
+ read_only: bool
+ requires_ai_consent: bool
+ # The flag gate, exactly as services/mcp/src/tools/toolDefinitions.ts reads it. The gate
+ # resolves per project, so a caller that needs the served catalogue for one project
+ # evaluates these itself.
+ feature_flag: str | None
+ feature_flag_behavior: FeatureFlagBehavior | None
+ feature_flag_variant: str | None
+ hidden_when_flag_on: str | None
+ # Names that took over this tool's job. A superseded tool is on its way out, so a surface
+ # that offers a choice of tools offers its successors instead.
+ superseded_by: tuple[str, ...]
+ feature_entitlement: str | None
+
+ @property
+ def is_superseded(self) -> bool:
+ return bool(self.superseded_by)
+
+
+def _definition_from_json(name: str, raw: Mapping[str, Any]) -> McpToolDefinition:
+ return McpToolDefinition(
+ name=name,
+ title=raw["title"],
+ summary=raw["summary"],
+ description=raw["description"],
+ category=raw["category"],
+ feature=raw["feature"],
+ required_scopes=tuple(raw.get("required_scopes") or ()),
+ read_only=bool(raw["annotations"]["readOnlyHint"]),
+ requires_ai_consent=bool(raw.get("requires_ai_consent", False)),
+ feature_flag=raw.get("feature_flag"),
+ feature_flag_behavior=raw.get("feature_flag_behavior"),
+ feature_flag_variant=raw.get("feature_flag_variant"),
+ hidden_when_flag_on=raw.get("hidden_when_flag_on"),
+ superseded_by=tuple(raw.get("superseded_by") or ()),
+ feature_entitlement=raw.get("feature_entitlement"),
+ )
+
+
+@lru_cache(maxsize=1)
+def get_mcp_tool_definitions() -> Mapping[str, McpToolDefinition]:
+ """Every catalogued MCP tool, keyed by tool name.
+
+ The files are committed artifacts, so the result is read once per process.
+ """
+ merged: dict[str, Any] = {}
+ for path in _TOOL_DEFINITION_PATHS:
+ merged.update(json.loads(path.read_text()))
+
+ return MappingProxyType({name: _definition_from_json(name, raw) for name, raw in merged.items()})
+
+
+@lru_cache(maxsize=1)
+def mcp_tool_required_scopes() -> frozenset[str]:
+ """Every scope some catalogued tool requires."""
+ return frozenset(
+ scope for definition in get_mcp_tool_definitions().values() for scope in definition.required_scopes
+ )
diff --git a/posthog/test/test_mcp_tool_definitions.py b/posthog/test/test_mcp_tool_definitions.py
new file mode 100644
index 000000000000..6175b0cc523c
--- /dev/null
+++ b/posthog/test/test_mcp_tool_definitions.py
@@ -0,0 +1,83 @@
+import json
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from unittest.mock import patch
+
+from django.conf import settings
+from django.test import SimpleTestCase
+
+from posthog.mcp_tool_definitions import get_mcp_tool_definitions, mcp_tool_required_scopes
+
+_SCHEMA_DIR = Path(settings.BASE_DIR) / "services" / "mcp" / "schema"
+
+
+def _raw(file_name: str) -> dict:
+ return json.loads((_SCHEMA_DIR / file_name).read_text())
+
+
+def _definition(**overrides) -> dict:
+ return {
+ "title": "Tool",
+ "summary": "A tool.",
+ "description": "A tool.",
+ "category": "Testing",
+ "feature": "testing",
+ "required_scopes": [],
+ "annotations": {
+ "destructiveHint": False,
+ "idempotentHint": True,
+ "openWorldHint": False,
+ "readOnlyHint": True,
+ },
+ **overrides,
+ }
+
+
+class TestMcpToolDefinitions(SimpleTestCase):
+ def setUp(self) -> None:
+ get_mcp_tool_definitions.cache_clear()
+ mcp_tool_required_scopes.cache_clear()
+ self.addCleanup(get_mcp_tool_definitions.cache_clear)
+ self.addCleanup(mcp_tool_required_scopes.cache_clear)
+
+ def test_merges_by_tool_name_with_the_generated_definition_winning(self) -> None:
+ # The MCP server's getToolDefinitions() keyed merge drops the overridden definition, so a
+ # catalogue built the other way round describes a tool the server does not serve, and
+ # advertises consent scopes no active tool requires.
+ with TemporaryDirectory() as tmp_dir:
+ handwritten = Path(tmp_dir) / "handwritten.json"
+ generated = Path(tmp_dir) / "generated.json"
+ handwritten.write_text(
+ json.dumps(
+ {
+ "shared": _definition(summary="Overridden.", required_scopes=["overridden:read"]),
+ "hand-written-only": _definition(required_scopes=["hand_written:read"]),
+ }
+ )
+ )
+ generated.write_text(
+ json.dumps({"shared": _definition(summary="Active.", required_scopes=["active:read"])})
+ )
+
+ with patch("posthog.mcp_tool_definitions._TOOL_DEFINITION_PATHS", (handwritten, generated)):
+ definitions = get_mcp_tool_definitions()
+
+ assert definitions["shared"].summary == "Active."
+ assert definitions["shared"].required_scopes == ("active:read",)
+ assert definitions["hand-written-only"].required_scopes == ("hand_written:read",)
+ assert mcp_tool_required_scopes() == frozenset({"active:read", "hand_written:read"})
+
+ def test_reads_the_real_committed_catalog(self) -> None:
+ # Guards the cross-service artifact paths and shape: if the files under
+ # services/mcp/schema/ move or change structure, this fails loudly instead of leaving
+ # every caller with an empty catalogue.
+ handwritten = _raw("tool-definitions.json")
+ generated = _raw("generated-tool-definitions.json")
+
+ definitions = get_mcp_tool_definitions()
+
+ assert set(handwritten) | set(generated) == set(definitions)
+ # A hand-written tool, absent if the loader reads only the generated file.
+ assert definitions["read-data-schema"].required_scopes
+ assert all(definition.title and definition.summary for definition in definitions.values())
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 51512685dbeb..3cffce110448 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -8,6 +8,12 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
## What lives here
+- `tool_catalogue.py`
+ Builds the scout tool catalogue from the committed MCP definitions through `posthog/mcp_tool_definitions.py`.
+ The read-only endpoint is `GET /api/projects/:id/signals/scout/configs/tool_catalogue/` in `views.py`.
+ It omits superseded tools and reports scope requirements and feature conditions.
+ Callers must evaluate feature flags for the project.
+
- `runner.py`
Per-run entrypoint (`arun_signals_scout` / `run_signals_scout`). Inserts the `SignalScoutRun` row, builds the prompt + toolset, spawns the sandbox session, pumps the agent loop until budget exhaustion or natural completion, finalizes the run, and returns a `RunResult`. The activity wrapper in `temporal/agentic/scout_scheduler.py` delegates straight to this.
The run's scope posture is composed here (`scout_scope_posture` in `posthog/temporal/oauth.py`): the fleet-wide scout preset plus the write scopes this one scout was granted on `SignalScoutConfig.write_scopes`, intersected against `SCOUT_GRANTABLE_WRITE_SCOPES` here and again at mint time, and withheld entirely on a dry run (`emit=False`) so a preview never mutates the project, and again when the acting user came from the team-level fallback (`resolve_acting_user_id_for_team`), since that member never approved the grant. The column value is handed to the posture builder unshaped, because coercing a stray JSON object with `list()` would turn its keys into a grant. The grant is stamped on the run row's `metadata["write_scopes"]` and on both lifecycle events, because the config can be widened or revoked afterwards and would otherwise rewrite what past runs could reach; the prompt's `# Write access` section is rendered from the same resolved value, so it can never name an object the token was refused. Who may set the grant is decided in `views.py` (`assert_can_grant_scout_write_scopes`): the scout's resolved acting user (`skill_loader.resolve_scout_acting_user_id`) or a project admin, never `LLMSkillOwner`, since any skill editor can rewrite that list; a scoped credential must also carry each scope it adds.
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index d2462c8798ad..f0feb1a916ea 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -4023,6 +4023,132 @@ class ScoutMetadataSerializer(serializers.Serializer):
limits = ScoutLimitsSerializer(help_text="The team's enforced scout run caps and current usage.")
+# --- Tool catalogue ---------------------------------------------------------
+
+
+class ScoutToolCatalogueEntrySerializer(serializers.Serializer):
+ """One MCP tool, with what a scout would need to call it."""
+
+ name = serializers.CharField(
+ source="definition.name",
+ help_text="The tool's permanent identifier, for example `insight-get`. This is the name a scout calls.",
+ )
+ title = serializers.CharField(
+ source="definition.title", help_text="The label people read, for example `Get insight`."
+ )
+ summary = serializers.CharField(
+ source="definition.summary",
+ help_text=(
+ "One line on what the tool does. The tool's full description runs to several kilobytes on some "
+ "tools, so it is not part of this listing."
+ ),
+ )
+ category = serializers.CharField(
+ source="definition.category",
+ help_text="The product area the tool belongs to, for example `Error tracking`. Use it to group the listing.",
+ )
+ feature = serializers.CharField(
+ source="definition.feature",
+ help_text="The feature key the MCP server filters on, for example `error_tracking`. Narrower than `category`.",
+ )
+ required_scopes = serializers.ListField(
+ source="definition.required_scopes",
+ child=serializers.CharField(),
+ help_text="The API scopes a token must carry to call the tool. Empty for a tool that needs none.",
+ )
+ # Not `read_only`: that name is a DRF `Field` attribute, so a field declared under it
+ # shadows the base class and fails the typecheck.
+ is_read_only = serializers.BooleanField(
+ source="definition.read_only",
+ help_text="True when the tool only reads. A false value means the tool can change the project's data.",
+ )
+ requires_ai_consent = serializers.BooleanField(
+ source="definition.requires_ai_consent",
+ help_text="True when the tool is hidden until the project consents to AI features.",
+ )
+ holdable = serializers.BooleanField(
+ help_text=(
+ "True when a scout run can hold every scope the tool requires. A false value means no scout "
+ "reaches the tool, whatever it is granted, so it cannot be configured for one."
+ )
+ )
+ missing_scopes = serializers.ListField(
+ child=serializers.CharField(),
+ help_text=(
+ "Required scopes the baseline `signals_scout` preset does not carry. On a holdable tool these "
+ "are what the scout has to be granted, or the preset it has to opt into. On a tool that is not "
+ "holdable they include every scope no scout can reach, and can also include scopes a person can "
+ "grant. Compare them with `grantable_write_scopes` and `presets` to tell the two apart."
+ ),
+ )
+ feature_flag = serializers.CharField(
+ source="definition.feature_flag",
+ allow_null=True,
+ help_text=(
+ "Feature flag key that gates the tool, or null when the tool is always served. The flag resolves "
+ "per project, so evaluate it for the project you are configuring before you offer the tool."
+ ),
+ )
+ feature_flag_behavior = serializers.CharField(
+ source="definition.feature_flag_behavior",
+ allow_null=True,
+ help_text=(
+ "How `feature_flag` gates the tool: `enable` (served only while the flag is on) or `disable` "
+ "(served only while the flag is off). Null means the default, `enable`."
+ ),
+ )
+ feature_flag_variant = serializers.CharField(
+ source="definition.feature_flag_variant",
+ allow_null=True,
+ help_text="Variant of `feature_flag` the tool needs, or null when any truthy value serves it.",
+ )
+ hidden_when_flag_on = serializers.CharField(
+ source="definition.hidden_when_flag_on",
+ allow_null=True,
+ help_text="A second flag key that hides the tool while it is on, independent of `feature_flag`. Usually null.",
+ )
+ feature_entitlement = serializers.CharField(
+ source="definition.feature_entitlement",
+ allow_null=True,
+ help_text="Plan feature the organization must have for the tool to be served, or null when the tool is free.",
+ )
+
+
+class ScoutScopePresetSerializer(serializers.Serializer):
+ """A scope preset a scout run can be dispatched with."""
+
+ name = serializers.CharField(
+ help_text=(
+ "The preset's name. `signals_scout` is what every scout holds; `signals_scout_reports` adds the "
+ "report channel and is used only by a scout whose skill opted into it."
+ )
+ )
+ scopes = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Every scope a token minted from this preset carries, including the internal ones.",
+ )
+
+
+class ScoutToolCatalogueSerializer(serializers.Serializer):
+ """The MCP tool catalogue, with the scout scope postures to read it against."""
+
+ tools = ScoutToolCatalogueEntrySerializer(
+ many=True,
+ help_text=("Every catalogued MCP tool, ordered by name. Tools that a successor has replaced are left out."),
+ )
+ presets = ScoutScopePresetSerializer(
+ many=True,
+ help_text="The scope presets a scout run can be dispatched with, and the scopes each one resolves to.",
+ )
+ grantable_write_scopes = serializers.ListField(
+ child=serializers.CharField(),
+ help_text=(
+ "The write scopes a person can grant to one scout from its settings. A scope outside this set "
+ "can never be added to a scout's token."
+ ),
+ )
+
+
# --- Members (reviewer routing) --------------------------------------------
diff --git a/products/signals/backend/scout_harness/tool_catalogue.py b/products/signals/backend/scout_harness/tool_catalogue.py
new file mode 100644
index 000000000000..518d93b91f14
--- /dev/null
+++ b/products/signals/backend/scout_harness/tool_catalogue.py
@@ -0,0 +1,95 @@
+"""The MCP tool catalogue as a scout sees it.
+
+A scout run holds an OAuth token minted from a scope preset in `posthog/temporal/oauth.py`,
+so the tools it can call are the catalogued tools whose required scopes that token carries.
+This module answers that question for every tool, which is what a per-scout tool picker needs
+before any of it can be configured.
+"""
+
+from __future__ import annotations
+
+from functools import lru_cache
+
+from posthog.dataclasses import frozen
+from posthog.mcp_tool_definitions import McpToolDefinition, get_mcp_tool_definitions
+from posthog.temporal.oauth import (
+ SCOUT_GRANTABLE_WRITE_SCOPES,
+ SCOUT_SCOPE_PRESETS,
+ ScoutScopePreset,
+ resolve_scopes,
+ scout_scope_posture,
+)
+
+
+@frozen
+class ScoutToolEntry:
+ definition: McpToolDefinition
+ # The widest posture a scout run can be dispatched with satisfies every required scope.
+ holdable: bool
+ # Required scopes the baseline `signals_scout` posture does not carry. On a holdable tool
+ # these name what the scout has to be granted, or which preset it has to opt into. On a
+ # tool that is not holdable they include every scope no scout can reach, next to any
+ # grantable ones.
+ missing_scopes: tuple[str, ...]
+
+
+@frozen
+class ScoutScopePresetEntry:
+ name: ScoutScopePreset
+ scopes: tuple[str, ...]
+
+
+@frozen
+class ScoutToolCatalogue:
+ tools: tuple[ScoutToolEntry, ...]
+ presets: tuple[ScoutScopePresetEntry, ...]
+ grantable_write_scopes: tuple[str, ...]
+
+
+def _preset_scopes(preset: ScoutScopePreset, *, extra_write_scopes: list[str] | None = None) -> frozenset[str]:
+ return frozenset(resolve_scopes(scout_scope_posture(preset, extra_write_scopes or [])))
+
+
+def _satisfies(scopes: frozenset[str], required_scope: str) -> bool:
+ # A write scope also satisfies the read scope on the same object, in the MCP server
+ # (`hasScope` in services/mcp/src/lib/api.ts) and in `posthog/permissions.py`. Scout tokens
+ # carry `signal_scout_internal:write` and never its read scope, so plain set membership
+ # would report tools a scout calls as out of reach.
+ if required_scope in scopes:
+ return True
+ return required_scope.endswith(":read") and f"{required_scope.removesuffix(':read')}:write" in scopes
+
+
+@lru_cache(maxsize=1)
+def get_scout_tool_catalogue() -> ScoutToolCatalogue:
+ """The catalogue every scout is measured against.
+
+ Derived from committed definition files and from the scope sets in
+ `posthog/temporal/oauth.py`, so it is the same for every project and is built once per
+ process. A superseded tool is left out: its definition names the successors that replaced
+ it, and a picker that offered it would configure a scout for a tool on its way out.
+ """
+ baseline = _preset_scopes("signals_scout")
+ widest = _preset_scopes("signals_scout_reports", extra_write_scopes=sorted(SCOUT_GRANTABLE_WRITE_SCOPES))
+
+ tools = []
+ for definition in get_mcp_tool_definitions().values():
+ if definition.is_superseded:
+ continue
+ required = set(definition.required_scopes)
+ tools.append(
+ ScoutToolEntry(
+ definition=definition,
+ holdable=all(_satisfies(widest, scope) for scope in required),
+ missing_scopes=tuple(sorted(scope for scope in required if not _satisfies(baseline, scope))),
+ )
+ )
+
+ return ScoutToolCatalogue(
+ tools=tuple(sorted(tools, key=lambda entry: entry.definition.name)),
+ presets=tuple(
+ ScoutScopePresetEntry(name=preset, scopes=tuple(sorted(_preset_scopes(preset))))
+ for preset in SCOUT_SCOPE_PRESETS
+ ),
+ grantable_write_scopes=tuple(sorted(SCOUT_GRANTABLE_WRITE_SCOPES)),
+ )
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 7f3223b02bbd..aa91f998b790 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -24,6 +24,7 @@ import dataclasses
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime
+from functools import lru_cache
from typing import Any, cast
from django.db import transaction
@@ -133,6 +134,7 @@ from products.signals.backend.scout_harness.serializers import (
ScoutOrigin,
ScoutRunIdsBatchRequestSerializer,
ScoutRunTokenCostsSerializer,
+ ScoutToolCatalogueSerializer,
ScratchpadEntrySerializer,
SearchMemoryQuerySerializer,
SearchRecentRunsQuerySerializer,
@@ -161,6 +163,7 @@ from products.signals.backend.scout_harness.team_limits import (
resolve_team_metadata,
withheld_skills_for_team,
)
+from products.signals.backend.scout_harness.tool_catalogue import get_scout_tool_catalogue
from products.signals.backend.scout_harness.tools.checks import (
InvalidCheckResultError,
InvalidCheckWriteError,
@@ -3017,6 +3020,16 @@ class SignalScoutViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
+@lru_cache(maxsize=1)
+def _scout_tool_catalogue_payload() -> dict[str, Any]:
+ """The rendered tool catalogue.
+
+ The catalogue is built from committed files and code constants, so it is identical for every
+ project and every caller. Rendering a thousand tools on each request would be pure waste.
+ """
+ return dict(ScoutToolCatalogueSerializer(get_scout_tool_catalogue()).data)
+
+
class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Per-scout config: list, register, tune, and delete each scout's schedule, enablement,
and emit posture.
@@ -3514,3 +3527,36 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
context = scout_config_context(team, [c.skill_name for c in configs], request)
return Response(SignalScoutConfigSerializer(configs, many=True, context=context).data)
+
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(
+ response=ScoutToolCatalogueSerializer,
+ description="Every catalogued MCP tool, with the scout scope postures to read it against.",
+ ),
+ },
+ summary="List the MCP tool catalogue",
+ description=(
+ "List every MCP tool a scout could be configured with. Each entry carries the tool's name, "
+ "label, one-line summary, category, and required scopes, plus `holdable`: whether a scout run "
+ "can hold every scope the tool needs, and `missing_scopes`: what it would have to be granted "
+ "on top of the baseline preset. The response also returns the scout scope presets and the "
+ "write scopes a person can grant to one scout, so a caller can show why a tool is out of "
+ "reach. Tools a successor has replaced are left out. A tool can carry a `feature_flag`, which "
+ "resolves per project: evaluate it for the project you are configuring before you offer the "
+ "tool. Read-only, and the same for every project."
+ ),
+ operation_id="signals_scout_config_tool_catalogue",
+ )
+ @action(
+ detail=False,
+ methods=["get"],
+ url_path="tool_catalogue",
+ url_name="tool-catalogue",
+ pagination_class=None,
+ # Custom actions need explicit scopes, as the `sync` action above notes. This one reads
+ # committed definition files and constants, so it uses the public read scope.
+ required_scopes=["signal_scout:read"],
+ )
+ def tool_catalogue(self, request: Request, *args, **kwargs) -> Response:
+ return Response(_scout_tool_catalogue_payload())
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index fcb3ccbafc40..eaeb2b852b1d 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -21,6 +21,7 @@ from social_django.models import UserSocialAuth
from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.egress.browserless.transport import BrowserlessEgressBudgetExhausted
+from posthog.mcp_tool_definitions import get_mcp_tool_definitions
from posthog.models import OAuthApplication
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.integration import Integration
@@ -31,6 +32,8 @@ from posthog.temporal.oauth import (
ARRAY_APP_CLIENT_ID_DEV,
ARRAY_APP_CLIENT_ID_EU,
ARRAY_APP_CLIENT_ID_US,
+ SCOUT_GRANTABLE_WRITE_SCOPES,
+ SCOUT_SCOPE_PRESETS,
PosthogMcpScopes,
create_oauth_access_token_for_user,
)
@@ -4117,6 +4120,64 @@ class TestScoutHarnessConfigAPI(APIBaseTest):
_METADATA_PAYLOAD_PATH = "products.signals.backend.scout_harness.team_limits.posthoganalytics.get_feature_flag_payload"
+class TestScoutHarnessToolCatalogueAPI(APIBaseTest):
+ """The read-only MCP tool catalogue a per-scout tool picker is built on."""
+
+ def _url(self) -> str:
+ return f"/api/projects/{self.team.id}/signals/scout/configs/tool_catalogue/"
+
+ def _tools(self) -> dict[str, dict]:
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return {tool["name"]: tool for tool in response.json()["tools"]}
+
+ def test_returns_the_catalogue_with_the_scout_scope_postures(self) -> None:
+ body = self.client.get(self._url()).json()
+
+ assert len(body["tools"]) > 500
+ assert [preset["name"] for preset in body["presets"]] == list(SCOUT_SCOPE_PRESETS)
+ assert set(body["grantable_write_scopes"]) == set(SCOUT_GRANTABLE_WRITE_SCOPES)
+
+ def test_leaves_out_the_tools_a_successor_replaced(self) -> None:
+ # A picker that offered a superseded tool would configure a scout for a tool on its way out.
+ superseded = {name for name, definition in get_mcp_tool_definitions().items() if definition.is_superseded}
+ assert superseded, "expected the catalogue to hold at least one superseded tool"
+
+ assert not superseded & set(self._tools())
+
+ def test_reports_what_a_scout_would_have_to_be_granted(self) -> None:
+ # `holdable` has to be measured against the scout postures, not against the full MCP scope
+ # set: a picker built on the wrong set offers tools a scout is refused for at call time.
+ tools = self._tools()
+
+ # Read scopes ride every scout token.
+ assert tools["insight-get"]["holdable"] is True
+ assert tools["insight-get"]["missing_scopes"] == []
+ # Scout tokens carry `signal_scout_internal:write` only, and a write scope satisfies its read scope.
+ assert tools["scout-members-list"]["holdable"] is True
+ assert tools["scout-members-list"]["missing_scopes"] == []
+ # Grantable from the scout's own settings, so it is reachable but not by default.
+ assert tools["dashboard-create"]["holdable"] is True
+ assert tools["dashboard-create"]["missing_scopes"] == ["dashboard:write"]
+ # Flag writes change what end users see, so no scout grant can ever cover them.
+ assert tools["create-feature-flag"]["holdable"] is False
+ assert tools["create-feature-flag"]["missing_scopes"] == ["feature_flag:write"]
+
+ def test_read_scope_is_enough_to_read_the_catalogue(self) -> None:
+ from posthog.models.personal_api_key import PersonalAPIKey
+ from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="k", user=self.user, secure_value=hash_key_value(raw), scopes=["signal_scout:read"]
+ )
+ self.client.logout()
+
+ response = self.client.get(self._url(), HTTP_AUTHORIZATION=f"Bearer {raw}")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+
class TestScoutHarnessMetadataAPI(APIBaseTest):
"""Scout metadata endpoint: enrollment, the alpha banner, and the enforced run limits, all
resolved from the `signals-scout` flag payload so the UI shows the throttle dispatch applies."""
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index dfc1d045df79..d3b64d6832ad 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -3682,6 +3682,79 @@ export interface SignalScoutManualRunApi {
started: boolean
}
+/**
+ * One MCP tool, with what a scout would need to call it.
+ */
+export interface ScoutToolCatalogueEntryApi {
+ /** The tool's permanent identifier, for example `insight-get`. This is the name a scout calls. */
+ name: string
+ /** The label people read, for example `Get insight`. */
+ title: string
+ /** One line on what the tool does. The tool's full description runs to several kilobytes on some tools, so it is not part of this listing. */
+ summary: string
+ /** The product area the tool belongs to, for example `Error tracking`. Use it to group the listing. */
+ category: string
+ /** The feature key the MCP server filters on, for example `error_tracking`. Narrower than `category`. */
+ feature: string
+ /** The API scopes a token must carry to call the tool. Empty for a tool that needs none. */
+ required_scopes: string[]
+ /** True when the tool only reads. A false value means the tool can change the project's data. */
+ is_read_only: boolean
+ /** True when the tool is hidden until the project consents to AI features. */
+ requires_ai_consent: boolean
+ /** True when a scout run can hold every scope the tool requires. A false value means no scout reaches the tool, whatever it is granted, so it cannot be configured for one. */
+ holdable: boolean
+ /** Required scopes the baseline `signals_scout` preset does not carry. On a holdable tool these are what the scout has to be granted, or the preset it has to opt into. On a tool that is not holdable they include every scope no scout can reach, and can also include scopes a person can grant. Compare them with `grantable_write_scopes` and `presets` to tell the two apart. */
+ missing_scopes: string[]
+ /**
+ * Feature flag key that gates the tool, or null when the tool is always served. The flag resolves per project, so evaluate it for the project you are configuring before you offer the tool.
+ * @nullable
+ */
+ feature_flag: string | null
+ /**
+ * How `feature_flag` gates the tool: `enable` (served only while the flag is on) or `disable` (served only while the flag is off). Null means the default, `enable`.
+ * @nullable
+ */
+ feature_flag_behavior: string | null
+ /**
+ * Variant of `feature_flag` the tool needs, or null when any truthy value serves it.
+ * @nullable
+ */
+ feature_flag_variant: string | null
+ /**
+ * A second flag key that hides the tool while it is on, independent of `feature_flag`. Usually null.
+ * @nullable
+ */
+ hidden_when_flag_on: string | null
+ /**
+ * Plan feature the organization must have for the tool to be served, or null when the tool is free.
+ * @nullable
+ */
+ feature_entitlement: string | null
+}
+
+/**
+ * A scope preset a scout run can be dispatched with.
+ */
+export interface ScoutScopePresetApi {
+ /** The preset's name. `signals_scout` is what every scout holds; `signals_scout_reports` adds the report channel and is used only by a scout whose skill opted into it. */
+ name: string
+ /** Every scope a token minted from this preset carries, including the internal ones. */
+ scopes: string[]
+}
+
+/**
+ * The MCP tool catalogue, with the scout scope postures to read it against.
+ */
+export interface ScoutToolCatalogueApi {
+ /** Every catalogued MCP tool, ordered by name. Tools that a successor has replaced are left out. */
+ tools: ScoutToolCatalogueEntryApi[]
+ /** The scope presets a scout run can be dispatched with, and the scopes each one resolves to. */
+ presets: ScoutScopePresetApi[]
+ /** The write scopes a person can grant to one scout from its settings. A scope outside this set can never be added to a scout's token. */
+ grantable_write_scopes: string[]
+}
+
/**
* One team a member belongs to, from the project's synced team roster.
*/
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 647e11ab2312..1244e14aaf90 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -63,6 +63,7 @@ import type {
ScoutSuggestionItemApi,
ScoutSuggestionRefreshApi,
ScoutSuggestionSetApi,
+ ScoutToolCatalogueApi,
ScratchpadEntryApi,
SignalReportApi,
SignalReportArtefactApi,
@@ -1371,6 +1372,24 @@ export const signalsScoutConfigSync = async (
})
}
+export const getSignalsScoutConfigToolCatalogueUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/signals/scout/configs/tool_catalogue/`
+}
+
+/**
+ * List every MCP tool a scout could be configured with. Each entry carries the tool's name, label, one-line summary, category, and required scopes, plus `holdable`: whether a scout run can hold every scope the tool needs, and `missing_scopes`: what it would have to be granted on top of the baseline preset. The response also returns the scout scope presets and the write scopes a person can grant to one scout, so a caller can show why a tool is out of reach. Tools a successor has replaced are left out. A tool can carry a `feature_flag`, which resolves per project: evaluate it for the project you are configuring before you offer the tool. Read-only, and the same for every project.
+ * @summary List the MCP tool catalogue
+ */
+export const signalsScoutConfigToolCatalogue = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<ScoutToolCatalogueApi> => {
+ return apiMutator<ScoutToolCatalogueApi>(getSignalsScoutConfigToolCatalogueUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getSignalsScoutMembersListUrl = (projectId: string, params?: SignalsScoutMembersListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 17b051bc958d..71112a0b05fb 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -1295,6 +1295,9 @@ tools:
description:
'DEPRECATED: renamed to scout-config-sync. This alias forwards to the same endpoint and will be removed.
Call scout-config-sync directly with the same arguments.'
+ signals-scout-config-tool-catalogue:
+ operation: signals_scout_config_tool_catalogue
+ enabled: false
signals-scout-config-update:
operation: signals_scout_config_update
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 88292f8fe8aa..338d5d849054 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -89182,6 +89182,16 @@ export namespace Schemas {
available: boolean;
}
+ /**
+ * A scope preset a scout run can be dispatched with.
+ */
+ export interface ScoutScopePreset {
+ /** The preset's name. `signals_scout` is what every scout holds; `signals_scout_reports` adds the report channel and is used only by a scout whose skill opted into it. */
+ name: string;
+ /** Every scope a token minted from this preset carries, including the internal ones. */
+ scopes: string[];
+ }
+
export interface ScoutSuggestionProposedConfig {
/**
* Suggested five-field cron schedule in the project timezone, or null for an interval.
@@ -89272,6 +89282,69 @@ export namespace Schemas {
items: ScoutSuggestionItem[];
}
+ /**
+ * One MCP tool, with what a scout would need to call it.
+ */
+ export interface ScoutToolCatalogueEntry {
+ /** The tool's permanent identifier, for example `insight-get`. This is the name a scout calls. */
+ name: string;
+ /** The label people read, for example `Get insight`. */
+ title: string;
+ /** One line on what the tool does. The tool's full description runs to several kilobytes on some tools, so it is not part of this listing. */
+ summary: string;
+ /** The product area the tool belongs to, for example `Error tracking`. Use it to group the listing. */
+ category: string;
+ /** The feature key the MCP server filters on, for example `error_tracking`. Narrower than `category`. */
+ feature: string;
+ /** The API scopes a token must carry to call the tool. Empty for a tool that needs none. */
+ required_scopes: string[];
+ /** True when the tool only reads. A false value means the tool can change the project's data. */
+ is_read_only: boolean;
+ /** True when the tool is hidden until the project consents to AI features. */
+ requires_ai_consent: boolean;
+ /** True when a scout run can hold every scope the tool requires. A false value means no scout reaches the tool, whatever it is granted, so it cannot be configured for one. */
+ holdable: boolean;
+ /** Required scopes the baseline `signals_scout` preset does not carry. On a holdable tool these are what the scout has to be granted, or the preset it has to opt into. On a tool that is not holdable they include every scope no scout can reach, and can also include scopes a person can grant. Compare them with `grantable_write_scopes` and `presets` to tell the two apart. */
+ missing_scopes: string[];
+ /**
+ * Feature flag key that gates the tool, or null when the tool is always served. The flag resolves per project, so evaluate it for the project you are configuring before you offer the tool.
+ * @nullable
+ */
+ feature_flag: string | null;
+ /**
+ * How `feature_flag` gates the tool: `enable` (served only while the flag is on) or `disable` (served only while the flag is off). Null means the default, `enable`.
+ * @nullable
+ */
+ feature_flag_behavior: string | null;
+ /**
+ * Variant of `feature_flag` the tool needs, or null when any truthy value serves it.
+ * @nullable
+ */
+ feature_flag_variant: string | null;
+ /**
+ * A second flag key that hides the tool while it is on, independent of `feature_flag`. Usually null.
+ * @nullable
+ */
+ hidden_when_flag_on: string | null;
+ /**
+ * Plan feature the organization must have for the tool to be served, or null when the tool is free.
+ * @nullable
+ */
+ feature_entitlement: string | null;
+ }
+
+ /**
+ * The MCP tool catalogue, with the scout scope postures to read it against.
+ */
+ export interface ScoutToolCatalogue {
+ /** Every catalogued MCP tool, ordered by name. Tools that a successor has replaced are left out. */
+ tools: ScoutToolCatalogueEntry[];
+ /** The scope presets a scout run can be dispatched with, and the scopes each one resolves to. */
+ presets: ScoutScopePreset[];
+ /** The write scopes a person can grant to one scout from its settings. A scope outside this set can never be added to a scout's token. */
+ grantable_write_scopes: string[];
+ }
+
/**
* `SignalScratchpad` projection used by `search-memory` and `remember`.
*/