: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(tasks): expose channel instructions update MCP tool (#80228)
Shy Alter352ce11d90d5
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex c55368a6a2a1..e7528bbcb23a 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -6090,6 +6090,24 @@ def list_channel_instruction_versions(return [_instructions_to_dto(row) for row in versions]+def task_can_publish_channel_instructions(task_id: str | UUID, team_id: int, channel_id: str | UUID) -> bool:+ task = Task.objects.filter(id=task_id, team_id=team_id).only("origin_product").first()+ if task is None:+ return False+ if task.origin_product != Task.OriginProduct.LOOP:+ return True++ run_state = (+ TaskRun.objects.filter(task_id=task.id, team_id=team_id)+ .order_by("-created_at")+ .values_list("state", flat=True)+ .first()+ )+ context_target = ((run_state or {}).get("config_snapshot") or {}).get("context_target") or {}+ outputs = context_target.get("outputs") or {}+ return bool(outputs.get("update_context")) and str(context_target.get("channel_id")) == str(channel_id)++def publish_channel_instructions(channel_id: str | UUID,team_id: int,diff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.pyindex 61e31072a492..6f73d9a0c56a 100644--- a/products/tasks/backend/presentation/views/channels_api.py+++ b/products/tasks/backend/presentation/views/channels_api.py@@ -8,6 +8,7 @@ from rest_framework.authentication import SessionAuthenticationfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound, PermissionDenied, ValidationErrorfrom rest_framework.permissions import IsAuthenticated+from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.mixins import validated_request@@ -83,6 +84,13 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):def _user_id(self) -> int | None:return getattr(self.request.user, "id", None)+ @staticmethod+ def _sandbox_task_id(request: Request) -> UUID | None:+ authenticator = request.successful_authenticator+ if not isinstance(authenticator, OAuthAccessTokenAuthentication):+ return None+ return authenticator.access_token.sandbox_task_id+@extend_schema(responses={200: OpenApiResponse(response=ChannelSerializer(many=True), description="List of channels")},summary="List channels",@@ -162,6 +170,12 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@extend_schema(**PUBLISH_INSTRUCTIONS_SCHEMA_KWARGS)@instructions.mapping.putdef publish_instructions(self, request, pk=None, **kwargs):+ sandbox_task_id = self._sandbox_task_id(request)+ if sandbox_task_id is not None and not tasks_facade.task_can_publish_channel_instructions(+ sandbox_task_id, self.team_id, pk+ ):+ raise PermissionDenied("This loop can update only the CONTEXT.md configured for this run.")+serializer = ChannelInstructionsWriteSerializer(data=request.data)serializer.is_valid(raise_exception=True)try:diff --git a/products/tasks/backend/tests/test_channel_extras.py b/products/tasks/backend/tests/test_channel_extras.pyindex 72b3e356cb11..d7c21745ef8d 100644--- a/products/tasks/backend/tests/test_channel_extras.py+++ b/products/tasks/backend/tests/test_channel_extras.py@@ -1,12 +1,18 @@-from uuid import uuid4+from datetime import timedelta+from uuid import UUID, uuid4from posthog.test.base import APIBaseTest+from django.utils import timezone as django_timezone+from rest_framework import status+from rest_framework.test import APIClient+from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.scoping import team_scope+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV-from products.tasks.backend.models import Channel, ChannelStar+from products.tasks.backend.models import Channel, ChannelStar, Task, TaskRunclass ChannelExtrasBaseTest(APIBaseTest):@@ -34,6 +40,65 @@ class TestChannelRetrieve(ChannelExtrasBaseTest):class TestChannelInstructions(ChannelExtrasBaseTest):+ def _sandbox_client(self, task_id: UUID) -> APIClient:+ application = OAuthApplication.objects.create(+ name="Loop sandbox",+ client_id=ARRAY_APP_CLIENT_ID_DEV,+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ algorithm="RS256",+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ user=self.user,+ )+ access_token = OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token="pha_loop_sandbox",+ expires=django_timezone.now() + timedelta(hours=1),+ scope="task:read task:write",+ scoped_teams=[self.team.id],+ sandbox_task_id=task_id,+ )+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")+ return client++ def test_loop_sandbox_can_publish_only_to_its_configured_context(self):+ with team_scope(self.team.id):+ other_channel = Channel.objects.create(team=self.team, name="other", created_by=self.user)+ task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ title="Maintain context",+ origin_product=Task.OriginProduct.LOOP,+ )+ TaskRun.objects.create(+ task=task,+ team=self.team,+ state={+ "config_snapshot": {+ "context_target": {+ "channel_id": str(self.channel.id),+ "outputs": {"update_context": True},+ }+ }+ },+ )++ client = self._sandbox_client(task.id)+ denied = client.put(+ f"/api/projects/{self.team.id}/task_channels/{other_channel.id}/instructions/",+ {"content": "wrong target", "base_version": 0},+ format="json",+ )+ allowed = client.put(+ f"{self.base}/instructions/", {"content": "configured target", "base_version": 0}, format="json"+ )++ assert denied.status_code == status.HTTP_403_FORBIDDEN+ assert allowed.status_code == status.HTTP_200_OK+def test_unpublished_reads_as_blank_version_zero(self):response = self.client.get(f"{self.base}/instructions/")assert response.status_code == status.HTTP_200_OKdiff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex 25102ecf9363..1213bd5a940f 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -44,6 +44,25 @@ tools:param_overrides:id:description: ID of the channel whose instructions to read.+ channel-instructions-update:+ operation: task_channels_instructions_update+ enabled: true+ scopes:+ - task:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: false+ title: Update channel instructions+ description: >+ Publish a complete replacement for a channel's CONTEXT.md. Read the current version with+ channel-instructions-retrieve first. Pass its version as base_version. This guard returns a conflict if+ another update changes the document.+ param_overrides:+ id:+ description: ID of the channel whose instructions to update.+ base_version:+ input_schema: ChannelInstructionsBaseVersionSchemachannel-list:operation: task_channels_listenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 9d461fe60ff7..945faf61cdcb 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1436,6 +1436,20 @@"readOnlyHint": true}},+ "channel-instructions-update": {+ "description": "Publish a complete replacement for a channel's CONTEXT.md. Read the current version with channel-instructions-retrieve first. Pass its version as base_version. This guard returns a conflict if another update changes the document.",+ "category": "Tasks",+ "feature": "tasks",+ "summary": "Update channel instructions",+ "title": "Update channel instructions",+ "required_scopes": ["task:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"channel-list": {"description": "List the project's channels (public channels plus the requester's personal #me channel). Use this to resolve a channel id from its name before creating or listing canvases or reading instructions.","category": "Tasks",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 7a70298e51b8..97125622c376 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1451,6 +1451,20 @@"readOnlyHint": true}},+ "channel-instructions-update": {+ "description": "Publish a complete replacement for a channel's CONTEXT.md. Read the current version with channel-instructions-retrieve first. Pass its version as base_version. This guard returns a conflict if another update changes the document.",+ "category": "Tasks",+ "feature": "tasks",+ "summary": "Update channel instructions",+ "title": "Update channel instructions",+ "required_scopes": ["task:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"channel-list": {"description": "List the project's channels (public channels plus the requester's personal #me channel). Use this to resolve a channel id from its name before creating or listing canvases or reading instructions.","category": "Tasks",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 367aca918410..de42d21e95d1 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -49,6 +49,12 @@},"required": ["name", "url"]},+ "ChannelInstructionsBaseVersionSchema": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991,+ "description": "Version returned by channel-instructions-retrieve. Use 0 when the channel has no instructions."+ },"DebugMcpUiAppsSchema": {"type": "object","properties": {diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex d661584066e0..d5ebbe468362 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 18 enabled ops+ * PostHog API - MCP 19 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -802,6 +802,39 @@ export const TaskChannelsInstructionsRetrieveParams = /* @__PURE__ */ zod.object),})+/**+ * Publish a new version of the channel's CONTEXT.md instructions. Pass base_version (the version you read) so a concurrent edit is rejected with 409 instead of overwritten.+ * @summary Publish channel instructions+ */+export const TaskChannelsInstructionsUpdateParams = /* @__PURE__ */ zod.object({+ id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const taskChannelsInstructionsUpdateBodyContentMax = 100000++export const taskChannelsInstructionsUpdateBodyBaseVersionMin = 0++export const TaskChannelsInstructionsUpdateBody = /* @__PURE__ */ zod+ .object({+ content: zod+ .string()+ .max(taskChannelsInstructionsUpdateBodyContentMax)+ .describe('The complete markdown instructions (CONTEXT.md) for the channel.'),+ base_version: zod+ .number()+ .min(taskChannelsInstructionsUpdateBodyBaseVersionMin)+ .nullish()+ .describe(+ 'Optimistic-concurrency guard: the version the edit is based on (0 for a channel with no instructions yet). A stale base is rejected with 409; omit to publish unguarded.'+ ),+ })+ .describe('Request body for publishing a new instructions version.')+/*** Get a list of tasks for the current project, with optional filtering by origin product, stage, organization, repository, and created_by.* @summary List tasksdiff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 0935db45664b..5f66b9522c94 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -4,6 +4,13 @@ import { z } from 'zod'// script, and both modules are pure constants/functions — no `.md` imports to choke on.import { normalizeParamAliases } from '../tools/cast-helpers'+export const ChannelInstructionsBaseVersionSchema = z+ .number()+ .int()+ .min(0)+ .max(9007199254740991)+ .describe('Version returned by channel-instructions-retrieve. Use 0 when the channel has no instructions.')+export const BusinessKnowledgeUrlSourceCreateSchema = z.object({name: z.string()diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.tsindex 1dab12776656..7a787b71135d 100644--- a/services/mcp/src/tools/generated/tasks.ts+++ b/services/mcp/src/tools/generated/tasks.ts@@ -16,6 +16,8 @@ import {LoopsRunsRetrieveQueryParams,TaskChannelsCreateBody,TaskChannelsInstructionsRetrieveParams,+ TaskChannelsInstructionsUpdateBody,+ TaskChannelsInstructionsUpdateParams,TaskChannelsListQueryParams,TaskChannelsRetrieveParams,TasksCreateBody,@@ -27,6 +29,7 @@ import {TasksRunsSessionLogsRetrieveParams,TasksRunsSessionLogsRetrieveQueryParams,} from '@/generated/tasks/api'+import { ChannelInstructionsBaseVersionSchema } from '@/schema/tool-inputs'import { getConfirmedActionRuntime } from '@/tools/confirmed-action-registry'import {executeConfirmedAction,@@ -76,6 +79,39 @@ const channelInstructionsRetrieve = (): ToolBase<},})+const ChannelInstructionsUpdateSchema = TaskChannelsInstructionsUpdateParams.omit({ project_id: true })+ .extend(TaskChannelsInstructionsUpdateBody.shape)+ .extend({+ id: TaskChannelsInstructionsUpdateParams.shape['id'].describe(+ 'ID of the channel whose instructions to update.'+ ),+ base_version: ChannelInstructionsBaseVersionSchema,+ })++const channelInstructionsUpdate = (): ToolBase<+ typeof ChannelInstructionsUpdateSchema,+ Schemas.ChannelInstructionsDTO+> => ({+ name: 'channel-instructions-update',+ schema: ChannelInstructionsUpdateSchema,+ handler: async (context: Context, params: z.infer<typeof ChannelInstructionsUpdateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.content !== undefined) {+ body['content'] = params.content+ }+ if (params.base_version !== undefined) {+ body['base_version'] = params.base_version+ }+ const result = await context.api.request<Schemas.ChannelInstructionsDTO>({+ method: 'PUT',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/task_channels/${encodeURIComponent(String(params.id))}/instructions/`,+ body,+ })+ return result+ },+})+const ChannelListSchema = TaskChannelsListQueryParamsconst channelList = (): ToolBase<typeof ChannelListSchema, Schemas.PaginatedChannelDTOList> => ({@@ -642,6 +678,7 @@ const tasksRunsSessionLogsRetrieve = (): ToolBase<typeof TasksRunsSessionLogsRetexport const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'channel-create': channelCreate,'channel-instructions-retrieve': channelInstructionsRetrieve,+ 'channel-instructions-update': channelInstructionsUpdate,'channel-list': channelList,'channel-retrieve': channelRetrieve,'loops-create-prepare': loopsCreatePrepare,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/channel-instructions-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/channel-instructions-update.jsonnew file mode 100644index 000000000000..1b49d08564ce--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/channel-instructions-update.json@@ -0,0 +1,22 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "base_version": {+ "description": "Version returned by channel-instructions-retrieve. Use 0 when the channel has no instructions.",+ "maximum": 9007199254740991,+ "minimum": 0,+ "type": "integer"+ },+ "content": {+ "description": "The complete markdown instructions (CONTEXT.md) for the channel.",+ "maxLength": 100000,+ "type": "string"+ },+ "id": {+ "description": "ID of the channel whose instructions to update.",+ "type": "string"+ }+ },+ "required": ["id", "content", "base_version"],+ "type": "object"+}