expandTask
Breaks down a parent task into subtasks by providing descriptions, project ID, and task ID. Optionally replaces existing subtasks with the 'force' flag. Outputs updated task details.
Instructions
Breaks down a specified parent task into multiple subtasks based on provided descriptions. Requires the project ID, the parent task ID, and an array of descriptions for the new subtasks. Optionally allows forcing the replacement of existing subtasks using the 'force' flag. Returns the updated parent task details, including the newly created subtasks.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| force | No | Optional flag (default false). If true, any existing subtasks of the parent task will be deleted before creating the new ones. If false and subtasks exist, the operation will fail. | |
| project_id | Yes | The unique identifier (UUID) of the project containing the parent task. | |
| subtask_descriptions | Yes | An array of descriptions (1-20) for the new subtasks to be created under the parent task. | |
| task_id | Yes | The unique identifier of the parent task to be expanded. |
Implementation Reference
- src/tools/expandTaskTool.ts:16-52 (handler)The main handler function for the 'expandTask' MCP tool. It processes the input arguments, calls TaskService.expandTask, formats the response as MCP content (JSON of updated task), and handles errors by throwing appropriate McpError types.const processRequest = async (args: ExpandTaskArgs) => { logger.info(`[${TOOL_NAME}] Received request with args:`, args); try { // Call the service method to expand the task const updatedParentTask = await taskService.expandTask({ project_id: args.project_id, task_id: args.task_id, subtask_descriptions: args.subtask_descriptions, force: args.force, }); // Format the successful response logger.info(`[${TOOL_NAME}] Successfully expanded task ${args.task_id} in project ${args.project_id}`); return { content: [{ type: "text" as const, // Return the updated parent task details, including new subtasks text: JSON.stringify(updatedParentTask) }] }; } catch (error: unknown) { // Handle potential errors logger.error(`[${TOOL_NAME}] Error processing request:`, error); if (error instanceof NotFoundError) { // Project or parent task not found throw new McpError(ErrorCode.InvalidParams, error.message); } else if (error instanceof ConflictError) { // Subtasks exist and force=false - map to InvalidParams as the request is invalid without force=true throw new McpError(ErrorCode.InvalidParams, error.message); } else { // Generic internal error const message = error instanceof Error ? error.message : 'An unknown error occurred while expanding the task.'; throw new McpError(ErrorCode.InternalError, message); } } };
- src/tools/expandTaskParams.ts:13-37 (schema)Zod schema definition for the 'expandTask' tool parameters (TOOL_PARAMS), including validation, descriptions, and types for project_id, task_id, subtask_descriptions, and force.export const TOOL_PARAMS = z.object({ project_id: z.string() .uuid("The project_id must be a valid UUID.") .describe("The unique identifier (UUID) of the project containing the parent task."), // Required, UUID format task_id: z.string() // Add .uuid() if task IDs are also UUIDs .min(1, "Parent task ID cannot be empty.") .describe("The unique identifier of the parent task to be expanded."), // Required, string (or UUID) subtask_descriptions: z.array( z.string() .min(1, "Subtask description cannot be empty.") .max(512, "Subtask description cannot exceed 512 characters.") .describe("A textual description for one of the new subtasks (1-512 characters).") ) .min(1, "At least one subtask description must be provided.") .max(20, "Cannot create more than 20 subtasks per call.") .describe("An array of descriptions (1-20) for the new subtasks to be created under the parent task."), // Required, array of strings, limits force: z.boolean() .optional() .default(false) .describe("Optional flag (default false). If true, any existing subtasks of the parent task will be deleted before creating the new ones. If false and subtasks exist, the operation will fail."), // Optional, boolean, default });
- src/tools/expandTaskTool.ts:14-58 (registration)The expandTaskTool function that registers the 'expandTask' tool on the MCP server using server.tool(), providing name, description, params schema, and the processRequest handler.export const expandTaskTool = (server: McpServer, taskService: TaskService): void => { const processRequest = async (args: ExpandTaskArgs) => { logger.info(`[${TOOL_NAME}] Received request with args:`, args); try { // Call the service method to expand the task const updatedParentTask = await taskService.expandTask({ project_id: args.project_id, task_id: args.task_id, subtask_descriptions: args.subtask_descriptions, force: args.force, }); // Format the successful response logger.info(`[${TOOL_NAME}] Successfully expanded task ${args.task_id} in project ${args.project_id}`); return { content: [{ type: "text" as const, // Return the updated parent task details, including new subtasks text: JSON.stringify(updatedParentTask) }] }; } catch (error: unknown) { // Handle potential errors logger.error(`[${TOOL_NAME}] Error processing request:`, error); if (error instanceof NotFoundError) { // Project or parent task not found throw new McpError(ErrorCode.InvalidParams, error.message); } else if (error instanceof ConflictError) { // Subtasks exist and force=false - map to InvalidParams as the request is invalid without force=true throw new McpError(ErrorCode.InvalidParams, error.message); } else { // Generic internal error const message = error instanceof Error ? error.message : 'An unknown error occurred while expanding the task.'; throw new McpError(ErrorCode.InternalError, message); } } }; // Register the tool with the server server.tool(TOOL_NAME, TOOL_DESCRIPTION, TOOL_PARAMS.shape, processRequest); logger.info(`[${TOOL_NAME}] Tool registered successfully.`); };
- src/tools/index.ts:58-58 (registration)Invocation of expandTaskTool during overall tool registration in the central registerTools function, passing the MCP server and TaskService instance.expandTaskTool(server, taskService);
- src/services/TaskService.ts:207-283 (helper)Core business logic for expanding a task: validates inputs, uses DB transaction to optionally delete existing subtasks (if force=true), creates new subtasks with given descriptions, constructs and returns FullTaskData with dependencies and subtasks.public async expandTask(input: ExpandTaskInput): Promise<FullTaskData> { const { project_id, task_id: parentTaskId, subtask_descriptions, force = false } = input; logger.info(`[TaskService] Attempting to expand task ${parentTaskId} in project ${project_id} with ${subtask_descriptions.length} subtasks (force=${force})`); // Use a transaction for the entire operation const expandTransaction = this.db.transaction(() => { // 1. Validate Parent Task Existence (within the transaction) const parentTask = this.taskRepository.findById(project_id, parentTaskId); if (!parentTask) { logger.warn(`[TaskService] Parent task ${parentTaskId} not found in project ${project_id}`); throw new NotFoundError(`Parent task with ID ${parentTaskId} not found in project ${project_id}.`); } // 2. Check for existing subtasks const existingSubtasks = this.taskRepository.findSubtasks(parentTaskId); // 3. Handle existing subtasks based on 'force' flag if (existingSubtasks.length > 0) { if (!force) { logger.warn(`[TaskService] Conflict: Task ${parentTaskId} already has subtasks and force=false.`); throw new ConflictError(`Task ${parentTaskId} already has subtasks. Use force=true to replace them.`); } else { logger.info(`[TaskService] Force=true: Deleting ${existingSubtasks.length} existing subtasks for parent ${parentTaskId}.`); this.taskRepository.deleteSubtasks(parentTaskId); // Note: Dependencies of deleted subtasks are implicitly handled by ON DELETE CASCADE in schema } } // 4. Create new subtasks const now = new Date().toISOString(); const createdSubtasks: TaskData[] = []; for (const description of subtask_descriptions) { const subtaskId = uuidv4(); const newSubtaskData: TaskData = { task_id: subtaskId, project_id: project_id, parent_task_id: parentTaskId, description: description, // Assuming length validation done by Zod status: 'todo', // Default status priority: 'medium', // Default priority created_at: now, updated_at: now, }; // Use the repository's create method (which handles its own transaction part for task+deps, but is fine here) // We pass an empty array for dependencies as expandTask doesn't set them for new subtasks this.taskRepository.create(newSubtaskData, []); createdSubtasks.push(newSubtaskData); } // 5. Fetch updated parent task details (including new subtasks and existing dependencies) // We re-fetch to get the consistent state after the transaction commits. // Note: This requires the transaction function to return the necessary data. // Alternatively, construct the FullTaskData manually here. Let's construct manually. const dependencies = this.taskRepository.findDependencies(parentTaskId); // Fetch parent's dependencies const finalParentData: FullTaskData = { ...parentTask, // Use data fetched at the start of transaction updated_at: now, // Update timestamp conceptually (though not saved unless status changes) dependencies: dependencies, subtasks: createdSubtasks, // Return the newly created subtasks }; return finalParentData; }); try { // Execute the transaction const result = expandTransaction(); logger.info(`[TaskService] Successfully expanded task ${parentTaskId} with ${subtask_descriptions.length} new subtasks.`); return result; } catch (error) { logger.error(`[TaskService] Error expanding task ${parentTaskId}:`, error); // Re-throw specific errors or generic internal error if (error instanceof NotFoundError || error instanceof ConflictError) { throw error; } throw new Error(`Failed to expand task: ${error instanceof Error ? error.message : 'Unknown error'}`); } }