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): let a scout token carry per-scout write scopes (#94575)

posthog[bot]d9c6052e0ad4
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index d757447bf36e..de8222553bd1 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -1,5 +1,6 @@
+from collections.abc import Iterable, Mapping
from datetime import timedelta
-from typing import Literal
+from typing import Any, Literal, TypedDict, cast
from uuid import UUID
from django.conf import settings
@@ -175,6 +176,49 @@ SCOUT_USER_WRITE_SCOPES: list[str] = [
]
+# The user-facing WRITE scopes a person may grant to ONE scout from its settings, on top of
+# the fixed posture above. `SCOUT_USER_WRITE_SCOPES` is the fleet-wide floor every scout
+# carries; this set is the ceiling of what a per-scout grant can add to it. Nothing here is
+# granted by default, and a scope outside this set can never be granted at all: a grant is
+# validated against this set where it is stored, and `resolve_scopes` intersects against it
+# again at mint time, so a stale or hand-edited grant cannot widen a token.
+#
+# Every entry is an artifact-shaped write, which is what makes an unattended agent holding one
+# acceptable at all. Kept out on purpose: `hog_function:write` and batch exports, because a
+# destination is arbitrary egress; `feature_flag:write`, `experiment:write` and `survey:write`,
+# because they change what end users see in production; `cohort:write` and `action:write` until
+# a scout needs them; and anything organization, user, member, or role shaped.
+#
+# These scopes are object-level rather than tool-level, so each one carries update and delete of
+# every matching object the token can reach, not only the objects the scout created. The reach
+# is not the same for all four, and any surface that offers a grant has to say so plainly:
+#
+# dashboard:write Every dashboard in the scout's project. Delete is a recoverable
+# soft-delete.
+# insight:write Every saved insight in the scout's project. Delete is a recoverable
+# soft-delete.
+# annotation:write Every annotation in the scout's project, AND every organization-scoped
+# annotation in the organization, including ones a sibling project owns
+# (see `_filter_queryset_by_parents_lookups` in the annotations viewset).
+# An update can also move an organization annotation to the scout's team.
+# alert:write Every insight alert in the scout's project. Delete is PERMANENT: the
+# viewset has no soft-delete, so it removes the alert and its check
+# history for good.
+#
+# The last two exceed the "recoverable, project-scoped" bar the other two meet. They stay in
+# the v1 set that #94263 puts to the team, because narrowing the set is that decision to make,
+# not a default to assume. Whoever confirms the set has to accept those two reaches, or drop
+# the scopes.
+SCOUT_GRANTABLE_WRITE_SCOPES: frozenset[str] = frozenset(
+ {
+ "dashboard:write",
+ "insight:write",
+ "annotation:write",
+ "alert:write",
+ }
+)
+
+
# Derived from posthog.scopes so the token issued to a sandboxed agent cannot
# drift out of subset of what the MCP server advertises in
# `services/mcp/src/lib/oauth-scopes.generated.ts` (itself generated from
@@ -196,7 +240,28 @@ MCP_WRITE_SCOPES: list[str] = _build_mcp_scopes("write")
TOKEN_EXPIRATION_SECONDS = 60 * 60 * 6 # 6 hours
-PosthogMcpScopes = McpScopePreset | list[str]
+# The two presets a scout run can hold. Named apart from `McpScopePreset` so a posture that
+# carries extra write scopes cannot be built on a non-scout preset: the extras exist for the
+# scout sandbox, and letting them ride on `read_only` would break the invariant that a
+# read-only task token carries no user-facing write scope.
+ScoutScopePreset = Literal["signals_scout", "signals_scout_reports"]
+SCOUT_SCOPE_PRESETS: tuple[ScoutScopePreset, ...] = ("signals_scout", "signals_scout_reports")
+
+
+class ScoutScopePosture(TypedDict):
+ """A scout preset plus the write scopes one scout was granted from its settings.
+
+ A plain dict rather than a dataclass because this value is stored on a task's
+ `pending_dispatch` JSON column and travels through Temporal payloads. It has to survive
+ `json.dumps` / `json.loads` unchanged, and be readable by a worker that was deployed
+ before the shape existed.
+ """
+
+ preset: ScoutScopePreset
+ extra_write_scopes: list[str]
+
+
+PosthogMcpScopes = McpScopePreset | list[str] | ScoutScopePosture
MCP_SCOPE_PRESETS = (
"read_only",
@@ -216,11 +281,66 @@ MCP_SCOPE_PRESETS = (
RESEARCH_WITHHELD_SCOPES: frozenset[str] = frozenset({"task:write"})
+def scout_scope_posture(
+ preset: ScoutScopePreset,
+ extra_write_scopes: Iterable[str] = (),
+) -> ScoutScopePosture:
+ """Build the scope posture one scout run is dispatched with.
+
+ Callers pass whatever the scout's stored grant holds. Anything outside
+ `SCOUT_GRANTABLE_WRITE_SCOPES` is dropped here rather than rejected, because a person is
+ told their input was invalid where they entered it, not at dispatch. A scope removed from
+ the allowlist after it was granted therefore stops reaching new runs with no data migration.
+ """
+ return {
+ "preset": preset,
+ "extra_write_scopes": _grantable_write_scopes(list(extra_write_scopes)),
+ }
+
+
+def _grantable_write_scopes(raw: object) -> list[str]:
+ """Intersect a stored grant with the allowlist, tolerating any shape JSON can hold.
+
+ A grant reaches this function straight from a JSON column, so it can be any JSON type and
+ its entries can be objects or lists. Non-string entries are dropped before the set is
+ built, because an unhashable entry makes `set(raw)` raise and aborts the run that a
+ malformed grant is supposed to degrade safely.
+ """
+ if not isinstance(raw, list):
+ return []
+ return sorted({scope for scope in raw if isinstance(scope, str)} & SCOUT_GRANTABLE_WRITE_SCOPES)
+
+
+def _read_scout_posture(posture: Mapping[str, Any]) -> tuple[McpScopePreset, list[str]]:
+ """Read a posture that has been through JSON, and intersect its extras with the allowlist.
+
+ This is the second of the two gates on a per-scout grant, and the one that binds. The
+ first gate validates what a person may store. This one runs at mint time, so a grant
+ written by an older deploy, edited by hand, or holding a scope the allowlist has since
+ dropped still cannot widen the token.
+
+ An unrecognized preset resolves to `read_only` with no extras, matching what
+ `resolve_scopes` already does with an unrecognized preset string. A malformed posture
+ then costs the run its tools instead of granting it something nobody chose.
+ """
+ preset = posture.get("preset")
+ if preset not in SCOUT_SCOPE_PRESETS:
+ return "read_only", []
+ return cast(McpScopePreset, preset), _grantable_write_scopes(posture.get("extra_write_scopes"))
+
+
def resolve_scopes(
scopes: PosthogMcpScopes = "read_only",
*,
include_internal_scopes: bool = True,
) -> list[str]:
+ if isinstance(scopes, dict):
+ # The per-scout posture: the fixed scout preset exactly as it resolves below, plus the
+ # write scopes this one scout was granted. Additive by design, so reads and the
+ # internal scopes stay identical across the fleet and only the grant differs.
+ preset, extra_write_scopes = _read_scout_posture(scopes)
+ preset_scopes = resolve_scopes(preset, include_internal_scopes=include_internal_scopes)
+ return list(dict.fromkeys([*preset_scopes, *extra_write_scopes]))
internal = list(INTERNAL_SCOPES) if include_internal_scopes else []
scratchpad = list(SCRATCHPAD_INTERNAL_SCOPES) if include_internal_scopes else []
if isinstance(scopes, str):
@@ -236,7 +356,7 @@ def resolve_scopes(
# `RESEARCH_WITHHELD_SCOPES` for why `task:write` comes back out.
reads = [scope for scope in (*MCP_READ_SCOPES, *internal) if scope not in RESEARCH_WITHHELD_SCOPES]
resolved = [*reads, *scratchpad]
- elif scopes in ("signals_scout", "signals_scout_reports"):
+ elif scopes in SCOUT_SCOPE_PRESETS:
# The scout sandbox: reads, the scout's own internal write scope, and a narrow
# allowlist of user-facing writes (`SCOUT_USER_WRITE_SCOPES`) for the durable
# artifacts a finding can produce (e.g. a notebook). Both extra sets are added
@@ -262,6 +382,13 @@ def resolve_scopes(
def has_write_scopes(scopes: PosthogMcpScopes) -> bool:
+ if isinstance(scopes, dict):
+ # Answer for the posture's preset, not a flat True. A malformed posture resolves to
+ # `read_only`, and reporting True there would turn read-only mode off for a token that
+ # carries no write scope: the MCP server would advertise write tools the token is then
+ # refused for.
+ preset, _ = _read_scout_posture(scopes)
+ return has_write_scopes(preset)
if isinstance(scopes, str):
# `signals_scout` reports True so the MCP server doesn't enable read-only mode for the
# scout sandbox — the agent IS allowed to call the write tools its preset exists for
diff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.py
index 555ee20affb7..1a59c6e34a78 100644
--- a/posthog/temporal/tests/test_oauth.py
+++ b/posthog/temporal/tests/test_oauth.py
@@ -1,5 +1,6 @@
import json
from pathlib import Path
+from typing import cast
from uuid import uuid4
from django.test import SimpleTestCase, TestCase, override_settings
@@ -15,14 +16,19 @@ from posthog.temporal.oauth import (
MCP_WRITE_SCOPES,
POSTHOG_AI_APP_CLIENT_ID_DEV,
RESEARCH_WITHHELD_SCOPES,
+ SCOUT_GRANTABLE_WRITE_SCOPES,
SCOUT_INTERNAL_SCOPES,
+ SCOUT_SCOPE_PRESETS,
SCOUT_USER_WRITE_SCOPES,
SCRATCHPAD_INTERNAL_SCOPES,
McpScopePreset,
+ ScoutScopePosture,
+ ScoutScopePreset,
create_oauth_access_token_for_user,
create_wizard_oauth_access_token_for_user,
has_write_scopes,
resolve_scopes,
+ scout_scope_posture,
)
_WIZARD_CLIENT_ID = "wizard-test-client-id"
@@ -122,6 +128,92 @@ class TestResolveScopes(SimpleTestCase):
for scope in INTERNAL_SCOPES:
assert scope not in result
+ def test_scout_posture_adds_only_the_granted_write_scopes(self) -> None:
+ # The feature itself: a grant reaches the token, and only the granted scope does.
+ # A posture that resolved to the whole allowlist would hand every scout that holds one
+ # grant the other three.
+ result = resolve_scopes(scout_scope_posture("signals_scout", ["dashboard:write"]))
+ assert set(result) == set(resolve_scopes("signals_scout")) | {"dashboard:write"}
+ assert "insight:write" not in result
+
+ @parameterized.expand([(preset,) for preset in SCOUT_SCOPE_PRESETS])
+ def test_scout_posture_without_a_grant_matches_the_plain_preset(self, preset: ScoutScopePreset) -> None:
+ # The fixed posture has to survive the new branch whole. A composition that rebuilt the
+ # preset by hand would drop `signal_scout_internal:write`, the scratchpad scopes, or the
+ # report channel, and the scout would lose the tools it exists to call.
+ assert set(resolve_scopes(scout_scope_posture(preset))) == set(resolve_scopes(preset))
+
+ @parameterized.expand(
+ [
+ ("write_scope_outside_the_allowlist", "feature_flag:write"),
+ # The report channel is granted by the preset a scout's skill opted into, never by
+ # the per-scout field. A baseline scout must not reach emit_report through a grant.
+ ("internal_scope", "signal_scout_report:write"),
+ ("scope_that_does_not_exist", "not_a_real_object:write"),
+ ]
+ )
+ def test_scout_posture_drops_scopes_outside_the_grantable_allowlist(self, _name: str, ungrantable: str) -> None:
+ # Mint-time intersection. A config row written before the allowlist shrank, or edited
+ # outside the API, reaches this function unchanged, so this is the gate that binds.
+ posture: ScoutScopePosture = {
+ "preset": "signals_scout",
+ "extra_write_scopes": [ungrantable, "dashboard:write"],
+ }
+ result = resolve_scopes(posture)
+ assert set(result) == set(resolve_scopes("signals_scout")) | {"dashboard:write"}
+
+ @parameterized.expand(
+ [
+ # A non-scout preset carrying extras is the invariant this guards: a read-only task
+ # token must never carry a user-facing write scope, whatever the posture claims.
+ (
+ "non_scout_preset",
+ cast(ScoutScopePosture, {"preset": "full", "extra_write_scopes": ["dashboard:write"]}),
+ ),
+ ("missing_preset", cast(ScoutScopePosture, {"extra_write_scopes": ["dashboard:write"]})),
+ ]
+ )
+ def test_malformed_scout_posture_resolves_to_read_only(self, _name: str, posture: ScoutScopePosture) -> None:
+ result = resolve_scopes(posture)
+ assert set(result) == set(resolve_scopes("read_only"))
+ assert not has_write_scopes(posture)
+
+ @parameterized.expand(
+ [
+ ("grant_is_not_a_list", "dashboard:write", set()),
+ # An entry JSON allows but a set cannot hold. Building the set before filtering
+ # raises TypeError, which aborts the run instead of degrading to the ungranted
+ # posture the way a malformed grant is meant to.
+ ("entry_is_an_object", [{"scope": "dashboard:write"}], set()),
+ ("entry_is_a_list", [["insight:write"], "dashboard:write"], {"dashboard:write"}),
+ ]
+ )
+ def test_scout_posture_tolerates_malformed_grant_entries(
+ self, _name: str, raw: object, expected_extra: set[str]
+ ) -> None:
+ posture = cast(ScoutScopePosture, {"preset": "signals_scout", "extra_write_scopes": raw})
+ assert set(resolve_scopes(posture)) == set(resolve_scopes("signals_scout")) | expected_extra
+
+ def test_scout_scope_posture_drops_ungrantable_scopes(self) -> None:
+ # The build-time gate. What this returns is both the mint request and the record of
+ # what a run was dispatched with, so a builder that passed its input through would widen
+ # the token and describe it wrongly at the same time.
+ assert scout_scope_posture("signals_scout", ["dashboard:write", "feature_flag:write"]) == {
+ "preset": "signals_scout",
+ "extra_write_scopes": ["dashboard:write"],
+ }
+
+ def test_scout_posture_survives_a_json_round_trip(self) -> None:
+ # The posture is stored on a task's `pending_dispatch` JSON column and travels through
+ # Temporal payloads, so it has to resolve the same after `json.dumps` / `json.loads`.
+ posture = scout_scope_posture("signals_scout_reports", ["insight:write", "dashboard:write"])
+ assert resolve_scopes(json.loads(json.dumps(posture))) == resolve_scopes(posture)
+
+ def test_grantable_write_scopes_are_mcp_write_scopes(self) -> None:
+ # A typo or an internal scope in the allowlist would offer a person a switch that grants
+ # nothing, because the MCP server gates its tools on scopes it advertises.
+ assert SCOUT_GRANTABLE_WRITE_SCOPES <= set(MCP_WRITE_SCOPES)
+
def test_custom_scopes(self) -> None:
custom = ["feature_flag:read", "feature_flag:write"]
result = resolve_scopes(custom)
@@ -178,6 +270,10 @@ class TestHasWriteScopes(SimpleTestCase):
# scratchpad tools the postures exist to grant.
("signals_research_preset", "signals_research", True),
("signals_implementation_preset", "signals_implementation", True),
+ # Read-only mode has to stay off for a scout posture, or the MCP server strips the
+ # scout's own tools whether or not the scout holds a grant.
+ ("scout_posture_with_a_grant", {"preset": "signals_scout", "extra_write_scopes": ["alert:write"]}, True),
+ ("scout_posture_without_a_grant", {"preset": "signals_scout_reports", "extra_write_scopes": []}, True),
("custom_with_mcp_write", ["feature_flag:read", "feature_flag:write"], True),
("custom_read_only", ["feature_flag:read", "insight:read"], False),
("custom_with_non_mcp_write", ["task:write"], False),
diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.py
index b810506e4648..9f709af939a2 100644
--- a/products/tasks/backend/temporal/oauth.py
+++ b/products/tasks/backend/temporal/oauth.py
@@ -12,6 +12,7 @@ from posthog.temporal.oauth import (
McpScopePreset,
PosthogMcpScopes,
SandboxOAuthApplication,
+ ScoutScopePosture,
create_oauth_access_token_for_user as _create_oauth_access_token_for_user,
create_wizard_oauth_access_token_for_user as _create_wizard_oauth_access_token_for_user,
resolve_scopes,
@@ -120,6 +121,13 @@ def _workflow_run_scopes(requested: PosthogMcpScopes, state: dict[str, Any] | No
snapshot = [str(scope) for scope in raw]
elif isinstance(raw, str) and raw in get_args(McpScopePreset):
snapshot = cast(McpScopePreset, raw)
+ elif isinstance(raw, dict):
+ # A snapshotted scout posture. Passed through unchecked because `resolve_scopes` reads
+ # it defensively: an unrecognized preset resolves to `read_only`, and the extra write
+ # scopes are intersected with the grantable allowlist there. Skipping the dict instead
+ # would drop the snapshot leg of the intersection, which is the half that stops a
+ # widened request from taking effect.
+ snapshot = cast(ScoutScopePosture, raw)
if snapshot is not None:
resolved &= set(resolve_scopes(snapshot, include_internal_scopes=True))
return sorted(scope for scope in resolved if scope not in LOOP_FIRED_RUN_EXCLUDED_SCOPES)
diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.py
index 0b08420feb82..578e676ab53e 100644
--- a/products/tasks/backend/temporal/tests/test_oauth.py
+++ b/products/tasks/backend/temporal/tests/test_oauth.py
@@ -452,11 +452,14 @@ def test_workflow_run_fails_closed_when_owner_is_not_a_current_org_member(mock_c
[
("full", "read_only"),
("read_only", "full"),
+ # A snapshotted scout posture is a dict rather than a preset string. Skipping it would
+ # drop the snapshot leg of the intersection and grant the request in full.
+ ("full", {"preset": "signals_scout", "extra_write_scopes": ["dashboard:write"]}),
],
)
@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")
def test_workflow_run_scopes_never_exceed_request_or_snapshot(
- mock_create: MagicMock, requested: PosthogMcpScopes, snapshot: str
+ mock_create: MagicMock, requested: PosthogMcpScopes, snapshot: PosthogMcpScopes
) -> None:
from posthog.models.organization import OrganizationMembership
from posthog.temporal.oauth import resolve_scopes
@@ -473,10 +476,10 @@ def test_workflow_run_scopes_never_exceed_request_or_snapshot(
create_oauth_access_token_for_run(task, state, scopes=requested)
granted = set(mock_create.call_args.kwargs["scopes"])
- read_only = set(resolve_scopes("read_only", include_internal_scopes=True))
# Whichever side is narrower wins: a teammate rerun requesting full cannot exceed the
# workflow's snapshot, and a narrow request is never widened to the snapshot.
- assert granted <= read_only
+ assert granted <= set(resolve_scopes(requested, include_internal_scopes=True))
+ assert granted <= set(resolve_scopes(snapshot, include_internal_scopes=True))
@pytest.mark.django_db