Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tasks): file tasks into the project tree on request (#61507)

Raquel Smithbd6a6e97634e
diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.py
index c98577cf275e..9d1721ca5e88 100644
--- a/posthog/api/file_system/registrations.py
+++ b/posthog/api/file_system/registrations.py
@@ -2,6 +2,8 @@ from __future__ import annotations
from typing import Any
+from rest_framework.exceptions import PermissionDenied
+
from posthog.api.file_system.deletion import (
HOG_FUNCTION_TYPES,
DeletionContext,
@@ -18,6 +20,8 @@ from posthog.models.user import User
from posthog.session_recordings.session_recording_playlist_api import log_playlist_activity
from products.cdp.backend.models.hog_functions.utils import humanize_hog_function_type
+from products.tasks.backend.api import task_visibility_q
+from products.tasks.backend.models import Task as _Task
def _first_non_blank(*values: str | None) -> str | None:
@@ -277,6 +281,43 @@ def _action_post_restore(context: RestoreContext, action: Any) -> None:
)
+def _ensure_task_visible_to_user(task: Any, user: Any | None) -> None:
+ # Mirror TaskViewSet.task_visibility_q: tasks belong to their creator (plus team-wide
+ # signal-pipeline tasks and legacy unowned tasks). Without this, anyone with file system
+ # write access could delete or restore another user's filed task via the generic flow.
+ user_id = getattr(user, "id", None)
+ if not _Task.objects.filter(task_visibility_q(user_id), pk=task.id).exists():
+ raise PermissionDenied("You do not have permission to modify this task.")
+
+
+def _task_pre_delete(context: DeletionContext, task: Any) -> None:
+ _ensure_task_visible_to_user(task, context.user)
+
+
+def _task_pre_restore(context: RestoreContext, task: Any) -> None:
+ _ensure_task_visible_to_user(task, context.user)
+
+
+def _task_post_delete(context: DeletionContext, task: Any) -> None:
+ _log_deletion_activity(
+ context,
+ scope="Task",
+ item_id=task.id,
+ name=_first_non_blank(getattr(task, "title", None)) or "Untitled task",
+ object_type="task",
+ )
+
+
+def _task_post_restore(context: RestoreContext, task: Any) -> None:
+ _log_restore_activity(
+ context,
+ scope="Task",
+ item_id=task.id,
+ name=_first_non_blank(getattr(task, "title", None)) or "Untitled task",
+ object_type="task",
+ )
+
+
def _hog_function_pre_delete(context: DeletionContext, hog_function: Any) -> None:
hog_function.enabled = False
@@ -414,6 +455,17 @@ def register_core_file_system_types() -> None:
register_post_delete_hook("cohort", _cohort_post_delete)
register_post_restore_hook("cohort", _cohort_post_restore)
+ register_file_system_type(
+ "task",
+ "tasks",
+ "Task",
+ undo_message="Send PATCH /api/projects/@current/tasks/{id} with deleted=false.",
+ )
+ register_pre_delete_hook("task", _task_pre_delete)
+ register_pre_restore_hook("task", _task_pre_restore)
+ register_post_delete_hook("task", _task_post_delete)
+ register_post_restore_hook("task", _task_post_restore)
+
for hog_type in HOG_FUNCTION_TYPES:
type_string = f"hog_function/{hog_type}"
register_file_system_type(
diff --git a/posthog/models/file_system/constants.py b/posthog/models/file_system/constants.py
index 697b03a1979e..002ee534dcbe 100644
--- a/posthog/models/file_system/constants.py
+++ b/posthog/models/file_system/constants.py
@@ -4,6 +4,9 @@ from django.db.models import Q
# stored as NULL; they are read as the default ("web"). New rows always store an explicit value.
DEFAULT_SURFACE = "web"
+# Surface for the desktop product tree, fully isolated from the default "web" tree.
+DESKTOP_SURFACE = "desktop"
+
def surface_q(surface: str) -> Q:
"""Build the read filter for a surface. The default surface also matches legacy NULL rows."""
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.py
index 583e322afbff..6b1a4dcd8419 100644
--- a/products/tasks/backend/api.py
+++ b/products/tasks/backend/api.py
@@ -36,6 +36,8 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import ServerTimingsGathered
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
from posthog.event_usage import groups
+from posthog.models.file_system.constants import DESKTOP_SURFACE
+from posthog.models.file_system.file_system import FileSystem, create_or_update_file, delete_file, surface_q
from posthog.models.integration import Integration
from posthog.models.user_push_token import UserPushToken
from posthog.permissions import APIScopePermission
@@ -84,6 +86,8 @@ from .serializers import (
SlackThreadContextQuerySerializer,
SlackThreadContextResponseSerializer,
TaskAutomationSerializer,
+ TaskFileRequestSerializer,
+ TaskFileResponseSerializer,
TaskListQuerySerializer,
TaskPresenceBeaconRequestSerializer,
TaskRepositoriesResponseSerializer,
@@ -900,6 +904,56 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
return Response(serializer.data)
+ @validated_request(
+ request_serializer=TaskFileRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskFileResponseSerializer, description="Task filed into the desktop project tree"
+ ),
+ 404: OpenApiResponse(description="Task not found"),
+ },
+ summary="File a task into the project tree",
+ description=(
+ "Add this task to the desktop project tree so it can be organized into folders. "
+ "Optionally pass a destination folder path. Idempotent — re-filing updates the existing entry."
+ ),
+ )
+ @action(detail=True, methods=["post"], url_path="file", required_scopes=["task:write"])
+ def file(self, request, pk=None, **kwargs):
+ task = cast(Task, self.get_object())
+ folder = (request.validated_data.get("folder") or "").strip() or "Tasks"
+ fs = task.get_file_system_representation(folder=folder)
+ create_or_update_file(
+ team=task.team,
+ base_folder=fs.base_folder,
+ name=fs.name,
+ file_type=fs.type,
+ ref=fs.ref,
+ href=fs.href,
+ meta=fs.meta,
+ created_at=task.created_at,
+ created_by_id=task.created_by_id,
+ surface=DESKTOP_SURFACE,
+ )
+ entry = (
+ FileSystem.objects.filter(surface_q(DESKTOP_SURFACE), team=task.team, type="task", ref=str(task.id))
+ .exclude(shortcut=True)
+ .first()
+ )
+ return Response(TaskFileResponseSerializer(entry).data)
+
+ @extend_schema(
+ request=None,
+ responses={204: OpenApiResponse(description="Task removed from the project tree")},
+ summary="Remove a task from the project tree",
+ description="Remove this task's entry from the desktop project tree. The task itself is not deleted.",
+ )
+ @action(detail=True, methods=["post"], url_path="unfile", required_scopes=["task:write"])
+ def unfile(self, request, pk=None, **kwargs):
+ task = cast(Task, self.get_object())
+ delete_file(team=task.team, file_type="task", ref=str(task.id), surface=DESKTOP_SURFACE)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
def perform_update(self, serializer):
task = cast(Task, serializer.instance)
logger.info(f"perform_update called for task {task.id} with validated_data: {serializer.validated_data}")
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 9d32c2cb1f0e..bfd3bb59264d 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -8,7 +8,7 @@ from collections.abc import Callable, Iterable
from datetime import datetime
from typing import TYPE_CHECKING, Any, Literal, Optional
-from django.db.models.signals import post_save
+from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from pydantic import BaseModel
@@ -28,6 +28,9 @@ import posthoganalytics
from posthog.event_usage import groups
from posthog.helpers.encrypted_fields import EncryptedJSONStringField
+from posthog.models.file_system.constants import DESKTOP_SURFACE
+from posthog.models.file_system.file_system import delete_file
+from posthog.models.file_system.file_system_representation import FileSystemRepresentation
from posthog.models.integration import Integration
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.team.team import Team
@@ -170,6 +173,23 @@ class Task(DeletedMetaFields, models.Model):
if is_new:
self._track_task_created()
+ def get_file_system_representation(self, folder: str = "Tasks") -> FileSystemRepresentation:
+ # Tasks are filed into the tree only on explicit request; this describes where a filed task
+ # lives. Tasks live only on the desktop surface, never the web app tree.
+ return FileSystemRepresentation(
+ base_folder=folder,
+ type="task",
+ ref=str(self.id),
+ name=self.title or "Untitled",
+ href=f"/tasks/{self.id}",
+ meta={
+ "created_at": str(self.created_at),
+ "created_by": self.created_by_id,
+ },
+ should_delete=bool(self.deleted),
+ surface=DESKTOP_SURFACE,
+ )
+
def capture_event(self, event: str, properties: dict | None = None) -> None:
try:
distinct_id = (
@@ -1393,3 +1413,23 @@ def track_task_run_completion(sender, instance: TaskRun, created: bool, **kwargs
task_run_id=str(instance.id),
error=str(e),
)
+
+
+# Tasks are filed into the project tree only on explicit request (see TaskViewSet.file). These
+# receivers never create an entry — they only remove a filed task's entry when the task is deleted,
+# so the tree can't surface a dead reference. delete_file is a no-op when no entry exists.
+@receiver(post_save, sender=Task)
+def _unfile_task_on_soft_delete(sender, instance: Task, **kwargs):
+ update_fields = kwargs.get("update_fields")
+ if update_fields is not None and "deleted" not in update_fields:
+ return
+ if instance.deleted:
+ delete_file(team=instance.team, file_type="task", ref=str(instance.id), surface=DESKTOP_SURFACE)
+
+
+@receiver(post_delete, sender=Task)
+def _unfile_task_on_hard_delete(sender, instance: Task, **kwargs):
+ try:
+ delete_file(team=instance.team, file_type="task", ref=str(instance.id), surface=DESKTOP_SURFACE)
+ except Team.DoesNotExist:
+ pass
diff --git a/products/tasks/backend/serializers.py b/products/tasks/backend/serializers.py
index c83de6eb0df6..691fa6c31e2c 100644
--- a/products/tasks/backend/serializers.py
+++ b/products/tasks/backend/serializers.py
@@ -81,6 +81,22 @@ def build_task_run_artifact_size_error(
return f"{artifact_name or 'Artifact'} exceeds the {max_mb}MB attachment limit"
+class TaskFileRequestSerializer(serializers.Serializer):
+ folder = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Destination folder path in the project tree (e.g. 'Tasks/Bugs'). Defaults to 'Tasks'.",
+ )
+
+
+class TaskFileResponseSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="Identifier of the project-tree entry for this task.")
+ path = serializers.CharField(help_text="Full slash-separated path of the filed task in the project tree.")
+ type = serializers.CharField(help_text="File system entry type. Always 'task'.")
+ ref = serializers.CharField(help_text="Identifier of the task this entry points to.")
+ href = serializers.CharField(help_text="In-app link to the task.")
+
+
class TaskSerializer(serializers.ModelSerializer):
repository = serializers.CharField(
max_length=255,
diff --git a/products/tasks/backend/tests/test_file_system.py b/products/tasks/backend/tests/test_file_system.py
new file mode 100644
index 000000000000..7f6c2ef5cfcd
--- /dev/null
+++ b/products/tasks/backend/tests/test_file_system.py
@@ -0,0 +1,151 @@
+from posthog.models import FileSystem
+from posthog.models.file_system.constants import DESKTOP_SURFACE, surface_q
+
+from products.tasks.backend.models import Task
+from products.tasks.backend.tests.test_api import BaseTaskAPITest
+
+
+class TestTaskFileSystem(BaseTaskAPITest):
+ def _task_rows(self, task: Task):
+ return FileSystem.objects.filter(team=self.team, type="task", ref=str(task.id)).exclude(shortcut=True)
+
+ def test_creating_a_task_does_not_file_it(self):
+ task = self.create_task(title="My Task")
+ self.assertFalse(FileSystem.objects.filter(team=self.team, type="task", ref=str(task.id)).exists())
+
+ def test_file_action_files_task_on_desktop_surface(self):
+ task = self.create_task(title="My Task")
+
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/file/")
+ self.assertEqual(response.status_code, 200, response.content)
+
+ entry = self._task_rows(task).get()
+ self.assertEqual(entry.path, "Tasks/My Task")
+ self.assertEqual(entry.href, f"/tasks/{task.id}")
+ self.assertEqual(entry.surface, DESKTOP_SURFACE)
+ self.assertEqual(response.json()["path"], "Tasks/My Task")
+
+ # Never leaks into the web app tree.
+ self.assertFalse(
+ FileSystem.objects.filter(surface_q("web"), team=self.team, type="task", ref=str(task.id)).exists()
+ )
+
+ def test_file_action_into_custom_folder(self):
+ task = self.create_task(title="My Task")
+
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/file/",
+ {"folder": "Tasks/Bugs"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(self._task_rows(task).get().path, "Tasks/Bugs/My Task")
+
+ def test_file_action_is_idempotent(self):
+ task = self.create_task(title="My Task")
+
+ self.client.post(f"/api/projects/@current/tasks/{task.id}/file/")
+ self.client.post(f"/api/projects/@current/tasks/{task.id}/file/")
+
+ self.assertEqual(self._task_rows(task).count(), 1)
+
+ def test_unfile_action_removes_entry_but_keeps_task(self):
+ task = self.create_task(title="My Task")
+ self.client.post(f"/api/projects/@current/tasks/{task.id}/file/")
+ self.assertEqual(self._task_rows(task).count(), 1)
+
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/unfile/")
+ self.assertEqual(response.status_code, 204, response.content)
+
+ self.assertFalse(self._task_rows(task).exists())
+ task.refresh_from_db()
+ self.assertFalse(task.deleted)
+
+ def test_soft_deleting_a_filed_task_removes_entry(self):
+ task = self.create_task(title="My Task")
+ self.client.post(f"/api/projects/@current/tasks/{task.id}/file/")
+ self.assertEqual(self._task_rows(task).count(), 1)
+
+ task.deleted = True
+ task.save()
+
+ self.assertFalse(self._task_rows(task).exists())
+
+ def test_hard_deleting_a_filed_task_removes_entry(self):
+ task = self.create_task(title="My Task")
+ self.client.post(f"/api/projects/@current/tasks/{task.id}/file/")
+ task_id = task.id
+ self.assertEqual(FileSystem.objects.filter(team=self.team, type="task", ref=str(task_id)).count(), 1)
+
+ # Task.delete() is blocked; queryset.delete() bypasses the override and fires post_delete.
+ Task.objects.filter(pk=task_id).delete()
+
+ self.assertFalse(FileSystem.objects.filter(team=self.team, type="task", ref=str(task_id)).exists())
+
+ def test_unfiled_sweep_does_not_file_tasks(self):
+ self.create_task(title="My Task")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/desktop_file_system/unfiled/?type=task")
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertFalse(FileSystem.objects.filter(team=self.team, type="task").exists())
+
+ def test_tree_delete_and_restore(self):
+ task = self.create_task(title="My Task")
+ self.client.post(f"/api/projects/@current/tasks/{task.id}/file/")
+ entry = self._task_rows(task).get()
+
+ # Deleting the tree entry soft-deletes the task and removes the row.
+ delete_response = self.client.delete(f"/api/projects/{self.team.id}/desktop_file_system/{entry.id}/")
+ self.assertEqual(delete_response.status_code, 200, delete_response.content)
+ task.refresh_from_db()
+ self.assertTrue(task.deleted)
+ self.assertFalse(self._task_rows(task).exists())
+
+ # Undo restores the task and recreates the row.
+ undo_response = self.client.post(
+ f"/api/projects/{self.team.id}/desktop_file_system/undo_delete/",
+ {"items": [{"type": "task", "ref": str(task.id), "path": entry.path}]},
+ format="json",
+ )
+ self.assertEqual(undo_response.status_code, 200, undo_response.content)
+ task.refresh_from_db()
+ self.assertFalse(task.deleted)
+ self.assertEqual(self._task_rows(task).get().path, "Tasks/My Task")
+
+ def test_tree_delete_blocked_for_other_users_task(self):
+ # A teammate filed a task they own. The current user (admin or not) must not be able to
+ # delete it via the generic file system endpoint, since that would soft-delete the task.
+ other_user = self.create_organization_user("victim")
+ task = self.create_task(title="Their Task", created_by=other_user)
+ self.client.force_authenticate(other_user)
+ self.client.post(f"/api/projects/@current/tasks/{task.id}/file/")
+ entry = self._task_rows(task).get()
+
+ self.client.force_authenticate(self.user)
+ response = self.client.delete(f"/api/projects/{self.team.id}/desktop_file_system/{entry.id}/")
+
+ self.assertEqual(response.status_code, 403, response.content)
+ task.refresh_from_db()
+ self.assertFalse(task.deleted)
+ self.assertTrue(self._task_rows(task).exists())
+
+ def test_tree_undo_blocked_for_other_users_task(self):
+ other_user = self.create_organization_user("victim")
+ task = self.create_task(title="Their Task", created_by=other_user)
+ self.client.force_authenticate(other_user)
+ self.client.post(f"/api/projects/@current/tasks/{task.id}/file/")
+ entry = self._task_rows(task).get()
+ # Soft-delete the task as the owner so undo has something to restore.
+ task.deleted = True
+ task.save()
+
+ self.client.force_authenticate(self.user)
+ undo_response = self.client.post(
+ f"/api/projects/{self.team.id}/desktop_file_system/undo_delete/",
+ {"items": [{"type": "task", "ref": str(task.id), "path": entry.path}]},
+ format="json",
+ )
+
+ self.assertEqual(undo_response.status_code, 403, undo_response.content)
+ task.refresh_from_db()
+ self.assertTrue(task.deleted)
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index a8b023b9f1f9..8c06596e1893 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -439,6 +439,24 @@ export interface PatchedTaskApi {
ci_prompt?: string | null
}
+export interface TaskFileRequestApi {
+ /** Destination folder path in the project tree (e.g. 'Tasks/Bugs'). Defaults to 'Tasks'. */
+ folder?: string
+}
+
+export interface TaskFileResponseApi {
+ /** Identifier of the project-tree entry for this task. */
+ id: string
+ /** Full slash-separated path of the filed task in the project tree. */
+ path: string
+ /** File system entry type. Always 'task'. */
+ type: string
+ /** Identifier of the task this entry points to. */
+ ref: string
+ /** In-app link to the task. */
+ href: string
+}
+
/**
* Request body for the presence beacon and beacon-leave endpoints.
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 36517a1ce8ce..f62124fd08f2 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -28,6 +28,8 @@ import type {
TaskApi,
TaskAutomationApi,
TaskAutomationsListParams,
+ TaskFileRequestApi,
+ TaskFileResponseApi,
TaskPresenceBeaconRequestApi,
TaskRepositoriesResponseApi,
TaskRunAppendLogRequestApi,
@@ -460,6 +462,28 @@ export const tasksDestroy = async (projectId: string, id: string, options?: Requ
})
}
+export const getTasksFileCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/tasks/${id}/file/`
+}
+
+/**
+ * Add this task to the desktop project tree so it can be organized into folders. Optionally pass a destination folder path. Idempotent — re-filing updates the existing entry.
+ * @summary File a task into the project tree
+ */
+export const tasksFileCreate = async (
+ projectId: string,
+ id: string,
+ taskFileRequestApi?: TaskFileRequestApi,
+ options?: RequestInit
+): Promise<TaskFileResponseApi> => {
+ return apiMutator<TaskFileResponseApi>(getTasksFileCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(taskFileRequestApi),
+ })
+}
+
export const getTasksPresenceCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/tasks/${id}/presence/`
}
@@ -569,6 +593,21 @@ export const tasksStagedArtifactsPrepareUploadCreate = async (
)
}
+export const getTasksUnfileCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/tasks/${id}/unfile/`
+}
+
+/**
+ * Remove this task's entry from the desktop project tree. The task itself is not deleted.
+ * @summary Remove a task from the project tree
+ */
+export const tasksUnfileCreate = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getTasksUnfileCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getTasksRunsListUrl = (projectId: string, taskId: string, params?: TasksRunsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index a6eaf83b1674..86ee567f04cf 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -384,6 +384,17 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.object({
ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),
})
+/**
+ * Add this task to the desktop project tree so it can be organized into folders. Optionally pass a destination folder path. Idempotent — re-filing updates the existing entry.
+ * @summary File a task into the project tree
+ */
+export const TasksFileCreateBody = /* @__PURE__ */ zod.object({
+ folder: zod
+ .string()
+ .optional()
+ .describe("Destination folder path in the project tree (e.g. 'Tasks\/Bugs'). Defaults to 'Tasks'."),
+})
+
/**
* Idempotent upsert: marks the calling user + `device_id` as actively watching this task for the next ~60 seconds. While at least one device for the user has a non-expired presence row for this task, the push fanout will skip ALL of that user's other registered devices for task notifications — the contract is 'if any device is demonstrably watching, suppress the others'. Clients call this every ~30s while the task screen is foregrounded. `device_id` is the UUID of the caller's UserPushToken row.
* @summary Beacon presence for a device watching this task
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index 7a709c1e7d6a..8763d2ae8afd 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -57,6 +57,20 @@ tools:
tasks-destroy:
operation: tasks_destroy
enabled: false
+ tasks-file-create:
+ operation: tasks_file_create
+ enabled: true
+ scopes:
+ - task:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: File a task into the project tree
+ description: >
+ Add a task to the desktop project tree so it can be organized into folders. Optionally pass a destination
+ `folder` path (defaults to `Tasks`). Idempotent — re-filing updates the existing entry.
+ feature_flag: tasks
tasks-list:
operation: tasks_list
enabled: true
@@ -252,6 +266,19 @@ tools:
tasks-summaries-create:
operation: tasks_summaries_create
enabled: false
+ tasks-unfile-create:
+ operation: tasks_unfile_create
+ enabled: true
+ scopes:
+ - task:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Remove a task from the project tree
+ description: |
+ Remove a task's entry from the desktop project tree. The task itself is not deleted.
+ feature_flag: tasks
tasks-update:
operation: tasks_update
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 93cd733dc8a5..02c0771cc490 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5109,6 +5109,21 @@
"readOnlyHint": true
}
},
+ "tasks-file-create": {
+ "description": "Add a task to the desktop project tree so it can be organized into folders. Optionally pass a destination `folder` path (defaults to `Tasks`). Idempotent — re-filing updates the existing entry.",
+ "category": "Tasks",
+ "feature": "tasks",
+ "summary": "File a task into the project tree",
+ "title": "File a task into the project tree",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "tasks"
+ },
"tasks-list": {
"description": "List agent tasks in the current project. Supports filtering by `origin_product`, `stage`, `organization`, `repository`, `created_by`, and `internal`. Returns lightweight task metadata only — call tasks-retrieve for the full task including its latest run, or tasks-runs-list for run history. Requires the calling token's organization to have Tasks access enabled.",
"category": "Tasks",
@@ -5184,6 +5199,21 @@
},
"feature_flag": "tasks"
},
+ "tasks-unfile-create": {
+ "description": "Remove a task's entry from the desktop project tree. The task itself is not deleted.",
+ "category": "Tasks",
+ "feature": "tasks",
+ "summary": "Remove a task from the project tree",
+ "title": "Remove a task from the project tree",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "tasks"
+ },
"update-feature-flag": {
"description": "Update a feature flag by ID in the current project.",
"category": "Feature flags",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index a8658bd15109..95f676de6f59 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5464,6 +5464,21 @@
"readOnlyHint": false
}
},
+ "tasks-file-create": {
+ "description": "Add a task to the desktop project tree so it can be organized into folders. Optionally pass a destination `folder` path (defaults to `Tasks`). Idempotent — re-filing updates the existing entry.",
+ "category": "Tasks",
+ "feature": "tasks",
+ "summary": "File a task into the project tree",
+ "title": "File a task into the project tree",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "tasks"
+ },
"tasks-list": {
"description": "List agent tasks in the current project. Supports filtering by `origin_product`, `stage`, `organization`, `repository`, `created_by`, and `internal`. Returns lightweight task metadata only — call tasks-retrieve for the full task including its latest run, or tasks-runs-list for run history. Requires the calling token's organization to have Tasks access enabled.",
"category": "Tasks",
@@ -5539,6 +5554,21 @@
},
"feature_flag": "tasks"
},
+ "tasks-unfile-create": {
+ "description": "Remove a task's entry from the desktop project tree. The task itself is not deleted.",
+ "category": "Tasks",
+ "feature": "tasks",
+ "summary": "Remove a task from the project tree",
+ "title": "Remove a task from the project tree",
+ "required_scopes": ["task:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "tasks"
+ },
"update-feature-flag": {
"description": "Update a feature flag by ID in the current project.",
"category": "Feature flags",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4b769c56100e..046f6816f928 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -38442,6 +38442,24 @@ export namespace Schemas {
deleted?: boolean;
}
+ export interface TaskFileRequest {
+ /** Destination folder path in the project tree (e.g. 'Tasks/Bugs'). Defaults to 'Tasks'. */
+ folder?: string;
+ }
+
+ export interface TaskFileResponse {
+ /** Identifier of the project-tree entry for this task. */
+ id: string;
+ /** Full slash-separated path of the filed task in the project tree. */
+ path: string;
+ /** File system entry type. Always 'task'. */
+ type: string;
+ /** Identifier of the task this entry points to. */
+ ref: string;
+ /** In-app link to the task. */
+ href: string;
+ }
+
/**
* Request body for the presence beacon and beacon-leave endpoints.
diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.ts
index 13f2b945af57..89009a317abf 100644
--- a/services/mcp/src/generated/tasks/api.ts
+++ b/services/mcp/src/generated/tasks/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 5 enabled ops
+ * PostHog API - MCP 7 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -81,6 +81,39 @@ export const TasksRetrieveParams = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Add this task to the desktop project tree so it can be organized into folders. Optionally pass a destination folder path. Idempotent — re-filing updates the existing entry.
+ * @summary File a task into the project tree
+ */
+export const TasksFileCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this task.'),
+ 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 TasksFileCreateBody = /* @__PURE__ */ zod.object({
+ folder: zod
+ .string()
+ .optional()
+ .describe("Destination folder path in the project tree (e.g. 'Tasks/Bugs'). Defaults to 'Tasks'."),
+})
+
+/**
+ * Remove this task's entry from the desktop project tree. The task itself is not deleted.
+ * @summary Remove a task from the project tree
+ */
+export const TasksUnfileCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this task.'),
+ 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/."
+ ),
+})
+
/**
* Get a list of runs for a specific task.
* @summary List task runs
diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.ts
index 095335686bfa..f8b1597de804 100644
--- a/services/mcp/src/tools/generated/tasks.ts
+++ b/services/mcp/src/tools/generated/tasks.ts
@@ -3,6 +3,8 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import {
+ TasksFileCreateBody,
+ TasksFileCreateParams,
TasksListQueryParams,
TasksRetrieveParams,
TasksRunsListParams,
@@ -10,10 +12,31 @@ import {
TasksRunsRetrieveParams,
TasksRunsSessionLogsRetrieveParams,
TasksRunsSessionLogsRetrieveQueryParams,
+ TasksUnfileCreateParams,
} from '@/generated/tasks/api'
import { withPostHogUrl, pickResponseFields, omitResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+const TasksFileCreateSchema = TasksFileCreateParams.omit({ project_id: true }).extend(TasksFileCreateBody.shape)
+
+const tasksFileCreate = (): ToolBase<typeof TasksFileCreateSchema, Schemas.TaskFileResponse> => ({
+ name: 'tasks-file-create',
+ schema: TasksFileCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof TasksFileCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.folder !== undefined) {
+ body['folder'] = params.folder
+ }
+ const result = await context.api.request<Schemas.TaskFileResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/tasks/${encodeURIComponent(String(params.id))}/file/`,
+ body,
+ })
+ return result
+ },
+})
+
const TasksListSchema = TasksListQueryParams
const tasksList = (): ToolBase<typeof TasksListSchema, WithPostHogUrl<Schemas.PaginatedTaskList>> => ({
@@ -173,10 +196,27 @@ const tasksRunsSessionLogsRetrieve = (): ToolBase<typeof TasksRunsSessionLogsRet
},
})
+const TasksUnfileCreateSchema = TasksUnfileCreateParams.omit({ project_id: true })
+
+const tasksUnfileCreate = (): ToolBase<typeof TasksUnfileCreateSchema, unknown> => ({
+ name: 'tasks-unfile-create',
+ schema: TasksUnfileCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof TasksUnfileCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/tasks/${encodeURIComponent(String(params.id))}/unfile/`,
+ })
+ return result
+ },
+})
+
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'tasks-file-create': tasksFileCreate,
'tasks-list': tasksList,
'tasks-retrieve': tasksRetrieve,
'tasks-runs-list': tasksRunsList,
'tasks-runs-retrieve': tasksRunsRetrieve,
'tasks-runs-session-logs-retrieve': tasksRunsSessionLogsRetrieve,
+ 'tasks-unfile-create': tasksUnfileCreate,
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-file-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-file-create.json
new file mode 100644
index 000000000000..37c839b30143
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-file-create.json
@@ -0,0 +1,15 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "folder": {
+ "description": "Destination folder path in the project tree (e.g. 'Tasks/Bugs'). Defaults to 'Tasks'.",
+ "type": "string"
+ },
+ "id": {
+ "description": "A UUID string identifying this task.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-unfile-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-unfile-create.json
new file mode 100644
index 000000000000..f0289641c9e3
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-unfile-create.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this task.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}