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(context-layer): allow task-scoped wiki tools (#94480)

Dylan Martin8bb5a09adcdd
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
index cfe220be0f31..888b64b08d6f 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts
@@ -405,6 +405,7 @@ export interface accessControlsLogicActions {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -578,6 +579,7 @@ export interface accessControlsLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -728,6 +730,7 @@ export interface accessControlsLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -850,6 +853,7 @@ export interface accessControlsLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
index 4e57e1294ce6..2cb0272f8f91 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts
@@ -230,6 +230,7 @@ export interface accessDetailLogicActions {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
index 78183959e04d..dccaf37942b2 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts
@@ -76,6 +76,7 @@ export interface addObjectOverrideModalLogicActions {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -196,6 +197,7 @@ export interface addObjectOverrideModalLogicActions {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -337,6 +339,7 @@ export interface addObjectOverrideModalLogicActions {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -462,6 +465,7 @@ export interface addObjectOverrideModalLogicActions {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -586,6 +590,7 @@ export interface addObjectOverrideModalLogicActions {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -731,6 +736,7 @@ export interface addObjectOverrideModalLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
index 3b756072cd17..3aa3aa067e65 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts
@@ -39,6 +39,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -165,6 +166,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -283,6 +285,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -414,6 +417,7 @@ export interface groupedAccessControlRuleModalLogicValues {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -550,6 +554,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -688,6 +693,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -806,6 +812,7 @@ export interface groupedAccessControlRuleModalLogicActions {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -963,6 +970,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -1083,6 +1091,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -1202,6 +1211,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -1321,6 +1331,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -1441,6 +1452,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -1560,6 +1572,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -1690,6 +1703,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -1809,6 +1823,7 @@ export interface groupedAccessControlRuleModalLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
index 67656c783430..e318fe63ea03 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts
@@ -330,6 +330,7 @@ export interface accessControlLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -552,6 +553,7 @@ export interface accessControlLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
@@ -671,6 +673,7 @@ export interface accessControlLogicMeta {
| 'clickhouse_test_cluster_perf'
| 'cohort'
| 'comment'
+ | 'context_layer_internal'
| 'conversation'
| 'customer_analytics'
| 'customer_journey'
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 301c287c3f54..1a77b21018c3 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -264,6 +264,7 @@ API_SCOPES.sort((a, b) => a.objectName.localeCompare(b.objectName))
export const API_SCOPES_OMITTED_FROM_MODAL: Partial<Record<APIScopeObject, string>> = {
// INTERNAL_API_SCOPE_OBJECTS — server-minted only, never user-grantable.
clickhouse_test_cluster_perf: 'Internal: minted programmatically only.',
+ context_layer_internal: 'Internal: permits channel-bound Context Wiki writes from task runs.',
internal_run: 'Internal: marks a server-minted sandbox/agent run credential.',
mcp_builtin_agent: 'Internal: identifies a trusted built-in agent credential.',
signal_scout_internal: 'Internal: sandbox-only writes for the headless Signals agent.',
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index fcd79b4fd52f..7f9d8e006fa8 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5862,6 +5862,7 @@ export const API_SCOPE_OBJECTS = [
'cohort',
'comment',
'conversation',
+ 'context_layer_internal',
'customer_analytics',
'customer_task',
'customer_journey',
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 2a604fd1e658..a3254b936049 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -33,6 +33,7 @@ APIScopeObject = Literal[
"cohort",
"comment",
"conversation",
+ "context_layer_internal",
"customer_analytics",
"customer_task",
"customer_journey",
@@ -158,6 +159,9 @@ API_SCOPE_ACTIONS: tuple[APIScopeActions, ...] = get_args(APIScopeActions)
INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(
{
"clickhouse_test_cluster_perf",
+ # Grants Context Wiki writes only to write-enabled sandbox runs. Kept
+ # separate from internal_run because read-only runs carry that marker.
+ "context_layer_internal",
# Narrows `internal_run`: the run behind this token was started by a person
# pressing a button, not by one of PostHog's own schedulers. Both markers are
# minted server-side, so neither can be self-granted; the LLM gateway meters
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index 6a9f3588c54f..1a7609102d8d 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -157,6 +157,7 @@ SCOUT_REPORT_SCOPES: list[str] = [
]
LOOP_CONTEXT_INTERNAL_SCOPE = "loop_context_internal:write"
+CONTEXT_LAYER_INTERNAL_SCOPE = "context_layer_internal:write"
# A deliberately narrow set of user-facing WRITE scopes granted to the Signals scout
@@ -422,6 +423,8 @@ def resolve_scopes(
resolved = [*MCP_READ_SCOPES, *internal]
else:
resolved = [*scopes, *internal]
+ if include_internal_scopes and "organization:write" in resolved:
+ resolved.append(CONTEXT_LAYER_INTERNAL_SCOPE)
return list(dict.fromkeys(resolved))
diff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.py
index 8ff09a1de2cc..92937997c9ea 100644
--- a/posthog/temporal/tests/test_oauth.py
+++ b/posthog/temporal/tests/test_oauth.py
@@ -15,6 +15,7 @@ from posthog.models import OAuthAccessToken, OAuthApplication, Organization, Tea
from posthog.scopes import MCP_BUILT_IN_AGENT_SCOPE
from posthog.temporal.oauth import (
ARRAY_APP_CLIENT_ID_DEV,
+ CONTEXT_LAYER_INTERNAL_SCOPE,
INTERNAL_SCOPES,
MCP_READ_SCOPES,
MCP_WRITE_SCOPES,
@@ -52,7 +53,12 @@ class TestResolveScopes(SimpleTestCase):
def test_full_preset(self) -> None:
result = resolve_scopes("full")
- assert set(result) == set(MCP_READ_SCOPES + MCP_WRITE_SCOPES + INTERNAL_SCOPES)
+ assert set(result) == set(MCP_READ_SCOPES + MCP_WRITE_SCOPES + INTERNAL_SCOPES + [CONTEXT_LAYER_INTERNAL_SCOPE])
+
+ def test_context_layer_write_scope_requires_organization_write(self) -> None:
+ assert CONTEXT_LAYER_INTERNAL_SCOPE not in resolve_scopes("read_only")
+ assert CONTEXT_LAYER_INTERNAL_SCOPE not in resolve_scopes(["task:write"])
+ assert CONTEXT_LAYER_INTERNAL_SCOPE in resolve_scopes(["organization:write"])
def test_signals_scout_preset_adds_scout_internal_write(self) -> None:
# `signals_scout` = `read_only` content PLUS the scout's own internal write scope
@@ -96,7 +102,13 @@ class TestResolveScopes(SimpleTestCase):
def test_signals_implementation_preset_is_full_plus_the_scratchpad(self) -> None:
result = resolve_scopes("signals_implementation")
- assert set(result) == set(MCP_READ_SCOPES + MCP_WRITE_SCOPES + INTERNAL_SCOPES + SCRATCHPAD_INTERNAL_SCOPES)
+ assert set(result) == set(
+ MCP_READ_SCOPES
+ + MCP_WRITE_SCOPES
+ + INTERNAL_SCOPES
+ + SCRATCHPAD_INTERNAL_SCOPES
+ + [CONTEXT_LAYER_INTERNAL_SCOPE]
+ )
def test_scratchpad_write_reaches_scouts_and_the_pipeline_only(self) -> None:
# Splitting the scope out of `signal_scout_internal` must not cost scouts their
diff --git a/products/context_layer/backend/presentation/views.py b/products/context_layer/backend/presentation/views.py
index 430965f7718d..ad0c7e0da170 100644
--- a/products/context_layer/backend/presentation/views.py
+++ b/products/context_layer/backend/presentation/views.py
@@ -11,7 +11,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.oauth_provenance import INTERNAL_RUN_SCOPE, get_oauth_access_token
from posthog.permissions import APIScopePermission, PostHogFeatureFlagPermission
from posthog.redis import get_client
-from posthog.temporal.oauth import LOOP_CONTEXT_INTERNAL_SCOPE
+from posthog.temporal.oauth import CONTEXT_LAYER_INTERNAL_SCOPE, LOOP_CONTEXT_INTERNAL_SCOPE
from products.context_layer.backend.facade import api as facade
from products.context_layer.backend.presentation.serializers import (
@@ -116,7 +116,10 @@ def _assert_run_write_in_scope(organization_id, team_id, request: Request, path:
# Both sides resolve inside this organization's own wiki index, so a run
# cannot reach another organization's pages even by naming its channel.
requested_channel_id = facade.resolve_page_channel(organization_id, path)
- if configured_channel_id == requested_channel_id:
+ if (
+ configured_channel_id == requested_channel_id
+ and facade.page_frontmatter_channel_id(content) == configured_channel_id
+ ):
return
if requested_channel_id is not None:
raise denied
@@ -455,15 +458,13 @@ class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
read_actions = ["page", "channel_page"]
write_actions = ["update_page", "commits"]
- # Which task scope each action accepts, and the provenance marker that has to
- # come with it. A sandbox run lands commits; a context-maintaining loop run
- # reads and rewrites its own page. Ordinary runs use organization scopes for
- # page operations, then the write path binds them to their task channel.
- _RUN_SCOPES = {
- "commits": ("task:write", INTERNAL_RUN_SCOPE),
- "page": ("task:read", LOOP_CONTEXT_INTERNAL_SCOPE),
- "channel_page": ("task:read", LOOP_CONTEXT_INTERNAL_SCOPE),
- "update_page": ("task:write", LOOP_CONTEXT_INTERNAL_SCOPE),
+ # Each task scope must come with server-minted run provenance. Page actions
+ # accept ordinary and loop runs; the write path binds each to its own target.
+ _RUN_TASK_SCOPES = {
+ "commits": "task:write",
+ "page": "task:read",
+ "channel_page": "task:read",
+ "update_page": "task:write",
}
def dangerously_get_required_scopes(self, request: Request, view=None) -> list[str] | None: # noqa: ANN001
@@ -477,13 +478,17 @@ class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
deriving. One consequence of INTERNAL: a `*` (full access) token does not
short-circuit this check, so it has to carry the organization scope too.
"""
- required = self._RUN_SCOPES.get(self.action)
- if required is not None:
- task_scope, provenance_scope = required
+ task_scope = self._RUN_TASK_SCOPES.get(self.action)
+ if task_scope is not None:
access_token = get_oauth_access_token(request)
token_scopes = set((getattr(access_token, "scope", "") or "").split())
- if provenance_scope in token_scopes:
- return [task_scope, provenance_scope]
+ if self.action != "commits" and LOOP_CONTEXT_INTERNAL_SCOPE in token_scopes:
+ return [task_scope, LOOP_CONTEXT_INTERNAL_SCOPE]
+ if INTERNAL_RUN_SCOPE in token_scopes:
+ required = [task_scope, INTERNAL_RUN_SCOPE]
+ if self.action in self.write_actions:
+ required.append(CONTEXT_LAYER_INTERNAL_SCOPE)
+ return required
if self.action in self.write_actions:
return ["organization:write"]
if self.action in self.read_actions:
diff --git a/products/context_layer/backend/test/test_api.py b/products/context_layer/backend/test/test_api.py
index 564d2666263d..5f73dc0177c1 100644
--- a/products/context_layer/backend/test/test_api.py
+++ b/products/context_layer/backend/test/test_api.py
@@ -72,7 +72,7 @@ class TestContextLayerAPI(APIBaseTest):
self._enable()
bundle_bytes = self._bundle_with_edit("areas/from-agent.md", _page("From an agent"))
# Minted the way production mints one: bound to a task, scoped to a team.
- token = self._bearer("task:write internal_run:read", scoped_teams=[self.team.id])
+ token = self._bearer("task:write internal_run:read context_layer_internal:write", scoped_teams=[self.team.id])
self.client.logout()
def post(base: str):
@@ -382,7 +382,13 @@ class TestContextLayerAPI(APIBaseTest):
)
def test_commits_accepts_a_sandbox_run_token(self, _flag) -> None:
- assert self._post_bundle_with_bearer("task:write internal_run:read").status_code == 200
+ assert (
+ self._post_bundle_with_bearer("task:write internal_run:read context_layer_internal:write").status_code
+ == 200
+ )
+
+ def test_commits_rejects_read_only_sandbox_run_token(self, _flag) -> None:
+ assert self._post_bundle_with_bearer("task:write internal_run:read").status_code == 403
def test_commits_rejects_task_write_without_run_provenance(self, _flag) -> None:
# task:write is user-grantable; without the server-minted internal_run:read
@@ -455,11 +461,13 @@ class TestContextLayerAPI(APIBaseTest):
assert proposed.status_code == 200, proposed.content
assert proposed.json() == {"path": f"projects/{self.team.id}/spaces/growth.md", "exists": False}
- def test_agent_route_accepts_organization_scopes_from_an_interactive_task(self, _flag) -> None:
+ def test_agent_route_accepts_task_scopes_from_an_interactive_task(self, _flag) -> None:
self._enable()
with team_scope(self.team.id):
channel = tasks_facade.resolve_channel(self.team.id, self.user.id, name="growth", star=False)
assert channel is not None
+ other_channel = tasks_facade.resolve_channel(self.team.id, self.user.id, name="sales", star=False)
+ assert other_channel is not None
task = apps.get_model("tasks", "Task").objects.create(
team=self.team,
created_by=self.user,
@@ -467,12 +475,20 @@ class TestContextLayerAPI(APIBaseTest):
channel_id=channel.id,
)
token = self._bearer(
- "organization:read organization:write task:write internal_run:read",
+ "task:read task:write internal_run:read context_layer_internal:write",
scoped_teams=[self.team.id],
sandbox_task_id=task.id,
)
self.client.logout()
+ moved = self.client.patch(
+ f"/api/projects/{self.team.id}/tasks/{task.id}/",
+ {"channel": str(other_channel.id)},
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert moved.status_code == 403, moved.content
+
proposed = self.client.get(
f"{self.agent_url}/channel-pages/{channel.id}/",
HTTP_AUTHORIZATION=f"Bearer {token}",
@@ -491,6 +507,18 @@ class TestContextLayerAPI(APIBaseTest):
)
assert created.status_code == 200, created.content
+ changed_frontmatter = self.client.put(
+ f"{self.agent_url}/pages/",
+ {
+ "path": proposed.json()["path"],
+ "content": f"---\nteam_id: {self.team.id}\nchannel_id: {other_channel.id}\nsummary: Sales channel context.\nstatus: active\n---\n\n# Sales\n",
+ "base_head": created.json()["head_sha"],
+ },
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert changed_frontmatter.status_code == 403, changed_frontmatter.content
+
outside_channel = self.client.put(
f"{self.agent_url}/pages/",
{"path": "AGENTS.md", "content": "# Owned\n", "base_head": created.json()["head_sha"]},
@@ -499,6 +527,43 @@ class TestContextLayerAPI(APIBaseTest):
)
assert outside_channel.status_code == 403, outside_channel.content
+ def test_read_only_task_token_cannot_update_its_channel_page(self, _flag) -> None:
+ with team_scope(self.team.id):
+ channel = tasks_facade.resolve_channel(self.team.id, self.user.id, name="growth", star=False)
+ assert channel is not None
+ head = self._enable()
+ task = apps.get_model("tasks", "Task").objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="Read the space context",
+ channel_id=channel.id,
+ )
+ token = self._bearer(
+ "organization:read task:read task:write internal_run:read",
+ scoped_teams=[self.team.id],
+ sandbox_task_id=task.id,
+ )
+ self.client.logout()
+
+ read = self.client.get(
+ f"{self.agent_url}/pages/",
+ {"path": f"projects/{self.team.id}/spaces/growth.md"},
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert read.status_code == 200, read.content
+
+ updated = self.client.put(
+ f"{self.agent_url}/pages/",
+ {
+ "path": f"projects/{self.team.id}/spaces/growth.md",
+ "content": read.json()["content"],
+ "base_head": head,
+ },
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert updated.status_code == 403, updated.content
+
def test_loop_token_creates_its_channels_missing_page_at_the_proposed_path(self, _flag) -> None:
self._enable()
with team_scope(self.team.id):
@@ -555,7 +620,11 @@ class TestContextLayerAPI(APIBaseTest):
def test_run_commit_landings_are_capped_per_day(self, _flag) -> None:
self._enable()
task = apps.get_model("tasks", "Task").objects.create(team=self.team, created_by=self.user, title="agent work")
- token = self._bearer("task:write internal_run:read", scoped_teams=[self.team.id], sandbox_task_id=task.id)
+ token = self._bearer(
+ "task:write internal_run:read context_layer_internal:write",
+ scoped_teams=[self.team.id],
+ sandbox_task_id=task.id,
+ )
self.client.logout()
def land(path: str):
@@ -598,7 +667,7 @@ class TestContextLayerAPI(APIBaseTest):
team=self.team, created_by=self.user, title="agent work", channel_id=channel.id
)
token = self._bearer(
- "task:read task:write internal_run:read organization:write",
+ "task:read task:write internal_run:read context_layer_internal:write",
scoped_teams=[self.team.id],
sandbox_task_id=task.id,
)
@@ -624,7 +693,7 @@ class TestContextLayerAPI(APIBaseTest):
def test_pages_reject_task_scopes_without_run_provenance(self, _flag) -> None:
self._enable()
- token = self._bearer("task:read task:write internal_run:read", scoped_teams=[self.team.id])
+ token = self._bearer("task:read task:write", scoped_teams=[self.team.id])
self.client.logout()
response = self.client.get(
f"{self.agent_url}/pages/",
diff --git a/products/context_layer/mcp/tools.yaml b/products/context_layer/mcp/tools.yaml
index 6cf7ec4150d2..356b7a112df2 100644
--- a/products/context_layer/mcp/tools.yaml
+++ b/products/context_layer/mcp/tools.yaml
@@ -126,3 +126,43 @@ tools:
title: Update a loop context wiki page
description: Replace a context wiki page using base_head concurrency for an unattended loop run.
feature_flag: context-layer
+ task-context-wiki-channel-resolve:
+ operation: context_layer_agent_channel_pages_retrieve
+ enabled: true
+ scopes:
+ - task:read
+ - internal_run:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Resolve this task's channel context page
+ description: Resolve the current task's channel id to its context wiki page path for an unattended task run.
+ feature_flag: context-layer
+ task-context-wiki-page-retrieve:
+ operation: context_layer_agent_pages_retrieve
+ enabled: true
+ scopes:
+ - task:read
+ - internal_run:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Read this task's context wiki page
+ description: Read a context wiki page and its head_sha for an unattended task run.
+ feature_flag: context-layer
+ task-context-wiki-page-update:
+ operation: context_layer_agent_pages_update
+ enabled: true
+ scopes:
+ - task:write
+ - internal_run:read
+ - context_layer_internal:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: false
+ title: Update this task's context wiki page
+ description: Replace the current task channel's context wiki page using base_head concurrency.
+ feature_flag: context-layer
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 0293ab6db3f9..90912a9efbb3 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -779,6 +779,13 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@extend_schema(request=TaskWriteSerializer, responses={200: TaskSerializer})
def partial_update(self, request, pk=None, **kwargs):
+ authenticator = request.successful_authenticator
+ if (
+ "channel" in request.data
+ and isinstance(authenticator, OAuthAccessTokenAuthentication)
+ and authenticator.access_token.sandbox_task_id is not None
+ ):
+ raise PermissionDenied("Task agents cannot move tasks between channels.")
serializer = self._write_serializer(request.data, partial=True)
task = tasks_facade.update_task(
pk, self.team_id, self._user_id(), validated_data=dict(serializer.validated_data)
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 5fce49cba70f..05327851b32c 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10947,6 +10947,51 @@
"readOnlyHint": true
}
},
+ "task-context-wiki-channel-resolve": {
+ "description": "Resolve the current task's channel id to its context wiki page path for an unattended task run.",
+ "category": "Context wiki",
+ "feature": "context_layer",
+ "summary": "Resolve this task's channel context page",
+ "title": "Resolve this task's channel context page",
+ "required_scopes": ["task:read", "internal_run:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "context-layer"
+ },
+ "task-context-wiki-page-retrieve": {
+ "description": "Read a context wiki page and its head_sha for an unattended task run.",
+ "category": "Context wiki",
+ "feature": "context_layer",
+ "summary": "Read this task's context wiki page",
+ "title": "Read this task's context wiki page",
+ "required_scopes": ["task:read", "internal_run:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "context-layer"
+ },
+ "task-context-wiki-page-update": {
+ "description": "Replace the current task channel's context wiki page using base_head concurrency.",
+ "category": "Context wiki",
+ "feature": "context_layer",
+ "summary": "Update this task's context wiki page",
+ "title": "Update this task's context wiki page",
+ "required_scopes": ["task:write", "internal_run:read", "context_layer_internal:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "context-layer"
+ },
"tasks-create": {
"description": "Create an agent task in the current project — a unit of work an AI agent picks up and actions, such as investigating an inbox report, fixing an error, or opening a pull request. `description` is the prompt handed to the agent, so make it specific and actionable. Pass `repository` in `organization/repo` format for code tasks so the agent knows where to work; omit it for investigation-only tasks. This creates the task record only — it does not start the agent. Returns the created task including its URL; open that URL to start the run. Requires the calling token's organization to have Tasks access enabled.",
"category": "Tasks",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c18e668481df..eaecc2e17296 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11547,6 +11547,51 @@
"readOnlyHint": false
}
},
+ "task-context-wiki-channel-resolve": {
+ "description": "Resolve the current task's channel id to its context wiki page path for an unattended task run.",
+ "category": "Context wiki",
+ "feature": "context_layer",
+ "summary": "Resolve this task's channel context page",
+ "title": "Resolve this task's channel context page",
+ "required_scopes": ["task:read", "internal_run:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "context-layer"
+ },
+ "task-context-wiki-page-retrieve": {
+ "description": "Read a context wiki page and its head_sha for an unattended task run.",
+ "category": "Context wiki",
+ "feature": "context_layer",
+ "summary": "Read this task's context wiki page",
+ "title": "Read this task's context wiki page",
+ "required_scopes": ["task:read", "internal_run:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "context-layer"
+ },
+ "task-context-wiki-page-update": {
+ "description": "Replace the current task channel's context wiki page using base_head concurrency.",
+ "category": "Context wiki",
+ "feature": "context_layer",
+ "summary": "Update this task's context wiki page",
+ "title": "Update this task's context wiki page",
+ "required_scopes": ["task:write", "internal_run:read", "context_layer_internal:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "context-layer"
+ },
"tasks-artifacts-list": {
"description": "List the current PostHog Desktop task's artifacts and canvases. Use the returned artifact ids to filter tasks-comments-list when the user asks about comments on a specific artifact. The current task is fixed by the host and cannot be selected by the caller.",
"category": "Tasks",
diff --git a/services/mcp/src/lib/api.ts b/services/mcp/src/lib/api.ts
index eae62c50f9b9..166a0a2c4fcd 100644
--- a/services/mcp/src/lib/api.ts
+++ b/services/mcp/src/lib/api.ts
@@ -1,4 +1,5 @@
const SERVER_MINT_ONLY_SCOPE_OBJECTS = new Set([
+ 'context_layer_internal',
'internal_run',
'loop_context_internal',
'mcp_builtin_agent',
diff --git a/services/mcp/src/lib/scope-preset.ts b/services/mcp/src/lib/scope-preset.ts
index 781985a33e67..0d9247f3b550 100644
--- a/services/mcp/src/lib/scope-preset.ts
+++ b/services/mcp/src/lib/scope-preset.ts
@@ -31,6 +31,7 @@ const SERVER_MINTED_MARKER_SCOPE = 'internal_run:read'
// plus the scratchpad object). A `:write` on one of these is internal provenance, not the
// user-facing write access that separates an implementation run from a research run.
const INTERNAL_WRITE_SCOPE_OBJECTS = new Set([
+ 'context_layer_internal',
'internal_run',
'loop_context_internal',
'mcp_builtin_agent',
diff --git a/services/mcp/src/tools/generated/context_layer.ts b/services/mcp/src/tools/generated/context_layer.ts
index 6db6dfb0cdfb..30dad4d6495c 100644
--- a/services/mcp/src/tools/generated/context_layer.ts
+++ b/services/mcp/src/tools/generated/context_layer.ts
@@ -156,6 +156,83 @@ const loopContextWikiPageUpdate = (): ToolBase<
},
})
+const TaskContextWikiChannelResolveSchema = () => {
+ const ContextLayerAgentChannelPagesRetrieveParams = orvalSchemas.ContextLayerAgentChannelPagesRetrieveParams()
+ return ContextLayerAgentChannelPagesRetrieveParams.omit({ project_id: true })
+}
+
+const taskContextWikiChannelResolve = (): ToolBase<
+ ReturnType<typeof TaskContextWikiChannelResolveSchema>,
+ Schemas.ChannelWikiPage
+> => ({
+ name: 'task-context-wiki-channel-resolve',
+ schema: TaskContextWikiChannelResolveSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof TaskContextWikiChannelResolveSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ChannelWikiPage>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/context_layer/agent/channel-pages/${encodeURIComponent(String(params.channel_id))}/`,
+ })
+ return result
+ },
+})
+
+const TaskContextWikiPageRetrieveSchema = () => {
+ const ContextLayerAgentPagesRetrieveQueryParams = orvalSchemas.ContextLayerAgentPagesRetrieveQueryParams()
+ return ContextLayerAgentPagesRetrieveQueryParams
+}
+
+const taskContextWikiPageRetrieve = (): ToolBase<
+ ReturnType<typeof TaskContextWikiPageRetrieveSchema>,
+ Schemas.WikiPage
+> => ({
+ name: 'task-context-wiki-page-retrieve',
+ schema: TaskContextWikiPageRetrieveSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof TaskContextWikiPageRetrieveSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.WikiPage>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/context_layer/agent/pages/`,
+ query: {
+ path: params.path,
+ },
+ })
+ return result
+ },
+})
+
+const TaskContextWikiPageUpdateSchema = () => {
+ const ContextLayerAgentPagesUpdateBody = orvalSchemas.ContextLayerAgentPagesUpdateBody()
+ return ContextLayerAgentPagesUpdateBody
+}
+
+const taskContextWikiPageUpdate = (): ToolBase<
+ ReturnType<typeof TaskContextWikiPageUpdateSchema>,
+ Schemas.ContextLayerStatus
+> => ({
+ name: 'task-context-wiki-page-update',
+ schema: TaskContextWikiPageUpdateSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof TaskContextWikiPageUpdateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.path !== undefined) {
+ body['path'] = params.path
+ }
+ if (params.content !== undefined) {
+ body['content'] = params.content
+ }
+ if (params.base_head !== undefined) {
+ body['base_head'] = params.base_head
+ }
+ const result = await context.api.request<Schemas.ContextLayerStatus>({
+ method: 'PUT',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/context_layer/agent/pages/`,
+ body,
+ })
+ return result
+ },
+})
+
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'context-wiki-channel-resolve': contextWikiChannelResolve,
'context-wiki-page-retrieve': contextWikiPageRetrieve,
@@ -163,4 +240,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'loop-context-wiki-channel-resolve': loopContextWikiChannelResolve,
'loop-context-wiki-page-retrieve': loopContextWikiPageRetrieve,
'loop-context-wiki-page-update': loopContextWikiPageUpdate,
+ 'task-context-wiki-channel-resolve': taskContextWikiChannelResolve,
+ 'task-context-wiki-page-retrieve': taskContextWikiPageRetrieve,
+ 'task-context-wiki-page-update': taskContextWikiPageUpdate,
}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 603383ad094d..cead19f81168 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -477,6 +477,7 @@ describe('OAUTH_SCOPES_SUPPORTED completeness', () => {
// (mirrors INTERNAL_API_SCOPE_OBJECTS in posthog/scopes.py). Tools may require them, but
// they are intentionally absent from OAUTH_SCOPES_SUPPORTED, so exclude them here.
const SERVER_MINT_ONLY_SCOPES = new Set([
+ 'context_layer_internal:write',
'internal_run:read',
'loop_context_internal:write',
'signal_scout_internal:read',
@@ -535,6 +536,7 @@ describe('server-minted scope matching', () => {
// dropping that rule hid `scout-members-list` from every scout's toolset and left reports
// with nobody to route to. Django authorizes the same tokens with the rule applied.
it.each([
+ 'context_layer_internal',
'internal_run',
'loop_context_internal',
'mcp_builtin_agent',
@@ -747,15 +749,22 @@ describe('Tool Filtering - Scoped Teams', () => {
})
it('keeps project-scoped tools visible when scopedTeams is non-empty', () => {
- const tools = getToolsForFeatures({ scopedTeams: [42] })
+ const tools = getToolsForFeatures({ scopedTeams: [42], featureFlags: { 'context-layer': true } })
expect(tools).toContain('dashboard-get')
expect(tools).toContain('feature-flag-get-all')
+ expect(tools).not.toContain('context-wiki-channel-resolve')
+ expect(tools).not.toContain('context-wiki-page-retrieve')
+ expect(tools).not.toContain('context-wiki-page-update')
+ expect(tools).toContain('task-context-wiki-channel-resolve')
+ expect(tools).toContain('task-context-wiki-page-retrieve')
+ expect(tools).toContain('task-context-wiki-page-update')
})
it('keeps org-scope tools visible when scopedTeams is empty (unscoped token)', () => {
- const tools = getToolsForFeatures({ scopedTeams: [] })
+ const tools = getToolsForFeatures({ scopedTeams: [], featureFlags: { 'context-layer': true } })
expect(tools).toContain('roles-list')
expect(tools).toContain('organization-get')
+ expect(tools).toContain('context-wiki-page-update')
})
it('keeps org-scope tools visible when scopedTeams is undefined', () => {
@@ -991,9 +1000,14 @@ describe('Tool Filtering - Feature Flags', () => {
}
})
- it('keeps public context wiki tools separate from internal loop tools', () => {
+ it('keeps human, task, and loop context wiki tools on separate scopes', () => {
const definitions = getToolDefinitions()
expect(definitions['context-wiki-page-update']!.required_scopes).toEqual(['organization:write'])
+ expect(definitions['task-context-wiki-page-update']!.required_scopes).toEqual([
+ 'task:write',
+ 'internal_run:read',
+ 'context_layer_internal:write',
+ ])
expect(definitions['loop-context-wiki-page-update']!.required_scopes).toEqual([
'task:write',
'loop_context_internal:write',
@@ -1005,6 +1019,22 @@ describe('Tool Filtering - Feature Flags', () => {
expect(definitions['loop-channel-instructions-update']!.feature_flag).toBeUndefined()
})
+ it('shows task context writes only to write-enabled task credentials', async () => {
+ const options = { featureFlags: { 'context-layer': true } }
+ const readOnlyTools = await getToolsFromContext(
+ createMockContext(['task:read', 'task:write', 'internal_run:read']),
+ options
+ )
+ const writeTools = await getToolsFromContext(
+ createMockContext(['task:read', 'task:write', 'internal_run:read', 'context_layer_internal:write']),
+ options
+ )
+
+ expect(readOnlyTools.map((tool) => tool.name)).toContain('task-context-wiki-page-retrieve')
+ expect(readOnlyTools.map((tool) => tool.name)).not.toContain('task-context-wiki-page-update')
+ expect(writeTools.map((tool) => tool.name)).toContain('task-context-wiki-page-update')
+ })
+
// Exercise the real predicate (toolPassesFlagGate) over hand-rolled entries
// so we can cover variant / behavior / missing-flag matrices without
// having to register fake tools into the global tool registry.