Skip to main content
Glama
bsmi021

MCP Task Manager Server

by bsmi021

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
NameRequiredDescriptionDefault
forceNoOptional 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_idYesThe unique identifier (UUID) of the project containing the parent task.
subtask_descriptionsYesAn array of descriptions (1-20) for the new subtasks to be created under the parent task.
task_idYesThe unique identifier of the parent task to be expanded.

Implementation Reference

  • 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);
            }
        }
    };
  • 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
    });
  • 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.`);
    };
  • Invocation of expandTaskTool during overall tool registration in the central registerTools function, passing the MCP server and TaskService instance.
    expandTaskTool(server, taskService);
  • 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'}`);
        }
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses key behavioral traits: it can replace existing subtasks with the 'force' flag, and the operation may fail if subtasks exist and 'force' is false. However, it doesn't cover aspects like permissions needed, rate limits, or error handling details, leaving gaps for a mutation tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized with four sentences that are front-loaded with the core purpose. Each sentence adds value: purpose, required inputs, optional behavior, and return details. There's no wasted text, though it could be slightly more structured for clarity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and no output schema, the description provides basic completeness for a mutation tool: it states the action, inputs, and return value. However, it lacks details on error cases, side effects, or output structure, which are important for a tool that modifies data. This makes it adequate but with clear gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds minimal value beyond the schema by mentioning the parameters (project ID, parent task ID, subtask descriptions, force flag) but doesn't provide additional semantic context or usage examples. Baseline 3 is appropriate given high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Breaks down a specified parent task into multiple subtasks based on provided descriptions.' It uses specific verbs ('breaks down,' 'creates') and identifies the resource (parent task). However, it doesn't explicitly differentiate from sibling tools like 'addTask' or 'updateTask,' which might also modify tasks.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context by mentioning the need for a parent task and project ID, but it doesn't provide explicit guidance on when to use this tool versus alternatives like 'addTask' or 'updateTask.' It hints at a specific scenario (breaking down tasks into subtasks) but lacks clear when-to-use or when-not-to-use statements.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/bsmi021/mcp-task-manager-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server