: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
feat(file-system): add versioned instructions for desktop folders (#61494)
Raquel Smithdb2fbbeeaed9
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex e3e5a37f493c..8cae00e3edaa 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -133,6 +133,7 @@ rules:|TeamSessionSummariesConfig|TeamWorkflowsConfig|FileSystem+ |FileSystemFolderInstructions|GithubCommentMapping|GitHubSyncConfig|GitHubSyncPlan@@ -368,6 +369,7 @@ rules:|TeamSessionSummariesConfig|TeamWorkflowsConfig|FileSystem+ |FileSystemFolderInstructions|GithubCommentMapping|GitHubSyncConfig|GitHubSyncPlandiff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 165badce6f2d..73ea66217849 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -2228,6 +2228,68 @@ export interface PatchedFileSystemApi {readonly last_viewed_at?: string | null}+export interface FolderInstructionsApi {+ /** Unique identifier for this instructions version. */+ readonly id: string+ /** Markdown instructions describing the contents of the folder. */+ readonly content: string+ /** Monotonically increasing version number, starting at 1. */+ readonly version: number+ /** Whether this is the current (latest) version for the folder. */+ readonly is_latest: boolean+ /** User who published this version. */+ readonly created_by: UserBasicApi+ /** When this version was published. */+ readonly created_at: string+ /** When this version row was last modified. */+ readonly updated_at: string+}++export interface FolderInstructionsPublishApi {+ /** Full markdown instructions to publish as a new version for the folder. */+ content: string+ /**+ * Latest version you are editing from, for optimistic concurrency. If provided and the folder's instructions have changed since, the request fails with 409. Use 0 when no instructions exist yet.+ * @minimum 0+ */+ base_version?: number+}++export interface PatchedFolderInstructionsPublishApi {+ /** Full markdown instructions to publish as a new version for the folder. */+ content?: string+ /**+ * Latest version you are editing from, for optimistic concurrency. If provided and the folder's instructions have changed since, the request fails with 409. Use 0 when no instructions exist yet.+ * @minimum 0+ */+ base_version?: number+}++/**+ * Version-history entry: metadata only, with the markdown content omitted.+ */+export interface FolderInstructionsVersionApi {+ /** Unique identifier for this instructions version. */+ readonly id: string+ /** Monotonically increasing version number, starting at 1. */+ readonly version: number+ /** Whether this is the current (latest) version for the folder. */+ readonly is_latest: boolean+ /** User who published this version. */+ readonly created_by: UserBasicApi+ /** When this version was published. */+ readonly created_at: string+}++export interface PaginatedFolderInstructionsVersionListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: FolderInstructionsVersionApi[]+}+export interface FileSystemShortcutApi {readonly id: string/** Display path of the shortcut in the sidebar. */@@ -3557,6 +3619,21 @@ export type DesktopFileSystemListParams = {search?: string}+export type DesktopFileSystemInstructionsVersionsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * A search term.+ */+ search?: string+}+export type DesktopFileSystemShortcutListParams = {/*** Number of results to return per page.diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex 28fe9dc088d6..3c49e61627e7 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -14,6 +14,7 @@ import type {CIMDVerificationTokenApi,CIMDVerificationTokenWithValueApi,CimdVerificationTokensListParams,+ DesktopFileSystemInstructionsVersionsListParams,DesktopFileSystemListParams,DesktopFileSystemShortcutListParams,DesktopPersistedFolderListParams,@@ -26,6 +27,8 @@ import type {FileSystemShortcutApi,FileSystemShortcutListParams,FileSystemShortcutReorderApi,+ FolderInstructionsApi,+ FolderInstructionsPublishApi,GitHubBranchesResponseApi,GitHubReposRefreshResponseApi,GitHubReposResponseApi,@@ -41,6 +44,7 @@ import type {PaginatedExportedAssetListApi,PaginatedFileSystemListApi,PaginatedFileSystemShortcutListApi,+ PaginatedFolderInstructionsVersionListApi,PaginatedOrganizationDomainListApi,PaginatedOrganizationInviteListApi,PaginatedOrganizationOAuthApplicationListApi,@@ -54,6 +58,7 @@ import type {PatchedEnterprisePropertyDefinitionApi,PatchedFileSystemApi,PatchedFileSystemShortcutApi,+ PatchedFolderInstructionsPublishApi,PatchedOrganizationDomainApi,PatchedPersistedFolderApi,PatchedProjectBackwardCompatApi,@@ -1064,6 +1069,8 @@ export const getDesktopFileSystemListUrl = (projectId: string, params?: DesktopF/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemList = async (projectId: string,@@ -1083,6 +1090,8 @@ export const getDesktopFileSystemCreateUrl = (projectId: string) => {/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemCreate = async (projectId: string,@@ -1104,6 +1113,8 @@ export const getDesktopFileSystemRetrieveUrl = (projectId: string, id: string) =/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemRetrieve = async (projectId: string,@@ -1123,6 +1134,8 @@ export const getDesktopFileSystemUpdateUrl = (projectId: string, id: string) =>/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemUpdate = async (projectId: string,@@ -1145,6 +1158,8 @@ export const getDesktopFileSystemPartialUpdateUrl = (projectId: string, id: stri/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemPartialUpdate = async (projectId: string,@@ -1167,6 +1182,8 @@ export const getDesktopFileSystemDestroyUrl = (projectId: string, id: string) =>/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {return apiMutator<void>(getDesktopFileSystemDestroyUrl(projectId, id), {@@ -1196,6 +1213,122 @@ export const desktopFileSystemCountCreate = async (})}+export const getDesktopFileSystemInstructionsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/desktop_file_system/${id}/instructions/`+}++/**+ * Return the latest non-deleted instructions for this folder.+ */+export const desktopFileSystemInstructionsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<FolderInstructionsApi> => {+ return apiMutator<FolderInstructionsApi>(getDesktopFileSystemInstructionsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getDesktopFileSystemInstructionsUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/desktop_file_system/${id}/instructions/`+}++/**+ * Publish a new version of the folder's instructions.+ */+export const desktopFileSystemInstructionsUpdate = async (+ projectId: string,+ id: string,+ folderInstructionsPublishApi: FolderInstructionsPublishApi,+ options?: RequestInit+): Promise<FolderInstructionsApi> => {+ return apiMutator<FolderInstructionsApi>(getDesktopFileSystemInstructionsUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(folderInstructionsPublishApi),+ })+}++export const getDesktopFileSystemInstructionsPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/desktop_file_system/${id}/instructions/`+}++/**+ * Publish a new version of the folder's instructions.+ */+export const desktopFileSystemInstructionsPartialUpdate = async (+ projectId: string,+ id: string,+ patchedFolderInstructionsPublishApi?: PatchedFolderInstructionsPublishApi,+ options?: RequestInit+): Promise<FolderInstructionsApi> => {+ return apiMutator<FolderInstructionsApi>(getDesktopFileSystemInstructionsPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedFolderInstructionsPublishApi),+ })+}++export const getDesktopFileSystemInstructionsDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/desktop_file_system/${id}/instructions/`+}++/**+ * Soft-delete every version of this folder's instructions.+ */+export const desktopFileSystemInstructionsDestroy = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getDesktopFileSystemInstructionsDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getDesktopFileSystemInstructionsVersionsListUrl = (+ projectId: string,+ id: string,+ params?: DesktopFileSystemInstructionsVersionsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/desktop_file_system/${id}/instructions/versions/?${stringifiedParams}`+ : `/api/projects/${projectId}/desktop_file_system/${id}/instructions/versions/`+}++/**+ * List the version history for this folder's instructions, newest first.+ */+export const desktopFileSystemInstructionsVersionsList = async (+ projectId: string,+ id: string,+ params?: DesktopFileSystemInstructionsVersionsListParams,+ options?: RequestInit+): Promise<PaginatedFolderInstructionsVersionListApi> => {+ return apiMutator<PaginatedFolderInstructionsVersionListApi>(+ getDesktopFileSystemInstructionsVersionsListUrl(projectId, id, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getDesktopFileSystemLinkCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/desktop_file_system/${id}/link/`}@@ -1203,6 +1336,8 @@ export const getDesktopFileSystemLinkCreateUrl = (projectId: string, id: string)/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemLinkCreate = async (projectId: string,@@ -1225,6 +1360,8 @@ export const getDesktopFileSystemMoveCreateUrl = (projectId: string, id: string)/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemMoveCreate = async (projectId: string,@@ -1267,6 +1404,8 @@ export const getDesktopFileSystemLogViewRetrieveUrl = (projectId: string) => {/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemLogViewRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {return apiMutator<void>(getDesktopFileSystemLogViewRetrieveUrl(projectId), {@@ -1282,6 +1421,8 @@ export const getDesktopFileSystemLogViewCreateUrl = (projectId: string) => {/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemLogViewCreate = async (projectId: string,@@ -1303,6 +1444,8 @@ export const getDesktopFileSystemUndoDeleteCreateUrl = (projectId: string) => {/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemUndoDeleteCreate = async (projectId: string,@@ -1324,6 +1467,8 @@ export const getDesktopFileSystemUnfiledRetrieveUrl = (projectId: string) => {/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemUnfiledRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {return apiMutator<void>(getDesktopFileSystemUnfiledRetrieveUrl(projectId), {diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex d2a06d5d767c..c5a3d139396e 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -2414,6 +2414,8 @@ export const DashboardsSharingRefreshCreateBody = /* @__PURE__ */ zod.object({/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemCreateBodyTypeMax = 100@@ -2431,6 +2433,8 @@ export const DesktopFileSystemCreateBody = /* @__PURE__ */ zod.object({/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemUpdateBodyTypeMax = 100@@ -2448,6 +2452,8 @@ export const DesktopFileSystemUpdateBody = /* @__PURE__ */ zod.object({/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemPartialUpdateBodyTypeMax = 100@@ -2478,9 +2484,43 @@ export const DesktopFileSystemCountCreateBody = /* @__PURE__ */ zod.object({shortcut: zod.boolean().nullish(),})+/**+ * Publish a new version of the folder's instructions.+ */+export const desktopFileSystemInstructionsUpdateBodyBaseVersionMin = 0++export const DesktopFileSystemInstructionsUpdateBody = /* @__PURE__ */ zod.object({+ content: zod.string().describe('Full markdown instructions to publish as a new version for the folder.'),+ base_version: zod+ .number()+ .min(desktopFileSystemInstructionsUpdateBodyBaseVersionMin)+ .optional()+ .describe(+ "Latest version you are editing from, for optimistic concurrency. If provided and the folder's instructions have changed since, the request fails with 409. Use 0 when no instructions exist yet."+ ),+})++/**+ * Publish a new version of the folder's instructions.+ */+export const desktopFileSystemInstructionsPartialUpdateBodyBaseVersionMin = 0++export const DesktopFileSystemInstructionsPartialUpdateBody = /* @__PURE__ */ zod.object({+ content: zod.string().optional().describe('Full markdown instructions to publish as a new version for the folder.'),+ base_version: zod+ .number()+ .min(desktopFileSystemInstructionsPartialUpdateBodyBaseVersionMin)+ .optional()+ .describe(+ "Latest version you are editing from, for optimistic concurrency. If provided and the folder's instructions have changed since, the request fails with 409. Use 0 when no instructions exist yet."+ ),+})+/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemLinkCreateBodyTypeMax = 100@@ -2498,6 +2538,8 @@ export const DesktopFileSystemLinkCreateBody = /* @__PURE__ */ zod.object({/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemMoveCreateBodyTypeMax = 100@@ -2531,6 +2573,8 @@ export const DesktopFileSystemCountByPathCreateBody = /* @__PURE__ */ zod.object/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemLogViewCreateBodyTypeMax = 100@@ -2548,6 +2592,8 @@ export const DesktopFileSystemLogViewCreateBody = /* @__PURE__ */ zod.object({/*** The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.*/export const desktopFileSystemUndoDeleteCreateBodyTypeMax = 100diff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.pyindex 2dc5687d49cc..5e83e7e9f5c2 100644--- a/posthog/api/file_system/file_system.py+++ b/posthog/api/file_system/file_system.py@@ -19,6 +19,20 @@ from posthog.api.file_system.deletion import (undo_delete as undo_delete_object,)from posthog.api.file_system.file_system_logging import log_api_file_system_view+from posthog.api.file_system.folder_instructions import (+ FolderInstructionsPublishSerializer,+ FolderInstructionsSerializer,+ FolderInstructionsVersionSerializer,+)+from posthog.api.file_system.folder_instructions_service import (+ FolderInstructionsVersionConflictError,+ FolderInstructionsVersionLimitError,+ delete_folder_instructions,+ ensure_blank_folder_instructions,+ get_folder_instructions_versions,+ get_latest_folder_instructions,+ publish_folder_instructions,+)from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import action@@ -169,6 +183,19 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# Product surface this tree serves. Subclass and override to expose a different surface# (e.g. "desktop") on its own route. The default surface also matches legacy NULL rows.file_system_surface: str = DEFAULT_SURFACE+ # GET /instructions/ and /instructions/versions/ are reads; PUT/PATCH/DELETE on+ # /instructions/ resolve to `publish_instructions` / `delete_instructions` via DRF's+ # method mapping, so they go in the write bucket.+ scope_object_read_actions = ["list", "retrieve", "instructions", "instructions_versions"]+ scope_object_write_actions = [+ "create",+ "update",+ "partial_update",+ "patch",+ "destroy",+ "publish_instructions",+ "delete_instructions",+ ]def _basename_regex(self, value: str) -> str:return rf"(^|(?<!\\)/)([^/]|\\.)*{re.escape(value)}([^/]|\\.)*$"@@ -913,6 +940,117 @@ class DesktopFileSystemViewSet(FileSystemViewSet):"""The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but isscoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++ Adds per-folder, versioned markdown instructions describing the contents of a folder."""file_system_surface = "desktop"++ def perform_create(self, serializer: serializers.BaseSerializer) -> None:+ super().perform_create(serializer)+ instance = cast(FileSystem, serializer.instance)+ self._ensure_blank_instructions_for_created_path(instance)++ def _ensure_blank_instructions_for_created_path(self, instance: FileSystem) -> None:+ """Give every desktop folder along the created path a blank instruction set.++ Covers the created folder itself plus any parent folders auto-created by the serializer,+ so a "channel" always has instructions from the moment it exists.+ """+ segments = split_path(instance.path)+ candidate_paths = [join_path(segments[:depth_index]) for depth_index in range(1, len(segments))]+ if instance.type == "folder":+ candidate_paths.append(instance.path)+ if not candidate_paths:+ return++ folders = self._scope_by_project(FileSystem.objects.filter(path__in=candidate_paths, type="folder"))+ user = self.request.user if isinstance(self.request.user, User) else None+ for folder in folders:+ ensure_blank_folder_instructions(folder, user=user)++ def _get_folder_or_400(self) -> FileSystem | Response:+ instance = self.get_object()+ if instance.type != "folder":+ return Response(+ {"detail": "Instructions can only be attached to folders."},+ status=status.HTTP_400_BAD_REQUEST,+ )+ return instance++ @extend_schema(responses={200: FolderInstructionsSerializer})+ @action(methods=["GET"], detail=True)+ def instructions(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Return the latest non-deleted instructions for this folder."""+ folder = self._get_folder_or_400()+ if isinstance(folder, Response):+ return folder++ latest = get_latest_folder_instructions(folder)+ if latest is None:+ return Response({"detail": "This folder has no instructions."}, status=status.HTTP_404_NOT_FOUND)++ return Response(FolderInstructionsSerializer(latest).data)++ @extend_schema(request=FolderInstructionsPublishSerializer, responses={200: FolderInstructionsSerializer})+ @instructions.mapping.put+ @instructions.mapping.patch+ def publish_instructions(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Publish a new version of the folder's instructions."""+ folder = self._get_folder_or_400()+ if isinstance(folder, Response):+ return folder++ payload = FolderInstructionsPublishSerializer(data=request.data)+ payload.is_valid(raise_exception=True)++ try:+ published = publish_folder_instructions(+ folder,+ content=payload.validated_data["content"],+ user=cast(User, request.user),+ base_version=payload.validated_data.get("base_version"),+ )+ except FolderInstructionsVersionConflictError as err:+ return Response(+ {+ "detail": "The instructions changed since you opened them. Reload the latest version and try again.",+ "current_version": err.current_version,+ },+ status=status.HTTP_409_CONFLICT,+ )+ except FolderInstructionsVersionLimitError as err:+ return Response(+ {"detail": f"This folder has reached the maximum of {err.max_version} instruction versions."},+ status=status.HTTP_400_BAD_REQUEST,+ )++ return Response(FolderInstructionsSerializer(published).data)++ @extend_schema(request=None, responses={204: None})+ @instructions.mapping.delete+ def delete_instructions(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Soft-delete every version of this folder's instructions."""+ folder = self._get_folder_or_400()+ if isinstance(folder, Response):+ return folder++ deleted_count = delete_folder_instructions(folder)+ if deleted_count == 0:+ return Response({"detail": "This folder has no instructions."}, status=status.HTTP_404_NOT_FOUND)++ return Response(status=status.HTTP_204_NO_CONTENT)++ @extend_schema(responses={200: FolderInstructionsVersionSerializer(many=True)})+ @action(methods=["GET"], detail=True, url_path="instructions/versions")+ def instructions_versions(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """List the version history for this folder's instructions, newest first."""+ folder = self._get_folder_or_400()+ if isinstance(folder, Response):+ return folder++ versions = get_folder_instructions_versions(folder)+ page = self.paginate_queryset(versions)+ if page is not None:+ return self.get_paginated_response(FolderInstructionsVersionSerializer(page, many=True).data)+ return Response(FolderInstructionsVersionSerializer(versions, many=True).data)diff --git a/posthog/api/file_system/folder_instructions.py b/posthog/api/file_system/folder_instructions.pynew file mode 100644index 000000000000..afbb55d86361--- /dev/null+++ b/posthog/api/file_system/folder_instructions.py@@ -0,0 +1,81 @@+from rest_framework import serializers++from posthog.api.file_system.folder_instructions_service import FOLDER_INSTRUCTIONS_MAX_BYTES+from posthog.api.shared import UserBasicSerializer+from posthog.models.file_system.folder_instructions import FileSystemFolderInstructions+++def validate_folder_instructions_content(value: str) -> str:+ if len(value.encode("utf-8")) > FOLDER_INSTRUCTIONS_MAX_BYTES:+ raise serializers.ValidationError(+ f"Folder instructions must be {FOLDER_INSTRUCTIONS_MAX_BYTES} bytes or fewer.",+ code="max_size",+ )+ return value+++class FolderInstructionsSerializer(serializers.ModelSerializer):+ created_by = UserBasicSerializer(read_only=True, help_text="User who published this version.")++ class Meta:+ model = FileSystemFolderInstructions+ fields = [+ "id",+ "content",+ "version",+ "is_latest",+ "created_by",+ "created_at",+ "updated_at",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "id": {"help_text": "Unique identifier for this instructions version."},+ "content": {"help_text": "Markdown instructions describing the contents of the folder."},+ "version": {"help_text": "Monotonically increasing version number, starting at 1."},+ "is_latest": {"help_text": "Whether this is the current (latest) version for the folder."},+ "created_at": {"help_text": "When this version was published."},+ "updated_at": {"help_text": "When this version row was last modified."},+ }+++class FolderInstructionsVersionSerializer(serializers.ModelSerializer):+ """Version-history entry: metadata only, with the markdown content omitted."""++ created_by = UserBasicSerializer(read_only=True, help_text="User who published this version.")++ class Meta:+ model = FileSystemFolderInstructions+ fields = [+ "id",+ "version",+ "is_latest",+ "created_by",+ "created_at",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "id": {"help_text": "Unique identifier for this instructions version."},+ "version": {"help_text": "Monotonically increasing version number, starting at 1."},+ "is_latest": {"help_text": "Whether this is the current (latest) version for the folder."},+ "created_at": {"help_text": "When this version was published."},+ }+++class FolderInstructionsPublishSerializer(serializers.Serializer):+ content = serializers.CharField(+ allow_blank=True,+ help_text="Full markdown instructions to publish as a new version for the folder.",+ )+ base_version = serializers.IntegerField(+ min_value=0,+ required=False,+ help_text=(+ "Latest version you are editing from, for optimistic concurrency. If provided and the "+ "folder's instructions have changed since, the request fails with 409. Use 0 when no "+ "instructions exist yet."+ ),+ )++ def validate_content(self, value: str) -> str:+ return validate_folder_instructions_content(value)diff --git a/posthog/api/file_system/folder_instructions_service.py b/posthog/api/file_system/folder_instructions_service.pynew file mode 100644index 000000000000..e7fbd240f65e--- /dev/null+++ b/posthog/api/file_system/folder_instructions_service.py@@ -0,0 +1,124 @@+from dataclasses import dataclass++from django.db import IntegrityError, transaction+from django.db.models import QuerySet++from posthog.models.file_system.file_system import FileSystem+from posthog.models.file_system.folder_instructions import FileSystemFolderInstructions+from posthog.models.user import User++# Generous cap on the markdown blob; folder instructions are descriptions, not documents.+FOLDER_INSTRUCTIONS_MAX_BYTES = 100_000+MAX_FOLDER_INSTRUCTIONS_VERSION = 2000+++class FolderInstructionsNotFoundError(Exception):+ pass+++@dataclass+class FolderInstructionsVersionConflictError(Exception):+ current_version: int+++@dataclass+class FolderInstructionsVersionLimitError(Exception):+ max_version: int+++def get_folder_instructions_versions(folder: FileSystem) -> QuerySet[FileSystemFolderInstructions]:+ """All non-deleted versions for a folder, newest first."""+ return (+ FileSystemFolderInstructions.objects.filter(folder=folder, deleted=False)+ .select_related("created_by")+ .order_by("-version", "-created_at", "-id")+ )+++def get_latest_folder_instructions(folder: FileSystem) -> FileSystemFolderInstructions | None:+ return get_folder_instructions_versions(folder).filter(is_latest=True).first()+++def publish_folder_instructions(+ folder: FileSystem,+ *,+ content: str,+ user: User,+ base_version: int | None = None,+) -> FileSystemFolderInstructions:+ """Create the first version, or publish a new version superseding the current latest.++ `base_version`, when provided, guards against lost updates: if the current latest version no+ longer matches it, a `FolderInstructionsVersionConflictError` is raised.+ """+ with transaction.atomic():+ current_latest = (+ FileSystemFolderInstructions.objects.select_for_update()+ .filter(folder=folder, deleted=False, is_latest=True)+ .order_by("-version", "-created_at", "-id")+ .first()+ )++ if current_latest is None:+ if base_version is not None and base_version != 0:+ raise FolderInstructionsVersionConflictError(current_version=0)+ return FileSystemFolderInstructions.objects.create(+ team=folder.team,+ folder=folder,+ content=content,+ version=1,+ is_latest=True,+ created_by=user,+ )++ if base_version is not None and base_version != current_latest.version:+ raise FolderInstructionsVersionConflictError(current_version=current_latest.version)+ if current_latest.version >= MAX_FOLDER_INSTRUCTIONS_VERSION:+ raise FolderInstructionsVersionLimitError(max_version=MAX_FOLDER_INSTRUCTIONS_VERSION)++ FileSystemFolderInstructions.objects.filter(pk=current_latest.pk).update(is_latest=False)+ return FileSystemFolderInstructions.objects.create(+ team=folder.team,+ folder=folder,+ content=content,+ version=current_latest.version + 1,+ is_latest=True,+ created_by=user,+ )+++def ensure_blank_folder_instructions(+ folder: FileSystem,+ *,+ user: User | None,+) -> FileSystemFolderInstructions | None:+ """Create a blank version-1 instructions row for a folder if it has none.++ Idempotent: returns None when instructions already exist (so every folder ends up with an+ instruction set, even an empty one, without ever clobbering existing content).+ """+ if FileSystemFolderInstructions.objects.filter(folder=folder, deleted=False).exists():+ return None+ try:+ return FileSystemFolderInstructions.objects.create(+ team=folder.team,+ folder=folder,+ content="",+ version=1,+ is_latest=True,+ created_by=user,+ )+ except IntegrityError:+ # A concurrent create won the race; the folder now has instructions.+ return None+++def delete_folder_instructions(folder: FileSystem) -> int:+ """Soft-delete every version for a folder. Returns the number of versions affected."""+ with transaction.atomic():+ count = (+ FileSystemFolderInstructions.objects.select_for_update()+ .filter(folder=folder, deleted=False)+ .update(deleted=True, is_latest=False)+ )+ return countdiff --git a/posthog/api/file_system/test/test_folder_instructions.py b/posthog/api/file_system/test/test_folder_instructions.pynew file mode 100644index 000000000000..d88c58468566--- /dev/null+++ b/posthog/api/file_system/test/test_folder_instructions.py@@ -0,0 +1,215 @@+from typing import cast+from uuid import UUID++from posthog.test.base import APIBaseTest++from rest_framework import status++from posthog.api.file_system.folder_instructions_service import FOLDER_INSTRUCTIONS_MAX_BYTES+from posthog.models import Organization, Team+from posthog.models.file_system.file_system import FileSystem+from posthog.models.file_system.folder_instructions import FileSystemFolderInstructions+++class TestDesktopFolderInstructionsAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ # Staff gate mirrors the desktop/web file system beta gating.+ self.user.is_staff = True+ self.user.save()++ def _create_desktop_folder(self, path: str = "MyFolder") -> str:+ response = self.client.post(+ f"/api/projects/{self.team.id}/desktop_file_system/",+ {"path": path, "type": "folder"},+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ return cast(str, response.json()["id"])++ def _instructions_url(self, folder_id: str) -> str:+ return f"/api/projects/{self.team.id}/desktop_file_system/{folder_id}/instructions/"++ def _folder_id_for_path(self, path: str) -> str:+ return str(FileSystem.objects.get(team=self.team, surface="desktop", path=path, type="folder").id)++ def test_new_channel_gets_blank_instructions_automatically(self):+ folder_id = self._create_desktop_folder()+ response = self.client.get(self._instructions_url(folder_id))+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(response.json()["version"], 1)+ self.assertEqual(response.json()["content"], "")+ self.assertEqual(response.json()["is_latest"], True)++ def test_nested_folder_creation_backfills_ancestor_instructions(self):+ self._create_desktop_folder("A/B/C")+ for path in ["A", "A/B", "A/B/C"]:+ folder_id = self._folder_id_for_path(path)+ response = self.client.get(self._instructions_url(folder_id))+ self.assertEqual(response.status_code, status.HTTP_200_OK, (path, response.json()))+ self.assertEqual(response.json()["content"], "")++ def test_creating_item_gives_parent_folder_blank_instructions(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/desktop_file_system/",+ {"path": "Parent/MyInsight", "type": "insight", "ref": "abc"},+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())++ parent_id = self._folder_id_for_path("Parent")+ get = self.client.get(self._instructions_url(parent_id))+ self.assertEqual(get.status_code, status.HTTP_200_OK, get.json())+ self.assertEqual(get.json()["content"], "")++ def test_publish_supersedes_blank_initial_version(self):+ folder_id = self._create_desktop_folder()++ publish = self.client.patch(+ self._instructions_url(folder_id),+ {"content": "# Campaigns\n\nQ1 marketing assets."},+ )+ self.assertEqual(publish.status_code, status.HTTP_200_OK, publish.json())+ # The auto-created blank version is 1, so the first real edit publishes version 2.+ self.assertEqual(publish.json()["version"], 2)+ self.assertEqual(publish.json()["content"], "# Campaigns\n\nQ1 marketing assets.")++ get = self.client.get(self._instructions_url(folder_id))+ self.assertEqual(get.json()["content"], "# Campaigns\n\nQ1 marketing assets.")+ self.assertEqual(get.json()["version"], 2)++ def test_publish_increments_and_supersedes(self):+ folder_id = self._create_desktop_folder()+ self.client.patch(self._instructions_url(folder_id), {"content": "first"})+ third = self.client.patch(self._instructions_url(folder_id), {"content": "second"})++ self.assertEqual(third.status_code, status.HTTP_200_OK, third.json())+ self.assertEqual(third.json()["version"], 3)++ get = self.client.get(self._instructions_url(folder_id))+ self.assertEqual(get.json()["content"], "second")++ rows = FileSystemFolderInstructions.objects.unscoped().filter(folder_id=UUID(folder_id)).order_by("version")+ self.assertEqual(+ [(r.version, r.content, r.is_latest) for r in rows],+ [(1, "", False), (2, "first", False), (3, "second", True)],+ )++ def test_versions_list_returns_history_newest_first(self):+ folder_id = self._create_desktop_folder()+ self.client.patch(self._instructions_url(folder_id), {"content": "v2"})+ self.client.patch(self._instructions_url(folder_id), {"content": "v3"})++ response = self.client.get(self._instructions_url(folder_id) + "versions/")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ body = response.json()+ versions = body["results"]+ self.assertEqual([v["version"] for v in versions], [3, 2, 1])+ # Version-history entries omit the markdown content (progressive disclosure).+ self.assertNotIn("content", versions[0])++ def test_publish_rejects_oversized_content(self):+ folder_id = self._create_desktop_folder()+ oversized = "x" * (FOLDER_INSTRUCTIONS_MAX_BYTES + 1)+ response = self.client.patch(self._instructions_url(folder_id), {"content": oversized})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())++ def test_optimistic_concurrency_conflict(self):+ folder_id = self._create_desktop_folder() # auto-creates blank version 1++ response = self.client.patch(self._instructions_url(folder_id), {"content": "stale", "base_version": 99})+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT, response.json())+ self.assertEqual(response.json()["current_version"], 1)++ def test_cannot_attach_instructions_to_non_folder(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/desktop_file_system/",+ {"path": "MyFolder/MyInsight", "type": "insight", "ref": "abc"},+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ item_id = response.json()["id"]++ response = self.client.patch(self._instructions_url(item_id), {"content": "nope"})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())++ def test_soft_delete_hides_instructions(self):+ folder_id = self._create_desktop_folder()+ self.client.patch(self._instructions_url(folder_id), {"content": "to delete"})++ delete = self.client.delete(self._instructions_url(folder_id))+ self.assertEqual(delete.status_code, status.HTTP_204_NO_CONTENT)++ get = self.client.get(self._instructions_url(folder_id))+ self.assertEqual(get.status_code, status.HTTP_404_NOT_FOUND, get.json())++ # A subsequent publish starts a fresh version 1 (soft-deleted rows are excluded).+ republish = self.client.patch(self._instructions_url(folder_id), {"content": "again"})+ self.assertEqual(republish.status_code, status.HTTP_200_OK, republish.json())+ self.assertEqual(republish.json()["version"], 1)++ def test_delete_when_none_exist_returns_404(self):+ # Folder created directly (not via the desktop API) has no auto-created instructions.+ folder = FileSystem.objects.create(+ team=self.team,+ path="OrphanFolder",+ depth=1,+ type="folder",+ surface="desktop",+ )+ response = self.client.delete(self._instructions_url(str(folder.id)))+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.json())++ def test_cannot_access_folder_from_another_team(self):+ other_org = Organization.objects.create(name="Other Org")+ other_team = Team.objects.create(organization=other_org, name="Other Team")+ other_folder = FileSystem.objects.create(+ team=other_team,+ path="Secret",+ depth=1,+ type="folder",+ surface="desktop",+ )++ response = self.client.patch(self._instructions_url(str(other_folder.id)), {"content": "leak"})+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.json())++ def test_personal_api_key_can_read_and_publish_instructions(self):+ folder_id = self._create_desktop_folder()+ key = self.create_personal_api_key_with_scopes(["file_system:write"])+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key}")++ url = self._instructions_url(folder_id)++ get = self.client.get(url)+ self.assertEqual(get.status_code, status.HTTP_200_OK, get.json())++ patch = self.client.patch(url, {"content": "hello"}, content_type="application/json")+ self.assertEqual(patch.status_code, status.HTTP_200_OK, patch.json())+ self.assertEqual(patch.json()["content"], "hello")++ versions = self.client.get(url + "versions/")+ self.assertEqual(versions.status_code, status.HTTP_200_OK, versions.json())++ def test_personal_api_key_with_read_only_scope_cannot_publish(self):+ folder_id = self._create_desktop_folder()+ key = self.create_personal_api_key_with_scopes(["file_system:read"])+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key}")++ url = self._instructions_url(folder_id)++ get = self.client.get(url)+ self.assertEqual(get.status_code, status.HTTP_200_OK, get.json())++ patch = self.client.patch(url, {"content": "hello"}, content_type="application/json")+ self.assertEqual(patch.status_code, status.HTTP_403_FORBIDDEN, patch.json())++ def test_web_surface_has_no_instructions_action(self):+ folder = FileSystem.objects.create(+ team=self.team,+ path="WebFolder",+ depth=1,+ type="folder",+ surface="web",+ )+ response = self.client.get(f"/api/projects/{self.team.id}/file_system/{folder.id}/instructions/")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.json())diff --git a/posthog/migrations/1213_filesystemfolderinstructions.py b/posthog/migrations/1213_filesystemfolderinstructions.pynew file mode 100644index 000000000000..48a53338ff15--- /dev/null+++ b/posthog/migrations/1213_filesystemfolderinstructions.py@@ -0,0 +1,73 @@+import django.utils.timezone+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1212_grandfather_stripe_provisioned_pat")]++ operations = [+ migrations.CreateModel(+ name="FileSystemFolderInstructions",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("content", models.TextField()),+ ("version", models.PositiveIntegerField(default=1)),+ ("is_latest", models.BooleanField(default=True)),+ ("deleted", models.BooleanField(default=False)),+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "folder",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="instruction_versions",+ to="posthog.filesystem",+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "abstract": False,+ },+ ),+ migrations.AddConstraint(+ model_name="filesystemfolderinstructions",+ constraint=models.UniqueConstraint(+ condition=models.Q(("deleted", False)),+ fields=("folder", "version"),+ name="unique_folder_instructions_version",+ ),+ ),+ migrations.AddConstraint(+ model_name="filesystemfolderinstructions",+ constraint=models.UniqueConstraint(+ condition=models.Q(("deleted", False), ("is_latest", True)),+ fields=("folder",),+ name="unique_folder_instructions_latest",+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 728ef8dce72a..16c06e1d6515 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1212_grandfather_stripe_provisioned_pat+1213_filesystemfolderinstructionsdiff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex 9c7b4ab9a634..b2d9cf87b3b0 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -29,6 +29,7 @@ from products.event_definitions.backend.models import EventPropertyfrom .role_external_reference import RoleExternalReferencefrom .exported_recording import ExportedRecordingfrom .file_system.file_system import FileSystem+from .file_system.folder_instructions import FileSystemFolderInstructionsfrom .file_system.file_system_view_log import FileSystemViewLogfrom .filters import Filter, RetentionFilterfrom .group import Group@@ -117,6 +118,7 @@ __all__ = ["RoleExternalReference","ExportedRecording","FileSystem",+ "FileSystemFolderInstructions","FileSystemViewLog","Filter","Group",diff --git a/posthog/models/file_system/folder_instructions.py b/posthog/models/file_system/folder_instructions.pynew file mode 100644index 000000000000..c6ea7e65d6cb--- /dev/null+++ b/posthog/models/file_system/folder_instructions.py@@ -0,0 +1,44 @@+from django.db import models+from django.db.models import Q+from django.utils import timezone++from posthog.models.file_system.file_system import FileSystem+from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel+++class FileSystemFolderInstructions(TeamScopedRootMixin, UUIDModel):+ """+ A versioned markdown instructions blob attached to a single FileSystem folder.++ Each edit publishes a new row (incrementing `version`, flipping the previous `is_latest`+ off), mirroring the skills store's versioning so history is preserved and auditable.+ """++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)+ folder = models.ForeignKey(FileSystem, on_delete=models.CASCADE, related_name="instruction_versions")++ # The markdown instructions describing the contents of the folder.+ content = models.TextField()++ version = models.PositiveIntegerField(default=1)+ is_latest = models.BooleanField(default=True)+ deleted = models.BooleanField(default=False)++ created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True)+ created_at = models.DateTimeField(default=timezone.now)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["folder", "version"],+ condition=Q(deleted=False),+ name="unique_folder_instructions_version",+ ),+ models.UniqueConstraint(+ fields=["folder"],+ condition=Q(deleted=False, is_latest=True),+ name="unique_folder_instructions_latest",+ ),+ ]diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex 0c00a091d5d4..8575fd287dcb 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -64,16 +64,90 @@ tools:enabled: falsedesktop-file-system-create:operation: desktop_file_system_create- enabled: false+ enabled: true+ scopes:+ - file_system:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Create desktop channel+ description: >+ Create a new channel (folder) on the desktop surface. Pass a slash-delimited `path` (parent folders are+ created automatically) and `type: folder`. A blank instruction set is created for the channel automatically;+ use the update-instructions tool to fill it in.+ param_overrides:+ path:+ description: >+ Slash-delimited location of the channel, e.g. "Marketing/Q1 Campaigns". Intermediate folders are+ created automatically.+ type:+ description: Use "folder" to create a channel.desktop-file-system-destroy:operation: desktop_file_system_destroyenabled: false+ desktop-file-system-instructions-destroy:+ operation: desktop_file_system_instructions_destroy+ enabled: false+ desktop-file-system-instructions-partial-update:+ operation: desktop_file_system_instructions_partial_update+ enabled: true+ scopes:+ - file_system:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Update channel instructions+ description: >+ Publish a new version of a channel's markdown instructions, describing what the channel contains. The `id`+ is the channel (folder) id. Each call creates a new version. To erase a channel's instructions, publish+ empty `content` — this clears the text while keeping the instruction set in place (the instruction set+ itself cannot be deleted).+ param_overrides:+ id:+ description: ID of the channel (desktop folder) whose instructions to update.+ content:+ description: >+ Full markdown instructions to publish. Pass an empty string to erase the channel's instructions+ while keeping the instruction set.+ desktop-file-system-instructions-retrieve:+ operation: desktop_file_system_instructions_retrieve+ enabled: true+ scopes:+ - file_system:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get channel instructions+ description: |+ Get the latest markdown instructions for a channel (desktop folder).+ param_overrides:+ id:+ description: ID of the channel (desktop folder) whose instructions to fetch.+ desktop-file-system-instructions-update:+ operation: desktop_file_system_instructions_update+ enabled: false+ desktop-file-system-instructions-versions-list:+ operation: desktop_file_system_instructions_versions_list+ enabled: falsedesktop-file-system-link-create:operation: desktop_file_system_link_createenabled: falsedesktop-file-system-list:operation: desktop_file_system_list- enabled: false+ enabled: true+ scopes:+ - file_system:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List desktop channels+ description: >+ List channels and items on the desktop surface. Filter with query params such as `type` (e.g. "folder"),+ `parent`, `path`, `depth`, or `search`.desktop-file-system-log-view-create:operation: desktop_file_system_log_view_createenabled: false@@ -88,7 +162,16 @@ tools:enabled: falsedesktop-file-system-retrieve:operation: desktop_file_system_retrieve- enabled: false+ enabled: true+ scopes:+ - file_system:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get desktop channel+ description: |+ Retrieve a single channel or item on the desktop surface by id.desktop-file-system-shortcut-create:operation: desktop_file_system_shortcut_createenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 3db408d4ef1d..8d283b4b737f 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1221,6 +1221,76 @@"readOnlyHint": false}},+ "desktop-file-system-create": {+ "description": "Create a new channel (folder) on the desktop surface. Pass a slash-delimited `path` (parent folders are created automatically) and `type: folder`. A blank instruction set is created for the channel automatically; use the update-instructions tool to fill it in.",+ "category": "Core",+ "feature": "core",+ "summary": "Create desktop channel",+ "title": "Create desktop channel",+ "required_scopes": ["file_system:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "desktop-file-system-instructions-partial-update": {+ "description": "Publish a new version of a channel's markdown instructions, describing what the channel contains. The `id` is the channel (folder) id. Each call creates a new version. To erase a channel's instructions, publish empty `content` — this clears the text while keeping the instruction set in place (the instruction set itself cannot be deleted).",+ "category": "Core",+ "feature": "core",+ "summary": "Update channel instructions",+ "title": "Update channel instructions",+ "required_scopes": ["file_system:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "desktop-file-system-instructions-retrieve": {+ "description": "Get the latest markdown instructions for a channel (desktop folder).",+ "category": "Core",+ "feature": "core",+ "summary": "Get channel instructions",+ "title": "Get channel instructions",+ "required_scopes": ["file_system:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "desktop-file-system-list": {+ "description": "List channels and items on the desktop surface. Filter with query params such as `type` (e.g. \"folder\"), `parent`, `path`, `depth`, or `search`.",+ "category": "Core",+ "feature": "core",+ "summary": "List desktop channels",+ "title": "List desktop channels",+ "required_scopes": ["file_system:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "desktop-file-system-retrieve": {+ "description": "Retrieve a single channel or item on the desktop surface by id.",+ "category": "Core",+ "feature": "core",+ "summary": "Get desktop channel",+ "title": "Get desktop channel",+ "required_scopes": ["file_system:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"docs-search": {"description": "Use this tool for any PostHog questions to search the documentation. If the user's question mentions multiple topics, search for each topic separately and combine the results. It relies on a hybrid (semantic + full-text) search, so phrase your query in natural language. Our product and docs change often, so this tool is required for accurate answers:\n\n- How to use PostHog\n- How to use PostHog features\n- How to contact support or other humans\n- How to report bugs\n- How to submit feature requests\n- To troubleshoot something\n- What default fields and properties are available for events and persons\n- …Or anything else PostHog-related\n\nFor troubleshooting, ask the user to provide the error messages they are encountering. If no error message is involved, ask the user to describe their expected results vs. the actual results they're seeing. You avoid suggesting things that the user has told you they've already tried.\n\nImportant:\n\n1. Don't rely on your training data or previous searches/answers. Always re-check facts against current docs and tutorials. If current docs or tutorials contradict core memory on product facts, prefer the docs result.\n2. Always search PostHog docs/tutorials and prioritize results from posthog.com over training data.\n3. Always include at least one relevant docs/tutorial link in your reply.\n4. Never suggest emailing [email protected] or say you'll create a support ticket.\n5. Never use Community Questions as a source or cite them; they're often outdated or incorrect.","category": "Docs",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 6ff8e5aa3484..e70a3752da0d 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1251,6 +1251,76 @@"readOnlyHint": false}},+ "desktop-file-system-create": {+ "description": "Create a new channel (folder) on the desktop surface. Pass a slash-delimited `path` (parent folders are created automatically) and `type: folder`. A blank instruction set is created for the channel automatically; use the update-instructions tool to fill it in.",+ "category": "Core",+ "feature": "core",+ "summary": "Create desktop channel",+ "title": "Create desktop channel",+ "required_scopes": ["file_system:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "desktop-file-system-instructions-partial-update": {+ "description": "Publish a new version of a channel's markdown instructions, describing what the channel contains. The `id` is the channel (folder) id. Each call creates a new version. To erase a channel's instructions, publish empty `content` — this clears the text while keeping the instruction set in place (the instruction set itself cannot be deleted).",+ "category": "Core",+ "feature": "core",+ "summary": "Update channel instructions",+ "title": "Update channel instructions",+ "required_scopes": ["file_system:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "desktop-file-system-instructions-retrieve": {+ "description": "Get the latest markdown instructions for a channel (desktop folder).",+ "category": "Core",+ "feature": "core",+ "summary": "Get channel instructions",+ "title": "Get channel instructions",+ "required_scopes": ["file_system:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "desktop-file-system-list": {+ "description": "List channels and items on the desktop surface. Filter with query params such as `type` (e.g. \"folder\"), `parent`, `path`, `depth`, or `search`.",+ "category": "Core",+ "feature": "core",+ "summary": "List desktop channels",+ "title": "List desktop channels",+ "required_scopes": ["file_system:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "desktop-file-system-retrieve": {+ "description": "Retrieve a single channel or item on the desktop surface by id.",+ "category": "Core",+ "feature": "core",+ "summary": "Get desktop channel",+ "title": "Get desktop channel",+ "required_scopes": ["file_system:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"docs-search": {"description": "Use this tool for any PostHog questions to search the documentation. If the user's question mentions multiple topics, search for each topic separately and combine the results. It relies on a hybrid (semantic + full-text) search, so phrase your query in natural language. Our product and docs change often, so this tool is required for accurate answers:\n\n- How to use PostHog\n- How to use PostHog features\n- How to contact support or other humans\n- How to report bugs\n- How to submit feature requests\n- To troubleshoot something\n- What default fields and properties are available for events and persons\n- …Or anything else PostHog-related\n\nFor troubleshooting, ask the user to provide the error messages they are encountering. If no error message is involved, ask the user to describe their expected results vs. the actual results they're seeing. You avoid suggesting things that the user has told you they've already tried.\n\nImportant:\n\n1. Don't rely on your training data or previous searches/answers. Always re-check facts against current docs and tutorials. If current docs or tutorials contradict core memory on product facts, prefer the docs result.\n2. Always search PostHog docs/tutorials and prioritize results from posthog.com over training data.\n3. Always include at least one relevant docs/tutorial link in your reply.\n4. Never suggest emailing [email protected] or say you'll create a support ticket.\n5. Never use Community Questions as a source or cite them; they're often outdated or incorrect.","category": "Docs",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3d5ddde1ab6c..9fb1007afe6f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18484,6 +18484,49 @@ export namespace Schemas {refreshing: boolean;}+ export interface FolderInstructions {+ /** Unique identifier for this instructions version. */+ readonly id: string;+ /** Markdown instructions describing the contents of the folder. */+ readonly content: string;+ /** Monotonically increasing version number, starting at 1. */+ readonly version: number;+ /** Whether this is the current (latest) version for the folder. */+ readonly is_latest: boolean;+ /** User who published this version. */+ readonly created_by: UserBasic;+ /** When this version was published. */+ readonly created_at: string;+ /** When this version row was last modified. */+ readonly updated_at: string;+ }++ export interface FolderInstructionsPublish {+ /** Full markdown instructions to publish as a new version for the folder. */+ content: string;+ /**+ * Latest version you are editing from, for optimistic concurrency. If provided and the folder's instructions have changed since, the request fails with 409. Use 0 when no instructions exist yet.+ * @minimum 0+ */+ base_version?: number;+ }++ /**+ * Version-history entry: metadata only, with the markdown content omitted.+ */+ export interface FolderInstructionsVersion {+ /** Unique identifier for this instructions version. */+ readonly id: string;+ /** Monotonically increasing version number, starting at 1. */+ readonly version: number;+ /** Whether this is the current (latest) version for the folder. */+ readonly is_latest: boolean;+ /** User who published this version. */+ readonly created_by: UserBasic;+ /** When this version was published. */+ readonly created_at: string;+ }+/*** Request body for `forget`.*/@@ -24296,6 +24339,15 @@ export namespace Schemas {results: FileSystemShortcut[];}+ export interface PaginatedFolderInstructionsVersionList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: FolderInstructionsVersion[];+ }+export interface PaginatedGroupUsageMetricList {count: number;/** @nullable */@@ -29584,6 +29636,16 @@ export namespace Schemas {readonly created_at?: string;}+ export interface PatchedFolderInstructionsPublish {+ /** Full markdown instructions to publish as a new version for the folder. */+ content?: string;+ /**+ * Latest version you are editing from, for optimistic concurrency. If provided and the folder's instructions have changed since, the request fails with 409. Use 0 when no instructions exist yet.+ * @minimum 0+ */+ base_version?: number;+ }+export interface PatchedGroupType {readonly group_type?: string;readonly group_type_index?: number;@@ -47732,6 +47794,21 @@ export namespace Schemas {search?: string;};+ export type DesktopFileSystemInstructionsVersionsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * A search term.+ */+ search?: string;+ };+export type DesktopFileSystemShortcutListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.tsindex fc1e8da22e72..919dfcb10b40 100644--- a/services/mcp/src/generated/core/api.ts+++ b/services/mcp/src/generated/core/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 11 enabled ops+ * PostHog API - MCP 16 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -267,6 +267,105 @@ export const OrganizationsProjectsPartialUpdateBody = /* @__PURE__ */ zod}).describe('Mixin for serializers to add user access control fields')+/**+ * The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but is+scoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.+ */+export const DesktopFileSystemListParams = /* @__PURE__ */ zod.object({+ 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 DesktopFileSystemListQueryParams = /* @__PURE__ */ zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+ search: zod.string().optional().describe('A search term.'),+})++/**+ * The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but is+scoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.+ */+export const DesktopFileSystemCreateParams = /* @__PURE__ */ zod.object({+ 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 desktopFileSystemCreateBodyTypeMax = 100++export const desktopFileSystemCreateBodyRefMax = 100++export const DesktopFileSystemCreateBody = /* @__PURE__ */ zod.object({+ path: zod.string(),+ type: zod.string().max(desktopFileSystemCreateBodyTypeMax).optional(),+ ref: zod.string().max(desktopFileSystemCreateBodyRefMax).nullish(),+ href: zod.string().nullish(),+ meta: zod.unknown().optional(),+ shortcut: zod.boolean().nullish(),+})++/**+ * The file tree for the desktop product surface. Reuses all FileSystemViewSet behaviour but is+scoped to the "desktop" surface, so its tree is fully isolated from the default "web" tree.++Adds per-folder, versioned markdown instructions describing the contents of a folder.+ */+export const DesktopFileSystemRetrieveParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this file system.'),+ 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/."+ ),+})++/**+ * Return the latest non-deleted instructions for this folder.+ */+export const DesktopFileSystemInstructionsRetrieveParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this file system.'),+ 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/."+ ),+})++/**+ * Publish a new version of the folder's instructions.+ */+export const DesktopFileSystemInstructionsPartialUpdateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this file system.'),+ 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 desktopFileSystemInstructionsPartialUpdateBodyBaseVersionMin = 0++export const DesktopFileSystemInstructionsPartialUpdateBody = /* @__PURE__ */ zod.object({+ content: zod.string().optional().describe('Full markdown instructions to publish as a new version for the folder.'),+ base_version: zod+ .number()+ .min(desktopFileSystemInstructionsPartialUpdateBodyBaseVersionMin)+ .optional()+ .describe(+ "Latest version you are editing from, for optimistic concurrency. If provided and the folder's instructions have changed since, the request fails with 409. Use 0 when no instructions exist yet."+ ),+})+export const SubscriptionsListParams = /* @__PURE__ */ zod.object({project_id: zod.string()diff --git a/services/mcp/src/tools/generated/core.ts b/services/mcp/src/tools/generated/core.tsindex 1911f1a2c3a6..69266976f545 100644--- a/services/mcp/src/tools/generated/core.ts+++ b/services/mcp/src/tools/generated/core.ts@@ -3,6 +3,12 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import {+ DesktopFileSystemCreateBody,+ DesktopFileSystemInstructionsPartialUpdateBody,+ DesktopFileSystemInstructionsPartialUpdateParams,+ DesktopFileSystemInstructionsRetrieveParams,+ DesktopFileSystemListQueryParams,+ DesktopFileSystemRetrieveParams,OrganizationsProjectsPartialUpdateBody,OrganizationsProjectsPartialUpdateParams,OrganizationsProjectsRetrieveParams,@@ -23,6 +29,142 @@ import { castStringToInt } from '@/tools/cast-helpers'import { withPostHogUrl, omitResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'+const DesktopFileSystemCreateSchema = DesktopFileSystemCreateBody.extend({+ path: DesktopFileSystemCreateBody.shape['path'].describe(+ 'Slash-delimited location of the channel, e.g. "Marketing/Q1 Campaigns". Intermediate folders are created automatically.'+ ),+ type: DesktopFileSystemCreateBody.shape['type'].describe('Use "folder" to create a channel.'),+})++const desktopFileSystemCreate = (): ToolBase<typeof DesktopFileSystemCreateSchema, Schemas.FileSystem> => ({+ name: 'desktop-file-system-create',+ schema: DesktopFileSystemCreateSchema,+ handler: async (context: Context, params: z.infer<typeof DesktopFileSystemCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.path !== undefined) {+ body['path'] = params.path+ }+ if (params.type !== undefined) {+ body['type'] = params.type+ }+ if (params.ref !== undefined) {+ body['ref'] = params.ref+ }+ if (params.href !== undefined) {+ body['href'] = params.href+ }+ if (params.meta !== undefined) {+ body['meta'] = params.meta+ }+ if (params.shortcut !== undefined) {+ body['shortcut'] = params.shortcut+ }+ const result = await context.api.request<Schemas.FileSystem>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/desktop_file_system/`,+ body,+ })+ return result+ },+})++const DesktopFileSystemInstructionsPartialUpdateSchema = DesktopFileSystemInstructionsPartialUpdateParams.omit({+ project_id: true,+})+ .extend(DesktopFileSystemInstructionsPartialUpdateBody.shape)+ .extend({+ id: DesktopFileSystemInstructionsPartialUpdateParams.shape['id'].describe(+ 'ID of the channel (desktop folder) whose instructions to update.'+ ),+ content: DesktopFileSystemInstructionsPartialUpdateBody.shape['content'].describe(+ "Full markdown instructions to publish. Pass an empty string to erase the channel's instructions while keeping the instruction set."+ ),+ })++const desktopFileSystemInstructionsPartialUpdate = (): ToolBase<+ typeof DesktopFileSystemInstructionsPartialUpdateSchema,+ Schemas.FolderInstructions+> => ({+ name: 'desktop-file-system-instructions-partial-update',+ schema: DesktopFileSystemInstructionsPartialUpdateSchema,+ handler: async (context: Context, params: z.infer<typeof DesktopFileSystemInstructionsPartialUpdateSchema>) => {+ 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.FolderInstructions>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/desktop_file_system/${encodeURIComponent(String(params.id))}/instructions/`,+ body,+ })+ return result+ },+})++const DesktopFileSystemInstructionsRetrieveSchema = DesktopFileSystemInstructionsRetrieveParams.omit({+ project_id: true,+}).extend({+ id: DesktopFileSystemInstructionsRetrieveParams.shape['id'].describe(+ 'ID of the channel (desktop folder) whose instructions to fetch.'+ ),+})++const desktopFileSystemInstructionsRetrieve = (): ToolBase<+ typeof DesktopFileSystemInstructionsRetrieveSchema,+ Schemas.FolderInstructions+> => ({+ name: 'desktop-file-system-instructions-retrieve',+ schema: DesktopFileSystemInstructionsRetrieveSchema,+ handler: async (context: Context, params: z.infer<typeof DesktopFileSystemInstructionsRetrieveSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.FolderInstructions>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/desktop_file_system/${encodeURIComponent(String(params.id))}/instructions/`,+ })+ return result+ },+})++const DesktopFileSystemListSchema = DesktopFileSystemListQueryParams++const desktopFileSystemList = (): ToolBase<typeof DesktopFileSystemListSchema, Schemas.PaginatedFileSystemList> => ({+ name: 'desktop-file-system-list',+ schema: DesktopFileSystemListSchema,+ handler: async (context: Context, params: z.infer<typeof DesktopFileSystemListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedFileSystemList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/desktop_file_system/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ search: params.search,+ },+ })+ return result+ },+})++const DesktopFileSystemRetrieveSchema = DesktopFileSystemRetrieveParams.omit({ project_id: true })++const desktopFileSystemRetrieve = (): ToolBase<typeof DesktopFileSystemRetrieveSchema, Schemas.FileSystem> => ({+ name: 'desktop-file-system-retrieve',+ schema: DesktopFileSystemRetrieveSchema,+ handler: async (context: Context, params: z.infer<typeof DesktopFileSystemRetrieveSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.FileSystem>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/desktop_file_system/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})+const ProjectGetSchema = OrganizationsProjectsRetrieveParams.omit({ organization_id: true }).extend({id: z.preprocess(castStringToInt,@@ -594,6 +736,11 @@ const userSettingsUpdate = (): ToolBase<typeof UserSettingsUpdateSchema, Schemas})export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'desktop-file-system-create': desktopFileSystemCreate,+ 'desktop-file-system-instructions-partial-update': desktopFileSystemInstructionsPartialUpdate,+ 'desktop-file-system-instructions-retrieve': desktopFileSystemInstructionsRetrieve,+ 'desktop-file-system-list': desktopFileSystemList,+ 'desktop-file-system-retrieve': desktopFileSystemRetrieve,'project-get': projectGet,'project-settings-update': projectSettingsUpdate,'subscriptions-create': subscriptionsCreate,diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.jsonindex a597f1b893e8..262393e2fd51 100644--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json+++ b/services/mcp/tests/unit/__snapshots__/exec-tool.json@@ -15,7 +15,7 @@"properties": {"command": {"type": "string",- "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> series.properties` — to see property filter structure of series\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"DO NOT GUESS – run `schema query-trends series` before populating this field\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval\n- batch-export\n- cdp-function\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- data-warehouse-data\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data\n- feature-flag\n- file-download-batch\n- hog-flows\n- inbox\n- insight\n- integration\n- llm-total-costs\n- llma-clustering\n- llma-evaluation\n- llma-personal\n- llma-prompt\n- llma-review\n- llma-score\n- llma-sentiment\n- llma-skill\n- llma-summarization\n- llma-tagger\n- llma-trace\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- query\n- read-data\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- signals-scout\n- sql-variables\n- subscriptions\n- survey\n- switch\n- usage-metrics\n- user\n- view\n- web-analytics-weekly\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-paths-actors` — List persons who traversed the paths defined by a paths insight\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nPostHog app links must be full URLs (origin + path) — bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`.\n\n- If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.\n- Otherwise build the link from the Base URL in the active-environment block (don't double-prefix):\n - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`, and most pages.\n - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"+ "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> series.properties` — to see property filter structure of series\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"DO NOT GUESS – run `schema query-trends series` before populating this field\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval\n- batch-export\n- cdp-function\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- data-warehouse-data\n- desktop-file-system\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data\n- feature-flag\n- file-download-batch\n- hog-flows\n- inbox\n- insight\n- integration\n- llm-total-costs\n- llma-clustering\n- llma-evaluation\n- llma-personal\n- llma-prompt\n- llma-review\n- llma-score\n- llma-sentiment\n- llma-skill\n- llma-summarization\n- llma-tagger\n- llma-trace\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- query\n- read-data\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- signals-scout\n- sql-variables\n- subscriptions\n- survey\n- switch\n- usage-metrics\n- user\n- view\n- web-analytics-weekly\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-paths-actors` — List persons who traversed the paths defined by a paths insight\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nPostHog app links must be full URLs (origin + path) — bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`.\n\n- If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.\n- Otherwise build the link from the Base URL in the active-environment block (don't double-prefix):\n - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`, and most pages.\n - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"}},"required": ["command"]diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-create.jsonnew file mode 100644index 000000000000..7fd3dd8ed5be--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-create.json@@ -0,0 +1,48 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "href": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "meta": {},+ "path": {+ "description": "Slash-delimited location of the channel, e.g. \"Marketing/Q1 Campaigns\". Intermediate folders are created automatically.",+ "type": "string"+ },+ "ref": {+ "anyOf": [+ {+ "maxLength": 100,+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "shortcut": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },+ "type": {+ "description": "Use \"folder\" to create a channel.",+ "maxLength": 100,+ "type": "string"+ }+ },+ "required": ["path"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-instructions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-instructions-partial-update.jsonnew file mode 100644index 000000000000..45b42988fcb1--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-instructions-partial-update.json@@ -0,0 +1,20 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "base_version": {+ "description": "Latest version you are editing from, for optimistic concurrency. If provided and the folder's instructions have changed since, the request fails with 409. Use 0 when no instructions exist yet.",+ "minimum": 0,+ "type": "number"+ },+ "content": {+ "description": "Full markdown instructions to publish. Pass an empty string to erase the channel's instructions while keeping the instruction set.",+ "type": "string"+ },+ "id": {+ "description": "ID of the channel (desktop folder) whose instructions to update.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-instructions-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-instructions-retrieve.jsonnew file mode 100644index 000000000000..2df6b56b1b0e--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-instructions-retrieve.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "ID of the channel (desktop folder) whose instructions to fetch.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-list.jsonnew file mode 100644index 000000000000..bc560e594d69--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-list.json@@ -0,0 +1,18 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "limit": {+ "description": "Number of results to return per page.",+ "type": "number"+ },+ "offset": {+ "description": "The initial index from which to return the results.",+ "type": "number"+ },+ "search": {+ "description": "A search term.",+ "type": "string"+ }+ },+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-retrieve.jsonnew file mode 100644index 000000000000..3b94139ed2d7--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/desktop-file-system-retrieve.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this file system.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}