: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(context-layer): route wiki tools through agent API (#92806)
Dylan Martin4deac6c3fde9
diff --git a/products/context_layer/backend/presentation/views.py b/products/context_layer/backend/presentation/views.pyindex 72bced5d4c55..430965f7718d 100644--- a/products/context_layer/backend/presentation/views.py+++ b/products/context_layer/backend/presentation/views.py@@ -79,57 +79,65 @@ def _read_page(organization_id, request: Request) -> Response: # noqa: ANN001return Response(WikiPageSerializer(wiki_page).data)-def _assert_loop_write_in_scope(organization_id, request: Request, path: str, content: str) -> None: # noqa: ANN001- """A loop run may only write the context page it was configured to maintain.+def _assert_run_write_in_scope(organization_id, team_id, request: Request, path: str, content: str) -> None: # noqa: ANN001+ """A sandbox run may only write the context page for its channel.Reads stay open, because the wiki is organization-wide reference materialevery agent is meant to draw on. Writes cannot be: the agent route's scope- override accepts a `task:write` token, so without this a loop steered by+ override accepts server-minted task tokens, so without this a run steered byinjected text could rewrite AGENTS.md, and with it the instructions every- agent in the organization starts from. Mirrors the target check the legacy- channel-instructions endpoint already makes.+ agent in the organization starts from. Ordinary tasks bind to their owning+ channel; loops bind to the context target in their frozen configuration.- A no-op for any caller without the loop provenance scope, so it is safe to- run on every write and both routes stay bound by it.+ A no-op for callers without run provenance, so direct human/API writes keep+ the organization-wide editing behavior of the non-agent route."""access_token = get_oauth_access_token(request)token_scopes = set((getattr(access_token, "scope", "") or "").split())- if LOOP_CONTEXT_INTERNAL_SCOPE not in token_scopes:+ is_loop_run = LOOP_CONTEXT_INTERNAL_SCOPE in token_scopes+ is_ordinary_run = INTERNAL_RUN_SCOPE in token_scopes+ if not is_loop_run and not is_ordinary_run:return- denied = PermissionDenied("This loop can update only the context page configured for this run.")+ denied = PermissionDenied("This run can update only the context page for its channel.")sandbox_task_id = getattr(access_token, "sandbox_task_id", None)- if sandbox_task_id is None:+ if sandbox_task_id is None or team_id is None:raise denied- # Both sides resolve inside this organization's own wiki index, so a run- # cannot reach another organization's pages even by naming its channel.- configured_channel_id = tasks_facade.loop_context_channel_id_for_task(sandbox_task_id)+ configured_channel_id = (+ tasks_facade.loop_context_channel_id_for_task(sandbox_task_id)+ if is_loop_run+ else tasks_facade.task_channel_id(sandbox_task_id, team_id)+ )if configured_channel_id is None:raise denied+ configured_channel_id = str(configured_channel_id)++ # 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:returnif requested_channel_id is not None:raise deniedtry:- _assert_loop_may_create_channel_page(organization_id, configured_channel_id, path, content, denied)+ _assert_run_may_create_channel_page(organization_id, configured_channel_id, path, content, denied)except facade.ContextLayerStoreError as error:# A vanished channel or wiki mid-write reads as out of scope, not a 500.raise denied from error-def _assert_loop_may_create_channel_page(+def _assert_run_may_create_channel_page(organization_id, # noqa: ANN001channel_id: str,path: str,content: str,denied: PermissionDenied,) -> None:- """A loop may create its channel's page when the channel truly has none.+ """A sandbox run may create its channel's page when the channel truly has none.Channels created after wiki enablement never went through the one-time- import, so their loops would otherwise fall back to legacy channel+ import, so their runs would otherwise fall back to legacy channelinstructions forever. Everything is pinned: the channel must have no page,the path must be exactly the one resolution proposed, nothing may alreadyexist there, and the content's frontmatter must claim the configured@@ -161,11 +169,15 @@ def _read_channel_page(organization_id, channel_id: str, *, propose_on_miss: booreturn Response(ChannelWikiPageSerializer({"path": path}).data)-def _write_page(organization_id, request: Request) -> Response: # noqa: ANN001+def _write_page(organization_id, request: Request, *, team_id=None) -> Response: # noqa: ANN001serializer = WikiPageWriteSerializer(data=request.data)serializer.is_valid(raise_exception=True)- _assert_loop_write_in_scope(- organization_id, request, serializer.validated_data["path"], serializer.validated_data["content"]+ _assert_run_write_in_scope(+ organization_id,+ team_id,+ request,+ serializer.validated_data["path"],+ serializer.validated_data["content"],)_assert_run_commit_cap(request)user = request.user@@ -445,7 +457,8 @@ class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# 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.+ # 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),@@ -513,7 +526,7 @@ class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):200: ContextLayerStatusSerializer,400: LintErrorSerializer,403: OpenApiResponse(- description="The wiki is unavailable, or a loop run targeted a page outside its own context."+ description="The wiki is unavailable, or a sandbox run targeted a page outside its channel."),409: HeadConflictSerializer,},@@ -521,7 +534,7 @@ class ContextLayerAgentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)@page.mapping.putdef update_page(self, request: Request, **kwargs) -> Response:- return _write_page(self.organization.id, request)+ return _write_page(self.organization.id, request, team_id=self.team_id)@extend_schema(request=CommitBundleSerializer,diff --git a/products/context_layer/backend/test/test_api.py b/products/context_layer/backend/test/test_api.pyindex 3f161cca68e2..564d2666263d 100644--- a/products/context_layer/backend/test/test_api.py+++ b/products/context_layer/backend/test/test_api.py@@ -455,6 +455,50 @@ class TestContextLayerAPI(APIBaseTest):assert proposed.status_code == 200, proposed.contentassert 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:+ 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+ task = apps.get_model("tasks", "Task").objects.create(+ team=self.team,+ created_by=self.user,+ title="Build the space context",+ channel_id=channel.id,+ )+ token = self._bearer(+ "organization:read organization:write task:write internal_run:read",+ scoped_teams=[self.team.id],+ sandbox_task_id=task.id,+ )+ self.client.logout()++ proposed = self.client.get(+ f"{self.agent_url}/channel-pages/{channel.id}/",+ HTTP_AUTHORIZATION=f"Bearer {token}",+ )+ assert proposed.status_code == 200, proposed.content+ assert proposed.json() == {"path": f"projects/{self.team.id}/spaces/growth.md", "exists": False}++ created = self.client.put(+ f"{self.agent_url}/pages/",+ {+ "path": proposed.json()["path"],+ "content": f"---\nteam_id: {self.team.id}\nchannel_id: {channel.id}\nsummary: Growth channel context.\nstatus: active\n---\n\n# Growth (project {self.team.id})\n",+ },+ format="json",+ HTTP_AUTHORIZATION=f"Bearer {token}",+ )+ assert created.status_code == 200, created.content++ outside_channel = self.client.put(+ f"{self.agent_url}/pages/",+ {"path": "AGENTS.md", "content": "# Owned\n", "base_head": created.json()["head_sha"]},+ format="json",+ HTTP_AUTHORIZATION=f"Bearer {token}",+ )+ assert outside_channel.status_code == 403, outside_channel.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):@@ -546,8 +590,13 @@ class TestContextLayerAPI(APIBaseTest):assert response.status_code == 403, response.contentdef test_run_page_writes_share_the_daily_landing_cap(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 Nonehead = self._enable()- task = apps.get_model("tasks", "Task").objects.create(team=self.team, created_by=self.user, title="agent work")+ task = apps.get_model("tasks", "Task").objects.create(+ 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",scoped_teams=[self.team.id],@@ -555,18 +604,22 @@ class TestContextLayerAPI(APIBaseTest):)self.client.logout()- def write(path: str, base_head: str):+ def write(base_head: str):return self.client.put(f"{self.agent_url}/pages/",- {"path": path, "content": _page(path), "base_head": base_head},+ {+ "path": f"projects/{self.team.id}/spaces/growth.md",+ "content": f"---\nteam_id: {self.team.id}\nchannel_id: {channel.id}\nsummary: Growth channel context.\nstatus: active\n---\n\n# Growth\n",+ "base_head": base_head,+ },format="json",HTTP_AUTHORIZATION=f"Bearer {token}",)with patch.object(views, "RUN_COMMITS_PER_DAY_CAP", 1):- first = write("areas/first.md", head)+ first = write(head)assert first.status_code == 200, first.content- capped = write("areas/second.md", first.json()["head_sha"])+ capped = write(first.json()["head_sha"])assert capped.status_code == 429def test_pages_reject_task_scopes_without_run_provenance(self, _flag) -> None:diff --git a/products/context_layer/mcp/tools.yaml b/products/context_layer/mcp/tools.yamlindex 1d65e58c5ebe..6cf7ec4150d2 100644--- a/products/context_layer/mcp/tools.yaml+++ b/products/context_layer/mcp/tools.yaml@@ -12,6 +12,9 @@ tools:context-layer-agent-commits-create:operation: context_layer_agent_commits_createenabled: false+ context-layer-channel-pages-retrieve:+ operation: context_layer_channel_pages_retrieve+ enabled: falsecontext-layer-commits-create:operation: context_layer_commits_createenabled: false@@ -27,6 +30,12 @@ tools:context-layer-export-retrieve:operation: context_layer_export_retrieveenabled: false+ context-layer-pages-retrieve:+ operation: context_layer_pages_retrieve+ enabled: false+ context-layer-pages-update:+ operation: context_layer_pages_update+ enabled: falsecontext-layer-status-retrieve:operation: context_layer_status_retrieveenabled: false@@ -37,7 +46,7 @@ tools:operation: context_layer_wiki_report_retrieveenabled: falsecontext-wiki-channel-resolve:- operation: context_layer_channel_pages_retrieve+ operation: context_layer_agent_channel_pages_retrieveenabled: truescopes:- organization:read@@ -51,7 +60,7 @@ tools:with context-wiki-page-retrieve and context-wiki-page-update. Do not derive a path from the channel name.feature_flag: context-layercontext-wiki-page-retrieve:- operation: context_layer_pages_retrieve+ operation: context_layer_agent_pages_retrieveenabled: truescopes:- organization:read@@ -65,7 +74,7 @@ tools:pass that head_sha as base_head when updating the page.feature_flag: context-layercontext-wiki-page-update:- operation: context_layer_pages_update+ operation: context_layer_agent_pages_updateenabled: truescopes:- organization:writediff --git a/services/mcp/src/generated/context_layer/api.ts b/services/mcp/src/generated/context_layer/api.tsindex 85ef514b6244..cfec8d604cf5 100644--- a/services/mcp/src/generated/context_layer/api.ts+++ b/services/mcp/src/generated/context_layer/api.ts@@ -3,77 +3,11 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 6 enabled ops+ * PostHog API - MCP 3 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'-/**- * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.- * @summary Resolve a channel's wiki page- */-export const ContextLayerChannelPagesRetrieveParams = /* @__PURE__ */ zod.object({- channel_id: zod.string(),- organization_id: zod- .string()- .describe(- "ID of the organization you're trying to access. To find the ID of the organization, make a call to \/api\/organizations\/."- ),-})--/**- * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.- * @summary Read a wiki page- */-export const ContextLayerPagesRetrieveParams = /* @__PURE__ */ zod.object({- organization_id: zod- .string()- .describe(- "ID of the organization you're trying to access. To find the ID of the organization, make a call to \/api\/organizations\/."- ),-})--export const ContextLayerPagesRetrieveQueryParams = /* @__PURE__ */ zod.object({- path: zod.string().describe('Repo-relative Markdown path of the page to read.'),-})--/**- * The organization's context wiki: a git repo of Markdown pages hosted by PostHog.- * @summary Create or replace a wiki page- */-export const ContextLayerPagesUpdateParams = /* @__PURE__ */ zod.object({- organization_id: zod- .string()- .describe(- "ID of the organization you're trying to access. To find the ID of the organization, make a call to \/api\/organizations\/."- ),-})--export const contextLayerPagesUpdateBodyPathMax = 512--export const contextLayerPagesUpdateBodyContentMax = 1000000--export const ContextLayerPagesUpdateBody = /* @__PURE__ */ zod- .object({- path: zod- .string()- .max(contextLayerPagesUpdateBodyPathMax)- .describe(- "Repo-relative Markdown path inside the wiki's structure, for example `projects\/12\/spaces\/general.md`."- ),- content: zod- .string()- .max(contextLayerPagesUpdateBodyContentMax)- .describe('The complete Markdown content for the page.'),- base_head: zod- .string()- .nullish()- .describe(- 'Optimistic-concurrency guard: the head sha the edit is based on. A moved head is rejected with 409 and the current head; omit to write unguarded.'- ),- })- .describe('Request body for creating or replacing one wiki page.')-/*** The channel's page path. When the channel has no page yet, responds with the canonical path to create it at and `exists: false`.* @summary Resolve a channel's wiki pagediff --git a/services/mcp/src/tools/generated/context_layer.ts b/services/mcp/src/tools/generated/context_layer.tsindex db8d38e796d0..00cca66af72b 100644--- a/services/mcp/src/tools/generated/context_layer.ts+++ b/services/mcp/src/tools/generated/context_layer.ts@@ -6,37 +6,34 @@ import {ContextLayerAgentChannelPagesRetrieveParams,ContextLayerAgentPagesRetrieveQueryParams,ContextLayerAgentPagesUpdateBody,- ContextLayerChannelPagesRetrieveParams,- ContextLayerPagesRetrieveQueryParams,- ContextLayerPagesUpdateBody,} from '@/generated/context_layer/api'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'-const ContextWikiChannelResolveSchema = ContextLayerChannelPagesRetrieveParams.omit({ organization_id: true })+const ContextWikiChannelResolveSchema = ContextLayerAgentChannelPagesRetrieveParams.omit({ project_id: true })const contextWikiChannelResolve = (): ToolBase<typeof ContextWikiChannelResolveSchema, Schemas.ChannelWikiPage> => ({name: 'context-wiki-channel-resolve',schema: ContextWikiChannelResolveSchema,handler: async (context: Context, params: z.infer<typeof ContextWikiChannelResolveSchema>) => {- const orgId = await context.stateManager.getOrgID()+ const projectId = await context.stateManager.getProjectId()const result = await context.api.request<Schemas.ChannelWikiPage>({method: 'GET',- path: `/api/organizations/${encodeURIComponent(String(orgId))}/context_layer/channel-pages/${encodeURIComponent(String(params.channel_id))}/`,+ path: `/api/projects/${encodeURIComponent(String(projectId))}/context_layer/agent/channel-pages/${encodeURIComponent(String(params.channel_id))}/`,})return result},})-const ContextWikiPageRetrieveSchema = ContextLayerPagesRetrieveQueryParams+const ContextWikiPageRetrieveSchema = ContextLayerAgentPagesRetrieveQueryParamsconst contextWikiPageRetrieve = (): ToolBase<typeof ContextWikiPageRetrieveSchema, Schemas.WikiPage> => ({name: 'context-wiki-page-retrieve',schema: ContextWikiPageRetrieveSchema,handler: async (context: Context, params: z.infer<typeof ContextWikiPageRetrieveSchema>) => {- const orgId = await context.stateManager.getOrgID()+ const projectId = await context.stateManager.getProjectId()const result = await context.api.request<Schemas.WikiPage>({method: 'GET',- path: `/api/organizations/${encodeURIComponent(String(orgId))}/context_layer/pages/`,+ path: `/api/projects/${encodeURIComponent(String(projectId))}/context_layer/agent/pages/`,query: {path: params.path,},@@ -45,13 +42,13 @@ const contextWikiPageRetrieve = (): ToolBase<typeof ContextWikiPageRetrieveSchem},})-const ContextWikiPageUpdateSchema = ContextLayerPagesUpdateBody+const ContextWikiPageUpdateSchema = ContextLayerAgentPagesUpdateBodyconst contextWikiPageUpdate = (): ToolBase<typeof ContextWikiPageUpdateSchema, Schemas.ContextLayerStatus> => ({name: 'context-wiki-page-update',schema: ContextWikiPageUpdateSchema,handler: async (context: Context, params: z.infer<typeof ContextWikiPageUpdateSchema>) => {- const orgId = await context.stateManager.getOrgID()+ const projectId = await context.stateManager.getProjectId()const body: Record<string, unknown> = {}if (params.path !== undefined) {body['path'] = params.path@@ -64,7 +61,7 @@ const contextWikiPageUpdate = (): ToolBase<typeof ContextWikiPageUpdateSchema, S}const result = await context.api.request<Schemas.ContextLayerStatus>({method: 'PUT',- path: `/api/organizations/${encodeURIComponent(String(orgId))}/context_layer/pages/`,+ path: `/api/projects/${encodeURIComponent(String(projectId))}/context_layer/agent/pages/`,body,})return resultdiff --git a/services/mcp/tests/unit/context-wiki-generated.test.ts b/services/mcp/tests/unit/context-wiki-generated.test.tsnew file mode 100644index 000000000000..6b510a75a145--- /dev/null+++ b/services/mcp/tests/unit/context-wiki-generated.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it, vi } from 'vitest'++import { ApiClient } from '@/api/client'+import { MemoryCache } from '@/lib/cache/MemoryCache'+import { SessionManager } from '@/lib/SessionManager'+import { StateManager } from '@/lib/StateManager'+import { GENERATED_TOOLS } from '@/tools/generated/context_layer'+import type { Context, State } from '@/tools/types'++function createMockContext(): Context {+ const api = new ApiClient({ apiToken: 'test-token', baseUrl: 'https://us.posthog.test' })+ const cache = new MemoryCache<State>('context-wiki-generated-test')+ const stateManager = new StateManager(cache, api)+ vi.spyOn(stateManager, 'getProjectId').mockResolvedValue('42')+ vi.spyOn(stateManager, 'getOrgID').mockRejectedValue(new Error('organization route must not be used'))++ return {+ api,+ stateManager,+ env: {+ MCP_APPS_BASE_URL: undefined,+ POSTHOG_ANALYTICS_API_KEY: undefined,+ POSTHOG_ANALYTICS_HOST: undefined,+ POSTHOG_API_BASE_URL: undefined,+ POSTHOG_PUBLIC_URL: undefined,+ POSTHOG_MCP_APPS_ANALYTICS_BASE_URL: undefined,+ POSTHOG_UI_APPS_TOKEN: undefined,+ },+ sessionManager: new SessionManager(cache),+ cache,+ getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},+ }+}++describe('context wiki generated tools', () => {+ it('uses the project-nested route for ordinary task tokens', async () => {+ const context = createMockContext()+ const request = vi.spyOn(context.api, 'request').mockResolvedValue({+ path: 'projects/42/spaces/activation-research.md',+ exists: false,+ })++ await GENERATED_TOOLS['context-wiki-channel-resolve']!().handler(context, {+ channel_id: 'channel-id',+ })++ expect(request).toHaveBeenCalledWith({+ method: 'GET',+ path: '/api/projects/42/context_layer/agent/channel-pages/channel-id/',+ })+ })+})