Compare commits
90 Commits
recovered-
...
remove-pac
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4641cff82 | ||
|
|
4386e74ed2 | ||
|
|
5d3d66ee64 | ||
|
|
bf38baf858 | ||
|
|
ab6746a0c0 | ||
|
|
c02483bc41 | ||
|
|
3148b57f1b | ||
|
|
47b79c0e29 | ||
|
|
0dfecec1b3 | ||
|
|
4386d01bf1 | ||
|
|
9a66db0309 | ||
|
|
b7580e038d | ||
|
|
b3e7ebefd9 | ||
|
|
189d9288c1 | ||
|
|
1a547fac91 | ||
|
|
3f1f96076c | ||
|
|
0f9bc3378d | ||
|
|
bdd582b9cb | ||
|
|
693369128d | ||
|
|
2b5fab5cb5 | ||
|
|
e6c062d061 | ||
|
|
689e2de94e | ||
|
|
ab5025e204 | ||
|
|
268577fd20 | ||
|
|
141e8a8585 | ||
|
|
76ecfc086a | ||
|
|
33bb596c01 | ||
|
|
8e478f9e5e | ||
|
|
bad16b200f | ||
|
|
1582fe32c1 | ||
|
|
87b1eb61ee | ||
|
|
f11e00a026 | ||
|
|
feddeafd6e | ||
|
|
d71e7872ea | ||
|
|
01bd121de2 | ||
|
|
cdd87ccc5e | ||
|
|
6442bf5ee1 | ||
|
|
f16a574ad8 | ||
|
|
6393f9f7fb | ||
|
|
74b67830ac | ||
|
|
a49a77d19f | ||
|
|
1a74b50658 | ||
|
|
e04c16cec6 | ||
|
|
3af469b35f | ||
|
|
d5ecca25db | ||
|
|
65f56978b2 | ||
|
|
5e22c8b4ba | ||
|
|
bdd0035fc0 | ||
|
|
c98b0cea11 | ||
|
|
f9ef0c1887 | ||
|
|
0e16d27294 | ||
|
|
3bfbe19fe3 | ||
|
|
087de784fa | ||
|
|
f76b69c935 | ||
|
|
6a6d06766b | ||
|
|
9f430ca48b | ||
|
|
ca87476919 | ||
|
|
fec9e12f49 | ||
|
|
d06e45bf12 | ||
|
|
535fb5be71 | ||
|
|
fba6131db7 | ||
|
|
7f0cdf9046 | ||
|
|
eecad5bfe0 | ||
|
|
fb4a8b6cb7 | ||
|
|
00e01d1d93 | ||
|
|
995e95263c | ||
|
|
0b7b395aa4 | ||
|
|
1679075b6b | ||
|
|
1908c4a337 | ||
|
|
43022d7010 | ||
|
|
04c2dee593 | ||
|
|
d0092a6e6f | ||
|
|
729ae4d2d5 | ||
|
|
219b40b516 | ||
|
|
05950ef318 | ||
|
|
9582c0a91f | ||
|
|
6d01ae3d47 | ||
|
|
d4f92858c2 | ||
|
|
e02ee96aff | ||
|
|
38f9e4deaa | ||
|
|
71410629ba | ||
|
|
450549d875 | ||
|
|
a49f5a117b | ||
|
|
bc9707f813 | ||
|
|
a56a3628b3 | ||
|
|
9dc5e75760 | ||
|
|
16f4d4b932 | ||
|
|
7fef5ab488 | ||
|
|
38e416ef33 | ||
|
|
aa185b28b2 |
@@ -2,4 +2,4 @@
|
|||||||
"task-master-ai": patch
|
"task-master-ai": patch
|
||||||
---
|
---
|
||||||
|
|
||||||
Add license to repo
|
Add CI for testing
|
||||||
5
.changeset/red-lights-mix.md
Normal file
5
.changeset/red-lights-mix.md
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"task-master-ai": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
Fix github actions creating npm releases on next branch push
|
||||||
@@ -4,10 +4,178 @@
|
|||||||
|
|
||||||
- Adjusts the MCP server invokation in the mcp.json we ship with `task-master init`. Fully functional now.
|
- Adjusts the MCP server invokation in the mcp.json we ship with `task-master init`. Fully functional now.
|
||||||
- Rename the npx -y command. It's now `npx -y task-master-ai task-master-mcp`
|
- Rename the npx -y command. It's now `npx -y task-master-ai task-master-mcp`
|
||||||
|
- Add additional binary alias: `task-master-mcp-server` pointing to the same MCP server script
|
||||||
|
|
||||||
|
- **Significant improvements to model configuration:**
|
||||||
|
- Increase context window from 64k to 128k tokens (MAX_TOKENS=128000) for handling larger codebases
|
||||||
|
- Reduce temperature from 0.4 to 0.2 for more consistent, deterministic outputs
|
||||||
|
- Set default model to "claude-3-7-sonnet-20250219" in configuration
|
||||||
|
- Update Perplexity model to "sonar-pro" for research operations
|
||||||
|
- Increase default subtasks generation from 4 to 5 for more granular task breakdown
|
||||||
|
- Set consistent default priority to "medium" for all new tasks
|
||||||
|
|
||||||
|
- **Clarify environment configuration approaches:**
|
||||||
|
- For direct MCP usage: Configure API keys directly in `.cursor/mcp.json`
|
||||||
|
- For npm package usage: Configure API keys in `.env` file
|
||||||
|
- Update templates with clearer placeholder values and formatting
|
||||||
|
- Provide explicit documentation about configuration methods in both environments
|
||||||
|
- Use consistent placeholder format "YOUR_ANTHROPIC_API_KEY_HERE" in mcp.json
|
||||||
|
|
||||||
- Rename MCP tools to better align with API conventions and natural language in client chat:
|
- Rename MCP tools to better align with API conventions and natural language in client chat:
|
||||||
- Rename `list-tasks` to `get-tasks` for more intuitive client requests like "get my tasks"
|
- Rename `list-tasks` to `get-tasks` for more intuitive client requests like "get my tasks"
|
||||||
- Rename `show-task` to `get-task` for consistency with GET-based API naming conventions
|
- Rename `show-task` to `get-task` for consistency with GET-based API naming conventions
|
||||||
|
|
||||||
|
- **Refine AI-based MCP tool implementation patterns:**
|
||||||
|
- Establish clear responsibilities for direct functions vs MCP tools when handling AI operations
|
||||||
|
- Update MCP direct function signatures to expect `context = { session }` for AI-based tools, without `reportProgress`
|
||||||
|
- Clarify that AI client initialization, API calls, and response parsing should be handled within the direct function
|
||||||
|
- Define standard error codes for AI operations (`AI_CLIENT_ERROR`, `RESPONSE_PARSING_ERROR`, etc.)
|
||||||
|
- Document that `reportProgress` should not be used within direct functions due to client validation issues
|
||||||
|
- Establish that progress indication within direct functions should use standard logging (`log.info()`)
|
||||||
|
- Clarify that `AsyncOperationManager` should manage progress reporting at the MCP tool layer, not in direct functions
|
||||||
|
- Update `mcp.mdc` rule to reflect the refined patterns for AI-based MCP tools
|
||||||
|
- **Document and implement the Logger Wrapper Pattern:**
|
||||||
|
- Add comprehensive documentation in `mcp.mdc` and `utilities.mdc` on the Logger Wrapper Pattern
|
||||||
|
- Explain the dual purpose of the wrapper: preventing runtime errors and controlling output format
|
||||||
|
- Include implementation examples with detailed explanations of why and when to use this pattern
|
||||||
|
- Clearly document that this pattern has proven successful in resolving issues in multiple MCP tools
|
||||||
|
- Cross-reference between rule files to ensure consistent guidance
|
||||||
|
- **Fix critical issue in `analyze-project-complexity` MCP tool:**
|
||||||
|
- Implement proper logger wrapper in `analyzeTaskComplexityDirect` to fix `mcpLog[level] is not a function` errors
|
||||||
|
- Update direct function to handle both Perplexity and Claude AI properly for research-backed analysis
|
||||||
|
- Improve silent mode handling with proper wasSilent state tracking
|
||||||
|
- Add comprehensive error handling for AI client errors and report file parsing
|
||||||
|
- Ensure proper report format detection and analysis with fallbacks
|
||||||
|
- Fix variable name conflicts between the `report` logging function and data structures in `analyzeTaskComplexity`
|
||||||
|
- **Fix critical issue in `update-task` MCP tool:**
|
||||||
|
- Implement proper logger wrapper in `updateTaskByIdDirect` to ensure mcpLog[level] calls work correctly
|
||||||
|
- Update Zod schema in `update-task.js` to accept both string and number type IDs
|
||||||
|
- Fix silent mode implementation with proper try/finally blocks
|
||||||
|
- Add comprehensive error handling for missing parameters, invalid task IDs, and failed updates
|
||||||
|
- **Refactor `update-subtask` MCP tool to follow established patterns:**
|
||||||
|
- Update `updateSubtaskByIdDirect` function to accept `context = { session }` parameter
|
||||||
|
- Add proper AI client initialization with error handling for both Anthropic and Perplexity
|
||||||
|
- Implement the Logger Wrapper Pattern to prevent mcpLog[level] errors
|
||||||
|
- Support both string and number subtask IDs with appropriate validation
|
||||||
|
- Update MCP tool to pass session to direct function but not reportProgress
|
||||||
|
- Remove commented-out calls to reportProgress for cleaner code
|
||||||
|
- Add comprehensive error handling for various failure scenarios
|
||||||
|
- Implement proper silent mode with try/finally blocks
|
||||||
|
- Ensure detailed successful update response information
|
||||||
|
- **Fix issues in `set-task-status` MCP tool:**
|
||||||
|
- Remove reportProgress parameter as it's not needed
|
||||||
|
- Improve project root handling for better session awareness
|
||||||
|
- Reorganize function call arguments for setTaskStatusDirect
|
||||||
|
- Add proper silent mode handling with try/catch/finally blocks
|
||||||
|
- Enhance logging for both success and error cases
|
||||||
|
- **Refactor `update` MCP tool to follow established patterns:**
|
||||||
|
- Update `updateTasksDirect` function to accept `context = { session }` parameter
|
||||||
|
- Add proper AI client initialization with error handling
|
||||||
|
- Update MCP tool to pass session to direct function but not reportProgress
|
||||||
|
- Simplify parameter validation using string type for 'from' parameter
|
||||||
|
- Improve error handling for AI client errors
|
||||||
|
- Implement proper silent mode handling with try/finally blocks
|
||||||
|
- Use `isSilentMode()` function instead of accessing global variables directly
|
||||||
|
- **Refactor `expand-task` MCP tool to follow established patterns:**
|
||||||
|
- Update `expandTaskDirect` function to accept `context = { session }` parameter
|
||||||
|
- Add proper AI client initialization with error handling
|
||||||
|
- Update MCP tool to pass session to direct function but not reportProgress
|
||||||
|
- Add comprehensive tests for the refactored implementation
|
||||||
|
- Improve error handling for AI client errors
|
||||||
|
- Remove non-existent 'force' parameter from direct function implementation
|
||||||
|
- Ensure direct function parameters match core function parameters
|
||||||
|
- Implement proper silent mode handling with try/finally blocks
|
||||||
|
- Use `isSilentMode()` function instead of accessing global variables directly
|
||||||
|
- **Refactor `parse-prd` MCP tool to follow established patterns:**
|
||||||
|
- Update `parsePRDDirect` function to accept `context = { session }` parameter for proper AI initialization
|
||||||
|
- Implement AI client initialization with proper error handling using `getAnthropicClientForMCP`
|
||||||
|
- Add the Logger Wrapper Pattern to ensure proper logging via `mcpLog`
|
||||||
|
- Update the core `parsePRD` function to accept an AI client parameter
|
||||||
|
- Implement proper silent mode handling with try/finally blocks
|
||||||
|
- Remove `reportProgress` usage from MCP tool for better client compatibility
|
||||||
|
- Fix console output that was breaking the JSON response format
|
||||||
|
- Improve error handling with specific error codes
|
||||||
|
- Pass session object to the direct function correctly
|
||||||
|
- Update task-manager-core.js to export AI client utilities for better organization
|
||||||
|
- Ensure proper option passing between functions to maintain logging context
|
||||||
|
|
||||||
|
- **Update MCP Logger to respect silent mode:**
|
||||||
|
- Import and check `isSilentMode()` function in logger implementation
|
||||||
|
- Skip all logging when silent mode is enabled
|
||||||
|
- Prevent console output from interfering with JSON responses
|
||||||
|
- Fix "Unexpected token 'I', "[INFO] Gene"... is not valid JSON" errors by suppressing log output during silent mode
|
||||||
|
|
||||||
|
- **Refactor `expand-all` MCP tool to follow established patterns:**
|
||||||
|
- Update `expandAllTasksDirect` function to accept `context = { session }` parameter
|
||||||
|
- Add proper AI client initialization with error handling for research-backed expansion
|
||||||
|
- Pass session to direct function but not reportProgress in the MCP tool
|
||||||
|
- Implement directory switching to work around core function limitations
|
||||||
|
- Add comprehensive error handling with specific error codes
|
||||||
|
- Ensure proper restoration of working directory after execution
|
||||||
|
- Use try/finally pattern for both silent mode and directory management
|
||||||
|
- Add comprehensive tests for the refactored implementation
|
||||||
|
|
||||||
|
- **Standardize and improve silent mode implementation across MCP direct functions:**
|
||||||
|
- Add proper import of all silent mode utilities: `import { enableSilentMode, disableSilentMode, isSilentMode } from 'utils.js'`
|
||||||
|
- Replace direct access to global silentMode variable with `isSilentMode()` function calls
|
||||||
|
- Implement consistent try/finally pattern to ensure silent mode is always properly disabled
|
||||||
|
- Add error handling with finally blocks to prevent silent mode from remaining enabled after errors
|
||||||
|
- Create proper mixed parameter/global silent mode check pattern: `const isSilent = options.silentMode || (typeof options.silentMode === 'undefined' && isSilentMode())`
|
||||||
|
- Update all direct functions to follow the new implementation pattern
|
||||||
|
- Fix issues with silent mode not being properly disabled when errors occur
|
||||||
|
|
||||||
|
- **Improve parameter handling between direct functions and core functions:**
|
||||||
|
- Verify direct function parameters match core function signatures
|
||||||
|
- Remove extraction and use of parameters that don't exist in core functions (e.g., 'force')
|
||||||
|
- Implement appropriate type conversion for parameters (e.g., `parseInt(args.id, 10)`)
|
||||||
|
- Set defaults that match core function expectations
|
||||||
|
- Add detailed documentation on parameter matching in guidelines
|
||||||
|
- Add explicit examples of correct parameter handling patterns
|
||||||
|
|
||||||
|
- **Create standardized MCP direct function implementation checklist:**
|
||||||
|
- Comprehensive imports and dependencies section
|
||||||
|
- Parameter validation and matching guidelines
|
||||||
|
- Silent mode implementation best practices
|
||||||
|
- Error handling and response format patterns
|
||||||
|
- Path resolution and core function call guidelines
|
||||||
|
- Function export and testing verification steps
|
||||||
|
- Specific issues to watch for related to silent mode, parameters, and error cases
|
||||||
|
- Add checklist to subtasks for uniform implementation across all direct functions
|
||||||
|
|
||||||
|
- **Implement centralized AI client utilities for MCP tools:**
|
||||||
|
- Create new `ai-client-utils.js` module with standardized client initialization functions
|
||||||
|
- Implement session-aware AI client initialization for both Anthropic and Perplexity
|
||||||
|
- Add comprehensive error handling with user-friendly error messages
|
||||||
|
- Create intelligent AI model selection based on task requirements
|
||||||
|
- Implement model configuration utilities that respect session environment variables
|
||||||
|
- Add extensive unit tests for all utility functions
|
||||||
|
- Significantly improve MCP tool reliability for AI operations
|
||||||
|
- **Specific implementations include:**
|
||||||
|
- `getAnthropicClientForMCP`: Initializes Anthropic client with session environment variables
|
||||||
|
- `getPerplexityClientForMCP`: Initializes Perplexity client with session environment variables
|
||||||
|
- `getModelConfig`: Retrieves model parameters from session or fallbacks to defaults
|
||||||
|
- `getBestAvailableAIModel`: Selects the best available model based on requirements
|
||||||
|
- `handleClaudeError`: Processes Claude API errors into user-friendly messages
|
||||||
|
- **Updated direct functions to use centralized AI utilities:**
|
||||||
|
- Refactored `addTaskDirect` to use the new AI client utilities with proper AsyncOperationManager integration
|
||||||
|
- Implemented comprehensive error handling for API key validation, AI processing, and response parsing
|
||||||
|
- Added session-aware parameter handling with proper propagation of context to AI streaming functions
|
||||||
|
- Ensured proper fallback to process.env when session variables aren't available
|
||||||
|
|
||||||
|
- **Refine AI services for reusable operations:**
|
||||||
|
- Refactor `ai-services.js` to support consistent AI operations across CLI and MCP
|
||||||
|
- Implement shared helpers for streaming responses, prompt building, and response parsing
|
||||||
|
- Standardize client initialization patterns with proper session parameter handling
|
||||||
|
- Enhance error handling and loading indicator management
|
||||||
|
- Fix process exit issues to prevent MCP server termination on API errors
|
||||||
|
- Ensure proper resource cleanup in all execution paths
|
||||||
|
- Add comprehensive test coverage for AI service functions
|
||||||
|
- **Key improvements include:**
|
||||||
|
- Stream processing safety with explicit completion detection
|
||||||
|
- Standardized function parameter patterns
|
||||||
|
- Session-aware parameter extraction with sensible defaults
|
||||||
|
- Proper cleanup using try/catch/finally patterns
|
||||||
|
|
||||||
- **Optimize MCP response payloads:**
|
- **Optimize MCP response payloads:**
|
||||||
- Add custom `processTaskResponse` function to `get-task` MCP tool to filter out unnecessary `allTasks` array data
|
- Add custom `processTaskResponse` function to `get-task` MCP tool to filter out unnecessary `allTasks` array data
|
||||||
- Significantly reduce response size by returning only the specific requested task instead of all tasks
|
- Significantly reduce response size by returning only the specific requested task instead of all tasks
|
||||||
@@ -28,6 +196,9 @@
|
|||||||
- Add examples of proper error handling and parameter validation to all relevant rules
|
- Add examples of proper error handling and parameter validation to all relevant rules
|
||||||
- Include new sections about handling dependencies during task removal operations
|
- Include new sections about handling dependencies during task removal operations
|
||||||
- Document naming conventions and implementation patterns for destructive operations
|
- Document naming conventions and implementation patterns for destructive operations
|
||||||
|
- Update silent mode implementation documentation with proper examples
|
||||||
|
- Add parameter handling guidelines emphasizing matching with core functions
|
||||||
|
- Update architecture documentation with dedicated section on silent mode implementation
|
||||||
|
|
||||||
- **Implement silent mode across all direct functions:**
|
- **Implement silent mode across all direct functions:**
|
||||||
- Add `enableSilentMode` and `disableSilentMode` utility imports to all direct function files
|
- Add `enableSilentMode` and `disableSilentMode` utility imports to all direct function files
|
||||||
@@ -124,3 +295,8 @@
|
|||||||
- Improve status counts display with clear text labels beside status icons for better readability.
|
- Improve status counts display with clear text labels beside status icons for better readability.
|
||||||
- Treat deferred and cancelled tasks as effectively complete for progress calculation while maintaining visual distinction.
|
- Treat deferred and cancelled tasks as effectively complete for progress calculation while maintaining visual distinction.
|
||||||
- **Fix `reportProgress` calls** to use the correct `{ progress, total? }` format.
|
- **Fix `reportProgress` calls** to use the correct `{ progress, total? }` format.
|
||||||
|
- **Standardize logging in core task-manager functions (`expandTask`, `expandAllTasks`, `updateTasks`, `updateTaskById`, `updateSubtaskById`, `parsePRD`, `analyzeTaskComplexity`):**
|
||||||
|
- Implement a local `report` function in each to handle context-aware logging.
|
||||||
|
- Use `report` to choose between `mcpLog` (if available) and global `log` (from `utils.js`).
|
||||||
|
- Only call global `log` when `outputFormat` is 'text' and silent mode is off.
|
||||||
|
- Wrap CLI UI elements (tables, boxes, spinners) in `outputFormat === 'text'` checks.
|
||||||
|
|||||||
@@ -2,16 +2,14 @@
|
|||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"taskmaster-ai": {
|
"taskmaster-ai": {
|
||||||
"command": "node",
|
"command": "node",
|
||||||
"args": [
|
"args": ["./mcp-server/server.js"],
|
||||||
"./mcp-server/server.js"
|
|
||||||
],
|
|
||||||
"env": {
|
"env": {
|
||||||
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
|
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
|
||||||
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
|
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
|
||||||
"MODEL": "claude-3-7-sonnet-20250219",
|
"MODEL": "claude-3-7-sonnet-20250219",
|
||||||
"PERPLEXITY_MODEL": "sonar-pro",
|
"PERPLEXITY_MODEL": "sonar-pro",
|
||||||
"MAX_TOKENS": 64000,
|
"MAX_TOKENS": 128000,
|
||||||
"TEMPERATURE": 0.4,
|
"TEMPERATURE": 0.2,
|
||||||
"DEFAULT_SUBTASKS": 5,
|
"DEFAULT_SUBTASKS": 5,
|
||||||
"DEFAULT_PRIORITY": "medium"
|
"DEFAULT_PRIORITY": "medium"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -155,7 +155,114 @@ alwaysApply: false
|
|||||||
- **UI for Presentation**: [`ui.js`](mdc:scripts/modules/ui.js) is used by command handlers and task/dependency managers to display information to the user. UI functions primarily consume data and format it for output, without modifying core application state.
|
- **UI for Presentation**: [`ui.js`](mdc:scripts/modules/ui.js) is used by command handlers and task/dependency managers to display information to the user. UI functions primarily consume data and format it for output, without modifying core application state.
|
||||||
- **Utilities for Common Tasks**: [`utils.js`](mdc:scripts/modules/utils.js) provides helper functions used by all other modules for configuration, logging, file operations, and common data manipulations.
|
- **Utilities for Common Tasks**: [`utils.js`](mdc:scripts/modules/utils.js) provides helper functions used by all other modules for configuration, logging, file operations, and common data manipulations.
|
||||||
- **AI Services Integration**: AI functionalities (complexity analysis, task expansion, PRD parsing) are invoked from [`task-manager.js`](mdc:scripts/modules/task-manager.js) and potentially [`commands.js`](mdc:scripts/modules/commands.js), likely using functions that would reside in a dedicated `ai-services.js` module or be integrated within `utils.js` or `task-manager.js`.
|
- **AI Services Integration**: AI functionalities (complexity analysis, task expansion, PRD parsing) are invoked from [`task-manager.js`](mdc:scripts/modules/task-manager.js) and potentially [`commands.js`](mdc:scripts/modules/commands.js), likely using functions that would reside in a dedicated `ai-services.js` module or be integrated within `utils.js` or `task-manager.js`.
|
||||||
- **MCP Server Interaction**: External tools interact with the `mcp-server`. MCP Tool `execute` methods use `getProjectRootFromSession` to find the project root, then call direct function wrappers (in `mcp-server/src/core/direct-functions/`) passing the root in `args`. These wrappers handle path finding for `tasks.json` (using `path-utils.js`), validation, caching, call the core logic from `scripts/modules/`, and return a standardized result. The final MCP response is formatted by `mcp-server/src/tools/utils.js`. See [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for details.
|
- **MCP Server Interaction**: External tools interact with the `mcp-server`. MCP Tool `execute` methods use `getProjectRootFromSession` to find the project root, then call direct function wrappers (in `mcp-server/src/core/direct-functions/`) passing the root in `args`. These wrappers handle path finding for `tasks.json` (using `path-utils.js`), validation, caching, call the core logic from `scripts/modules/` (passing logging context via the standard wrapper pattern detailed in mcp.mdc), and return a standardized result. The final MCP response is formatted by `mcp-server/src/tools/utils.js`. See [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for details.
|
||||||
|
|
||||||
|
## Silent Mode Implementation Pattern in MCP Direct Functions
|
||||||
|
|
||||||
|
Direct functions (the `*Direct` functions in `mcp-server/src/core/direct-functions/`) need to carefully implement silent mode to prevent console logs from interfering with the structured JSON responses required by MCP. This involves both using `enableSilentMode`/`disableSilentMode` around core function calls AND passing the MCP logger via the standard wrapper pattern (see mcp.mdc). Here's the standard pattern for correct implementation:
|
||||||
|
|
||||||
|
1. **Import Silent Mode Utilities**:
|
||||||
|
```javascript
|
||||||
|
import { enableSilentMode, disableSilentMode, isSilentMode } from '../../../../scripts/modules/utils.js';
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Parameter Matching with Core Functions**:
|
||||||
|
- ✅ **DO**: Ensure direct function parameters match the core function parameters
|
||||||
|
- ✅ **DO**: Check the original core function signature before implementing
|
||||||
|
- ❌ **DON'T**: Add parameters to direct functions that don't exist in core functions
|
||||||
|
```javascript
|
||||||
|
// Example: Core function signature
|
||||||
|
// async function expandTask(tasksPath, taskId, numSubtasks, useResearch, additionalContext, options)
|
||||||
|
|
||||||
|
// Direct function implementation - extract only parameters that exist in core
|
||||||
|
export async function expandTaskDirect(args, log, context = {}) {
|
||||||
|
// Extract parameters that match the core function
|
||||||
|
const taskId = parseInt(args.id, 10);
|
||||||
|
const numSubtasks = args.num ? parseInt(args.num, 10) : undefined;
|
||||||
|
const useResearch = args.research === true;
|
||||||
|
const additionalContext = args.prompt || '';
|
||||||
|
|
||||||
|
// Later pass these parameters in the correct order to the core function
|
||||||
|
const result = await expandTask(
|
||||||
|
tasksPath,
|
||||||
|
taskId,
|
||||||
|
numSubtasks,
|
||||||
|
useResearch,
|
||||||
|
additionalContext,
|
||||||
|
{ mcpLog: log, session: context.session }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Checking Silent Mode State**:
|
||||||
|
- ✅ **DO**: Always use `isSilentMode()` function to check current status
|
||||||
|
- ❌ **DON'T**: Directly access the global `silentMode` variable or `global.silentMode`
|
||||||
|
```javascript
|
||||||
|
// CORRECT: Use the function to check current state
|
||||||
|
if (!isSilentMode()) {
|
||||||
|
// Only create a loading indicator if not in silent mode
|
||||||
|
loadingIndicator = startLoadingIndicator('Processing...');
|
||||||
|
}
|
||||||
|
|
||||||
|
// INCORRECT: Don't access global variables directly
|
||||||
|
if (!silentMode) { // ❌ WRONG
|
||||||
|
loadingIndicator = startLoadingIndicator('Processing...');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Wrapping Core Function Calls**:
|
||||||
|
- ✅ **DO**: Use a try/finally block pattern to ensure silent mode is always restored
|
||||||
|
- ✅ **DO**: Enable silent mode before calling core functions that produce console output
|
||||||
|
- ✅ **DO**: Disable silent mode in a finally block to ensure it runs even if errors occur
|
||||||
|
- ❌ **DON'T**: Enable silent mode without ensuring it gets disabled
|
||||||
|
```javascript
|
||||||
|
export async function someDirectFunction(args, log) {
|
||||||
|
try {
|
||||||
|
// Argument preparation
|
||||||
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
const someArg = args.someArg;
|
||||||
|
|
||||||
|
// Enable silent mode to prevent console logs
|
||||||
|
enableSilentMode();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Call core function which might produce console output
|
||||||
|
const result = await someCoreFunction(tasksPath, someArg);
|
||||||
|
|
||||||
|
// Return standardized result object
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: result,
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
// ALWAYS disable silent mode in finally block
|
||||||
|
disableSilentMode();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Standard error handling
|
||||||
|
log.error(`Error in direct function: ${error.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: { code: 'OPERATION_ERROR', message: error.message },
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
5. **Mixed Parameter and Global Silent Mode Handling**:
|
||||||
|
- For functions that need to handle both a passed `silentMode` parameter and check global state:
|
||||||
|
```javascript
|
||||||
|
// Check both the function parameter and global state
|
||||||
|
const isSilent = options.silentMode || (typeof options.silentMode === 'undefined' && isSilentMode());
|
||||||
|
|
||||||
|
if (!isSilent) {
|
||||||
|
console.log('Operation starting...');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
By following these patterns consistently, direct functions will properly manage console output suppression while ensuring that silent mode is always properly reset, even when errors occur. This creates a more robust system that helps prevent unexpected silent mode states that could cause logging problems in subsequent operations.
|
||||||
|
|
||||||
- **Testing Architecture**:
|
- **Testing Architecture**:
|
||||||
|
|
||||||
@@ -205,7 +312,7 @@ Follow these steps to add MCP support for an existing Task Master command (see [
|
|||||||
|
|
||||||
1. **Ensure Core Logic Exists**: Verify the core functionality is implemented and exported from the relevant module in `scripts/modules/`.
|
1. **Ensure Core Logic Exists**: Verify the core functionality is implemented and exported from the relevant module in `scripts/modules/`.
|
||||||
|
|
||||||
2. **Create Direct Function File in `mcp-server/src/core/direct-functions/`**:
|
2. **Create Direct Function File in `mcp-server/src/core/direct-functions/`:**
|
||||||
- Create a new file (e.g., `your-command.js`) using **kebab-case** naming.
|
- Create a new file (e.g., `your-command.js`) using **kebab-case** naming.
|
||||||
- Import necessary core functions, **`findTasksJsonPath` from `../utils/path-utils.js`**, and **silent mode utilities**.
|
- Import necessary core functions, **`findTasksJsonPath` from `../utils/path-utils.js`**, and **silent mode utilities**.
|
||||||
- Implement `async function yourCommandDirect(args, log)` using **camelCase** with `Direct` suffix:
|
- Implement `async function yourCommandDirect(args, log)` using **camelCase** with `Direct` suffix:
|
||||||
|
|||||||
@@ -152,8 +152,8 @@ When implementing commands that delete or remove data (like `remove-task` or `re
|
|||||||
```javascript
|
```javascript
|
||||||
// ✅ DO: Suggest alternatives for destructive operations
|
// ✅ DO: Suggest alternatives for destructive operations
|
||||||
console.log(chalk.yellow('Note: If you just want to exclude this task from active work, consider:'));
|
console.log(chalk.yellow('Note: If you just want to exclude this task from active work, consider:'));
|
||||||
console.log(chalk.cyan(` task-master set-status --id=${taskId} --status=cancelled`));
|
console.log(chalk.cyan(` task-master set-status --id='${taskId}' --status='cancelled'`));
|
||||||
console.log(chalk.cyan(` task-master set-status --id=${taskId} --status=deferred`));
|
console.log(chalk.cyan(` task-master set-status --id='${taskId}' --status='deferred'`));
|
||||||
console.log('This preserves the task and its history for reference.');
|
console.log('This preserves the task and its history for reference.');
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -253,7 +253,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
|
|||||||
const taskId = parseInt(options.id, 10);
|
const taskId = parseInt(options.id, 10);
|
||||||
if (isNaN(taskId) || taskId <= 0) {
|
if (isNaN(taskId) || taskId <= 0) {
|
||||||
console.error(chalk.red(`Error: Invalid task ID: ${options.id}. Task ID must be a positive integer.`));
|
console.error(chalk.red(`Error: Invalid task ID: ${options.id}. Task ID must be a positive integer.`));
|
||||||
console.log(chalk.yellow('Usage example: task-master update-task --id=23 --prompt="Update with new information"'));
|
console.log(chalk.yellow('Usage example: task-master update-task --id=\'23\' --prompt=\'Update with new information.\nEnsure proper error handling.\''));
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -299,8 +299,8 @@ When implementing commands that delete or remove data (like `remove-task` or `re
|
|||||||
(dependencies.length > 0 ? chalk.white(`Dependencies: ${dependencies.join(', ')}`) + '\n' : '') +
|
(dependencies.length > 0 ? chalk.white(`Dependencies: ${dependencies.join(', ')}`) + '\n' : '') +
|
||||||
'\n' +
|
'\n' +
|
||||||
chalk.white.bold('Next Steps:') + '\n' +
|
chalk.white.bold('Next Steps:') + '\n' +
|
||||||
chalk.cyan(`1. Run ${chalk.yellow(`task-master show ${parentId}`)} to see the parent task with all subtasks`) + '\n' +
|
chalk.cyan(`1. Run ${chalk.yellow(`task-master show '${parentId}'`)} to see the parent task with all subtasks`) + '\n' +
|
||||||
chalk.cyan(`2. Run ${chalk.yellow(`task-master set-status --id=${parentId}.${subtask.id} --status=in-progress`)} to start working on it`),
|
chalk.cyan(`2. Run ${chalk.yellow(`task-master set-status --id='${parentId}.${subtask.id}' --status='in-progress'`)} to start working on it`),
|
||||||
{ padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
|
{ padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
|
||||||
));
|
));
|
||||||
```
|
```
|
||||||
@@ -375,7 +375,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
|
|||||||
' --option1 <value> Description of option1 (required)\n' +
|
' --option1 <value> Description of option1 (required)\n' +
|
||||||
' --option2 <value> Description of option2\n\n' +
|
' --option2 <value> Description of option2\n\n' +
|
||||||
chalk.cyan('Examples:') + '\n' +
|
chalk.cyan('Examples:') + '\n' +
|
||||||
' task-master command --option1=value --option2=value',
|
' task-master command --option1=\'value1\' --option2=\'value2\'',
|
||||||
{ padding: 1, borderColor: 'blue', borderStyle: 'round' }
|
{ padding: 1, borderColor: 'blue', borderStyle: 'round' }
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -418,7 +418,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
|
|||||||
// Provide more helpful error messages for common issues
|
// Provide more helpful error messages for common issues
|
||||||
if (error.message.includes('task') && error.message.includes('not found')) {
|
if (error.message.includes('task') && error.message.includes('not found')) {
|
||||||
console.log(chalk.yellow('\nTo fix this issue:'));
|
console.log(chalk.yellow('\nTo fix this issue:'));
|
||||||
console.log(' 1. Run task-master list to see all available task IDs');
|
console.log(' 1. Run \'task-master list\' to see all available task IDs');
|
||||||
console.log(' 2. Use a valid task ID with the --id parameter');
|
console.log(' 2. Use a valid task ID with the --id parameter');
|
||||||
} else if (error.message.includes('API key')) {
|
} else if (error.message.includes('API key')) {
|
||||||
console.log(chalk.yellow('\nThis error is related to API keys. Check your environment variables.'));
|
console.log(chalk.yellow('\nThis error is related to API keys. Check your environment variables.'));
|
||||||
@@ -562,3 +562,45 @@ When implementing commands that delete or remove data (like `remove-task` or `re
|
|||||||
```
|
```
|
||||||
|
|
||||||
Refer to [`commands.js`](mdc:scripts/modules/commands.js) for implementation examples and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.
|
Refer to [`commands.js`](mdc:scripts/modules/commands.js) for implementation examples and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.
|
||||||
|
// Helper function to show add-subtask command help
|
||||||
|
function showAddSubtaskHelp() {
|
||||||
|
console.log(boxen(
|
||||||
|
chalk.white.bold('Add Subtask Command Help') + '\n\n' +
|
||||||
|
chalk.cyan('Usage:') + '\n' +
|
||||||
|
` task-master add-subtask --parent=<id> [options]\n\n` +
|
||||||
|
chalk.cyan('Options:') + '\n' +
|
||||||
|
' -p, --parent <id> Parent task ID (required)\n' +
|
||||||
|
' -i, --task-id <id> Existing task ID to convert to subtask\n' +
|
||||||
|
' -t, --title <title> Title for the new subtask\n' +
|
||||||
|
' -d, --description <text> Description for the new subtask\n' +
|
||||||
|
' --details <text> Implementation details for the new subtask\n' +
|
||||||
|
' --dependencies <ids> Comma-separated list of dependency IDs\n' +
|
||||||
|
' -s, --status <status> Status for the new subtask (default: "pending")\n' +
|
||||||
|
' -f, --file <file> Path to the tasks file (default: "tasks/tasks.json")\n' +
|
||||||
|
' --skip-generate Skip regenerating task files\n\n' +
|
||||||
|
chalk.cyan('Examples:') + '\n' +
|
||||||
|
' task-master add-subtask --parent=\'5\' --task-id=\'8\'\n' +
|
||||||
|
' task-master add-subtask -p \'5\' -t \'Implement login UI\' -d \'Create the login form\'\n' +
|
||||||
|
' task-master add-subtask -p \'5\' -t \'Handle API Errors\' --details $\'Handle 401 Unauthorized.\nHandle 500 Server Error.\'',
|
||||||
|
{ padding: 1, borderColor: 'blue', borderStyle: 'round' }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to show remove-subtask command help
|
||||||
|
function showRemoveSubtaskHelp() {
|
||||||
|
console.log(boxen(
|
||||||
|
chalk.white.bold('Remove Subtask Command Help') + '\n\n' +
|
||||||
|
chalk.cyan('Usage:') + '\n' +
|
||||||
|
` task-master remove-subtask --id=<parentId.subtaskId> [options]\n\n` +
|
||||||
|
chalk.cyan('Options:') + '\n' +
|
||||||
|
' -i, --id <id> Subtask ID(s) to remove in format "parentId.subtaskId" (can be comma-separated, required)\n' +
|
||||||
|
' -c, --convert Convert the subtask to a standalone task instead of deleting it\n' +
|
||||||
|
' -f, --file <file> Path to the tasks file (default: "tasks/tasks.json")\n' +
|
||||||
|
' --skip-generate Skip regenerating task files\n\n' +
|
||||||
|
chalk.cyan('Examples:') + '\n' +
|
||||||
|
' task-master remove-subtask --id=\'5.2\'\n' +
|
||||||
|
' task-master remove-subtask --id=\'5.2,6.3,7.1\'\n' +
|
||||||
|
' task-master remove-subtask --id=\'5.2\' --convert',
|
||||||
|
{ padding: 1, borderColor: 'blue', borderStyle: 'round' }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ Task Master offers two primary ways to interact:
|
|||||||
|
|
||||||
## Standard Development Workflow Process
|
## Standard Development Workflow Process
|
||||||
|
|
||||||
- Start new projects by running `init` tool / `task-master init` or `parse_prd` / `task-master parse-prd --input=<prd-file.txt>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to generate initial tasks.json
|
- Start new projects by running `init` tool / `task-master init` or `parse_prd` / `task-master parse-prd --input='<prd-file.txt>'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to generate initial tasks.json
|
||||||
- Begin coding sessions with `get_tasks` / `task-master list` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to see current tasks, status, and IDs
|
- Begin coding sessions with `get_tasks` / `task-master list` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to see current tasks, status, and IDs
|
||||||
- Determine the next task to work on using `next_task` / `task-master next` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
|
- Determine the next task to work on using `next_task` / `task-master next` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
|
||||||
- Analyze task complexity with `analyze_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) before breaking down tasks
|
- Analyze task complexity with `analyze_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) before breaking down tasks
|
||||||
@@ -45,7 +45,7 @@ Task Master offers two primary ways to interact:
|
|||||||
- Update dependent tasks when implementation differs from original plan using `update` / `task-master update --from=<id> --prompt="..."` or `update_task` / `task-master update-task --id=<id> --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
|
- Update dependent tasks when implementation differs from original plan using `update` / `task-master update --from=<id> --prompt="..."` or `update_task` / `task-master update-task --id=<id> --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
|
||||||
- Add new tasks discovered during implementation using `add_task` / `task-master add-task --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
|
- Add new tasks discovered during implementation using `add_task` / `task-master add-task --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
|
||||||
- Add new subtasks as needed using `add_subtask` / `task-master add-subtask --parent=<id> --title="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
|
- Add new subtasks as needed using `add_subtask` / `task-master add-subtask --parent=<id> --title="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
|
||||||
- Append notes or details to subtasks using `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
|
- Append notes or details to subtasks using `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='Add implementation notes here...\nMore details...'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
|
||||||
- Generate task files with `generate` / `task-master generate` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) after updating tasks.json
|
- Generate task files with `generate` / `task-master generate` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) after updating tasks.json
|
||||||
- Maintain valid dependency structure with `add_dependency`/`remove_dependency` tools or `task-master add-dependency`/`remove-dependency` commands, `validate_dependencies` / `task-master validate-dependencies`, and `fix_dependencies` / `task-master fix-dependencies` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) when needed
|
- Maintain valid dependency structure with `add_dependency`/`remove_dependency` tools or `task-master add-dependency`/`remove-dependency` commands, `validate_dependencies` / `task-master validate-dependencies`, and `fix_dependencies` / `task-master fix-dependencies` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) when needed
|
||||||
- Respect dependency chains and task priorities when selecting work
|
- Respect dependency chains and task priorities when selecting work
|
||||||
@@ -74,8 +74,8 @@ Task Master offers two primary ways to interact:
|
|||||||
- When implementation differs significantly from planned approach
|
- When implementation differs significantly from planned approach
|
||||||
- When future tasks need modification due to current implementation choices
|
- When future tasks need modification due to current implementation choices
|
||||||
- When new dependencies or requirements emerge
|
- When new dependencies or requirements emerge
|
||||||
- Use `update` / `task-master update --from=<futureTaskId> --prompt="<explanation>"` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to update multiple future tasks.
|
- Use `update` / `task-master update --from=<futureTaskId> --prompt='<explanation>\nUpdate context...'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to update multiple future tasks.
|
||||||
- Use `update_task` / `task-master update-task --id=<taskId> --prompt="<explanation>"` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to update a single specific task.
|
- Use `update_task` / `task-master update-task --id=<taskId> --prompt='<explanation>\nUpdate context...'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to update a single specific task.
|
||||||
|
|
||||||
## Task Status Management
|
## Task Status Management
|
||||||
|
|
||||||
@@ -150,6 +150,59 @@ Task Master offers two primary ways to interact:
|
|||||||
- Task files are automatically regenerated after dependency changes
|
- Task files are automatically regenerated after dependency changes
|
||||||
- Dependencies are visualized with status indicators in task listings and files
|
- Dependencies are visualized with status indicators in task listings and files
|
||||||
|
|
||||||
|
## Iterative Subtask Implementation
|
||||||
|
|
||||||
|
Once a task has been broken down into subtasks using `expand_task` or similar methods, follow this iterative process for implementation:
|
||||||
|
|
||||||
|
1. **Understand the Goal (Preparation):**
|
||||||
|
* Use `get_task` / `task-master show <subtaskId>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to thoroughly understand the specific goals and requirements of the subtask.
|
||||||
|
|
||||||
|
2. **Initial Exploration & Planning (Iteration 1):**
|
||||||
|
* This is the first attempt at creating a concrete implementation plan.
|
||||||
|
* Explore the codebase to identify the precise files, functions, and even specific lines of code that will need modification.
|
||||||
|
* Determine the intended code changes (diffs) and their locations.
|
||||||
|
* Gather *all* relevant details from this exploration phase.
|
||||||
|
|
||||||
|
3. **Log the Plan:**
|
||||||
|
* Run `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='<detailed plan>'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
|
||||||
|
* Provide the *complete and detailed* findings from the exploration phase in the prompt. Include file paths, line numbers, proposed diffs, reasoning, and any potential challenges identified. Do not omit details. The goal is to create a rich, timestamped log within the subtask's `details`.
|
||||||
|
|
||||||
|
4. **Verify the Plan:**
|
||||||
|
* Run `get_task` / `task-master show <subtaskId>` again to confirm that the detailed implementation plan has been successfully appended to the subtask's details.
|
||||||
|
|
||||||
|
5. **Begin Implementation:**
|
||||||
|
* Set the subtask status using `set_task_status` / `task-master set-status --id=<subtaskId> --status=in-progress` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
|
||||||
|
* Start coding based on the logged plan.
|
||||||
|
|
||||||
|
6. **Refine and Log Progress (Iteration 2+):**
|
||||||
|
* As implementation progresses, you will encounter challenges, discover nuances, or confirm successful approaches.
|
||||||
|
* **Before appending new information**: Briefly review the *existing* details logged in the subtask (using `get_task` or recalling from context) to ensure the update adds fresh insights and avoids redundancy.
|
||||||
|
* **Regularly** use `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='<update details>\n- What worked...\n- What didn't work...'` to append new findings.
|
||||||
|
* **Crucially, log:**
|
||||||
|
* What worked ("fundamental truths" discovered).
|
||||||
|
* What didn't work and why (to avoid repeating mistakes).
|
||||||
|
* Specific code snippets or configurations that were successful.
|
||||||
|
* Decisions made, especially if confirmed with user input.
|
||||||
|
* Any deviations from the initial plan and the reasoning.
|
||||||
|
* The objective is to continuously enrich the subtask's details, creating a log of the implementation journey that helps the AI (and human developers) learn, adapt, and avoid repeating errors.
|
||||||
|
|
||||||
|
7. **Review & Update Rules (Post-Implementation):**
|
||||||
|
* Once the implementation for the subtask is functionally complete, review all code changes and the relevant chat history.
|
||||||
|
* Identify any new or modified code patterns, conventions, or best practices established during the implementation.
|
||||||
|
* Create new or update existing Cursor rules in the `.cursor/rules/` directory to capture these patterns, following the guidelines in [`cursor_rules.mdc`](mdc:.cursor/rules/cursor_rules.mdc) and [`self_improve.mdc`](mdc:.cursor/rules/self_improve.mdc).
|
||||||
|
|
||||||
|
8. **Mark Task Complete:**
|
||||||
|
* After verifying the implementation and updating any necessary rules, mark the subtask as completed: `set_task_status` / `task-master set-status --id=<subtaskId> --status=done`.
|
||||||
|
|
||||||
|
9. **Commit Changes (If using Git):**
|
||||||
|
* Stage the relevant code changes and any updated/new rule files (`git add .`).
|
||||||
|
* Craft a comprehensive Git commit message summarizing the work done for the subtask, including both code implementation and any rule adjustments.
|
||||||
|
* Execute the commit command directly in the terminal (e.g., `git commit -m 'feat(module): Implement feature X for subtask <subtaskId>\n\n- Details about changes...\n- Updated rule Y for pattern Z'`).
|
||||||
|
* Consider if a Changeset is needed according to [`changeset.mdc`](mdc:.cursor/rules/changeset.mdc). If so, run `npm run changeset`, stage the generated file, and amend the commit or create a new one.
|
||||||
|
|
||||||
|
10. **Proceed to Next Subtask:**
|
||||||
|
* Identify the next subtask in the dependency chain (e.g., using `next_task` / `task-master next`) and repeat this iterative process starting from step 1.
|
||||||
|
|
||||||
## Code Analysis & Refactoring Techniques
|
## Code Analysis & Refactoring Techniques
|
||||||
|
|
||||||
- **Top-Level Function Search**:
|
- **Top-Level Function Search**:
|
||||||
|
|||||||
@@ -67,65 +67,127 @@ When implementing a new direct function in `mcp-server/src/core/direct-functions
|
|||||||
```
|
```
|
||||||
|
|
||||||
4. **Comprehensive Error Handling**:
|
4. **Comprehensive Error Handling**:
|
||||||
- ✅ **DO**: Wrap core function calls in try/catch blocks
|
- ✅ **DO**: Wrap core function calls *and AI calls* in try/catch blocks
|
||||||
- ✅ **DO**: Log errors with appropriate severity and context
|
- ✅ **DO**: Log errors with appropriate severity and context
|
||||||
- ✅ **DO**: Return standardized error objects with code and message
|
- ✅ **DO**: Return standardized error objects with code and message (`{ success: false, error: { code: '...', message: '...' } }`)
|
||||||
- ✅ **DO**: Handle file system errors separately from function-specific errors
|
- ✅ **DO**: Handle file system errors, AI client errors, AI processing errors, and core function errors distinctly with appropriate codes.
|
||||||
- **Example**:
|
- **Example**:
|
||||||
```javascript
|
```javascript
|
||||||
try {
|
try {
|
||||||
// Core function call
|
// Core function call or AI logic
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Failed to execute command: ${error.message}`);
|
log.error(`Failed to execute direct function logic: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: error.code || 'DIRECT_FUNCTION_ERROR',
|
code: error.code || 'DIRECT_FUNCTION_ERROR', // Use specific codes like AI_CLIENT_ERROR, etc.
|
||||||
message: error.message,
|
message: error.message,
|
||||||
details: error.stack
|
details: error.stack // Optional: Include stack in debug mode
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false // Ensure this is included if applicable
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
5. **Silent Mode Implementation**:
|
5. **Handling Logging Context (`mcpLog`)**:
|
||||||
- ✅ **DO**: Import silent mode utilities at the top of your file
|
- **Requirement**: Core functions that use the internal `report` helper function (common in `task-manager.js`, `dependency-manager.js`, etc.) expect the `options` object to potentially contain an `mcpLog` property. This `mcpLog` object **must** have callable methods for each log level (e.g., `mcpLog.info(...)`, `mcpLog.error(...)`).
|
||||||
|
- **Challenge**: The `log` object provided by FastMCP to the direct function's context, while functional, might not perfectly match this expected structure or could change in the future. Passing it directly can lead to runtime errors like `mcpLog[level] is not a function`.
|
||||||
|
- **Solution: The Logger Wrapper Pattern**: To reliably bridge the FastMCP `log` object and the core function's `mcpLog` expectation, use a simple wrapper object within the direct function:
|
||||||
```javascript
|
```javascript
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
// Standard logWrapper pattern within a Direct Function
|
||||||
```
|
const logWrapper = {
|
||||||
- ✅ **DO**: Wrap core function calls with silent mode control
|
info: (message, ...args) => log.info(message, ...args),
|
||||||
```javascript
|
warn: (message, ...args) => log.warn(message, ...args),
|
||||||
// Enable silent mode before the core function call
|
error: (message, ...args) => log.error(message, ...args),
|
||||||
enableSilentMode();
|
debug: (message, ...args) => log.debug && log.debug(message, ...args), // Handle optional debug
|
||||||
|
success: (message, ...args) => log.info(message, ...args) // Map success to info if needed
|
||||||
|
};
|
||||||
|
|
||||||
// Execute core function
|
// ... later when calling the core function ...
|
||||||
const result = await coreFunction(param1, param2);
|
await coreFunction(
|
||||||
|
// ... other arguments ...
|
||||||
// Restore normal logging
|
tasksPath,
|
||||||
disableSilentMode();
|
taskId,
|
||||||
|
{
|
||||||
|
mcpLog: logWrapper, // Pass the wrapper object
|
||||||
|
session
|
||||||
|
},
|
||||||
|
'json' // Pass 'json' output format if supported by core function
|
||||||
|
);
|
||||||
```
|
```
|
||||||
- ✅ **DO**: Add proper error handling to ensure silent mode is disabled
|
- **Critical For JSON Output Format**: Passing the `logWrapper` as `mcpLog` serves a dual purpose:
|
||||||
|
1. **Prevents Runtime Errors**: It ensures the `mcpLog[level](...)` calls within the core function succeed
|
||||||
|
2. **Controls Output Format**: In functions like `updateTaskById` and `updateSubtaskById`, the presence of `mcpLog` in the options triggers setting `outputFormat = 'json'` (instead of 'text'). This prevents UI elements (spinners, boxes) from being generated, which would break the JSON response.
|
||||||
|
- **Proven Solution**: This pattern has successfully fixed multiple issues in our MCP tools (including `update-task` and `update-subtask`), where direct passing of the `log` object or omitting `mcpLog` led to either runtime errors or JSON parsing failures from UI output.
|
||||||
|
- **When To Use**: Implement this wrapper in any direct function that calls a core function with an `options` object that might use `mcpLog` for logging or output format control.
|
||||||
|
- **Why it Works**: The `logWrapper` explicitly defines the `.info()`, `.warn()`, `.error()`, etc., methods that the core function's `report` helper needs, ensuring the `mcpLog[level](...)` call succeeds. It simply forwards the logging calls to the actual FastMCP `log` object.
|
||||||
|
- **Combined with Silent Mode**: Remember that using the `logWrapper` for `mcpLog` is **necessary *in addition* to using `enableSilentMode()` / `disableSilentMode()`** (see next point). The wrapper handles structured logging *within* the core function, while silent mode suppresses direct `console.log` and UI elements (spinners, boxes) that would break the MCP JSON response.
|
||||||
|
|
||||||
|
6. **Silent Mode Implementation**:
|
||||||
|
- ✅ **DO**: Import silent mode utilities at the top: `import { enableSilentMode, disableSilentMode, isSilentMode } from '../../../../scripts/modules/utils.js';`
|
||||||
|
- ✅ **DO**: Ensure core Task Master functions called from direct functions do **not** pollute `stdout` with console output (banners, spinners, logs) that would break MCP's JSON communication.
|
||||||
|
- **Preferred**: Modify the core function to accept an `outputFormat: 'json'` parameter and check it internally before printing UI elements. Pass `'json'` from the direct function.
|
||||||
|
- **Required Fallback/Guarantee**: If the core function cannot be modified or its output suppression is unreliable, **wrap the core function call** within the direct function using `enableSilentMode()` / `disableSilentMode()` in a `try/finally` block. This guarantees no console output interferes with the MCP response.
|
||||||
|
- ✅ **DO**: Use `isSilentMode()` function to check global silent mode status if needed (rare in direct functions), NEVER access the global `silentMode` variable directly.
|
||||||
|
- ❌ **DON'T**: Wrap AI client initialization or AI API calls in `enable/disableSilentMode`; their logging is controlled via the `log` object (passed potentially within the `logWrapper` for core functions).
|
||||||
|
- ❌ **DON'T**: Assume a core function is silent just because it *should* be. Verify or use the `enable/disableSilentMode` wrapper.
|
||||||
|
- **Example (Direct Function Guaranteeing Silence and using Log Wrapper)**:
|
||||||
```javascript
|
```javascript
|
||||||
|
export async function coreWrapperDirect(args, log, context = {}) {
|
||||||
|
const { session } = context;
|
||||||
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
|
// Create the logger wrapper
|
||||||
|
const logWrapper = { /* ... as defined above ... */ };
|
||||||
|
|
||||||
|
enableSilentMode(); // Ensure silence for direct console output
|
||||||
try {
|
try {
|
||||||
enableSilentMode();
|
// Call core function, passing wrapper and 'json' format
|
||||||
// Core function execution
|
const result = await coreFunction(
|
||||||
const result = await coreFunction(param1, param2);
|
tasksPath,
|
||||||
disableSilentMode();
|
args.param1,
|
||||||
|
{ mcpLog: logWrapper, session },
|
||||||
|
'json' // Explicitly request JSON format if supported
|
||||||
|
);
|
||||||
return { success: true, data: result };
|
return { success: true, data: result };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
log.error(`Error: ${error.message}`);
|
||||||
disableSilentMode();
|
// Return standardized error object
|
||||||
log.error(`Error in function: ${error.message}`);
|
return { success: false, error: { /* ... */ } };
|
||||||
return {
|
} finally {
|
||||||
success: false,
|
disableSilentMode(); // Critical: Always disable in finally
|
||||||
error: { code: 'ERROR_CODE', message: error.message }
|
}
|
||||||
};
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
- ❌ **DON'T**: Forget to disable silent mode when errors occur
|
|
||||||
- ❌ **DON'T**: Leave silent mode enabled outside a direct function's scope
|
7. **Debugging MCP/Core Logic Interaction**:
|
||||||
- ❌ **DON'T**: Skip silent mode for core function calls that generate logs
|
- ✅ **DO**: If an MCP tool fails with unclear errors (like JSON parsing failures), run the equivalent `task-master` CLI command in the terminal. The CLI often provides more detailed error messages originating from the core logic (e.g., `ReferenceError`, stack traces) that are obscured by the MCP layer.
|
||||||
|
|
||||||
|
### Specific Guidelines for AI-Based Direct Functions
|
||||||
|
|
||||||
|
Direct functions that interact with AI (e.g., `addTaskDirect`, `expandTaskDirect`) have additional responsibilities:
|
||||||
|
|
||||||
|
- **Context Parameter**: These functions receive an additional `context` object as their third parameter. **Critically, this object should only contain `{ session }`**. Do NOT expect or use `reportProgress` from this context.
|
||||||
|
```javascript
|
||||||
|
export async function yourAIDirect(args, log, context = {}) {
|
||||||
|
const { session } = context; // Only expect session
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- **AI Client Initialization**:
|
||||||
|
- ✅ **DO**: Use the utilities from [`mcp-server/src/core/utils/ai-client-utils.js`](mdc:mcp-server/src/core/utils/ai-client-utils.js) (e.g., `getAnthropicClientForMCP(session, log)`) to get AI client instances. These correctly use the `session` object to resolve API keys.
|
||||||
|
- ✅ **DO**: Wrap client initialization in a try/catch block and return a specific `AI_CLIENT_ERROR` on failure.
|
||||||
|
- **AI Interaction**:
|
||||||
|
- ✅ **DO**: Build prompts using helper functions where appropriate (e.g., from `ai-prompt-helpers.js`).
|
||||||
|
- ✅ **DO**: Make the AI API call using appropriate helpers (e.g., `_handleAnthropicStream`). Pass the `log` object to these helpers for internal logging. **Do NOT pass `reportProgress`**.
|
||||||
|
- ✅ **DO**: Parse the AI response using helpers (e.g., `parseTaskJsonResponse`) and handle parsing errors with a specific code (e.g., `RESPONSE_PARSING_ERROR`).
|
||||||
|
- **Calling Core Logic**:
|
||||||
|
- ✅ **DO**: After successful AI interaction, call the relevant core Task Master function (from `scripts/modules/`) if needed (e.g., `addTaskDirect` calls `addTask`).
|
||||||
|
- ✅ **DO**: Pass necessary data, including potentially the parsed AI results, to the core function.
|
||||||
|
- ✅ **DO**: If the core function can produce console output, call it with an `outputFormat: 'json'` argument (or similar, depending on the function) to suppress CLI output. Ensure the core function is updated to respect this. Use `enableSilentMode/disableSilentMode` around the core function call as a fallback if `outputFormat` is not supported or insufficient.
|
||||||
|
- **Progress Indication**:
|
||||||
|
- ❌ **DON'T**: Call `reportProgress` within the direct function.
|
||||||
|
- ✅ **DO**: If intermediate progress status is needed *within* the long-running direct function, use standard logging: `log.info('Progress: Processing AI response...')`.
|
||||||
|
|
||||||
## Tool Definition and Execution
|
## Tool Definition and Execution
|
||||||
|
|
||||||
@@ -159,14 +221,21 @@ server.addTool({
|
|||||||
The `execute` function receives validated arguments and the FastMCP context:
|
The `execute` function receives validated arguments and the FastMCP context:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
// Standard signature
|
||||||
execute: async (args, context) => {
|
execute: async (args, context) => {
|
||||||
// Tool implementation
|
// Tool implementation
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Destructured signature (recommended)
|
||||||
|
execute: async (args, { log, reportProgress, session }) => {
|
||||||
|
// Tool implementation
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- **args**: The first parameter contains all the validated parameters defined in the tool's schema.
|
- **args**: The first parameter contains all the validated parameters defined in the tool's schema.
|
||||||
- **context**: The second parameter is an object containing `{ log, reportProgress, session }` provided by FastMCP.
|
- **context**: The second parameter is an object containing `{ log, reportProgress, session }` provided by FastMCP.
|
||||||
- ✅ **DO**: `execute: async (args, { log, reportProgress, session }) => {}`
|
- ✅ **DO**: Use `{ log, session }` when calling direct functions.
|
||||||
|
- ⚠️ **WARNING**: Avoid passing `reportProgress` down to direct functions due to client compatibility issues. See Progress Reporting Convention below.
|
||||||
|
|
||||||
### Standard Tool Execution Pattern
|
### Standard Tool Execution Pattern
|
||||||
|
|
||||||
@@ -174,20 +243,27 @@ The `execute` method within each MCP tool (in `mcp-server/src/tools/*.js`) shoul
|
|||||||
|
|
||||||
1. **Log Entry**: Log the start of the tool execution with relevant arguments.
|
1. **Log Entry**: Log the start of the tool execution with relevant arguments.
|
||||||
2. **Get Project Root**: Use the `getProjectRootFromSession(session, log)` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) to extract the project root path from the client session. Fall back to `args.projectRoot` if the session doesn't provide a root.
|
2. **Get Project Root**: Use the `getProjectRootFromSession(session, log)` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) to extract the project root path from the client session. Fall back to `args.projectRoot` if the session doesn't provide a root.
|
||||||
3. **Call Direct Function**: Invoke the corresponding `*Direct` function wrapper (e.g., `listTasksDirect` from [`task-master-core.js`](mdc:mcp-server/src/core/task-master-core.js)), passing an updated `args` object that includes the resolved `projectRoot`, along with the `log` object: `await someDirectFunction({ ...args, projectRoot: resolvedRootFolder }, log);`
|
3. **Call Direct Function**: Invoke the corresponding `*Direct` function wrapper (e.g., `listTasksDirect` from [`task-master-core.js`](mdc:mcp-server/src/core/task-master-core.js)), passing an updated `args` object that includes the resolved `projectRoot`. Crucially, the third argument (context) passed to the direct function should **only include `{ log, session }`**. **Do NOT pass `reportProgress`**.
|
||||||
|
```javascript
|
||||||
|
// Example call to a non-AI direct function
|
||||||
|
const result = await someDirectFunction({ ...args, projectRoot }, log);
|
||||||
|
|
||||||
|
// Example call to an AI-based direct function
|
||||||
|
const resultAI = await someAIDirect({ ...args, projectRoot }, log, { session });
|
||||||
|
```
|
||||||
4. **Handle Result**: Receive the result object (`{ success, data/error, fromCache }`) from the `*Direct` function.
|
4. **Handle Result**: Receive the result object (`{ success, data/error, fromCache }`) from the `*Direct` function.
|
||||||
5. **Format Response**: Pass this result object to the `handleApiResult` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) for standardized MCP response formatting and error handling.
|
5. **Format Response**: Pass this result object to the `handleApiResult` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) for standardized MCP response formatting and error handling.
|
||||||
6. **Return**: Return the formatted response object provided by `handleApiResult`.
|
6. **Return**: Return the formatted response object provided by `handleApiResult`.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// Example execute method structure
|
// Example execute method structure for a tool calling an AI-based direct function
|
||||||
import { getProjectRootFromSession, handleApiResult, createErrorResponse } from './utils.js';
|
import { getProjectRootFromSession, handleApiResult, createErrorResponse } from './utils.js';
|
||||||
import { someDirectFunction } from '../core/task-master-core.js';
|
import { someAIDirectFunction } from '../core/task-master-core.js';
|
||||||
|
|
||||||
// ... inside server.addTool({...})
|
// ... inside server.addTool({...})
|
||||||
execute: async (args, { log, reportProgress, session }) => {
|
execute: async (args, { log, session }) => { // Note: reportProgress is omitted here
|
||||||
try {
|
try {
|
||||||
log.info(`Starting tool execution with args: ${JSON.stringify(args)}`);
|
log.info(`Starting AI tool execution with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// 1. Get Project Root
|
// 1. Get Project Root
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
@@ -196,17 +272,17 @@ execute: async (args, { log, reportProgress, session }) => {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Call Direct Function (passing resolved root)
|
// 2. Call AI-Based Direct Function (passing only log and session in context)
|
||||||
const result = await someDirectFunction({
|
const result = await someAIDirectFunction({
|
||||||
...args,
|
...args,
|
||||||
projectRoot: rootFolder // Ensure projectRoot is explicitly passed
|
projectRoot: rootFolder // Ensure projectRoot is explicitly passed
|
||||||
}, log);
|
}, log, { session }); // Pass session here, NO reportProgress
|
||||||
|
|
||||||
// 3. Handle and Format Response
|
// 3. Handle and Format Response
|
||||||
return handleApiResult(result, log);
|
return handleApiResult(result, log);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error during tool execution: ${error.message}`);
|
log.error(`Error during AI tool execution: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -214,15 +290,17 @@ execute: async (args, { log, reportProgress, session }) => {
|
|||||||
|
|
||||||
### Using AsyncOperationManager for Background Tasks
|
### Using AsyncOperationManager for Background Tasks
|
||||||
|
|
||||||
For tools that execute long-running operations, use the AsyncOperationManager to run them in the background:
|
For tools that execute potentially long-running operations *where the AI call is just one part* (e.g., `expand-task`, `update`), use the AsyncOperationManager. The `add-task` command, as refactored, does *not* require this in the MCP tool layer because the direct function handles the primary AI work and returns the final result synchronously from the perspective of the MCP tool.
|
||||||
|
|
||||||
|
For tools that *do* use `AsyncOperationManager`:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
import { asyncOperationManager } from '../core/utils/async-manager.js';
|
import { AsyncOperationManager } from '../utils/async-operation-manager.js'; // Correct path assuming utils location
|
||||||
import { getProjectRootFromSession, createContentResponse, createErrorResponse } from './utils.js';
|
import { getProjectRootFromSession, createContentResponse, createErrorResponse } from './utils.js';
|
||||||
import { someIntensiveDirect } from '../core/task-master-core.js';
|
import { someIntensiveDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
// ... inside server.addTool({...})
|
// ... inside server.addTool({...})
|
||||||
execute: async (args, { log, reportProgress, session }) => {
|
execute: async (args, { log, session }) => { // Note: reportProgress omitted
|
||||||
try {
|
try {
|
||||||
log.info(`Starting background operation with args: ${JSON.stringify(args)}`);
|
log.info(`Starting background operation with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
@@ -233,52 +311,58 @@ execute: async (args, { log, reportProgress, session }) => {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Add operation to the async manager
|
// Create operation description
|
||||||
const operationId = asyncOperationManager.addOperation(
|
const operationDescription = `Expanding task ${args.id}...`; // Example
|
||||||
someIntensiveDirect, // The direct function to execute
|
|
||||||
{ ...args, projectRoot: rootFolder }, // Args to pass
|
// 2. Start async operation using AsyncOperationManager
|
||||||
{ log, reportProgress, session } // Context to preserve
|
const operation = AsyncOperationManager.createOperation(
|
||||||
|
operationDescription,
|
||||||
|
async (reportProgressCallback) => { // This callback is provided by AsyncOperationManager
|
||||||
|
// This runs in the background
|
||||||
|
try {
|
||||||
|
// Report initial progress *from the manager's callback*
|
||||||
|
reportProgressCallback({ progress: 0, status: 'Starting operation...' });
|
||||||
|
|
||||||
|
// Call the direct function (passing only session context)
|
||||||
|
const result = await someIntensiveDirect(
|
||||||
|
{ ...args, projectRoot: rootFolder },
|
||||||
|
log,
|
||||||
|
{ session } // Pass session, NO reportProgress
|
||||||
|
);
|
||||||
|
|
||||||
|
// Report final progress *from the manager's callback*
|
||||||
|
reportProgressCallback({
|
||||||
|
progress: 100,
|
||||||
|
status: result.success ? 'Operation completed' : 'Operation failed',
|
||||||
|
result: result.data, // Include final data if successful
|
||||||
|
error: result.error // Include error object if failed
|
||||||
|
});
|
||||||
|
|
||||||
|
return result; // Return the direct function's result
|
||||||
|
} catch (error) {
|
||||||
|
// Handle errors within the async task
|
||||||
|
reportProgressCallback({
|
||||||
|
progress: 100,
|
||||||
|
status: 'Operation failed critically',
|
||||||
|
error: { message: error.message, code: error.code || 'ASYNC_OPERATION_FAILED' }
|
||||||
|
});
|
||||||
|
throw error; // Re-throw for the manager to catch
|
||||||
|
}
|
||||||
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// 3. Return immediate response with operation ID
|
// 3. Return immediate response with operation ID
|
||||||
return createContentResponse({
|
return {
|
||||||
message: "Operation started successfully",
|
status: 202, // StatusCodes.ACCEPTED
|
||||||
operationId,
|
body: {
|
||||||
status: "pending"
|
success: true,
|
||||||
});
|
message: 'Operation started',
|
||||||
|
operationId: operation.id
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error starting background operation: ${error.message}`);
|
log.error(`Error starting background operation: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(`Failed to start operation: ${error.message}`); // Use standard error response
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Clients should then use the `get_operation_status` tool to check on operation progress:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
// In get-operation-status.js
|
|
||||||
import { asyncOperationManager } from '../core/utils/async-manager.js';
|
|
||||||
import { createContentResponse, createErrorResponse } from './utils.js';
|
|
||||||
|
|
||||||
// ... inside server.addTool({...})
|
|
||||||
execute: async (args, { log }) => {
|
|
||||||
try {
|
|
||||||
const { operationId } = args;
|
|
||||||
log.info(`Checking status of operation: ${operationId}`);
|
|
||||||
|
|
||||||
const status = asyncOperationManager.getStatus(operationId);
|
|
||||||
|
|
||||||
if (status.status === 'not_found') {
|
|
||||||
return createErrorResponse(status.error.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
return createContentResponse({
|
|
||||||
...status,
|
|
||||||
message: `Operation status: ${status.status}`
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
log.error(`Error checking operation status: ${error.message}`);
|
|
||||||
return createErrorResponse(error.message);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -322,7 +406,7 @@ export function registerInitializeProjectTool(server) {
|
|||||||
|
|
||||||
### Logging Convention
|
### Logging Convention
|
||||||
|
|
||||||
The `log` object (destructured from `context`) provides standardized logging methods. Use it within both the `execute` method and the `*Direct` functions.
|
The `log` object (destructured from `context`) provides standardized logging methods. Use it within both the `execute` method and the `*Direct` functions. **If progress indication is needed within a direct function, use `log.info()` instead of `reportProgress`**.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// Proper logging usage
|
// Proper logging usage
|
||||||
@@ -330,19 +414,14 @@ log.info(`Starting ${toolName} with parameters: ${JSON.stringify(sanitizedArgs)}
|
|||||||
log.debug("Detailed operation info", { data });
|
log.debug("Detailed operation info", { data });
|
||||||
log.warn("Potential issue detected");
|
log.warn("Potential issue detected");
|
||||||
log.error(`Error occurred: ${error.message}`, { stack: error.stack });
|
log.error(`Error occurred: ${error.message}`, { stack: error.stack });
|
||||||
|
log.info('Progress: 50% - AI call initiated...'); // Example progress logging
|
||||||
```
|
```
|
||||||
|
|
||||||
### Progress Reporting Convention
|
### Progress Reporting Convention
|
||||||
|
|
||||||
Use `reportProgress` (destructured from `context`) for long-running operations. It expects an object `{ progress: number, total?: number }`.
|
- ⚠️ **DEPRECATED within Direct Functions**: The `reportProgress` function passed in the `context` object should **NOT** be called from within `*Direct` functions. Doing so can cause client-side validation errors due to missing/incorrect `progressToken` handling.
|
||||||
|
- ✅ **DO**: For tools using `AsyncOperationManager`, use the `reportProgressCallback` function *provided by the manager* within the background task definition (as shown in the `AsyncOperationManager` example above) to report progress updates for the *overall operation*.
|
||||||
```javascript
|
- ✅ **DO**: If finer-grained progress needs to be indicated *during* the execution of a `*Direct` function (whether called directly or via `AsyncOperationManager`), use `log.info()` statements (e.g., `log.info('Progress: Parsing AI response...')`).
|
||||||
await reportProgress({ progress: 0 }); // Start
|
|
||||||
// ... work ...
|
|
||||||
await reportProgress({ progress: 50 }); // Intermediate (total optional)
|
|
||||||
// ... more work ...
|
|
||||||
await reportProgress({ progress: 100 }); // Complete
|
|
||||||
```
|
|
||||||
|
|
||||||
### Session Usage Convention
|
### Session Usage Convention
|
||||||
|
|
||||||
@@ -350,32 +429,39 @@ The `session` object (destructured from `context`) contains authenticated sessio
|
|||||||
|
|
||||||
- **Authentication**: Access user-specific data (`session.userId`, etc.) if authentication is implemented.
|
- **Authentication**: Access user-specific data (`session.userId`, etc.) if authentication is implemented.
|
||||||
- **Project Root**: The primary use in Task Master is accessing `session.roots` to determine the client's project root directory via the `getProjectRootFromSession` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)). See the Standard Tool Execution Pattern above.
|
- **Project Root**: The primary use in Task Master is accessing `session.roots` to determine the client's project root directory via the `getProjectRootFromSession` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)). See the Standard Tool Execution Pattern above.
|
||||||
|
- **Environment Variables**: The `session.env` object is critical for AI tools. Pass the `session` object to the `*Direct` function's context, and then to AI client utility functions (like `getAnthropicClientForMCP`) which will extract API keys and other relevant environment settings (e.g., `MODEL`, `MAX_TOKENS`) from `session.env`.
|
||||||
- **Capabilities**: Can be used to check client capabilities (`session.clientCapabilities`).
|
- **Capabilities**: Can be used to check client capabilities (`session.clientCapabilities`).
|
||||||
|
|
||||||
## Direct Function Wrappers (`*Direct`)
|
## Direct Function Wrappers (`*Direct`)
|
||||||
|
|
||||||
These functions, located in `mcp-server/src/core/direct-functions/`, form the core logic execution layer for MCP tools.
|
These functions, located in `mcp-server/src/core/direct-functions/`, form the core logic execution layer for MCP tools.
|
||||||
|
|
||||||
- **Purpose**: Bridge MCP tools and core Task Master modules (`scripts/modules/*`).
|
- **Purpose**: Bridge MCP tools and core Task Master modules (`scripts/modules/*`). Handle AI interactions if applicable.
|
||||||
- **Responsibilities**:
|
- **Responsibilities**:
|
||||||
- Receive `args` (including the `projectRoot` determined by the tool) and `log` object.
|
- Receive `args` (including the `projectRoot` determined by the tool), `log` object, and optionally a `context` object (containing **only `{ session }` if needed).
|
||||||
- **Find `tasks.json`**: Use `findTasksJsonPath(args, log)` from [`core/utils/path-utils.js`](mdc:mcp-server/src/core/utils/path-utils.js). This function prioritizes the provided `args.projectRoot`.
|
- **Find `tasks.json`**: Use `findTasksJsonPath(args, log)` from [`core/utils/path-utils.js`](mdc:mcp-server/src/core/utils/path-utils.js).
|
||||||
- Validate arguments specific to the core logic.
|
- Validate arguments specific to the core logic.
|
||||||
- **Implement Silent Mode**: Import and use `enableSilentMode` and `disableSilentMode` around core function calls.
|
- **Handle AI Logic (if applicable)**: Initialize AI clients (using `session` from context), build prompts, make AI calls, parse responses.
|
||||||
- **Implement Caching**: Use `getCachedOrExecute` from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js) for read operations.
|
- **Implement Caching (if applicable)**: Use `getCachedOrExecute` from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js) for read operations.
|
||||||
- Call the underlying function from the core Task Master modules.
|
- **Call Core Logic**: Call the underlying function from the core Task Master modules, passing necessary data (including AI results if applicable).
|
||||||
- Handle errors gracefully.
|
- ✅ **DO**: Pass `outputFormat: 'json'` (or similar) to the core function if it might produce console output.
|
||||||
- Return a standardized result object: `{ success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }`.
|
- ✅ **DO**: Wrap the core function call with `enableSilentMode/disableSilentMode` if necessary.
|
||||||
|
- Handle errors gracefully (AI errors, core logic errors, file errors).
|
||||||
|
- Return a standardized result object: `{ success: boolean, data?: any, error?: { code: string, message: string }, fromCache?: boolean }`.
|
||||||
|
- ❌ **DON'T**: Call `reportProgress`. Use `log.info` for progress indication if needed.
|
||||||
|
|
||||||
## Key Principles
|
## Key Principles
|
||||||
|
|
||||||
- **Prefer Direct Function Calls**: MCP tools should always call `*Direct` wrappers instead of `executeTaskMasterCommand`.
|
- **Prefer Direct Function Calls**: MCP tools should always call `*Direct` wrappers instead of `executeTaskMasterCommand`.
|
||||||
- **Standardized Execution Flow**: Follow the pattern: MCP Tool -> `getProjectRootFromSession` -> `*Direct` Function -> Core Logic.
|
- **Standardized Execution Flow**: Follow the pattern: MCP Tool -> `getProjectRootFromSession` -> `*Direct` Function -> Core Logic / AI Logic.
|
||||||
- **Path Resolution via Direct Functions**: The `*Direct` function is responsible for finding the exact `tasks.json` path using `findTasksJsonPath`, relying on the `projectRoot` passed in `args`.
|
- **Path Resolution via Direct Functions**: The `*Direct` function is responsible for finding the exact `tasks.json` path using `findTasksJsonPath`, relying on the `projectRoot` passed in `args`.
|
||||||
- **Silent Mode in Direct Functions**: Wrap all core function calls with `enableSilentMode()` and `disableSilentMode()` to prevent logs from interfering with JSON responses.
|
- **AI Logic in Direct Functions**: For AI-based tools, the `*Direct` function handles AI client initialization, calls, and parsing, using the `session` object passed in its context.
|
||||||
- **Async Processing for Intensive Operations**: Use AsyncOperationManager for CPU-intensive or long-running operations.
|
- **Silent Mode in Direct Functions**: Wrap *core function* calls (from `scripts/modules`) with `enableSilentMode()` and `disableSilentMode()` if they produce console output not handled by `outputFormat`. Do not wrap AI calls.
|
||||||
|
- **Selective Async Processing**: Use `AsyncOperationManager` in the *MCP Tool layer* for operations involving multiple steps or long waits beyond a single AI call (e.g., file processing + AI call + file writing). Simple AI calls handled entirely within the `*Direct` function (like `addTaskDirect`) may not need it at the tool layer.
|
||||||
|
- **No `reportProgress` in Direct Functions**: Do not pass or use `reportProgress` within `*Direct` functions. Use `log.info()` for internal progress or report progress from the `AsyncOperationManager` callback in the MCP tool layer.
|
||||||
|
- **Output Formatting**: Ensure core functions called by `*Direct` functions can suppress CLI output, ideally via an `outputFormat` parameter.
|
||||||
- **Project Initialization**: Use the initialize_project tool for setting up new projects in integrated environments.
|
- **Project Initialization**: Use the initialize_project tool for setting up new projects in integrated environments.
|
||||||
- **Centralized Utilities**: Use helpers from `mcp-server/src/tools/utils.js` (like `handleApiResult`, `getProjectRootFromSession`, `getCachedOrExecute`) and `mcp-server/src/core/utils/path-utils.js` (`findTasksJsonPath`). See [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc).
|
- **Centralized Utilities**: Use helpers from `mcp-server/src/tools/utils.js`, `mcp-server/src/core/utils/path-utils.js`, and `mcp-server/src/core/utils/ai-client-utils.js`. See [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc).
|
||||||
- **Caching in Direct Functions**: Caching logic resides *within* the `*Direct` functions using `getCachedOrExecute`.
|
- **Caching in Direct Functions**: Caching logic resides *within* the `*Direct` functions using `getCachedOrExecute`.
|
||||||
|
|
||||||
## Resources and Resource Templates
|
## Resources and Resource Templates
|
||||||
@@ -392,32 +478,38 @@ Resources provide LLMs with static or dynamic data without executing tools.
|
|||||||
|
|
||||||
Follow these steps to add MCP support for an existing Task Master command (see [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for more detail):
|
Follow these steps to add MCP support for an existing Task Master command (see [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for more detail):
|
||||||
|
|
||||||
1. **Ensure Core Logic Exists**: Verify the core functionality is implemented and exported from the relevant module in `scripts/modules/`.
|
1. **Ensure Core Logic Exists**: Verify the core functionality is implemented and exported from the relevant module in `scripts/modules/`. Ensure the core function can suppress console output (e.g., via an `outputFormat` parameter).
|
||||||
|
|
||||||
2. **Create Direct Function File in `mcp-server/src/core/direct-functions/`**:
|
2. **Create Direct Function File in `mcp-server/src/core/direct-functions/`**:
|
||||||
- Create a new file (e.g., `your-command.js`) using **kebab-case** naming.
|
- Create a new file (e.g., `your-command.js`) using **kebab-case** naming.
|
||||||
- Import necessary core functions, **`findTasksJsonPath` from `../utils/path-utils.js`**, and **silent mode utilities**.
|
- Import necessary core functions, `findTasksJsonPath`, silent mode utilities, and potentially AI client/prompt utilities.
|
||||||
- Implement `async function yourCommandDirect(args, log)` using **camelCase** with `Direct` suffix:
|
- Implement `async function yourCommandDirect(args, log, context = {})` using **camelCase** with `Direct` suffix. **Remember `context` should only contain `{ session }` if needed (for AI keys/config).**
|
||||||
- **Path Resolution**: Obtain the tasks file path using `const tasksPath = findTasksJsonPath(args, log);`. This handles project root detection automatically based on `args.projectRoot`.
|
- **Path Resolution**: Obtain `tasksPath` using `findTasksJsonPath(args, log)`.
|
||||||
- Parse other `args` and perform necessary validation.
|
- Parse other `args` and perform necessary validation.
|
||||||
- **Implement Silent Mode**: Wrap core function calls with enableSilentMode/disableSilentMode.
|
- **Handle AI (if applicable)**: Initialize clients using `get*ClientForMCP(session, log)`, build prompts, call AI, parse response. Handle AI-specific errors.
|
||||||
- **If Caching**: Implement caching using `getCachedOrExecute` from `../../tools/utils.js`.
|
- **Implement Caching (if applicable)**: Use `getCachedOrExecute`.
|
||||||
- **If Not Caching**: Directly call the core logic function within a try/catch block.
|
- **Call Core Logic**:
|
||||||
- Format the return as `{ success: true/false, data/error, fromCache: boolean }`.
|
- Wrap with `enableSilentMode/disableSilentMode` if necessary.
|
||||||
|
- Pass `outputFormat: 'json'` (or similar) if applicable.
|
||||||
|
- Handle errors from the core function.
|
||||||
|
- Format the return as `{ success: true/false, data/error, fromCache?: boolean }`.
|
||||||
|
- ❌ **DON'T**: Call `reportProgress`.
|
||||||
- Export the wrapper function.
|
- Export the wrapper function.
|
||||||
|
|
||||||
3. **Update `task-master-core.js` with Import/Export**: Import and re-export your `*Direct` function and add it to the `directFunctions` map.
|
3. **Update `task-master-core.js` with Import/Export**: Import and re-export your `*Direct` function and add it to the `directFunctions` map.
|
||||||
|
|
||||||
4. **Create MCP Tool (`mcp-server/src/tools/`)**:
|
4. **Create MCP Tool (`mcp-server/src/tools/`)**:
|
||||||
- Create a new file (e.g., `your-command.js`) using **kebab-case**.
|
- Create a new file (e.g., `your-command.js`) using **kebab-case**.
|
||||||
- Import `zod`, `handleApiResult`, `createErrorResponse`, **`getProjectRootFromSession`**, and your `yourCommandDirect` function.
|
- Import `zod`, `handleApiResult`, `createErrorResponse`, `getProjectRootFromSession`, and your `yourCommandDirect` function. Import `AsyncOperationManager` if needed.
|
||||||
- Implement `registerYourCommandTool(server)`.
|
- Implement `registerYourCommandTool(server)`.
|
||||||
- Define the tool `name` using **snake_case** (e.g., `your_command`).
|
- Define the tool `name` using **snake_case** (e.g., `your_command`).
|
||||||
- Define the `parameters` using `zod`. **Crucially, define `projectRoot` as optional**: `projectRoot: z.string().optional().describe(...)`. Include `file` if applicable.
|
- Define the `parameters` using `zod`. Include `projectRoot: z.string().optional()`.
|
||||||
- Implement the standard `async execute(args, { log, reportProgress, session })` method:
|
- Implement the `async execute(args, { log, session })` method (omitting `reportProgress` from destructuring).
|
||||||
- Get `rootFolder` using `getProjectRootFromSession` (with fallback to `args.projectRoot`).
|
- Get `rootFolder` using `getProjectRootFromSession(session, log)`.
|
||||||
- Call `yourCommandDirect({ ...args, projectRoot: rootFolder }, log)`.
|
- **Determine Execution Strategy**:
|
||||||
- Pass the result to `handleApiResult(result, log, 'Error Message')`.
|
- **If using `AsyncOperationManager`**: Create the operation, call the `*Direct` function from within the async task callback (passing `log` and `{ session }`), report progress *from the callback*, and return the initial `ACCEPTED` response.
|
||||||
|
- **If calling `*Direct` function synchronously** (like `add-task`): Call `await yourCommandDirect({ ...args, projectRoot }, log, { session });`. Handle the result with `handleApiResult`.
|
||||||
|
- ❌ **DON'T**: Pass `reportProgress` down to the direct function in either case.
|
||||||
|
|
||||||
5. **Register Tool**: Import and call `registerYourCommandTool` in `mcp-server/src/tools/index.js`.
|
5. **Register Tool**: Import and call `registerYourCommandTool` in `mcp-server/src/tools/index.js`.
|
||||||
|
|
||||||
|
|||||||
@@ -34,9 +34,9 @@ The standard pattern for adding a feature follows this workflow:
|
|||||||
## Critical Checklist for New Features
|
## Critical Checklist for New Features
|
||||||
|
|
||||||
- **Comprehensive Function Exports**:
|
- **Comprehensive Function Exports**:
|
||||||
- ✅ **DO**: Export all helper functions and utility methods needed by your new function
|
- ✅ **DO**: Export **all core functions, helper functions (like `generateSubtaskPrompt`), and utility methods** needed by your new function or command from their respective modules.
|
||||||
- ✅ **DO**: Review dependencies and ensure functions like `findTaskById`, `taskExists` are exported
|
- ✅ **DO**: **Explicitly review the module's `export { ... }` block** at the bottom of the file to ensure every required dependency (even seemingly minor helpers like `findTaskById`, `taskExists`, specific prompt generators, AI call handlers, etc.) is included.
|
||||||
- ❌ **DON'T**: Assume internal functions are already exported - always check and add them explicitly
|
- ❌ **DON'T**: Assume internal functions are already exported - **always verify**. A missing export will cause runtime errors (e.g., `ReferenceError: generateSubtaskPrompt is not defined`).
|
||||||
- **Example**: If implementing a feature that checks task existence, ensure the helper function is in exports:
|
- **Example**: If implementing a feature that checks task existence, ensure the helper function is in exports:
|
||||||
```javascript
|
```javascript
|
||||||
// At the bottom of your module file:
|
// At the bottom of your module file:
|
||||||
@@ -45,14 +45,21 @@ The standard pattern for adding a feature follows this workflow:
|
|||||||
yourNewFunction,
|
yourNewFunction,
|
||||||
taskExists, // Helper function used by yourNewFunction
|
taskExists, // Helper function used by yourNewFunction
|
||||||
findTaskById, // Helper function used by yourNewFunction
|
findTaskById, // Helper function used by yourNewFunction
|
||||||
|
generateSubtaskPrompt, // Helper needed by expand/add features
|
||||||
|
getSubtasksFromAI, // Helper needed by expand/add features
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Parameter Completeness**:
|
- **Parameter Completeness and Matching**:
|
||||||
- ✅ **DO**: Pass all required parameters to functions you call within your implementation
|
- ✅ **DO**: Pass all required parameters to functions you call within your implementation
|
||||||
- ✅ **DO**: Check function signatures before implementing calls to them
|
- ✅ **DO**: Check function signatures before implementing calls to them
|
||||||
|
- ✅ **DO**: Verify that direct function parameters match their core function counterparts
|
||||||
|
- ✅ **DO**: When implementing a direct function for MCP, ensure it only accepts parameters that exist in the core function
|
||||||
|
- ✅ **DO**: Verify the expected *internal structure* of complex object parameters (like the `mcpLog` object, see mcp.mdc for the required logger wrapper pattern)
|
||||||
|
- ❌ **DON'T**: Add parameters to direct functions that don't exist in core functions
|
||||||
- ❌ **DON'T**: Assume default parameter values will handle missing arguments
|
- ❌ **DON'T**: Assume default parameter values will handle missing arguments
|
||||||
- **Example**: When calling file generation, pass both required parameters:
|
- ❌ **DON'T**: Assume object parameters will work without verifying their required internal structure or methods.
|
||||||
|
- **Example**: When calling file generation, pass all required parameters:
|
||||||
```javascript
|
```javascript
|
||||||
// ✅ DO: Pass all required parameters
|
// ✅ DO: Pass all required parameters
|
||||||
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
||||||
@@ -61,11 +68,58 @@ The standard pattern for adding a feature follows this workflow:
|
|||||||
await generateTaskFiles(tasksPath); // Error - missing outputDir parameter
|
await generateTaskFiles(tasksPath); // Error - missing outputDir parameter
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Example**: Properly match direct function parameters to core function:
|
||||||
|
```javascript
|
||||||
|
// Core function signature
|
||||||
|
async function expandTask(tasksPath, taskId, numSubtasks, useResearch = false, additionalContext = '', options = {}) {
|
||||||
|
// Implementation...
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ DO: Match direct function parameters to core function
|
||||||
|
export async function expandTaskDirect(args, log, context = {}) {
|
||||||
|
// Extract only parameters that exist in the core function
|
||||||
|
const taskId = parseInt(args.id, 10);
|
||||||
|
const numSubtasks = args.num ? parseInt(args.num, 10) : undefined;
|
||||||
|
const useResearch = args.research === true;
|
||||||
|
const additionalContext = args.prompt || '';
|
||||||
|
|
||||||
|
// Call core function with matched parameters
|
||||||
|
const result = await expandTask(
|
||||||
|
tasksPath,
|
||||||
|
taskId,
|
||||||
|
numSubtasks,
|
||||||
|
useResearch,
|
||||||
|
additionalContext,
|
||||||
|
{ mcpLog: log, session: context.session }
|
||||||
|
);
|
||||||
|
|
||||||
|
// Return result
|
||||||
|
return { success: true, data: result, fromCache: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ DON'T: Use parameters that don't exist in the core function
|
||||||
|
export async function expandTaskDirect(args, log, context = {}) {
|
||||||
|
// DON'T extract parameters that don't exist in the core function!
|
||||||
|
const force = args.force === true; // ❌ WRONG - 'force' doesn't exist in core function
|
||||||
|
|
||||||
|
// DON'T pass non-existent parameters to core functions
|
||||||
|
const result = await expandTask(
|
||||||
|
tasksPath,
|
||||||
|
args.id,
|
||||||
|
args.num,
|
||||||
|
args.research,
|
||||||
|
args.prompt,
|
||||||
|
force, // ❌ WRONG - this parameter doesn't exist in the core function
|
||||||
|
{ mcpLog: log }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
- **Consistent File Path Handling**:
|
- **Consistent File Path Handling**:
|
||||||
- ✅ **DO**: Use consistent file naming conventions: `task_${id.toString().padStart(3, '0')}.txt`
|
- ✅ DO: Use consistent file naming conventions: `task_${id.toString().padStart(3, '0')}.txt`
|
||||||
- ✅ **DO**: Use `path.join()` for composing file paths
|
- ✅ DO: Use `path.join()` for composing file paths
|
||||||
- ✅ **DO**: Use appropriate file extensions (.txt for tasks, .json for data)
|
- ✅ DO: Use appropriate file extensions (.txt for tasks, .json for data)
|
||||||
- ❌ **DON'T**: Hardcode path separators or inconsistent file extensions
|
- ❌ DON'T: Hardcode path separators or inconsistent file extensions
|
||||||
- **Example**: Creating file paths for tasks:
|
- **Example**: Creating file paths for tasks:
|
||||||
```javascript
|
```javascript
|
||||||
// ✅ DO: Use consistent file naming and path.join
|
// ✅ DO: Use consistent file naming and path.join
|
||||||
@@ -79,10 +133,10 @@ The standard pattern for adding a feature follows this workflow:
|
|||||||
```
|
```
|
||||||
|
|
||||||
- **Error Handling and Reporting**:
|
- **Error Handling and Reporting**:
|
||||||
- ✅ **DO**: Use structured error objects with code and message properties
|
- ✅ DO: Use structured error objects with code and message properties
|
||||||
- ✅ **DO**: Include clear error messages identifying the specific problem
|
- ✅ DO: Include clear error messages identifying the specific problem
|
||||||
- ✅ **DO**: Handle both function-specific errors and potential file system errors
|
- ✅ DO: Handle both function-specific errors and potential file system errors
|
||||||
- ✅ **DO**: Log errors at appropriate severity levels
|
- ✅ DO: Log errors at appropriate severity levels
|
||||||
- **Example**: Structured error handling in core functions:
|
- **Example**: Structured error handling in core functions:
|
||||||
```javascript
|
```javascript
|
||||||
try {
|
try {
|
||||||
@@ -98,33 +152,43 @@ The standard pattern for adding a feature follows this workflow:
|
|||||||
```
|
```
|
||||||
|
|
||||||
- **Silent Mode Implementation**:
|
- **Silent Mode Implementation**:
|
||||||
- ✅ **DO**: Import silent mode utilities in direct functions: `import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';`
|
- ✅ **DO**: Import all silent mode utilities together:
|
||||||
- ✅ **DO**: Wrap core function calls with silent mode:
|
|
||||||
```javascript
|
```javascript
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
import { enableSilentMode, disableSilentMode, isSilentMode } from '../../../../scripts/modules/utils.js';
|
||||||
enableSilentMode();
|
|
||||||
|
|
||||||
// Call the core function
|
|
||||||
const result = await coreFunction(...);
|
|
||||||
|
|
||||||
// Restore normal logging
|
|
||||||
disableSilentMode();
|
|
||||||
```
|
```
|
||||||
- ✅ **DO**: Ensure silent mode is disabled in error handling:
|
- ✅ **DO**: Always use `isSilentMode()` function to check global silent mode status, never reference global variables.
|
||||||
|
- ✅ **DO**: Wrap core function calls **within direct functions** using `enableSilentMode()` and `disableSilentMode()` in a `try/finally` block if the core function might produce console output (like banners, spinners, direct `console.log`s) that isn't reliably controlled by an `outputFormat` parameter.
|
||||||
```javascript
|
```javascript
|
||||||
|
// Direct Function Example:
|
||||||
try {
|
try {
|
||||||
enableSilentMode();
|
// Prefer passing 'json' if the core function reliably handles it
|
||||||
// Core function call
|
const result = await coreFunction(...args, 'json');
|
||||||
disableSilentMode();
|
// OR, if outputFormat is not enough/unreliable:
|
||||||
|
// enableSilentMode(); // Enable *before* the call
|
||||||
|
// const result = await coreFunction(...args);
|
||||||
|
// disableSilentMode(); // Disable *after* the call (typically in finally)
|
||||||
|
|
||||||
|
return { success: true, data: result };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
log.error(`Error: ${error.message}`);
|
||||||
disableSilentMode();
|
return { success: false, error: { message: error.message } };
|
||||||
throw error; // Rethrow to be caught by outer catch block
|
} finally {
|
||||||
|
// If you used enable/disable, ensure disable is called here
|
||||||
|
// disableSilentMode();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
- ✅ **DO**: Add silent mode handling in all direct functions that call core functions
|
- ✅ **DO**: Core functions themselves *should* ideally check `outputFormat === 'text'` before displaying UI elements (banners, spinners, boxes) and use internal logging (`log`/`report`) that respects silent mode. The `enable/disableSilentMode` wrapper in the direct function is a safety net.
|
||||||
- ❌ **DON'T**: Forget to disable silent mode, which would suppress all future logs
|
- ✅ **DO**: Handle mixed parameter/global silent mode correctly for functions accepting both (less common now, prefer `outputFormat`):
|
||||||
- ❌ **DON'T**: Enable silent mode outside of direct functions in the MCP server
|
```javascript
|
||||||
|
// Check both the passed parameter and global silent mode
|
||||||
|
const isSilent = silentMode || (typeof silentMode === 'undefined' && isSilentMode());
|
||||||
|
```
|
||||||
|
- ❌ **DON'T**: Forget to disable silent mode in a `finally` block if you enabled it.
|
||||||
|
- ❌ **DON'T**: Access the global `silentMode` flag directly.
|
||||||
|
|
||||||
|
- **Debugging Strategy**:
|
||||||
|
- ✅ **DO**: If an MCP tool fails with vague errors (e.g., JSON parsing issues like `Unexpected token ... is not valid JSON`), **try running the equivalent CLI command directly in the terminal** (e.g., `task-master expand --all`). CLI output often provides much more specific error messages (like missing function definitions or stack traces from the core logic) that pinpoint the root cause.
|
||||||
|
- ❌ **DON'T**: Rely solely on MCP logs if the error is unclear; use the CLI as a complementary debugging tool for core logic issues.
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// 1. CORE LOGIC: Add function to appropriate module (example in task-manager.js)
|
// 1. CORE LOGIC: Add function to appropriate module (example in task-manager.js)
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
|||||||
|
|
||||||
**Note:** For interacting with Taskmaster programmatically or via integrated tools, using the **MCP tools is strongly recommended** due to better performance, structured data, and error handling. The CLI commands serve as a user-friendly alternative and fallback. See [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for MCP implementation details and [`commands.mdc`](mdc:.cursor/rules/commands.mdc) for CLI implementation guidelines.
|
**Note:** For interacting with Taskmaster programmatically or via integrated tools, using the **MCP tools is strongly recommended** due to better performance, structured data, and error handling. The CLI commands serve as a user-friendly alternative and fallback. See [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for MCP implementation details and [`commands.mdc`](mdc:.cursor/rules/commands.mdc) for CLI implementation guidelines.
|
||||||
|
|
||||||
|
**Important:** Several MCP tools involve AI processing and are long-running operations that may take up to a minute to complete. When using these tools, always inform users that the operation is in progress and to wait patiently for results. The AI-powered tools include: `parse_prd`, `analyze_project_complexity`, `update_subtask`, `update_task`, `update`, `expand_all`, `expand_task`, and `add_task`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Initialization & Setup
|
## Initialization & Setup
|
||||||
@@ -49,6 +51,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
|||||||
* `force`: `Use this to allow Taskmaster to overwrite an existing 'tasks.json' without asking for confirmation.` (CLI: `-f, --force`)
|
* `force`: `Use this to allow Taskmaster to overwrite an existing 'tasks.json' without asking for confirmation.` (CLI: `-f, --force`)
|
||||||
* **Usage:** Useful for bootstrapping a project from an existing requirements document.
|
* **Usage:** Useful for bootstrapping a project from an existing requirements document.
|
||||||
* **Notes:** Task Master will strictly adhere to any specific requirements mentioned in the PRD (libraries, database schemas, frameworks, tech stacks, etc.) while filling in any gaps where the PRD isn't fully specified. Tasks are designed to provide the most direct implementation path while avoiding over-engineering.
|
* **Notes:** Task Master will strictly adhere to any specific requirements mentioned in the PRD (libraries, database schemas, frameworks, tech stacks, etc.) while filling in any gaps where the PRD isn't fully specified. Tasks are designed to provide the most direct implementation path while avoiding over-engineering.
|
||||||
|
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -99,6 +102,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
|||||||
* `priority`: `Set the priority for the new task ('high', 'medium', 'low'; default: 'medium').` (CLI: `--priority <priority>`)
|
* `priority`: `Set the priority for the new task ('high', 'medium', 'low'; default: 'medium').` (CLI: `--priority <priority>`)
|
||||||
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
||||||
* **Usage:** Quickly add newly identified tasks during development.
|
* **Usage:** Quickly add newly identified tasks during development.
|
||||||
|
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
|
||||||
|
|
||||||
### 7. Add Subtask (`add_subtask`)
|
### 7. Add Subtask (`add_subtask`)
|
||||||
|
|
||||||
@@ -127,7 +131,8 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
|||||||
* `prompt`: `Required. Explain the change or new context for Taskmaster to apply to the tasks (e.g., "We are now using React Query instead of Redux Toolkit for data fetching").` (CLI: `-p, --prompt <text>`)
|
* `prompt`: `Required. Explain the change or new context for Taskmaster to apply to the tasks (e.g., "We are now using React Query instead of Redux Toolkit for data fetching").` (CLI: `-p, --prompt <text>`)
|
||||||
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates based on external knowledge (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
|
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates based on external knowledge (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
|
||||||
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
||||||
* **Usage:** Handle significant implementation changes or pivots that affect multiple future tasks.
|
* **Usage:** Handle significant implementation changes or pivots that affect multiple future tasks. Example CLI: `task-master update --from='18' --prompt='Switching to React Query.\nNeed to refactor data fetching...'`
|
||||||
|
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
|
||||||
|
|
||||||
### 9. Update Task (`update_task`)
|
### 9. Update Task (`update_task`)
|
||||||
|
|
||||||
@@ -139,19 +144,21 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
|||||||
* `prompt`: `Required. Explain the specific changes or provide the new information Taskmaster should incorporate into this task.` (CLI: `-p, --prompt <text>`)
|
* `prompt`: `Required. Explain the specific changes or provide the new information Taskmaster should incorporate into this task.` (CLI: `-p, --prompt <text>`)
|
||||||
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
|
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
|
||||||
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
||||||
* **Usage:** Refine a specific task based on new understanding or feedback.
|
* **Usage:** Refine a specific task based on new understanding or feedback. Example CLI: `task-master update-task --id='15' --prompt='Clarification: Use PostgreSQL instead of MySQL.\nUpdate schema details...'`
|
||||||
|
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
|
||||||
|
|
||||||
### 10. Update Subtask (`update_subtask`)
|
### 10. Update Subtask (`update_subtask`)
|
||||||
|
|
||||||
* **MCP Tool:** `update_subtask`
|
* **MCP Tool:** `update_subtask`
|
||||||
* **CLI Command:** `task-master update-subtask [options]`
|
* **CLI Command:** `task-master update-subtask [options]`
|
||||||
* **Description:** `Append timestamped notes or details to a specific Taskmaster subtask without overwriting existing content.`
|
* **Description:** `Append timestamped notes or details to a specific Taskmaster subtask without overwriting existing content. Intended for iterative implementation logging.`
|
||||||
* **Key Parameters/Options:**
|
* **Key Parameters/Options:**
|
||||||
* `id`: `Required. The specific ID of the Taskmaster subtask (e.g., '15.2') you want to add information to.` (CLI: `-i, --id <id>`)
|
* `id`: `Required. The specific ID of the Taskmaster subtask (e.g., '15.2') you want to add information to.` (CLI: `-i, --id <id>`)
|
||||||
* `prompt`: `Required. Provide the information or notes Taskmaster should append to the subtask's details.` (CLI: `-p, --prompt <text>`)
|
* `prompt`: `Required. Provide the information or notes Taskmaster should append to the subtask's details. Ensure this adds *new* information not already present.` (CLI: `-p, --prompt <text>`)
|
||||||
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
|
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
|
||||||
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
||||||
* **Usage:** Add implementation notes, code snippets, or clarifications to a subtask during development.
|
* **Usage:** Add implementation notes, code snippets, or clarifications to a subtask during development. Before calling, review the subtask's current details to append only fresh insights, helping to build a detailed log of the implementation journey and avoid redundancy. Example CLI: `task-master update-subtask --id='15.2' --prompt='Discovered that the API requires header X.\nImplementation needs adjustment...'`
|
||||||
|
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
|
||||||
|
|
||||||
### 11. Set Task Status (`set_task_status`)
|
### 11. Set Task Status (`set_task_status`)
|
||||||
|
|
||||||
@@ -193,6 +200,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
|||||||
* `force`: `Use this to make Taskmaster replace existing subtasks with newly generated ones.` (CLI: `--force`)
|
* `force`: `Use this to make Taskmaster replace existing subtasks with newly generated ones.` (CLI: `--force`)
|
||||||
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
||||||
* **Usage:** Generate a detailed implementation plan for a complex task before starting coding.
|
* **Usage:** Generate a detailed implementation plan for a complex task before starting coding.
|
||||||
|
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
|
||||||
|
|
||||||
### 14. Expand All Tasks (`expand_all`)
|
### 14. Expand All Tasks (`expand_all`)
|
||||||
|
|
||||||
@@ -206,6 +214,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
|||||||
* `force`: `Make Taskmaster replace existing subtasks.` (CLI: `--force`)
|
* `force`: `Make Taskmaster replace existing subtasks.` (CLI: `--force`)
|
||||||
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
||||||
* **Usage:** Useful after initial task generation or complexity analysis to break down multiple tasks at once.
|
* **Usage:** Useful after initial task generation or complexity analysis to break down multiple tasks at once.
|
||||||
|
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
|
||||||
|
|
||||||
### 15. Clear Subtasks (`clear_subtasks`)
|
### 15. Clear Subtasks (`clear_subtasks`)
|
||||||
|
|
||||||
@@ -278,45 +287,67 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
|||||||
|
|
||||||
## Analysis & Reporting
|
## Analysis & Reporting
|
||||||
|
|
||||||
### 21. Analyze Complexity (`analyze_complexity`)
|
### 21. Analyze Project Complexity (`analyze_project_complexity`)
|
||||||
|
|
||||||
* **MCP Tool:** `analyze_complexity`
|
* **MCP Tool:** `analyze_project_complexity`
|
||||||
* **CLI Command:** `task-master analyze-complexity [options]`
|
* **CLI Command:** `task-master analyze-complexity [options]`
|
||||||
* **Description:** `Let Taskmaster analyze the complexity of your tasks and generate a report with recommendations for which ones need breaking down.`
|
* **Description:** `Have Taskmaster analyze your tasks to determine their complexity and suggest which ones need to be broken down further.`
|
||||||
* **Key Parameters/Options:**
|
* **Key Parameters/Options:**
|
||||||
* `output`: `Where Taskmaster should save the JSON complexity analysis report (default: 'scripts/task-complexity-report.json').` (CLI: `-o, --output <file>`)
|
* `output`: `Where to save the complexity analysis report (default: 'scripts/task-complexity-report.json').` (CLI: `-o, --output <file>`)
|
||||||
* `threshold`: `The minimum complexity score (1-10) for Taskmaster to recommend expanding a task.` (CLI: `-t, --threshold <number>`)
|
* `threshold`: `The minimum complexity score (1-10) that should trigger a recommendation to expand a task.` (CLI: `-t, --threshold <number>`)
|
||||||
* `research`: `Enable Taskmaster to use Perplexity AI for more informed complexity analysis (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
|
* `research`: `Enable Perplexity AI for more accurate complexity analysis (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
|
||||||
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
||||||
* **Usage:** Identify which tasks are likely too large and need further breakdown before implementation.
|
* **Usage:** Used before breaking down tasks to identify which ones need the most attention.
|
||||||
|
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
|
||||||
|
|
||||||
### 22. Complexity Report (`complexity_report`)
|
### 22. View Complexity Report (`complexity_report`)
|
||||||
|
|
||||||
* **MCP Tool:** `complexity_report`
|
* **MCP Tool:** `complexity_report`
|
||||||
* **CLI Command:** `task-master complexity-report [options]`
|
* **CLI Command:** `task-master complexity-report [options]`
|
||||||
* **Description:** `Display the Taskmaster task complexity analysis report generated by 'analyze-complexity'.`
|
* **Description:** `Display the task complexity analysis report in a readable format.`
|
||||||
* **Key Parameters/Options:**
|
* **Key Parameters/Options:**
|
||||||
* `file`: `Path to the JSON complexity report file (default: 'scripts/task-complexity-report.json').` (CLI: `-f, --file <file>`)
|
* `file`: `Path to the complexity report (default: 'scripts/task-complexity-report.json').` (CLI: `-f, --file <file>`)
|
||||||
* **Usage:** View the formatted results of the complexity analysis to guide task expansion.
|
* **Usage:** Review and understand the complexity analysis results after running analyze-complexity.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## File Generation
|
## File Management
|
||||||
|
|
||||||
### 23. Generate Task Files (`generate`)
|
### 23. Generate Task Files (`generate`)
|
||||||
|
|
||||||
* **MCP Tool:** `generate`
|
* **MCP Tool:** `generate`
|
||||||
* **CLI Command:** `task-master generate [options]`
|
* **CLI Command:** `task-master generate [options]`
|
||||||
* **Description:** `Generate individual markdown files for each task and subtask defined in your Taskmaster 'tasks.json'.`
|
* **Description:** `Create or update individual Markdown files for each task based on your tasks.json.`
|
||||||
* **Key Parameters/Options:**
|
* **Key Parameters/Options:**
|
||||||
* `file`: `Path to your Taskmaster 'tasks.json' file containing the task data (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
* `output`: `The directory where Taskmaster should save the task files (default: in a 'tasks' directory).` (CLI: `-o, --output <directory>`)
|
||||||
* `output`: `The directory where Taskmaster should save the generated markdown task files (default: 'tasks').` (CLI: `-o, --output <dir>`)
|
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
|
||||||
* **Usage:** Create/update the individual `.md` files in the `tasks/` directory, useful for tracking changes in git or viewing tasks individually.
|
* **Usage:** Run this after making changes to tasks.json to keep individual task files up to date.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Configuration & Metadata
|
## Environment Variables Configuration
|
||||||
|
|
||||||
- **Environment Variables**: Taskmaster relies on environment variables for configuration (API keys, model preferences, default settings). See [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) or the project README for a list.
|
Taskmaster's behavior can be customized via environment variables. These affect both CLI and MCP server operation:
|
||||||
- **`tasks.json`**: The core data file containing the array of tasks and their details. See [`tasks.mdc`](mdc:.cursor/rules/tasks.mdc) for details.
|
|
||||||
- **`task_xxx.md` files**: Individual markdown files generated by the `generate` command/tool, reflecting the content of `tasks.json`.
|
* **ANTHROPIC_API_KEY** (Required): Your Anthropic API key for Claude.
|
||||||
|
* **MODEL**: Claude model to use (default: `claude-3-opus-20240229`).
|
||||||
|
* **MAX_TOKENS**: Maximum tokens for AI responses (default: 8192).
|
||||||
|
* **TEMPERATURE**: Temperature for AI model responses (default: 0.7).
|
||||||
|
* **DEBUG**: Enable debug logging (`true`/`false`, default: `false`).
|
||||||
|
* **LOG_LEVEL**: Console output level (`debug`, `info`, `warn`, `error`, default: `info`).
|
||||||
|
* **DEFAULT_SUBTASKS**: Default number of subtasks for `expand` (default: 5).
|
||||||
|
* **DEFAULT_PRIORITY**: Default priority for new tasks (default: `medium`).
|
||||||
|
* **PROJECT_NAME**: Project name used in metadata.
|
||||||
|
* **PROJECT_VERSION**: Project version used in metadata.
|
||||||
|
* **PERPLEXITY_API_KEY**: API key for Perplexity AI (for `--research` flags).
|
||||||
|
* **PERPLEXITY_MODEL**: Perplexity model to use (default: `sonar-medium-online`).
|
||||||
|
|
||||||
|
Set these in your `.env` file in the project root or in your environment before running Taskmaster.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
For implementation details:
|
||||||
|
* CLI commands: See [`commands.mdc`](mdc:.cursor/rules/commands.mdc)
|
||||||
|
* MCP server: See [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)
|
||||||
|
* Task structure: See [`tasks.mdc`](mdc:.cursor/rules/tasks.mdc)
|
||||||
|
* Workflow: See [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc)
|
||||||
|
|||||||
@@ -109,6 +109,29 @@ alwaysApply: false
|
|||||||
- ✅ DO: Use appropriate icons for different log levels
|
- ✅ DO: Use appropriate icons for different log levels
|
||||||
- ✅ DO: Respect the configured log level
|
- ✅ DO: Respect the configured log level
|
||||||
- ❌ DON'T: Add direct console.log calls outside the logging utility
|
- ❌ DON'T: Add direct console.log calls outside the logging utility
|
||||||
|
- **Note on Passed Loggers**: When a logger object (like the FastMCP `log` object) is passed *as a parameter* (e.g., as `mcpLog`) into core Task Master functions, the receiving function often expects specific methods (`.info`, `.warn`, `.error`, etc.) to be directly callable on that object (e.g., `mcpLog[level](...)`). If the passed logger doesn't have this exact structure, a wrapper object may be needed. See the **Handling Logging Context (`mcpLog`)** section in [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for the standard pattern used in direct functions.
|
||||||
|
|
||||||
|
- **Logger Wrapper Pattern**:
|
||||||
|
- ✅ DO: Use the logger wrapper pattern when passing loggers to prevent `mcpLog[level] is not a function` errors:
|
||||||
|
```javascript
|
||||||
|
// Standard logWrapper pattern to wrap FastMCP's log object
|
||||||
|
const logWrapper = {
|
||||||
|
info: (message, ...args) => log.info(message, ...args),
|
||||||
|
warn: (message, ...args) => log.warn(message, ...args),
|
||||||
|
error: (message, ...args) => log.error(message, ...args),
|
||||||
|
debug: (message, ...args) => log.debug && log.debug(message, ...args),
|
||||||
|
success: (message, ...args) => log.info(message, ...args) // Map success to info
|
||||||
|
};
|
||||||
|
|
||||||
|
// Pass this wrapper as mcpLog to ensure consistent method availability
|
||||||
|
// This also ensures output format is set to 'json' in many core functions
|
||||||
|
const options = { mcpLog: logWrapper, session };
|
||||||
|
```
|
||||||
|
- ✅ DO: Implement this pattern in any direct function that calls core functions expecting `mcpLog`
|
||||||
|
- ✅ DO: Use this solution in conjunction with silent mode for complete output control
|
||||||
|
- ❌ DON'T: Pass the FastMCP `log` object directly as `mcpLog` to core functions
|
||||||
|
- **Important**: This pattern has successfully fixed multiple issues in MCP tools (e.g., `update-task`, `update-subtask`) where using or omitting `mcpLog` incorrectly led to runtime errors or JSON parsing failures.
|
||||||
|
- For complete implementation details, see the **Handling Logging Context (`mcpLog`)** section in [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc).
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// ✅ DO: Implement a proper logging utility
|
// ✅ DO: Implement a proper logging utility
|
||||||
@@ -135,6 +158,107 @@ alwaysApply: false
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Silent Mode Utilities (in `scripts/modules/utils.js`)
|
||||||
|
|
||||||
|
- **Silent Mode Control**:
|
||||||
|
- ✅ DO: Use the exported silent mode functions rather than accessing global variables
|
||||||
|
- ✅ DO: Always use `isSilentMode()` to check the current silent mode state
|
||||||
|
- ✅ DO: Ensure silent mode is disabled in a `finally` block to prevent it from staying enabled
|
||||||
|
- ❌ DON'T: Access the global `silentMode` variable directly
|
||||||
|
- ❌ DON'T: Forget to disable silent mode after enabling it
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// ✅ DO: Use the silent mode control functions properly
|
||||||
|
|
||||||
|
// Example of proper implementation in utils.js:
|
||||||
|
|
||||||
|
// Global silent mode flag (private to the module)
|
||||||
|
let silentMode = false;
|
||||||
|
|
||||||
|
// Enable silent mode
|
||||||
|
function enableSilentMode() {
|
||||||
|
silentMode = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disable silent mode
|
||||||
|
function disableSilentMode() {
|
||||||
|
silentMode = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if silent mode is enabled
|
||||||
|
function isSilentMode() {
|
||||||
|
return silentMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Example of proper usage in another module:
|
||||||
|
import { enableSilentMode, disableSilentMode, isSilentMode } from './utils.js';
|
||||||
|
|
||||||
|
// Check current status
|
||||||
|
if (!isSilentMode()) {
|
||||||
|
console.log('Silent mode is not enabled');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use try/finally pattern to ensure silent mode is disabled
|
||||||
|
try {
|
||||||
|
enableSilentMode();
|
||||||
|
// Do something that should suppress console output
|
||||||
|
performOperation();
|
||||||
|
} finally {
|
||||||
|
disableSilentMode();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Integration with Logging**:
|
||||||
|
- ✅ DO: Make the `log` function respect silent mode
|
||||||
|
```javascript
|
||||||
|
function log(level, ...args) {
|
||||||
|
// Skip logging if silent mode is enabled
|
||||||
|
if (isSilentMode()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rest of logging logic...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Common Patterns for Silent Mode**:
|
||||||
|
- ✅ DO: In **direct functions** (`mcp-server/src/core/direct-functions/*`) that call **core functions** (`scripts/modules/*`), ensure console output from the core function is suppressed to avoid breaking MCP JSON responses.
|
||||||
|
- **Preferred Method**: Update the core function to accept an `outputFormat` parameter (e.g., `outputFormat = 'text'`) and make it check `outputFormat === 'text'` before displaying any UI elements (banners, spinners, boxes, direct `console.log`s). Pass `'json'` from the direct function.
|
||||||
|
- **Necessary Fallback/Guarantee**: If the core function *cannot* be modified or its output suppression via `outputFormat` is unreliable, **wrap the core function call within the direct function** using `enableSilentMode()` and `disableSilentMode()` in a `try/finally` block. This acts as a safety net.
|
||||||
|
```javascript
|
||||||
|
// Example in a direct function
|
||||||
|
export async function someOperationDirect(args, log) {
|
||||||
|
let result;
|
||||||
|
const tasksPath = findTasksJsonPath(args, log); // Get path first
|
||||||
|
|
||||||
|
// Option 1: Core function handles 'json' format (Preferred)
|
||||||
|
try {
|
||||||
|
result = await coreFunction(tasksPath, ...otherArgs, 'json'); // Pass 'json'
|
||||||
|
return { success: true, data: result, fromCache: false };
|
||||||
|
} catch (error) {
|
||||||
|
// Handle error...
|
||||||
|
}
|
||||||
|
|
||||||
|
// Option 2: Core function output unreliable (Fallback/Guarantee)
|
||||||
|
try {
|
||||||
|
enableSilentMode(); // Enable before call
|
||||||
|
result = await coreFunction(tasksPath, ...otherArgs); // Call without format param
|
||||||
|
} catch (error) {
|
||||||
|
// Handle error...
|
||||||
|
log.error(`Failed: ${error.message}`);
|
||||||
|
return { success: false, error: { /* ... */ } };
|
||||||
|
} finally {
|
||||||
|
disableSilentMode(); // ALWAYS disable in finally
|
||||||
|
}
|
||||||
|
return { success: true, data: result, fromCache: false }; // Assuming success if no error caught
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- ✅ DO: For functions that accept a silent mode parameter but also need to check global state (less common):
|
||||||
|
```javascript
|
||||||
|
// Check both the passed parameter and global silent mode
|
||||||
|
const isSilent = options.silentMode || (typeof options.silentMode === 'undefined' && isSilentMode());
|
||||||
|
```
|
||||||
|
|
||||||
## File Operations (in `scripts/modules/utils.js`)
|
## File Operations (in `scripts/modules/utils.js`)
|
||||||
|
|
||||||
- **Error Handling**:
|
- **Error Handling**:
|
||||||
|
|||||||
@@ -5,16 +5,16 @@ PERPLEXITY_API_KEY=your_perplexity_api_key_here # Format: pplx-...
|
|||||||
# Model Configuration
|
# Model Configuration
|
||||||
MODEL=claude-3-7-sonnet-20250219 # Recommended models: claude-3-7-sonnet-20250219, claude-3-opus-20240229
|
MODEL=claude-3-7-sonnet-20250219 # Recommended models: claude-3-7-sonnet-20250219, claude-3-opus-20240229
|
||||||
PERPLEXITY_MODEL=sonar-pro # Perplexity model for research-backed subtasks
|
PERPLEXITY_MODEL=sonar-pro # Perplexity model for research-backed subtasks
|
||||||
MAX_TOKENS=64000 # Maximum tokens for model responses
|
MAX_TOKENS=128000 # Maximum tokens for model responses
|
||||||
TEMPERATURE=0.4 # Temperature for model responses (0.0-1.0)
|
TEMPERATURE=0.2 # Temperature for model responses (0.0-1.0)
|
||||||
|
|
||||||
# Logging Configuration
|
# Logging Configuration
|
||||||
DEBUG=false # Enable debug logging (true/false)
|
DEBUG=false # Enable debug logging (true/false)
|
||||||
LOG_LEVEL=info # Log level (debug, info, warn, error)
|
LOG_LEVEL=info # Log level (debug, info, warn, error)
|
||||||
|
|
||||||
# Task Generation Settings
|
# Task Generation Settings
|
||||||
DEFAULT_SUBTASKS=4 # Default number of subtasks when expanding
|
DEFAULT_SUBTASKS=5 # Default number of subtasks when expanding
|
||||||
DEFAULT_PRIORITY=medium # Default priority for generated tasks (high, medium, low)
|
DEFAULT_PRIORITY=medium # Default priority for generated tasks (high, medium, low)
|
||||||
|
|
||||||
# Project Metadata (Optional)
|
# Project Metadata (Optional)
|
||||||
PROJECT_NAME=Your Project Name # Override default project name in tasks.json
|
PROJECT_NAME=Your Project Name # Override default project name in tasks.json
|
||||||
95
.github/workflows/ci.yml
vendored
Normal file
95
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
- next
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
- next
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
setup:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: 'npm'
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
id: install
|
||||||
|
run: npm ci
|
||||||
|
timeout-minutes: 2
|
||||||
|
|
||||||
|
- name: Cache node_modules
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: node_modules
|
||||||
|
key: ${{ runner.os }}-node-modules-${{ hashFiles('**/package-lock.json') }}
|
||||||
|
|
||||||
|
format-check:
|
||||||
|
needs: setup
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
|
||||||
|
- name: Restore node_modules
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: node_modules
|
||||||
|
key: ${{ runner.os }}-node-modules-${{ hashFiles('**/package-lock.json') }}
|
||||||
|
|
||||||
|
- name: Format Check
|
||||||
|
run: npm run format-check
|
||||||
|
env:
|
||||||
|
FORCE_COLOR: 1
|
||||||
|
|
||||||
|
test:
|
||||||
|
needs: setup
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
|
||||||
|
- name: Restore node_modules
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: node_modules
|
||||||
|
key: ${{ runner.os }}-node-modules-${{ hashFiles('**/package-lock.json') }}
|
||||||
|
|
||||||
|
- name: Run Tests
|
||||||
|
run: |
|
||||||
|
npm run test:coverage -- --coverageThreshold '{"global":{"branches":0,"functions":0,"lines":0,"statements":0}}' --detectOpenHandles --forceExit
|
||||||
|
env:
|
||||||
|
NODE_ENV: test
|
||||||
|
CI: true
|
||||||
|
FORCE_COLOR: 1
|
||||||
|
timeout-minutes: 10
|
||||||
|
|
||||||
|
- name: Upload Test Results
|
||||||
|
if: always()
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: test-results
|
||||||
|
path: |
|
||||||
|
test-results
|
||||||
|
coverage
|
||||||
|
junit.xml
|
||||||
|
retention-days: 30
|
||||||
15
.github/workflows/release.yml
vendored
15
.github/workflows/release.yml
vendored
@@ -3,7 +3,6 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
- next
|
|
||||||
jobs:
|
jobs:
|
||||||
release:
|
release:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -15,9 +14,21 @@ jobs:
|
|||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 20
|
node-version: 20
|
||||||
|
cache: 'npm'
|
||||||
|
|
||||||
|
- name: Cache node_modules
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
node_modules
|
||||||
|
*/*/node_modules
|
||||||
|
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-node-
|
||||||
|
|
||||||
- name: Install Dependencies
|
- name: Install Dependencies
|
||||||
run: npm install
|
run: npm ci
|
||||||
|
timeout-minutes: 2
|
||||||
|
|
||||||
- name: Create Release Pull Request or Publish to npm
|
- name: Create Release Pull Request or Publish to npm
|
||||||
uses: changesets/action@v1
|
uses: changesets/action@v1
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -9,6 +9,9 @@ jspm_packages/
|
|||||||
.env.test.local
|
.env.test.local
|
||||||
.env.production.local
|
.env.production.local
|
||||||
|
|
||||||
|
# Cursor configuration -- might have ENV variables. Included by default
|
||||||
|
# .cursor/mcp.json
|
||||||
|
|
||||||
# Logs
|
# Logs
|
||||||
logs
|
logs
|
||||||
*.log
|
*.log
|
||||||
|
|||||||
6
.prettierignore
Normal file
6
.prettierignore
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
# Ignore artifacts:
|
||||||
|
build
|
||||||
|
coverage
|
||||||
|
.changeset
|
||||||
|
tasks
|
||||||
|
package-lock.json
|
||||||
11
.prettierrc
Normal file
11
.prettierrc
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"printWidth": 80,
|
||||||
|
"tabWidth": 2,
|
||||||
|
"useTabs": true,
|
||||||
|
"semi": true,
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "none",
|
||||||
|
"bracketSpacing": true,
|
||||||
|
"arrowParens": "always",
|
||||||
|
"endOfLine": "lf"
|
||||||
|
}
|
||||||
@@ -1,5 +1,13 @@
|
|||||||
# task-master-ai
|
# task-master-ai
|
||||||
|
|
||||||
|
## 0.10.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#80](https://github.com/eyaltoledano/claude-task-master/pull/80) [`aa185b2`](https://github.com/eyaltoledano/claude-task-master/commit/aa185b28b248b4ca93f9195b502e2f5187868eaa) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove non-existent package `@model-context-protocol/sdk`
|
||||||
|
|
||||||
|
- [#45](https://github.com/eyaltoledano/claude-task-master/pull/45) [`757fd47`](https://github.com/eyaltoledano/claude-task-master/commit/757fd478d2e2eff8506ae746c3470c6088f4d944) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add license to repo
|
||||||
|
|
||||||
## 0.10.0
|
## 0.10.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
90
LICENSE.md
90
LICENSE.md
@@ -1,90 +0,0 @@
|
|||||||
# Dual License
|
|
||||||
|
|
||||||
This project is licensed under two separate licenses:
|
|
||||||
|
|
||||||
1. [Business Source License 1.1](#business-source-license-11) (BSL 1.1) for commercial use of Task Master itself
|
|
||||||
2. [Apache License 2.0](#apache-license-20) for all other uses
|
|
||||||
|
|
||||||
## Business Source License 1.1
|
|
||||||
|
|
||||||
Terms: https://mariadb.com/bsl11/
|
|
||||||
|
|
||||||
Licensed Work: Task Master AI
|
|
||||||
Additional Use Grant: You may use Task Master AI to create and commercialize your own projects and products.
|
|
||||||
|
|
||||||
Change Date: 2025-03-30
|
|
||||||
Change License: None
|
|
||||||
|
|
||||||
The Licensed Work is subject to the Business Source License 1.1. If you are interested in using the Licensed Work in a way that competes directly with Task Master, please contact the licensors.
|
|
||||||
|
|
||||||
### Licensor
|
|
||||||
|
|
||||||
- Eyal Toledano (GitHub: @eyaltoledano)
|
|
||||||
- Ralph (GitHub: @Crunchyman-ralph)
|
|
||||||
|
|
||||||
### Commercial Use Restrictions
|
|
||||||
|
|
||||||
This license explicitly restricts certain commercial uses of Task Master AI to the Licensors listed above. Restricted commercial uses include:
|
|
||||||
|
|
||||||
1. Creating commercial products or services that directly compete with Task Master AI
|
|
||||||
2. Selling Task Master AI itself as a service
|
|
||||||
3. Offering Task Master AI's functionality as a commercial managed service
|
|
||||||
4. Reselling or redistributing Task Master AI for a fee
|
|
||||||
|
|
||||||
### Explicitly Permitted Uses
|
|
||||||
|
|
||||||
The following uses are explicitly allowed under this license:
|
|
||||||
|
|
||||||
1. Using Task Master AI to create and commercialize your own projects
|
|
||||||
2. Using Task Master AI in commercial environments for internal development
|
|
||||||
3. Building and selling products or services that were created using Task Master AI
|
|
||||||
4. Using Task Master AI for commercial development as long as you're not selling Task Master AI itself
|
|
||||||
|
|
||||||
### Additional Terms
|
|
||||||
|
|
||||||
1. The right to commercialize Task Master AI itself is exclusively reserved for the Licensors
|
|
||||||
2. No party may create commercial products that directly compete with Task Master AI without explicit written permission
|
|
||||||
3. Forks of this repository are subject to the same restrictions regarding direct competition
|
|
||||||
4. Contributors agree that their contributions will be subject to this same dual licensing structure
|
|
||||||
|
|
||||||
## Apache License 2.0
|
|
||||||
|
|
||||||
For all uses other than those restricted above. See [APACHE-LICENSE](./APACHE-LICENSE) for the full license text.
|
|
||||||
|
|
||||||
### Permitted Use Definition
|
|
||||||
|
|
||||||
You may use Task Master AI for any purpose, including commercial purposes, as long as you are not:
|
|
||||||
|
|
||||||
1. Creating a direct competitor to Task Master AI
|
|
||||||
2. Selling Task Master AI itself as a service
|
|
||||||
3. Redistributing Task Master AI for a fee
|
|
||||||
|
|
||||||
### Requirements for Use
|
|
||||||
|
|
||||||
1. You must include appropriate copyright notices
|
|
||||||
2. You must state significant changes made to the software
|
|
||||||
3. You must preserve all license notices
|
|
||||||
|
|
||||||
## Questions and Commercial Licensing
|
|
||||||
|
|
||||||
For questions about licensing or to inquire about commercial use that may compete with Task Master, please contact:
|
|
||||||
|
|
||||||
- Eyal Toledano (GitHub: @eyaltoledano)
|
|
||||||
- Ralph (GitHub: @Crunchyman-ralph)
|
|
||||||
|
|
||||||
## Examples
|
|
||||||
|
|
||||||
### ✅ Allowed Uses
|
|
||||||
|
|
||||||
- Using Task Master to create a commercial SaaS product
|
|
||||||
- Using Task Master in your company for development
|
|
||||||
- Creating and selling products that were built using Task Master
|
|
||||||
- Using Task Master to generate code for commercial projects
|
|
||||||
- Offering consulting services where you use Task Master
|
|
||||||
|
|
||||||
### ❌ Restricted Uses
|
|
||||||
|
|
||||||
- Creating a competing AI task management tool
|
|
||||||
- Selling access to Task Master as a service
|
|
||||||
- Creating a hosted version of Task Master
|
|
||||||
- Reselling Task Master's functionality
|
|
||||||
@@ -58,6 +58,7 @@ This will prompt you for project details and set up a new project with the neces
|
|||||||
### Important Notes
|
### Important Notes
|
||||||
|
|
||||||
1. **ES Modules Configuration:**
|
1. **ES Modules Configuration:**
|
||||||
|
|
||||||
- This project uses ES Modules (ESM) instead of CommonJS.
|
- This project uses ES Modules (ESM) instead of CommonJS.
|
||||||
- This is set via `"type": "module"` in your package.json.
|
- This is set via `"type": "module"` in your package.json.
|
||||||
- Use `import/export` syntax instead of `require()`.
|
- Use `import/export` syntax instead of `require()`.
|
||||||
|
|||||||
691
README.md
691
README.md
@@ -1,58 +1,68 @@
|
|||||||
# Task Master
|
# Task Master [](https://github.com/eyaltoledano/claude-task-master/stargazers)
|
||||||
|
|
||||||
### by [@eyaltoledano](https://x.com/eyaltoledano)
|
[](https://github.com/eyaltoledano/claude-task-master/actions/workflows/ci.yml) [](https://badge.fury.io/js/task-master-ai)  [](LICENSE)
|
||||||
|
|
||||||
|
### By [@eyaltoledano](https://x.com/eyaltoledano) & [@RalphEcom](https://x.com/RalphEcom)
|
||||||
|
|
||||||
|
[](https://x.com/eyaltoledano)
|
||||||
|
[](https://x.com/RalphEcom)
|
||||||
|
|
||||||
A task management system for AI-driven development with Claude, designed to work seamlessly with Cursor AI.
|
A task management system for AI-driven development with Claude, designed to work seamlessly with Cursor AI.
|
||||||
|
|
||||||
## Licensing
|
|
||||||
|
|
||||||
Task Master is licensed under the MIT License with Commons Clause. This means you can:
|
|
||||||
|
|
||||||
✅ **Allowed**:
|
|
||||||
|
|
||||||
- Use Task Master for any purpose (personal, commercial, academic)
|
|
||||||
- Modify the code
|
|
||||||
- Distribute copies
|
|
||||||
- Create and sell products built using Task Master
|
|
||||||
|
|
||||||
❌ **Not Allowed**:
|
|
||||||
|
|
||||||
- Sell Task Master itself
|
|
||||||
- Offer Task Master as a hosted service
|
|
||||||
- Create competing products based on Task Master
|
|
||||||
|
|
||||||
See the [LICENSE](LICENSE) file for the complete license text.
|
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- Node.js 14.0.0 or higher
|
|
||||||
- Anthropic API key (Claude API)
|
- Anthropic API key (Claude API)
|
||||||
- Anthropic SDK version 0.39.0 or higher
|
|
||||||
- OpenAI SDK (for Perplexity API integration, optional)
|
- OpenAI SDK (for Perplexity API integration, optional)
|
||||||
|
|
||||||
## Configuration
|
## Quick Start
|
||||||
|
|
||||||
The script can be configured through environment variables in a `.env` file at the root of the project:
|
### Option 1 | MCP (Recommended):
|
||||||
|
|
||||||
### Required Configuration
|
MCP (Model Control Protocol) provides the easiest way to get started with Task Master directly in your editor.
|
||||||
|
|
||||||
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude
|
1. **Add the MCP config to your editor** (Cursor recommended, but it works with other text editors):
|
||||||
|
|
||||||
### Optional Configuration
|
```json
|
||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"taskmaster-ai": {
|
||||||
|
"command": "npx",
|
||||||
|
"args": ["-y", "task-master-ai", "mcp-server"],
|
||||||
|
"env": {
|
||||||
|
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
|
||||||
|
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
|
||||||
|
"MODEL": "claude-3-7-sonnet-20250219",
|
||||||
|
"PERPLEXITY_MODEL": "sonar-pro",
|
||||||
|
"MAX_TOKENS": 128000,
|
||||||
|
"TEMPERATURE": 0.2,
|
||||||
|
"DEFAULT_SUBTASKS": 5,
|
||||||
|
"DEFAULT_PRIORITY": "medium"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
- `MODEL`: Specify which Claude model to use (default: "claude-3-7-sonnet-20250219")
|
2. **Enable the MCP** in your editor
|
||||||
- `MAX_TOKENS`: Maximum tokens for model responses (default: 4000)
|
|
||||||
- `TEMPERATURE`: Temperature for model responses (default: 0.7)
|
|
||||||
- `PERPLEXITY_API_KEY`: Your Perplexity API key for research-backed subtask generation
|
|
||||||
- `PERPLEXITY_MODEL`: Specify which Perplexity model to use (default: "sonar-medium-online")
|
|
||||||
- `DEBUG`: Enable debug logging (default: false)
|
|
||||||
- `LOG_LEVEL`: Log level - debug, info, warn, error (default: info)
|
|
||||||
- `DEFAULT_SUBTASKS`: Default number of subtasks when expanding (default: 3)
|
|
||||||
- `DEFAULT_PRIORITY`: Default priority for generated tasks (default: medium)
|
|
||||||
- `PROJECT_NAME`: Override default project name in tasks.json
|
|
||||||
- `PROJECT_VERSION`: Override default version in tasks.json
|
|
||||||
|
|
||||||
## Installation
|
3. **Prompt the AI** to initialize Task Master:
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you please initialize taskmaster-ai into my project?
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Use common commands** directly through your AI assistant:
|
||||||
|
|
||||||
|
```txt
|
||||||
|
Can you parse my PRD at scripts/prd.txt?
|
||||||
|
What's the next task I should work on?
|
||||||
|
Can you help me implement task 3?
|
||||||
|
Can you help me expand task 4?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Option 2: Using Command Line
|
||||||
|
|
||||||
|
#### Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Install globally
|
# Install globally
|
||||||
@@ -62,7 +72,7 @@ npm install -g task-master-ai
|
|||||||
npm install task-master-ai
|
npm install task-master-ai
|
||||||
```
|
```
|
||||||
|
|
||||||
### Initialize a new project
|
#### Initialize a new project
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# If installed globally
|
# If installed globally
|
||||||
@@ -74,14 +84,7 @@ npx task-master-init
|
|||||||
|
|
||||||
This will prompt you for project details and set up a new project with the necessary files and structure.
|
This will prompt you for project details and set up a new project with the necessary files and structure.
|
||||||
|
|
||||||
### Important Notes
|
#### Common Commands
|
||||||
|
|
||||||
1. This package uses ES modules. Your package.json should include `"type": "module"`.
|
|
||||||
2. The Anthropic SDK version should be 0.39.0 or higher.
|
|
||||||
|
|
||||||
## Quick Start with Global Commands
|
|
||||||
|
|
||||||
After installing the package globally, you can use these CLI commands from any directory:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Initialize a new project
|
# Initialize a new project
|
||||||
@@ -100,6 +103,16 @@ task-master next
|
|||||||
task-master generate
|
task-master generate
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
For more detailed information, check out the documentation in the `docs` directory:
|
||||||
|
|
||||||
|
- [Configuration Guide](docs/configuration.md) - Set up environment variables and customize Task Master
|
||||||
|
- [Tutorial](docs/tutorial.md) - Step-by-step guide to getting started with Task Master
|
||||||
|
- [Command Reference](docs/command-reference.md) - Complete list of all available commands
|
||||||
|
- [Task Structure](docs/task-structure.md) - Understanding the task format and features
|
||||||
|
- [Example Interactions](docs/examples.md) - Common Cursor AI interaction examples
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
### If `task-master init` doesn't respond:
|
### If `task-master init` doesn't respond:
|
||||||
@@ -118,577 +131,25 @@ cd claude-task-master
|
|||||||
node scripts/init.js
|
node scripts/init.js
|
||||||
```
|
```
|
||||||
|
|
||||||
## Task Structure
|
## Star History
|
||||||
|
|
||||||
Tasks in tasks.json have the following structure:
|
[](https://www.star-history.com/#eyaltoledano/claude-task-master&Timeline)
|
||||||
|
|
||||||
- `id`: Unique identifier for the task (Example: `1`)
|
## Licensing
|
||||||
- `title`: Brief, descriptive title of the task (Example: `"Initialize Repo"`)
|
|
||||||
- `description`: Concise description of what the task involves (Example: `"Create a new repository, set up initial structure."`)
|
|
||||||
- `status`: Current state of the task (Example: `"pending"`, `"done"`, `"deferred"`)
|
|
||||||
- `dependencies`: IDs of tasks that must be completed before this task (Example: `[1, 2]`)
|
|
||||||
- Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending)
|
|
||||||
- This helps quickly identify which prerequisite tasks are blocking work
|
|
||||||
- `priority`: Importance level of the task (Example: `"high"`, `"medium"`, `"low"`)
|
|
||||||
- `details`: In-depth implementation instructions (Example: `"Use GitHub client ID/secret, handle callback, set session token."`)
|
|
||||||
- `testStrategy`: Verification approach (Example: `"Deploy and call endpoint to confirm 'Hello World' response."`)
|
|
||||||
- `subtasks`: List of smaller, more specific tasks that make up the main task (Example: `[{"id": 1, "title": "Configure OAuth", ...}]`)
|
|
||||||
|
|
||||||
## Integrating with Cursor AI
|
Task Master is licensed under the MIT License with Commons Clause. This means you can:
|
||||||
|
|
||||||
Claude Task Master is designed to work seamlessly with [Cursor AI](https://www.cursor.so/), providing a structured workflow for AI-driven development.
|
✅ **Allowed**:
|
||||||
|
|
||||||
### Setup with Cursor
|
- Use Task Master for any purpose (personal, commercial, academic)
|
||||||
|
- Modify the code
|
||||||
|
- Distribute copies
|
||||||
|
- Create and sell products built using Task Master
|
||||||
|
|
||||||
1. After initializing your project, open it in Cursor
|
❌ **Not Allowed**:
|
||||||
2. The `.cursor/rules/dev_workflow.mdc` file is automatically loaded by Cursor, providing the AI with knowledge about the task management system
|
|
||||||
3. Place your PRD document in the `scripts/` directory (e.g., `scripts/prd.txt`)
|
|
||||||
4. Open Cursor's AI chat and switch to Agent mode
|
|
||||||
|
|
||||||
### Setting up MCP in Cursor
|
- Sell Task Master itself
|
||||||
|
- Offer Task Master as a hosted service
|
||||||
|
- Create competing products based on Task Master
|
||||||
|
|
||||||
To enable enhanced task management capabilities directly within Cursor using the Model Control Protocol (MCP):
|
See the [LICENSE](LICENSE) file for the complete license text and [licensing details](docs/licensing.md) for more information.
|
||||||
|
|
||||||
1. Go to Cursor settings
|
|
||||||
2. Navigate to the MCP section
|
|
||||||
3. Click on "Add New MCP Server"
|
|
||||||
4. Configure with the following details:
|
|
||||||
- Name: "Task Master"
|
|
||||||
- Type: "Command"
|
|
||||||
- Command: "npx -y --package task-master-ai task-master-mcp"
|
|
||||||
5. Save the settings
|
|
||||||
|
|
||||||
Once configured, you can interact with Task Master's task management commands directly through Cursor's interface, providing a more integrated experience.
|
|
||||||
|
|
||||||
### Initial Task Generation
|
|
||||||
|
|
||||||
In Cursor's AI chat, instruct the agent to generate tasks from your PRD:
|
|
||||||
|
|
||||||
```
|
|
||||||
Please use the task-master parse-prd command to generate tasks from my PRD. The PRD is located at scripts/prd.txt.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master parse-prd scripts/prd.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
This will:
|
|
||||||
|
|
||||||
- Parse your PRD document
|
|
||||||
- Generate a structured `tasks.json` file with tasks, dependencies, priorities, and test strategies
|
|
||||||
- The agent will understand this process due to the Cursor rules
|
|
||||||
|
|
||||||
### Generate Individual Task Files
|
|
||||||
|
|
||||||
Next, ask the agent to generate individual task files:
|
|
||||||
|
|
||||||
```
|
|
||||||
Please generate individual task files from tasks.json
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master generate
|
|
||||||
```
|
|
||||||
|
|
||||||
This creates individual task files in the `tasks/` directory (e.g., `task_001.txt`, `task_002.txt`), making it easier to reference specific tasks.
|
|
||||||
|
|
||||||
## AI-Driven Development Workflow
|
|
||||||
|
|
||||||
The Cursor agent is pre-configured (via the rules file) to follow this workflow:
|
|
||||||
|
|
||||||
### 1. Task Discovery and Selection
|
|
||||||
|
|
||||||
Ask the agent to list available tasks:
|
|
||||||
|
|
||||||
```
|
|
||||||
What tasks are available to work on next?
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will:
|
|
||||||
|
|
||||||
- Run `task-master list` to see all tasks
|
|
||||||
- Run `task-master next` to determine the next task to work on
|
|
||||||
- Analyze dependencies to determine which tasks are ready to be worked on
|
|
||||||
- Prioritize tasks based on priority level and ID order
|
|
||||||
- Suggest the next task(s) to implement
|
|
||||||
|
|
||||||
### 2. Task Implementation
|
|
||||||
|
|
||||||
When implementing a task, the agent will:
|
|
||||||
|
|
||||||
- Reference the task's details section for implementation specifics
|
|
||||||
- Consider dependencies on previous tasks
|
|
||||||
- Follow the project's coding standards
|
|
||||||
- Create appropriate tests based on the task's testStrategy
|
|
||||||
|
|
||||||
You can ask:
|
|
||||||
|
|
||||||
```
|
|
||||||
Let's implement task 3. What does it involve?
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Task Verification
|
|
||||||
|
|
||||||
Before marking a task as complete, verify it according to:
|
|
||||||
|
|
||||||
- The task's specified testStrategy
|
|
||||||
- Any automated tests in the codebase
|
|
||||||
- Manual verification if required
|
|
||||||
|
|
||||||
### 4. Task Completion
|
|
||||||
|
|
||||||
When a task is completed, tell the agent:
|
|
||||||
|
|
||||||
```
|
|
||||||
Task 3 is now complete. Please update its status.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master set-status --id=3 --status=done
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5. Handling Implementation Drift
|
|
||||||
|
|
||||||
If during implementation, you discover that:
|
|
||||||
|
|
||||||
- The current approach differs significantly from what was planned
|
|
||||||
- Future tasks need to be modified due to current implementation choices
|
|
||||||
- New dependencies or requirements have emerged
|
|
||||||
|
|
||||||
Tell the agent:
|
|
||||||
|
|
||||||
```
|
|
||||||
We've changed our approach. We're now using Express instead of Fastify. Please update all future tasks to reflect this change.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master update --from=4 --prompt="Now we are using Express instead of Fastify."
|
|
||||||
```
|
|
||||||
|
|
||||||
This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work.
|
|
||||||
|
|
||||||
### 6. Breaking Down Complex Tasks
|
|
||||||
|
|
||||||
For complex tasks that need more granularity:
|
|
||||||
|
|
||||||
```
|
|
||||||
Task 5 seems complex. Can you break it down into subtasks?
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master expand --id=5 --num=3
|
|
||||||
```
|
|
||||||
|
|
||||||
You can provide additional context:
|
|
||||||
|
|
||||||
```
|
|
||||||
Please break down task 5 with a focus on security considerations.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master expand --id=5 --prompt="Focus on security aspects"
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also expand all pending tasks:
|
|
||||||
|
|
||||||
```
|
|
||||||
Please break down all pending tasks into subtasks.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master expand --all
|
|
||||||
```
|
|
||||||
|
|
||||||
For research-backed subtask generation using Perplexity AI:
|
|
||||||
|
|
||||||
```
|
|
||||||
Please break down task 5 using research-backed generation.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master expand --id=5 --research
|
|
||||||
```
|
|
||||||
|
|
||||||
## Command Reference
|
|
||||||
|
|
||||||
Here's a comprehensive reference of all available commands:
|
|
||||||
|
|
||||||
### Parse PRD
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Parse a PRD file and generate tasks
|
|
||||||
task-master parse-prd <prd-file.txt>
|
|
||||||
|
|
||||||
# Limit the number of tasks generated
|
|
||||||
task-master parse-prd <prd-file.txt> --num-tasks=10
|
|
||||||
```
|
|
||||||
|
|
||||||
### List Tasks
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# List all tasks
|
|
||||||
task-master list
|
|
||||||
|
|
||||||
# List tasks with a specific status
|
|
||||||
task-master list --status=<status>
|
|
||||||
|
|
||||||
# List tasks with subtasks
|
|
||||||
task-master list --with-subtasks
|
|
||||||
|
|
||||||
# List tasks with a specific status and include subtasks
|
|
||||||
task-master list --status=<status> --with-subtasks
|
|
||||||
```
|
|
||||||
|
|
||||||
### Show Next Task
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Show the next task to work on based on dependencies and status
|
|
||||||
task-master next
|
|
||||||
```
|
|
||||||
|
|
||||||
### Show Specific Task
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Show details of a specific task
|
|
||||||
task-master show <id>
|
|
||||||
# or
|
|
||||||
task-master show --id=<id>
|
|
||||||
|
|
||||||
# View a specific subtask (e.g., subtask 2 of task 1)
|
|
||||||
task-master show 1.2
|
|
||||||
```
|
|
||||||
|
|
||||||
### Update Tasks
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Update tasks from a specific ID and provide context
|
|
||||||
task-master update --from=<id> --prompt="<prompt>"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Update a Specific Task
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Update a single task by ID with new information
|
|
||||||
task-master update-task --id=<id> --prompt="<prompt>"
|
|
||||||
|
|
||||||
# Use research-backed updates with Perplexity AI
|
|
||||||
task-master update-task --id=<id> --prompt="<prompt>" --research
|
|
||||||
```
|
|
||||||
|
|
||||||
### Update a Subtask
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Append additional information to a specific subtask
|
|
||||||
task-master update-subtask --id=<parentId.subtaskId> --prompt="<prompt>"
|
|
||||||
|
|
||||||
# Example: Add details about API rate limiting to subtask 2 of task 5
|
|
||||||
task-master update-subtask --id=5.2 --prompt="Add rate limiting of 100 requests per minute"
|
|
||||||
|
|
||||||
# Use research-backed updates with Perplexity AI
|
|
||||||
task-master update-subtask --id=<parentId.subtaskId> --prompt="<prompt>" --research
|
|
||||||
```
|
|
||||||
|
|
||||||
Unlike the `update-task` command which replaces task information, the `update-subtask` command _appends_ new information to the existing subtask details, marking it with a timestamp. This is useful for iteratively enhancing subtasks while preserving the original content.
|
|
||||||
|
|
||||||
### Remove Task
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Remove a task permanently
|
|
||||||
task-master remove-task --id=<id>
|
|
||||||
|
|
||||||
# Remove a subtask permanently
|
|
||||||
task-master remove-task --id=<parentId.subtaskId>
|
|
||||||
|
|
||||||
# Skip the confirmation prompt
|
|
||||||
task-master remove-task --id=<id> --yes
|
|
||||||
```
|
|
||||||
|
|
||||||
The `remove-task` command permanently deletes a task or subtask from `tasks.json`. It also automatically cleans up any references to the deleted task in other tasks' dependencies. Consider using 'blocked', 'cancelled', or 'deferred' status instead if you want to keep the task for reference.
|
|
||||||
|
|
||||||
### Generate Task Files
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Generate individual task files from tasks.json
|
|
||||||
task-master generate
|
|
||||||
```
|
|
||||||
|
|
||||||
### Set Task Status
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Set status of a single task
|
|
||||||
task-master set-status --id=<id> --status=<status>
|
|
||||||
|
|
||||||
# Set status for multiple tasks
|
|
||||||
task-master set-status --id=1,2,3 --status=<status>
|
|
||||||
|
|
||||||
# Set status for subtasks
|
|
||||||
task-master set-status --id=1.1,1.2 --status=<status>
|
|
||||||
```
|
|
||||||
|
|
||||||
When marking a task as "done", all of its subtasks will automatically be marked as "done" as well.
|
|
||||||
|
|
||||||
### Expand Tasks
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Expand a specific task with subtasks
|
|
||||||
task-master expand --id=<id> --num=<number>
|
|
||||||
|
|
||||||
# Expand with additional context
|
|
||||||
task-master expand --id=<id> --prompt="<context>"
|
|
||||||
|
|
||||||
# Expand all pending tasks
|
|
||||||
task-master expand --all
|
|
||||||
|
|
||||||
# Force regeneration of subtasks for tasks that already have them
|
|
||||||
task-master expand --all --force
|
|
||||||
|
|
||||||
# Research-backed subtask generation for a specific task
|
|
||||||
task-master expand --id=<id> --research
|
|
||||||
|
|
||||||
# Research-backed generation for all tasks
|
|
||||||
task-master expand --all --research
|
|
||||||
```
|
|
||||||
|
|
||||||
### Clear Subtasks
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Clear subtasks from a specific task
|
|
||||||
task-master clear-subtasks --id=<id>
|
|
||||||
|
|
||||||
# Clear subtasks from multiple tasks
|
|
||||||
task-master clear-subtasks --id=1,2,3
|
|
||||||
|
|
||||||
# Clear subtasks from all tasks
|
|
||||||
task-master clear-subtasks --all
|
|
||||||
```
|
|
||||||
|
|
||||||
### Analyze Task Complexity
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Analyze complexity of all tasks
|
|
||||||
task-master analyze-complexity
|
|
||||||
|
|
||||||
# Save report to a custom location
|
|
||||||
task-master analyze-complexity --output=my-report.json
|
|
||||||
|
|
||||||
# Use a specific LLM model
|
|
||||||
task-master analyze-complexity --model=claude-3-opus-20240229
|
|
||||||
|
|
||||||
# Set a custom complexity threshold (1-10)
|
|
||||||
task-master analyze-complexity --threshold=6
|
|
||||||
|
|
||||||
# Use an alternative tasks file
|
|
||||||
task-master analyze-complexity --file=custom-tasks.json
|
|
||||||
|
|
||||||
# Use Perplexity AI for research-backed complexity analysis
|
|
||||||
task-master analyze-complexity --research
|
|
||||||
```
|
|
||||||
|
|
||||||
### View Complexity Report
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Display the task complexity analysis report
|
|
||||||
task-master complexity-report
|
|
||||||
|
|
||||||
# View a report at a custom location
|
|
||||||
task-master complexity-report --file=my-report.json
|
|
||||||
```
|
|
||||||
|
|
||||||
### Managing Task Dependencies
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Add a dependency to a task
|
|
||||||
task-master add-dependency --id=<id> --depends-on=<id>
|
|
||||||
|
|
||||||
# Remove a dependency from a task
|
|
||||||
task-master remove-dependency --id=<id> --depends-on=<id>
|
|
||||||
|
|
||||||
# Validate dependencies without fixing them
|
|
||||||
task-master validate-dependencies
|
|
||||||
|
|
||||||
# Find and fix invalid dependencies automatically
|
|
||||||
task-master fix-dependencies
|
|
||||||
```
|
|
||||||
|
|
||||||
### Add a New Task
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Add a new task using AI
|
|
||||||
task-master add-task --prompt="Description of the new task"
|
|
||||||
|
|
||||||
# Add a task with dependencies
|
|
||||||
task-master add-task --prompt="Description" --dependencies=1,2,3
|
|
||||||
|
|
||||||
# Add a task with priority
|
|
||||||
task-master add-task --prompt="Description" --priority=high
|
|
||||||
```
|
|
||||||
|
|
||||||
## Feature Details
|
|
||||||
|
|
||||||
### Analyzing Task Complexity
|
|
||||||
|
|
||||||
The `analyze-complexity` command:
|
|
||||||
|
|
||||||
- Analyzes each task using AI to assess its complexity on a scale of 1-10
|
|
||||||
- Recommends optimal number of subtasks based on configured DEFAULT_SUBTASKS
|
|
||||||
- Generates tailored prompts for expanding each task
|
|
||||||
- Creates a comprehensive JSON report with ready-to-use commands
|
|
||||||
- Saves the report to scripts/task-complexity-report.json by default
|
|
||||||
|
|
||||||
The generated report contains:
|
|
||||||
|
|
||||||
- Complexity analysis for each task (scored 1-10)
|
|
||||||
- Recommended number of subtasks based on complexity
|
|
||||||
- AI-generated expansion prompts customized for each task
|
|
||||||
- Ready-to-run expansion commands directly within each task analysis
|
|
||||||
|
|
||||||
### Viewing Complexity Report
|
|
||||||
|
|
||||||
The `complexity-report` command:
|
|
||||||
|
|
||||||
- Displays a formatted, easy-to-read version of the complexity analysis report
|
|
||||||
- Shows tasks organized by complexity score (highest to lowest)
|
|
||||||
- Provides complexity distribution statistics (low, medium, high)
|
|
||||||
- Highlights tasks recommended for expansion based on threshold score
|
|
||||||
- Includes ready-to-use expansion commands for each complex task
|
|
||||||
- If no report exists, offers to generate one on the spot
|
|
||||||
|
|
||||||
### Smart Task Expansion
|
|
||||||
|
|
||||||
The `expand` command automatically checks for and uses the complexity report:
|
|
||||||
|
|
||||||
When a complexity report exists:
|
|
||||||
|
|
||||||
- Tasks are automatically expanded using the recommended subtask count and prompts
|
|
||||||
- When expanding all tasks, they're processed in order of complexity (highest first)
|
|
||||||
- Research-backed generation is preserved from the complexity analysis
|
|
||||||
- You can still override recommendations with explicit command-line options
|
|
||||||
|
|
||||||
Example workflow:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Generate the complexity analysis report with research capabilities
|
|
||||||
task-master analyze-complexity --research
|
|
||||||
|
|
||||||
# Review the report in a readable format
|
|
||||||
task-master complexity-report
|
|
||||||
|
|
||||||
# Expand tasks using the optimized recommendations
|
|
||||||
task-master expand --id=8
|
|
||||||
# or expand all tasks
|
|
||||||
task-master expand --all
|
|
||||||
```
|
|
||||||
|
|
||||||
### Finding the Next Task
|
|
||||||
|
|
||||||
The `next` command:
|
|
||||||
|
|
||||||
- Identifies tasks that are pending/in-progress and have all dependencies satisfied
|
|
||||||
- Prioritizes tasks by priority level, dependency count, and task ID
|
|
||||||
- Displays comprehensive information about the selected task:
|
|
||||||
- Basic task details (ID, title, priority, dependencies)
|
|
||||||
- Implementation details
|
|
||||||
- Subtasks (if they exist)
|
|
||||||
- Provides contextual suggested actions:
|
|
||||||
- Command to mark the task as in-progress
|
|
||||||
- Command to mark the task as done
|
|
||||||
- Commands for working with subtasks
|
|
||||||
|
|
||||||
### Viewing Specific Task Details
|
|
||||||
|
|
||||||
The `show` command:
|
|
||||||
|
|
||||||
- Displays comprehensive details about a specific task or subtask
|
|
||||||
- Shows task status, priority, dependencies, and detailed implementation notes
|
|
||||||
- For parent tasks, displays all subtasks and their status
|
|
||||||
- For subtasks, shows parent task relationship
|
|
||||||
- Provides contextual action suggestions based on the task's state
|
|
||||||
- Works with both regular tasks and subtasks (using the format taskId.subtaskId)
|
|
||||||
|
|
||||||
## Best Practices for AI-Driven Development
|
|
||||||
|
|
||||||
1. **Start with a detailed PRD**: The more detailed your PRD, the better the generated tasks will be.
|
|
||||||
|
|
||||||
2. **Review generated tasks**: After parsing the PRD, review the tasks to ensure they make sense and have appropriate dependencies.
|
|
||||||
|
|
||||||
3. **Analyze task complexity**: Use the complexity analysis feature to identify which tasks should be broken down further.
|
|
||||||
|
|
||||||
4. **Follow the dependency chain**: Always respect task dependencies - the Cursor agent will help with this.
|
|
||||||
|
|
||||||
5. **Update as you go**: If your implementation diverges from the plan, use the update command to keep future tasks aligned with your current approach.
|
|
||||||
|
|
||||||
6. **Break down complex tasks**: Use the expand command to break down complex tasks into manageable subtasks.
|
|
||||||
|
|
||||||
7. **Regenerate task files**: After any updates to tasks.json, regenerate the task files to keep them in sync.
|
|
||||||
|
|
||||||
8. **Communicate context to the agent**: When asking the Cursor agent to help with a task, provide context about what you're trying to achieve.
|
|
||||||
|
|
||||||
9. **Validate dependencies**: Periodically run the validate-dependencies command to check for invalid or circular dependencies.
|
|
||||||
|
|
||||||
## Example Cursor AI Interactions
|
|
||||||
|
|
||||||
### Starting a new project
|
|
||||||
|
|
||||||
```
|
|
||||||
I've just initialized a new project with Claude Task Master. I have a PRD at scripts/prd.txt.
|
|
||||||
Can you help me parse it and set up the initial tasks?
|
|
||||||
```
|
|
||||||
|
|
||||||
### Working on tasks
|
|
||||||
|
|
||||||
```
|
|
||||||
What's the next task I should work on? Please consider dependencies and priorities.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Implementing a specific task
|
|
||||||
|
|
||||||
```
|
|
||||||
I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it?
|
|
||||||
```
|
|
||||||
|
|
||||||
### Managing subtasks
|
|
||||||
|
|
||||||
```
|
|
||||||
I need to regenerate the subtasks for task 3 with a different approach. Can you help me clear and regenerate them?
|
|
||||||
```
|
|
||||||
|
|
||||||
### Handling changes
|
|
||||||
|
|
||||||
```
|
|
||||||
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
|
||||||
```
|
|
||||||
|
|
||||||
### Completing work
|
|
||||||
|
|
||||||
```
|
|
||||||
I've finished implementing the authentication system described in task 2. All tests are passing.
|
|
||||||
Please mark it as complete and tell me what I should work on next.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Analyzing complexity
|
|
||||||
|
|
||||||
```
|
|
||||||
Can you analyze the complexity of our tasks to help me understand which ones need to be broken down further?
|
|
||||||
```
|
|
||||||
|
|
||||||
### Viewing complexity report
|
|
||||||
|
|
||||||
```
|
|
||||||
Can you show me the complexity report in a more readable format?
|
|
||||||
```
|
|
||||||
|
|||||||
@@ -21,9 +21,11 @@ In an AI-driven development process—particularly with tools like [Cursor](http
|
|||||||
The script can be configured through environment variables in a `.env` file at the root of the project:
|
The script can be configured through environment variables in a `.env` file at the root of the project:
|
||||||
|
|
||||||
### Required Configuration
|
### Required Configuration
|
||||||
|
|
||||||
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude
|
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude
|
||||||
|
|
||||||
### Optional Configuration
|
### Optional Configuration
|
||||||
|
|
||||||
- `MODEL`: Specify which Claude model to use (default: "claude-3-7-sonnet-20250219")
|
- `MODEL`: Specify which Claude model to use (default: "claude-3-7-sonnet-20250219")
|
||||||
- `MAX_TOKENS`: Maximum tokens for model responses (default: 4000)
|
- `MAX_TOKENS`: Maximum tokens for model responses (default: 4000)
|
||||||
- `TEMPERATURE`: Temperature for model responses (default: 0.7)
|
- `TEMPERATURE`: Temperature for model responses (default: 0.7)
|
||||||
@@ -39,6 +41,7 @@ The script can be configured through environment variables in a `.env` file at t
|
|||||||
## How It Works
|
## How It Works
|
||||||
|
|
||||||
1. **`tasks.json`**:
|
1. **`tasks.json`**:
|
||||||
|
|
||||||
- A JSON file at the project root containing an array of tasks (each with `id`, `title`, `description`, `status`, etc.).
|
- A JSON file at the project root containing an array of tasks (each with `id`, `title`, `description`, `status`, etc.).
|
||||||
- The `meta` field can store additional info like the project's name, version, or reference to the PRD.
|
- The `meta` field can store additional info like the project's name, version, or reference to the PRD.
|
||||||
- Tasks can have `subtasks` for more detailed implementation steps.
|
- Tasks can have `subtasks` for more detailed implementation steps.
|
||||||
@@ -111,6 +114,7 @@ task-master update --file=custom-tasks.json --from=5 --prompt="Change database f
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- The `--prompt` parameter is required and should explain the changes or new context
|
- The `--prompt` parameter is required and should explain the changes or new context
|
||||||
- Only tasks that aren't marked as 'done' will be updated
|
- Only tasks that aren't marked as 'done' will be updated
|
||||||
- Tasks with ID >= the specified --from value will be updated
|
- Tasks with ID >= the specified --from value will be updated
|
||||||
@@ -134,6 +138,7 @@ task-master set-status --id=1,2,3 --status=done
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- When marking a parent task as "done", all of its subtasks will automatically be marked as "done" as well
|
- When marking a parent task as "done", all of its subtasks will automatically be marked as "done" as well
|
||||||
- Common status values are 'done', 'pending', and 'deferred', but any string is accepted
|
- Common status values are 'done', 'pending', and 'deferred', but any string is accepted
|
||||||
- You can specify multiple task IDs by separating them with commas
|
- You can specify multiple task IDs by separating them with commas
|
||||||
@@ -183,6 +188,7 @@ task-master clear-subtasks --all
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- After clearing subtasks, task files are automatically regenerated
|
- After clearing subtasks, task files are automatically regenerated
|
||||||
- This is useful when you want to regenerate subtasks with a different approach
|
- This is useful when you want to regenerate subtasks with a different approach
|
||||||
- Can be combined with the `expand` command to immediately generate new subtasks
|
- Can be combined with the `expand` command to immediately generate new subtasks
|
||||||
@@ -198,6 +204,7 @@ The script integrates with two AI services:
|
|||||||
The Perplexity integration uses the OpenAI client to connect to Perplexity's API, which provides enhanced research capabilities for generating more informed subtasks. If the Perplexity API is unavailable or encounters an error, the script will automatically fall back to using Anthropic's Claude.
|
The Perplexity integration uses the OpenAI client to connect to Perplexity's API, which provides enhanced research capabilities for generating more informed subtasks. If the Perplexity API is unavailable or encounters an error, the script will automatically fall back to using Anthropic's Claude.
|
||||||
|
|
||||||
To use the Perplexity integration:
|
To use the Perplexity integration:
|
||||||
|
|
||||||
1. Obtain a Perplexity API key
|
1. Obtain a Perplexity API key
|
||||||
2. Add `PERPLEXITY_API_KEY` to your `.env` file
|
2. Add `PERPLEXITY_API_KEY` to your `.env` file
|
||||||
3. Optionally specify `PERPLEXITY_MODEL` in your `.env` file (default: "sonar-medium-online")
|
3. Optionally specify `PERPLEXITY_MODEL` in your `.env` file (default: "sonar-medium-online")
|
||||||
@@ -206,6 +213,7 @@ To use the Perplexity integration:
|
|||||||
## Logging
|
## Logging
|
||||||
|
|
||||||
The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
|
The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
|
||||||
|
|
||||||
- `debug`: Detailed information, typically useful for troubleshooting
|
- `debug`: Detailed information, typically useful for troubleshooting
|
||||||
- `info`: Confirmation that things are working as expected (default)
|
- `info`: Confirmation that things are working as expected (default)
|
||||||
- `warn`: Warning messages that don't prevent execution
|
- `warn`: Warning messages that don't prevent execution
|
||||||
@@ -228,17 +236,20 @@ task-master remove-dependency --id=<id> --depends-on=<id>
|
|||||||
These commands:
|
These commands:
|
||||||
|
|
||||||
1. **Allow precise dependency management**:
|
1. **Allow precise dependency management**:
|
||||||
|
|
||||||
- Add dependencies between tasks with automatic validation
|
- Add dependencies between tasks with automatic validation
|
||||||
- Remove dependencies when they're no longer needed
|
- Remove dependencies when they're no longer needed
|
||||||
- Update task files automatically after changes
|
- Update task files automatically after changes
|
||||||
|
|
||||||
2. **Include validation checks**:
|
2. **Include validation checks**:
|
||||||
|
|
||||||
- Prevent circular dependencies (a task depending on itself)
|
- Prevent circular dependencies (a task depending on itself)
|
||||||
- Prevent duplicate dependencies
|
- Prevent duplicate dependencies
|
||||||
- Verify that both tasks exist before adding/removing dependencies
|
- Verify that both tasks exist before adding/removing dependencies
|
||||||
- Check if dependencies exist before attempting to remove them
|
- Check if dependencies exist before attempting to remove them
|
||||||
|
|
||||||
3. **Provide clear feedback**:
|
3. **Provide clear feedback**:
|
||||||
|
|
||||||
- Success messages confirm when dependencies are added/removed
|
- Success messages confirm when dependencies are added/removed
|
||||||
- Error messages explain why operations failed (if applicable)
|
- Error messages explain why operations failed (if applicable)
|
||||||
|
|
||||||
@@ -263,6 +274,7 @@ task-master validate-dependencies --file=custom-tasks.json
|
|||||||
```
|
```
|
||||||
|
|
||||||
This command:
|
This command:
|
||||||
|
|
||||||
- Scans all tasks and subtasks for non-existent dependencies
|
- Scans all tasks and subtasks for non-existent dependencies
|
||||||
- Identifies potential self-dependencies (tasks referencing themselves)
|
- Identifies potential self-dependencies (tasks referencing themselves)
|
||||||
- Reports all found issues without modifying files
|
- Reports all found issues without modifying files
|
||||||
@@ -284,6 +296,7 @@ task-master fix-dependencies --file=custom-tasks.json
|
|||||||
```
|
```
|
||||||
|
|
||||||
This command:
|
This command:
|
||||||
|
|
||||||
1. **Validates all dependencies** across tasks and subtasks
|
1. **Validates all dependencies** across tasks and subtasks
|
||||||
2. **Automatically removes**:
|
2. **Automatically removes**:
|
||||||
- References to non-existent tasks and subtasks
|
- References to non-existent tasks and subtasks
|
||||||
@@ -321,6 +334,7 @@ task-master analyze-complexity --research
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- The command uses Claude to analyze each task's complexity (or Perplexity with --research flag)
|
- The command uses Claude to analyze each task's complexity (or Perplexity with --research flag)
|
||||||
- Tasks are scored on a scale of 1-10
|
- Tasks are scored on a scale of 1-10
|
||||||
- Each task receives a recommended number of subtasks based on DEFAULT_SUBTASKS configuration
|
- Each task receives a recommended number of subtasks based on DEFAULT_SUBTASKS configuration
|
||||||
@@ -345,12 +359,14 @@ task-master expand --id=8 --num=5 --prompt="Custom prompt"
|
|||||||
```
|
```
|
||||||
|
|
||||||
When a complexity report exists:
|
When a complexity report exists:
|
||||||
|
|
||||||
- The `expand` command will use the recommended subtask count from the report (unless overridden)
|
- The `expand` command will use the recommended subtask count from the report (unless overridden)
|
||||||
- It will use the tailored expansion prompt from the report (unless a custom prompt is provided)
|
- It will use the tailored expansion prompt from the report (unless a custom prompt is provided)
|
||||||
- When using `--all`, tasks are sorted by complexity score (highest first)
|
- When using `--all`, tasks are sorted by complexity score (highest first)
|
||||||
- The `--research` flag is preserved from the complexity analysis to expansion
|
- The `--research` flag is preserved from the complexity analysis to expansion
|
||||||
|
|
||||||
The output report structure is:
|
The output report structure is:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"meta": {
|
"meta": {
|
||||||
@@ -369,7 +385,7 @@ The output report structure is:
|
|||||||
"expansionPrompt": "Create subtasks that handle detecting...",
|
"expansionPrompt": "Create subtasks that handle detecting...",
|
||||||
"reasoning": "This task requires sophisticated logic...",
|
"reasoning": "This task requires sophisticated logic...",
|
||||||
"expansionCommand": "task-master expand --id=8 --num=6 --prompt=\"Create subtasks...\" --research"
|
"expansionCommand": "task-master expand --id=8 --num=6 --prompt=\"Create subtasks...\" --research"
|
||||||
},
|
}
|
||||||
// More tasks sorted by complexity score (highest first)
|
// More tasks sorted by complexity score (highest first)
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,7 +49,13 @@ function runDevScript(args) {
|
|||||||
console.error('\nDEBUG - CLI Wrapper Analysis:');
|
console.error('\nDEBUG - CLI Wrapper Analysis:');
|
||||||
console.error('- Original command: ' + process.argv.join(' '));
|
console.error('- Original command: ' + process.argv.join(' '));
|
||||||
console.error('- Transformed args: ' + args.join(' '));
|
console.error('- Transformed args: ' + args.join(' '));
|
||||||
console.error('- dev.js will receive: node ' + devScriptPath + ' ' + args.join(' ') + '\n');
|
console.error(
|
||||||
|
'- dev.js will receive: node ' +
|
||||||
|
devScriptPath +
|
||||||
|
' ' +
|
||||||
|
args.join(' ') +
|
||||||
|
'\n'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// For testing: If TEST_MODE is set, just print args and exit
|
// For testing: If TEST_MODE is set, just print args and exit
|
||||||
@@ -86,11 +92,13 @@ function createDevScriptAction(commandName) {
|
|||||||
// If camelCase flags were found, show error and exit
|
// If camelCase flags were found, show error and exit
|
||||||
if (camelCaseFlags.length > 0) {
|
if (camelCaseFlags.length > 0) {
|
||||||
console.error('\nError: Please use kebab-case for CLI flags:');
|
console.error('\nError: Please use kebab-case for CLI flags:');
|
||||||
camelCaseFlags.forEach(flag => {
|
camelCaseFlags.forEach((flag) => {
|
||||||
console.error(` Instead of: --${flag.original}`);
|
console.error(` Instead of: --${flag.original}`);
|
||||||
console.error(` Use: --${flag.kebabCase}`);
|
console.error(` Use: --${flag.kebabCase}`);
|
||||||
});
|
});
|
||||||
console.error('\nExample: task-master parse-prd --num-tasks=5 instead of --numTasks=5\n');
|
console.error(
|
||||||
|
'\nExample: task-master parse-prd --num-tasks=5 instead of --numTasks=5\n'
|
||||||
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,9 +121,11 @@ function createDevScriptAction(commandName) {
|
|||||||
// It's a flag - pass through as is
|
// It's a flag - pass through as is
|
||||||
commandArgs.push(arg);
|
commandArgs.push(arg);
|
||||||
// Skip the next arg if this is a flag with a value (not --flag=value format)
|
// Skip the next arg if this is a flag with a value (not --flag=value format)
|
||||||
if (!arg.includes('=') &&
|
if (
|
||||||
|
!arg.includes('=') &&
|
||||||
i + 1 < process.argv.length &&
|
i + 1 < process.argv.length &&
|
||||||
!process.argv[i+1].startsWith('--')) {
|
!process.argv[i + 1].startsWith('--')
|
||||||
|
) {
|
||||||
commandArgs.push(process.argv[++i]);
|
commandArgs.push(process.argv[++i]);
|
||||||
}
|
}
|
||||||
} else if (!positionals.has(arg)) {
|
} else if (!positionals.has(arg)) {
|
||||||
@@ -143,7 +153,9 @@ function createDevScriptAction(commandName) {
|
|||||||
userOptions.add(kebabName);
|
userOptions.add(kebabName);
|
||||||
|
|
||||||
// Add the camelCase version as well
|
// Add the camelCase version as well
|
||||||
const camelName = kebabName.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
|
const camelName = kebabName.replace(/-([a-z])/g, (_, letter) =>
|
||||||
|
letter.toUpperCase()
|
||||||
|
);
|
||||||
userOptions.add(camelName);
|
userOptions.add(camelName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -167,7 +179,10 @@ function createDevScriptAction(commandName) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Skip built-in Commander properties and options the user provided
|
// Skip built-in Commander properties and options the user provided
|
||||||
if (['parent', 'commands', 'options', 'rawArgs'].includes(key) || userOptions.has(key)) {
|
if (
|
||||||
|
['parent', 'commands', 'options', 'rawArgs'].includes(key) ||
|
||||||
|
userOptions.has(key)
|
||||||
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -224,9 +239,17 @@ function registerInitCommand(program) {
|
|||||||
.option('--dry-run', 'Show what would be done without making changes')
|
.option('--dry-run', 'Show what would be done without making changes')
|
||||||
.action((options) => {
|
.action((options) => {
|
||||||
// Pass through any options to the init script
|
// Pass through any options to the init script
|
||||||
const args = ['--yes', 'name', 'description', 'version', 'author', 'skip-install', 'dry-run']
|
const args = [
|
||||||
.filter(opt => options[opt])
|
'--yes',
|
||||||
.map(opt => {
|
'name',
|
||||||
|
'description',
|
||||||
|
'version',
|
||||||
|
'author',
|
||||||
|
'skip-install',
|
||||||
|
'dry-run'
|
||||||
|
]
|
||||||
|
.filter((opt) => options[opt])
|
||||||
|
.map((opt) => {
|
||||||
if (opt === 'yes' || opt === 'skip-install' || opt === 'dry-run') {
|
if (opt === 'yes' || opt === 'skip-install' || opt === 'dry-run') {
|
||||||
return `--${opt}`;
|
return `--${opt}`;
|
||||||
}
|
}
|
||||||
@@ -279,24 +302,18 @@ const tempProgram = new Command();
|
|||||||
registerCommands(tempProgram);
|
registerCommands(tempProgram);
|
||||||
|
|
||||||
// For each command in the temp instance, add a modified version to our actual program
|
// For each command in the temp instance, add a modified version to our actual program
|
||||||
tempProgram.commands.forEach(cmd => {
|
tempProgram.commands.forEach((cmd) => {
|
||||||
if (['init', 'dev'].includes(cmd.name())) {
|
if (['init', 'dev'].includes(cmd.name())) {
|
||||||
// Skip commands we've already defined specially
|
// Skip commands we've already defined specially
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a new command with the same name and description
|
// Create a new command with the same name and description
|
||||||
const newCmd = program
|
const newCmd = program.command(cmd.name()).description(cmd.description());
|
||||||
.command(cmd.name())
|
|
||||||
.description(cmd.description());
|
|
||||||
|
|
||||||
// Copy all options
|
// Copy all options
|
||||||
cmd.options.forEach(opt => {
|
cmd.options.forEach((opt) => {
|
||||||
newCmd.option(
|
newCmd.option(opt.flags, opt.description, opt.defaultValue);
|
||||||
opt.flags,
|
|
||||||
opt.description,
|
|
||||||
opt.defaultValue
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Set the action to proxy to dev.js
|
// Set the action to proxy to dev.js
|
||||||
@@ -311,14 +328,21 @@ process.on('uncaughtException', (err) => {
|
|||||||
// Check if this is a commander.js unknown option error
|
// Check if this is a commander.js unknown option error
|
||||||
if (err.code === 'commander.unknownOption') {
|
if (err.code === 'commander.unknownOption') {
|
||||||
const option = err.message.match(/'([^']+)'/)?.[1];
|
const option = err.message.match(/'([^']+)'/)?.[1];
|
||||||
const commandArg = process.argv.find(arg => !arg.startsWith('-') &&
|
const commandArg = process.argv.find(
|
||||||
|
(arg) =>
|
||||||
|
!arg.startsWith('-') &&
|
||||||
arg !== 'task-master' &&
|
arg !== 'task-master' &&
|
||||||
!arg.includes('/') &&
|
!arg.includes('/') &&
|
||||||
arg !== 'node');
|
arg !== 'node'
|
||||||
|
);
|
||||||
const command = commandArg || 'unknown';
|
const command = commandArg || 'unknown';
|
||||||
|
|
||||||
console.error(chalk.red(`Error: Unknown option '${option}'`));
|
console.error(chalk.red(`Error: Unknown option '${option}'`));
|
||||||
console.error(chalk.yellow(`Run 'task-master ${command} --help' to see available options for this command`));
|
console.error(
|
||||||
|
chalk.yellow(
|
||||||
|
`Run 'task-master ${command} --help' to see available options for this command`
|
||||||
|
)
|
||||||
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -327,7 +351,9 @@ process.on('uncaughtException', (err) => {
|
|||||||
const command = err.message.match(/'([^']+)'/)?.[1];
|
const command = err.message.match(/'([^']+)'/)?.[1];
|
||||||
|
|
||||||
console.error(chalk.red(`Error: Unknown command '${command}'`));
|
console.error(chalk.red(`Error: Unknown command '${command}'`));
|
||||||
console.error(chalk.yellow(`Run 'task-master --help' to see available commands`));
|
console.error(
|
||||||
|
chalk.yellow(`Run 'task-master --help' to see available commands`)
|
||||||
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -90,13 +90,13 @@ export const simpleFunction = adaptForMcp(originalFunction);
|
|||||||
// Split implementation - completely different code paths for CLI vs MCP
|
// Split implementation - completely different code paths for CLI vs MCP
|
||||||
export const complexFunction = sourceSplitFunction(
|
export const complexFunction = sourceSplitFunction(
|
||||||
// CLI version with UI
|
// CLI version with UI
|
||||||
function(param1, param2) {
|
function (param1, param2) {
|
||||||
displayBanner();
|
displayBanner();
|
||||||
console.log(`Processing ${param1}...`);
|
console.log(`Processing ${param1}...`);
|
||||||
// ... CLI implementation
|
// ... CLI implementation
|
||||||
},
|
},
|
||||||
// MCP version with structured return
|
// MCP version with structured return
|
||||||
function(param1, param2, options = {}) {
|
function (param1, param2, options = {}) {
|
||||||
// ... MCP implementation
|
// ... MCP implementation
|
||||||
return { success: true, data };
|
return { success: true, data };
|
||||||
}
|
}
|
||||||
@@ -186,22 +186,22 @@ const commandMap = {
|
|||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// In mcp-server/src/tools/newFeature.js
|
// In mcp-server/src/tools/newFeature.js
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
executeTaskMasterCommand,
|
executeTaskMasterCommand,
|
||||||
createContentResponse,
|
createContentResponse,
|
||||||
createErrorResponse,
|
createErrorResponse
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
|
|
||||||
export function registerNewFeatureTool(server) {
|
export function registerNewFeatureTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "newFeature",
|
name: 'newFeature',
|
||||||
description: "Run the new feature",
|
description: 'Run the new feature',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
param1: z.string().describe("First parameter"),
|
param1: z.string().describe('First parameter'),
|
||||||
param2: z.number().optional().describe("Second parameter"),
|
param2: z.number().optional().describe('Second parameter'),
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z.string().describe("Root directory of the project")
|
projectRoot: z.string().describe('Root directory of the project')
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log }) => {
|
execute: async (args, { log }) => {
|
||||||
try {
|
try {
|
||||||
@@ -216,7 +216,7 @@ export function registerNewFeatureTool(server) {
|
|||||||
|
|
||||||
// Execute the command
|
// Execute the command
|
||||||
const result = await executeTaskMasterCommand(
|
const result = await executeTaskMasterCommand(
|
||||||
"new-feature",
|
'new-feature',
|
||||||
log,
|
log,
|
||||||
cmdArgs,
|
cmdArgs,
|
||||||
projectRoot
|
projectRoot
|
||||||
@@ -231,7 +231,7 @@ export function registerNewFeatureTool(server) {
|
|||||||
log.error(`Error in new feature: ${error.message}`);
|
log.error(`Error in new feature: ${error.message}`);
|
||||||
return createErrorResponse(`Error in new feature: ${error.message}`);
|
return createErrorResponse(`Error in new feature: ${error.message}`);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -240,7 +240,7 @@ export function registerNewFeatureTool(server) {
|
|||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// In mcp-server/src/tools/index.js
|
// In mcp-server/src/tools/index.js
|
||||||
import { registerNewFeatureTool } from "./newFeature.js";
|
import { registerNewFeatureTool } from './newFeature.js';
|
||||||
|
|
||||||
export function registerTaskMasterTools(server) {
|
export function registerTaskMasterTools(server) {
|
||||||
// ... existing registrations
|
// ... existing registrations
|
||||||
1913
context/mcp-protocol-schema-03262025.json
Normal file
1913
context/mcp-protocol-schema-03262025.json
Normal file
File diff suppressed because it is too large
Load Diff
22
docs/README.md
Normal file
22
docs/README.md
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
# Task Master Documentation
|
||||||
|
|
||||||
|
Welcome to the Task Master documentation. Use the links below to navigate to the information you need:
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
- [Configuration Guide](configuration.md) - Set up environment variables and customize Task Master
|
||||||
|
- [Tutorial](tutorial.md) - Step-by-step guide to getting started with Task Master
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
- [Command Reference](command-reference.md) - Complete list of all available commands
|
||||||
|
- [Task Structure](task-structure.md) - Understanding the task format and features
|
||||||
|
|
||||||
|
## Examples & Licensing
|
||||||
|
|
||||||
|
- [Example Interactions](examples.md) - Common Cursor AI interaction examples
|
||||||
|
- [Licensing Information](licensing.md) - Detailed information about the license
|
||||||
|
|
||||||
|
## Need More Help?
|
||||||
|
|
||||||
|
If you can't find what you're looking for in these docs, please check the [main README](../README.md) or visit our [GitHub repository](https://github.com/eyaltoledano/claude-task-master).
|
||||||
@@ -26,9 +26,7 @@ export async function someAiOperationDirect(args, log, context) {
|
|||||||
model: modelConfig.model,
|
model: modelConfig.model,
|
||||||
max_tokens: modelConfig.maxTokens,
|
max_tokens: modelConfig.maxTokens,
|
||||||
temperature: modelConfig.temperature,
|
temperature: modelConfig.temperature,
|
||||||
messages: [
|
messages: [{ role: 'user', content: 'Your prompt here' }]
|
||||||
{ role: 'user', content: 'Your prompt here' }
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -64,7 +62,10 @@ export async function someAiOperationDirect(args, log, context) {
|
|||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// In your MCP tool implementation:
|
// In your MCP tool implementation:
|
||||||
import { AsyncOperationManager, StatusCodes } from '../../utils/async-operation-manager.js';
|
import {
|
||||||
|
AsyncOperationManager,
|
||||||
|
StatusCodes
|
||||||
|
} from '../../utils/async-operation-manager.js';
|
||||||
import { someAiOperationDirect } from '../../core/direct-functions/some-ai-operation.js';
|
import { someAiOperationDirect } from '../../core/direct-functions/some-ai-operation.js';
|
||||||
|
|
||||||
export async function someAiOperation(args, context) {
|
export async function someAiOperation(args, context) {
|
||||||
@@ -87,15 +88,11 @@ export async function someAiOperation(args, context) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Call direct function with session and progress reporting
|
// Call direct function with session and progress reporting
|
||||||
const result = await someAiOperationDirect(
|
const result = await someAiOperationDirect(args, log, {
|
||||||
args,
|
|
||||||
log,
|
|
||||||
{
|
|
||||||
reportProgress,
|
reportProgress,
|
||||||
mcpLog: log,
|
mcpLog: log,
|
||||||
session
|
session
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
// Final progress update
|
// Final progress update
|
||||||
reportProgress({
|
reportProgress({
|
||||||
@@ -178,9 +175,7 @@ export async function researchOperationDirect(args, log, context) {
|
|||||||
// Call Perplexity
|
// Call Perplexity
|
||||||
const response = await client.chat.completions.create({
|
const response = await client.chat.completions.create({
|
||||||
model: context.session?.env?.PERPLEXITY_MODEL || 'sonar-medium-online',
|
model: context.session?.env?.PERPLEXITY_MODEL || 'sonar-medium-online',
|
||||||
messages: [
|
messages: [{ role: 'user', content: args.researchQuery }],
|
||||||
{ role: 'user', content: args.researchQuery }
|
|
||||||
],
|
|
||||||
temperature: 0.1
|
temperature: 0.1
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -226,7 +221,7 @@ const modelConfig = getModelConfig(context.session, operationDefaults);
|
|||||||
const response = await client.messages.create({
|
const response = await client.messages.create({
|
||||||
model: modelConfig.model,
|
model: modelConfig.model,
|
||||||
max_tokens: modelConfig.maxTokens,
|
max_tokens: modelConfig.maxTokens,
|
||||||
temperature: modelConfig.temperature,
|
temperature: modelConfig.temperature
|
||||||
// Other parameters...
|
// Other parameters...
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
@@ -234,20 +229,24 @@ const response = await client.messages.create({
|
|||||||
## Best Practices
|
## Best Practices
|
||||||
|
|
||||||
1. **Error Handling**:
|
1. **Error Handling**:
|
||||||
|
|
||||||
- Always use try/catch blocks around both client initialization and API calls
|
- Always use try/catch blocks around both client initialization and API calls
|
||||||
- Use `handleClaudeError` to provide user-friendly error messages
|
- Use `handleClaudeError` to provide user-friendly error messages
|
||||||
- Return standardized error objects with code and message
|
- Return standardized error objects with code and message
|
||||||
|
|
||||||
2. **Progress Reporting**:
|
2. **Progress Reporting**:
|
||||||
|
|
||||||
- Report progress at key points (starting, processing, completing)
|
- Report progress at key points (starting, processing, completing)
|
||||||
- Include meaningful status messages
|
- Include meaningful status messages
|
||||||
- Include error details in progress reports when failures occur
|
- Include error details in progress reports when failures occur
|
||||||
|
|
||||||
3. **Session Handling**:
|
3. **Session Handling**:
|
||||||
|
|
||||||
- Always pass the session from the context to the AI client getters
|
- Always pass the session from the context to the AI client getters
|
||||||
- Use `getModelConfig` to respect user settings from session
|
- Use `getModelConfig` to respect user settings from session
|
||||||
|
|
||||||
4. **Model Selection**:
|
4. **Model Selection**:
|
||||||
|
|
||||||
- Use `getBestAvailableAIModel` when you need to select between different models
|
- Use `getBestAvailableAIModel` when you need to select between different models
|
||||||
- Set `requiresResearch: true` when you need Perplexity capabilities
|
- Set `requiresResearch: true` when you need Perplexity capabilities
|
||||||
|
|
||||||
|
|||||||
205
docs/command-reference.md
Normal file
205
docs/command-reference.md
Normal file
@@ -0,0 +1,205 @@
|
|||||||
|
# Task Master Command Reference
|
||||||
|
|
||||||
|
Here's a comprehensive reference of all available commands:
|
||||||
|
|
||||||
|
## Parse PRD
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Parse a PRD file and generate tasks
|
||||||
|
task-master parse-prd <prd-file.txt>
|
||||||
|
|
||||||
|
# Limit the number of tasks generated
|
||||||
|
task-master parse-prd <prd-file.txt> --num-tasks=10
|
||||||
|
```
|
||||||
|
|
||||||
|
## List Tasks
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# List all tasks
|
||||||
|
task-master list
|
||||||
|
|
||||||
|
# List tasks with a specific status
|
||||||
|
task-master list --status=<status>
|
||||||
|
|
||||||
|
# List tasks with subtasks
|
||||||
|
task-master list --with-subtasks
|
||||||
|
|
||||||
|
# List tasks with a specific status and include subtasks
|
||||||
|
task-master list --status=<status> --with-subtasks
|
||||||
|
```
|
||||||
|
|
||||||
|
## Show Next Task
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Show the next task to work on based on dependencies and status
|
||||||
|
task-master next
|
||||||
|
```
|
||||||
|
|
||||||
|
## Show Specific Task
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Show details of a specific task
|
||||||
|
task-master show <id>
|
||||||
|
# or
|
||||||
|
task-master show --id=<id>
|
||||||
|
|
||||||
|
# View a specific subtask (e.g., subtask 2 of task 1)
|
||||||
|
task-master show 1.2
|
||||||
|
```
|
||||||
|
|
||||||
|
## Update Tasks
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Update tasks from a specific ID and provide context
|
||||||
|
task-master update --from=<id> --prompt="<prompt>"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Update a Specific Task
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Update a single task by ID with new information
|
||||||
|
task-master update-task --id=<id> --prompt="<prompt>"
|
||||||
|
|
||||||
|
# Use research-backed updates with Perplexity AI
|
||||||
|
task-master update-task --id=<id> --prompt="<prompt>" --research
|
||||||
|
```
|
||||||
|
|
||||||
|
## Update a Subtask
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Append additional information to a specific subtask
|
||||||
|
task-master update-subtask --id=<parentId.subtaskId> --prompt="<prompt>"
|
||||||
|
|
||||||
|
# Example: Add details about API rate limiting to subtask 2 of task 5
|
||||||
|
task-master update-subtask --id=5.2 --prompt="Add rate limiting of 100 requests per minute"
|
||||||
|
|
||||||
|
# Use research-backed updates with Perplexity AI
|
||||||
|
task-master update-subtask --id=<parentId.subtaskId> --prompt="<prompt>" --research
|
||||||
|
```
|
||||||
|
|
||||||
|
Unlike the `update-task` command which replaces task information, the `update-subtask` command _appends_ new information to the existing subtask details, marking it with a timestamp. This is useful for iteratively enhancing subtasks while preserving the original content.
|
||||||
|
|
||||||
|
## Generate Task Files
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Generate individual task files from tasks.json
|
||||||
|
task-master generate
|
||||||
|
```
|
||||||
|
|
||||||
|
## Set Task Status
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Set status of a single task
|
||||||
|
task-master set-status --id=<id> --status=<status>
|
||||||
|
|
||||||
|
# Set status for multiple tasks
|
||||||
|
task-master set-status --id=1,2,3 --status=<status>
|
||||||
|
|
||||||
|
# Set status for subtasks
|
||||||
|
task-master set-status --id=1.1,1.2 --status=<status>
|
||||||
|
```
|
||||||
|
|
||||||
|
When marking a task as "done", all of its subtasks will automatically be marked as "done" as well.
|
||||||
|
|
||||||
|
## Expand Tasks
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Expand a specific task with subtasks
|
||||||
|
task-master expand --id=<id> --num=<number>
|
||||||
|
|
||||||
|
# Expand with additional context
|
||||||
|
task-master expand --id=<id> --prompt="<context>"
|
||||||
|
|
||||||
|
# Expand all pending tasks
|
||||||
|
task-master expand --all
|
||||||
|
|
||||||
|
# Force regeneration of subtasks for tasks that already have them
|
||||||
|
task-master expand --all --force
|
||||||
|
|
||||||
|
# Research-backed subtask generation for a specific task
|
||||||
|
task-master expand --id=<id> --research
|
||||||
|
|
||||||
|
# Research-backed generation for all tasks
|
||||||
|
task-master expand --all --research
|
||||||
|
```
|
||||||
|
|
||||||
|
## Clear Subtasks
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Clear subtasks from a specific task
|
||||||
|
task-master clear-subtasks --id=<id>
|
||||||
|
|
||||||
|
# Clear subtasks from multiple tasks
|
||||||
|
task-master clear-subtasks --id=1,2,3
|
||||||
|
|
||||||
|
# Clear subtasks from all tasks
|
||||||
|
task-master clear-subtasks --all
|
||||||
|
```
|
||||||
|
|
||||||
|
## Analyze Task Complexity
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Analyze complexity of all tasks
|
||||||
|
task-master analyze-complexity
|
||||||
|
|
||||||
|
# Save report to a custom location
|
||||||
|
task-master analyze-complexity --output=my-report.json
|
||||||
|
|
||||||
|
# Use a specific LLM model
|
||||||
|
task-master analyze-complexity --model=claude-3-opus-20240229
|
||||||
|
|
||||||
|
# Set a custom complexity threshold (1-10)
|
||||||
|
task-master analyze-complexity --threshold=6
|
||||||
|
|
||||||
|
# Use an alternative tasks file
|
||||||
|
task-master analyze-complexity --file=custom-tasks.json
|
||||||
|
|
||||||
|
# Use Perplexity AI for research-backed complexity analysis
|
||||||
|
task-master analyze-complexity --research
|
||||||
|
```
|
||||||
|
|
||||||
|
## View Complexity Report
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Display the task complexity analysis report
|
||||||
|
task-master complexity-report
|
||||||
|
|
||||||
|
# View a report at a custom location
|
||||||
|
task-master complexity-report --file=my-report.json
|
||||||
|
```
|
||||||
|
|
||||||
|
## Managing Task Dependencies
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Add a dependency to a task
|
||||||
|
task-master add-dependency --id=<id> --depends-on=<id>
|
||||||
|
|
||||||
|
# Remove a dependency from a task
|
||||||
|
task-master remove-dependency --id=<id> --depends-on=<id>
|
||||||
|
|
||||||
|
# Validate dependencies without fixing them
|
||||||
|
task-master validate-dependencies
|
||||||
|
|
||||||
|
# Find and fix invalid dependencies automatically
|
||||||
|
task-master fix-dependencies
|
||||||
|
```
|
||||||
|
|
||||||
|
## Add a New Task
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Add a new task using AI
|
||||||
|
task-master add-task --prompt="Description of the new task"
|
||||||
|
|
||||||
|
# Add a task with dependencies
|
||||||
|
task-master add-task --prompt="Description" --dependencies=1,2,3
|
||||||
|
|
||||||
|
# Add a task with priority
|
||||||
|
task-master add-task --prompt="Description" --priority=high
|
||||||
|
```
|
||||||
|
|
||||||
|
## Initialize a Project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Initialize a new project with Task Master structure
|
||||||
|
task-master init
|
||||||
|
```
|
||||||
65
docs/configuration.md
Normal file
65
docs/configuration.md
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
# Configuration
|
||||||
|
|
||||||
|
Task Master can be configured through environment variables in a `.env` file at the root of your project.
|
||||||
|
|
||||||
|
## Required Configuration
|
||||||
|
|
||||||
|
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude (Example: `ANTHROPIC_API_KEY=sk-ant-api03-...`)
|
||||||
|
|
||||||
|
## Optional Configuration
|
||||||
|
|
||||||
|
- `MODEL` (Default: `"claude-3-7-sonnet-20250219"`): Claude model to use (Example: `MODEL=claude-3-opus-20240229`)
|
||||||
|
- `MAX_TOKENS` (Default: `"4000"`): Maximum tokens for responses (Example: `MAX_TOKENS=8000`)
|
||||||
|
- `TEMPERATURE` (Default: `"0.7"`): Temperature for model responses (Example: `TEMPERATURE=0.5`)
|
||||||
|
- `DEBUG` (Default: `"false"`): Enable debug logging (Example: `DEBUG=true`)
|
||||||
|
- `LOG_LEVEL` (Default: `"info"`): Console output level (Example: `LOG_LEVEL=debug`)
|
||||||
|
- `DEFAULT_SUBTASKS` (Default: `"3"`): Default subtask count (Example: `DEFAULT_SUBTASKS=5`)
|
||||||
|
- `DEFAULT_PRIORITY` (Default: `"medium"`): Default priority (Example: `DEFAULT_PRIORITY=high`)
|
||||||
|
- `PROJECT_NAME` (Default: `"MCP SaaS MVP"`): Project name in metadata (Example: `PROJECT_NAME=My Awesome Project`)
|
||||||
|
- `PROJECT_VERSION` (Default: `"1.0.0"`): Version in metadata (Example: `PROJECT_VERSION=2.1.0`)
|
||||||
|
- `PERPLEXITY_API_KEY`: For research-backed features (Example: `PERPLEXITY_API_KEY=pplx-...`)
|
||||||
|
- `PERPLEXITY_MODEL` (Default: `"sonar-medium-online"`): Perplexity model (Example: `PERPLEXITY_MODEL=sonar-large-online`)
|
||||||
|
|
||||||
|
## Example .env File
|
||||||
|
|
||||||
|
```
|
||||||
|
# Required
|
||||||
|
ANTHROPIC_API_KEY=sk-ant-api03-your-api-key
|
||||||
|
|
||||||
|
# Optional - Claude Configuration
|
||||||
|
MODEL=claude-3-7-sonnet-20250219
|
||||||
|
MAX_TOKENS=4000
|
||||||
|
TEMPERATURE=0.7
|
||||||
|
|
||||||
|
# Optional - Perplexity API for Research
|
||||||
|
PERPLEXITY_API_KEY=pplx-your-api-key
|
||||||
|
PERPLEXITY_MODEL=sonar-medium-online
|
||||||
|
|
||||||
|
# Optional - Project Info
|
||||||
|
PROJECT_NAME=My Project
|
||||||
|
PROJECT_VERSION=1.0.0
|
||||||
|
|
||||||
|
# Optional - Application Configuration
|
||||||
|
DEFAULT_SUBTASKS=3
|
||||||
|
DEFAULT_PRIORITY=medium
|
||||||
|
DEBUG=false
|
||||||
|
LOG_LEVEL=info
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### If `task-master init` doesn't respond:
|
||||||
|
|
||||||
|
Try running it with Node directly:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node node_modules/claude-task-master/scripts/init.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Or clone the repository and run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/eyaltoledano/claude-task-master.git
|
||||||
|
cd claude-task-master
|
||||||
|
node scripts/init.js
|
||||||
|
```
|
||||||
53
docs/examples.md
Normal file
53
docs/examples.md
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
# Example Cursor AI Interactions
|
||||||
|
|
||||||
|
Here are some common interactions with Cursor AI when using Task Master:
|
||||||
|
|
||||||
|
## Starting a new project
|
||||||
|
|
||||||
|
```
|
||||||
|
I've just initialized a new project with Claude Task Master. I have a PRD at scripts/prd.txt.
|
||||||
|
Can you help me parse it and set up the initial tasks?
|
||||||
|
```
|
||||||
|
|
||||||
|
## Working on tasks
|
||||||
|
|
||||||
|
```
|
||||||
|
What's the next task I should work on? Please consider dependencies and priorities.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Implementing a specific task
|
||||||
|
|
||||||
|
```
|
||||||
|
I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it?
|
||||||
|
```
|
||||||
|
|
||||||
|
## Managing subtasks
|
||||||
|
|
||||||
|
```
|
||||||
|
I need to regenerate the subtasks for task 3 with a different approach. Can you help me clear and regenerate them?
|
||||||
|
```
|
||||||
|
|
||||||
|
## Handling changes
|
||||||
|
|
||||||
|
```
|
||||||
|
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
||||||
|
```
|
||||||
|
|
||||||
|
## Completing work
|
||||||
|
|
||||||
|
```
|
||||||
|
I've finished implementing the authentication system described in task 2. All tests are passing.
|
||||||
|
Please mark it as complete and tell me what I should work on next.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Analyzing complexity
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you analyze the complexity of our tasks to help me understand which ones need to be broken down further?
|
||||||
|
```
|
||||||
|
|
||||||
|
## Viewing complexity report
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you show me the complexity report in a more readable format?
|
||||||
|
```
|
||||||
18
docs/licensing.md
Normal file
18
docs/licensing.md
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# Licensing
|
||||||
|
|
||||||
|
Task Master is licensed under the MIT License with Commons Clause. This means you can:
|
||||||
|
|
||||||
|
## ✅ Allowed:
|
||||||
|
|
||||||
|
- Use Task Master for any purpose (personal, commercial, academic)
|
||||||
|
- Modify the code
|
||||||
|
- Distribute copies
|
||||||
|
- Create and sell products built using Task Master
|
||||||
|
|
||||||
|
## ❌ Not Allowed:
|
||||||
|
|
||||||
|
- Sell Task Master itself
|
||||||
|
- Offer Task Master as a hosted service
|
||||||
|
- Create competing products based on Task Master
|
||||||
|
|
||||||
|
See the [LICENSE](../LICENSE) file for the complete license text.
|
||||||
File diff suppressed because it is too large
Load Diff
139
docs/task-structure.md
Normal file
139
docs/task-structure.md
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
# Task Structure
|
||||||
|
|
||||||
|
Tasks in Task Master follow a specific format designed to provide comprehensive information for both humans and AI assistants.
|
||||||
|
|
||||||
|
## Task Fields in tasks.json
|
||||||
|
|
||||||
|
Tasks in tasks.json have the following structure:
|
||||||
|
|
||||||
|
- `id`: Unique identifier for the task (Example: `1`)
|
||||||
|
- `title`: Brief, descriptive title of the task (Example: `"Initialize Repo"`)
|
||||||
|
- `description`: Concise description of what the task involves (Example: `"Create a new repository, set up initial structure."`)
|
||||||
|
- `status`: Current state of the task (Example: `"pending"`, `"done"`, `"deferred"`)
|
||||||
|
- `dependencies`: IDs of tasks that must be completed before this task (Example: `[1, 2]`)
|
||||||
|
- Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending)
|
||||||
|
- This helps quickly identify which prerequisite tasks are blocking work
|
||||||
|
- `priority`: Importance level of the task (Example: `"high"`, `"medium"`, `"low"`)
|
||||||
|
- `details`: In-depth implementation instructions (Example: `"Use GitHub client ID/secret, handle callback, set session token."`)
|
||||||
|
- `testStrategy`: Verification approach (Example: `"Deploy and call endpoint to confirm 'Hello World' response."`)
|
||||||
|
- `subtasks`: List of smaller, more specific tasks that make up the main task (Example: `[{"id": 1, "title": "Configure OAuth", ...}]`)
|
||||||
|
|
||||||
|
## Task File Format
|
||||||
|
|
||||||
|
Individual task files follow this format:
|
||||||
|
|
||||||
|
```
|
||||||
|
# Task ID: <id>
|
||||||
|
# Title: <title>
|
||||||
|
# Status: <status>
|
||||||
|
# Dependencies: <comma-separated list of dependency IDs>
|
||||||
|
# Priority: <priority>
|
||||||
|
# Description: <brief description>
|
||||||
|
# Details:
|
||||||
|
<detailed implementation notes>
|
||||||
|
|
||||||
|
# Test Strategy:
|
||||||
|
<verification approach>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Features in Detail
|
||||||
|
|
||||||
|
### Analyzing Task Complexity
|
||||||
|
|
||||||
|
The `analyze-complexity` command:
|
||||||
|
|
||||||
|
- Analyzes each task using AI to assess its complexity on a scale of 1-10
|
||||||
|
- Recommends optimal number of subtasks based on configured DEFAULT_SUBTASKS
|
||||||
|
- Generates tailored prompts for expanding each task
|
||||||
|
- Creates a comprehensive JSON report with ready-to-use commands
|
||||||
|
- Saves the report to scripts/task-complexity-report.json by default
|
||||||
|
|
||||||
|
The generated report contains:
|
||||||
|
|
||||||
|
- Complexity analysis for each task (scored 1-10)
|
||||||
|
- Recommended number of subtasks based on complexity
|
||||||
|
- AI-generated expansion prompts customized for each task
|
||||||
|
- Ready-to-run expansion commands directly within each task analysis
|
||||||
|
|
||||||
|
### Viewing Complexity Report
|
||||||
|
|
||||||
|
The `complexity-report` command:
|
||||||
|
|
||||||
|
- Displays a formatted, easy-to-read version of the complexity analysis report
|
||||||
|
- Shows tasks organized by complexity score (highest to lowest)
|
||||||
|
- Provides complexity distribution statistics (low, medium, high)
|
||||||
|
- Highlights tasks recommended for expansion based on threshold score
|
||||||
|
- Includes ready-to-use expansion commands for each complex task
|
||||||
|
- If no report exists, offers to generate one on the spot
|
||||||
|
|
||||||
|
### Smart Task Expansion
|
||||||
|
|
||||||
|
The `expand` command automatically checks for and uses the complexity report:
|
||||||
|
|
||||||
|
When a complexity report exists:
|
||||||
|
|
||||||
|
- Tasks are automatically expanded using the recommended subtask count and prompts
|
||||||
|
- When expanding all tasks, they're processed in order of complexity (highest first)
|
||||||
|
- Research-backed generation is preserved from the complexity analysis
|
||||||
|
- You can still override recommendations with explicit command-line options
|
||||||
|
|
||||||
|
Example workflow:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Generate the complexity analysis report with research capabilities
|
||||||
|
task-master analyze-complexity --research
|
||||||
|
|
||||||
|
# Review the report in a readable format
|
||||||
|
task-master complexity-report
|
||||||
|
|
||||||
|
# Expand tasks using the optimized recommendations
|
||||||
|
task-master expand --id=8
|
||||||
|
# or expand all tasks
|
||||||
|
task-master expand --all
|
||||||
|
```
|
||||||
|
|
||||||
|
### Finding the Next Task
|
||||||
|
|
||||||
|
The `next` command:
|
||||||
|
|
||||||
|
- Identifies tasks that are pending/in-progress and have all dependencies satisfied
|
||||||
|
- Prioritizes tasks by priority level, dependency count, and task ID
|
||||||
|
- Displays comprehensive information about the selected task:
|
||||||
|
- Basic task details (ID, title, priority, dependencies)
|
||||||
|
- Implementation details
|
||||||
|
- Subtasks (if they exist)
|
||||||
|
- Provides contextual suggested actions:
|
||||||
|
- Command to mark the task as in-progress
|
||||||
|
- Command to mark the task as done
|
||||||
|
- Commands for working with subtasks
|
||||||
|
|
||||||
|
### Viewing Specific Task Details
|
||||||
|
|
||||||
|
The `show` command:
|
||||||
|
|
||||||
|
- Displays comprehensive details about a specific task or subtask
|
||||||
|
- Shows task status, priority, dependencies, and detailed implementation notes
|
||||||
|
- For parent tasks, displays all subtasks and their status
|
||||||
|
- For subtasks, shows parent task relationship
|
||||||
|
- Provides contextual action suggestions based on the task's state
|
||||||
|
- Works with both regular tasks and subtasks (using the format taskId.subtaskId)
|
||||||
|
|
||||||
|
## Best Practices for AI-Driven Development
|
||||||
|
|
||||||
|
1. **Start with a detailed PRD**: The more detailed your PRD, the better the generated tasks will be.
|
||||||
|
|
||||||
|
2. **Review generated tasks**: After parsing the PRD, review the tasks to ensure they make sense and have appropriate dependencies.
|
||||||
|
|
||||||
|
3. **Analyze task complexity**: Use the complexity analysis feature to identify which tasks should be broken down further.
|
||||||
|
|
||||||
|
4. **Follow the dependency chain**: Always respect task dependencies - the Cursor agent will help with this.
|
||||||
|
|
||||||
|
5. **Update as you go**: If your implementation diverges from the plan, use the update command to keep future tasks aligned with your current approach.
|
||||||
|
|
||||||
|
6. **Break down complex tasks**: Use the expand command to break down complex tasks into manageable subtasks.
|
||||||
|
|
||||||
|
7. **Regenerate task files**: After any updates to tasks.json, regenerate the task files to keep them in sync.
|
||||||
|
|
||||||
|
8. **Communicate context to the agent**: When asking the Cursor agent to help with a task, provide context about what you're trying to achieve.
|
||||||
|
|
||||||
|
9. **Validate dependencies**: Periodically run the validate-dependencies command to check for invalid or circular dependencies.
|
||||||
355
docs/tutorial.md
Normal file
355
docs/tutorial.md
Normal file
@@ -0,0 +1,355 @@
|
|||||||
|
# Task Master Tutorial
|
||||||
|
|
||||||
|
This tutorial will guide you through setting up and using Task Master for AI-driven development.
|
||||||
|
|
||||||
|
## Initial Setup
|
||||||
|
|
||||||
|
There are two ways to set up Task Master: using MCP (recommended) or via npm installation.
|
||||||
|
|
||||||
|
### Option 1: Using MCP (Recommended)
|
||||||
|
|
||||||
|
MCP (Model Control Protocol) provides the easiest way to get started with Task Master directly in your editor.
|
||||||
|
|
||||||
|
1. **Add the MCP config to your editor** (Cursor recommended, but it works with other text editors):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"taskmaster-ai": {
|
||||||
|
"command": "npx",
|
||||||
|
"args": ["-y", "task-master-ai", "mcp-server"],
|
||||||
|
"env": {
|
||||||
|
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
|
||||||
|
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
|
||||||
|
"MODEL": "claude-3-7-sonnet-20250219",
|
||||||
|
"PERPLEXITY_MODEL": "sonar-pro",
|
||||||
|
"MAX_TOKENS": 128000,
|
||||||
|
"TEMPERATURE": 0.2,
|
||||||
|
"DEFAULT_SUBTASKS": 5,
|
||||||
|
"DEFAULT_PRIORITY": "medium"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Enable the MCP** in your editor settings
|
||||||
|
|
||||||
|
3. **Prompt the AI** to initialize Task Master:
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you please initialize taskmaster-ai into my project?
|
||||||
|
```
|
||||||
|
|
||||||
|
The AI will:
|
||||||
|
|
||||||
|
- Create necessary project structure
|
||||||
|
- Set up initial configuration files
|
||||||
|
- Guide you through the rest of the process
|
||||||
|
|
||||||
|
4. Place your PRD document in the `scripts/` directory (e.g., `scripts/prd.txt`)
|
||||||
|
|
||||||
|
5. **Use natural language commands** to interact with Task Master:
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you parse my PRD at scripts/prd.txt?
|
||||||
|
What's the next task I should work on?
|
||||||
|
Can you help me implement task 3?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Option 2: Manual Installation
|
||||||
|
|
||||||
|
If you prefer to use the command line interface directly:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install globally
|
||||||
|
npm install -g task-master-ai
|
||||||
|
|
||||||
|
# OR install locally within your project
|
||||||
|
npm install task-master-ai
|
||||||
|
```
|
||||||
|
|
||||||
|
Initialize a new project:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# If installed globally
|
||||||
|
task-master init
|
||||||
|
|
||||||
|
# If installed locally
|
||||||
|
npx task-master-init
|
||||||
|
```
|
||||||
|
|
||||||
|
This will prompt you for project details and set up a new project with the necessary files and structure.
|
||||||
|
|
||||||
|
## Common Commands
|
||||||
|
|
||||||
|
After setting up Task Master, you can use these commands (either via AI prompts or CLI):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Parse a PRD and generate tasks
|
||||||
|
task-master parse-prd your-prd.txt
|
||||||
|
|
||||||
|
# List all tasks
|
||||||
|
task-master list
|
||||||
|
|
||||||
|
# Show the next task to work on
|
||||||
|
task-master next
|
||||||
|
|
||||||
|
# Generate task files
|
||||||
|
task-master generate
|
||||||
|
```
|
||||||
|
|
||||||
|
## Setting up Cursor AI Integration
|
||||||
|
|
||||||
|
Task Master is designed to work seamlessly with [Cursor AI](https://www.cursor.so/), providing a structured workflow for AI-driven development.
|
||||||
|
|
||||||
|
### Using Cursor with MCP (Recommended)
|
||||||
|
|
||||||
|
If you've already set up Task Master with MCP in Cursor, the integration is automatic. You can simply use natural language to interact with Task Master:
|
||||||
|
|
||||||
|
```
|
||||||
|
What tasks are available to work on next?
|
||||||
|
Can you analyze the complexity of our tasks?
|
||||||
|
I'd like to implement task 4. What does it involve?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Manual Cursor Setup
|
||||||
|
|
||||||
|
If you're not using MCP, you can still set up Cursor integration:
|
||||||
|
|
||||||
|
1. After initializing your project, open it in Cursor
|
||||||
|
2. The `.cursor/rules/dev_workflow.mdc` file is automatically loaded by Cursor, providing the AI with knowledge about the task management system
|
||||||
|
3. Place your PRD document in the `scripts/` directory (e.g., `scripts/prd.txt`)
|
||||||
|
4. Open Cursor's AI chat and switch to Agent mode
|
||||||
|
|
||||||
|
### Alternative MCP Setup in Cursor
|
||||||
|
|
||||||
|
You can also set up the MCP server in Cursor settings:
|
||||||
|
|
||||||
|
1. Go to Cursor settings
|
||||||
|
2. Navigate to the MCP section
|
||||||
|
3. Click on "Add New MCP Server"
|
||||||
|
4. Configure with the following details:
|
||||||
|
- Name: "Task Master"
|
||||||
|
- Type: "Command"
|
||||||
|
- Command: "npx -y --package task-master-ai task-master-mcp"
|
||||||
|
5. Save the settings
|
||||||
|
|
||||||
|
Once configured, you can interact with Task Master's task management commands directly through Cursor's interface, providing a more integrated experience.
|
||||||
|
|
||||||
|
## Initial Task Generation
|
||||||
|
|
||||||
|
In Cursor's AI chat, instruct the agent to generate tasks from your PRD:
|
||||||
|
|
||||||
|
```
|
||||||
|
Please use the task-master parse-prd command to generate tasks from my PRD. The PRD is located at scripts/prd.txt.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master parse-prd scripts/prd.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
This will:
|
||||||
|
|
||||||
|
- Parse your PRD document
|
||||||
|
- Generate a structured `tasks.json` file with tasks, dependencies, priorities, and test strategies
|
||||||
|
- The agent will understand this process due to the Cursor rules
|
||||||
|
|
||||||
|
### Generate Individual Task Files
|
||||||
|
|
||||||
|
Next, ask the agent to generate individual task files:
|
||||||
|
|
||||||
|
```
|
||||||
|
Please generate individual task files from tasks.json
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master generate
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates individual task files in the `tasks/` directory (e.g., `task_001.txt`, `task_002.txt`), making it easier to reference specific tasks.
|
||||||
|
|
||||||
|
## AI-Driven Development Workflow
|
||||||
|
|
||||||
|
The Cursor agent is pre-configured (via the rules file) to follow this workflow:
|
||||||
|
|
||||||
|
### 1. Task Discovery and Selection
|
||||||
|
|
||||||
|
Ask the agent to list available tasks:
|
||||||
|
|
||||||
|
```
|
||||||
|
What tasks are available to work on next?
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will:
|
||||||
|
|
||||||
|
- Run `task-master list` to see all tasks
|
||||||
|
- Run `task-master next` to determine the next task to work on
|
||||||
|
- Analyze dependencies to determine which tasks are ready to be worked on
|
||||||
|
- Prioritize tasks based on priority level and ID order
|
||||||
|
- Suggest the next task(s) to implement
|
||||||
|
|
||||||
|
### 2. Task Implementation
|
||||||
|
|
||||||
|
When implementing a task, the agent will:
|
||||||
|
|
||||||
|
- Reference the task's details section for implementation specifics
|
||||||
|
- Consider dependencies on previous tasks
|
||||||
|
- Follow the project's coding standards
|
||||||
|
- Create appropriate tests based on the task's testStrategy
|
||||||
|
|
||||||
|
You can ask:
|
||||||
|
|
||||||
|
```
|
||||||
|
Let's implement task 3. What does it involve?
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Task Verification
|
||||||
|
|
||||||
|
Before marking a task as complete, verify it according to:
|
||||||
|
|
||||||
|
- The task's specified testStrategy
|
||||||
|
- Any automated tests in the codebase
|
||||||
|
- Manual verification if required
|
||||||
|
|
||||||
|
### 4. Task Completion
|
||||||
|
|
||||||
|
When a task is completed, tell the agent:
|
||||||
|
|
||||||
|
```
|
||||||
|
Task 3 is now complete. Please update its status.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master set-status --id=3 --status=done
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Handling Implementation Drift
|
||||||
|
|
||||||
|
If during implementation, you discover that:
|
||||||
|
|
||||||
|
- The current approach differs significantly from what was planned
|
||||||
|
- Future tasks need to be modified due to current implementation choices
|
||||||
|
- New dependencies or requirements have emerged
|
||||||
|
|
||||||
|
Tell the agent:
|
||||||
|
|
||||||
|
```
|
||||||
|
We've changed our approach. We're now using Express instead of Fastify. Please update all future tasks to reflect this change.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master update --from=4 --prompt="Now we are using Express instead of Fastify."
|
||||||
|
```
|
||||||
|
|
||||||
|
This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work.
|
||||||
|
|
||||||
|
### 6. Breaking Down Complex Tasks
|
||||||
|
|
||||||
|
For complex tasks that need more granularity:
|
||||||
|
|
||||||
|
```
|
||||||
|
Task 5 seems complex. Can you break it down into subtasks?
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master expand --id=5 --num=3
|
||||||
|
```
|
||||||
|
|
||||||
|
You can provide additional context:
|
||||||
|
|
||||||
|
```
|
||||||
|
Please break down task 5 with a focus on security considerations.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master expand --id=5 --prompt="Focus on security aspects"
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also expand all pending tasks:
|
||||||
|
|
||||||
|
```
|
||||||
|
Please break down all pending tasks into subtasks.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master expand --all
|
||||||
|
```
|
||||||
|
|
||||||
|
For research-backed subtask generation using Perplexity AI:
|
||||||
|
|
||||||
|
```
|
||||||
|
Please break down task 5 using research-backed generation.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master expand --id=5 --research
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example Cursor AI Interactions
|
||||||
|
|
||||||
|
### Starting a new project
|
||||||
|
|
||||||
|
```
|
||||||
|
I've just initialized a new project with Claude Task Master. I have a PRD at scripts/prd.txt.
|
||||||
|
Can you help me parse it and set up the initial tasks?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Working on tasks
|
||||||
|
|
||||||
|
```
|
||||||
|
What's the next task I should work on? Please consider dependencies and priorities.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Implementing a specific task
|
||||||
|
|
||||||
|
```
|
||||||
|
I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Managing subtasks
|
||||||
|
|
||||||
|
```
|
||||||
|
I need to regenerate the subtasks for task 3 with a different approach. Can you help me clear and regenerate them?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Handling changes
|
||||||
|
|
||||||
|
```
|
||||||
|
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Completing work
|
||||||
|
|
||||||
|
```
|
||||||
|
I've finished implementing the authentication system described in task 2. All tests are passing.
|
||||||
|
Please mark it as complete and tell me what I should work on next.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Analyzing complexity
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you analyze the complexity of our tasks to help me understand which ones need to be broken down further?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Viewing complexity report
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you show me the complexity report in a more readable format?
|
||||||
|
```
|
||||||
41
entries.json
41
entries.json
@@ -1,41 +0,0 @@
|
|||||||
import os
|
|
||||||
import json
|
|
||||||
|
|
||||||
# Path to Cursor's history folder
|
|
||||||
history_path = os.path.expanduser('~/Library/Application Support/Cursor/User/History')
|
|
||||||
|
|
||||||
# File to search for
|
|
||||||
target_file = 'tasks/tasks.json'
|
|
||||||
|
|
||||||
# Function to search through all entries.json files
|
|
||||||
def search_entries_for_file(history_path, target_file):
|
|
||||||
matching_folders = []
|
|
||||||
for folder in os.listdir(history_path):
|
|
||||||
folder_path = os.path.join(history_path, folder)
|
|
||||||
if not os.path.isdir(folder_path):
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Look for entries.json
|
|
||||||
entries_file = os.path.join(folder_path, 'entries.json')
|
|
||||||
if not os.path.exists(entries_file):
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Parse entries.json to find the resource key
|
|
||||||
with open(entries_file, 'r') as f:
|
|
||||||
data = json.load(f)
|
|
||||||
resource = data.get('resource', None)
|
|
||||||
if resource and target_file in resource:
|
|
||||||
matching_folders.append(folder_path)
|
|
||||||
|
|
||||||
return matching_folders
|
|
||||||
|
|
||||||
# Search for the target file
|
|
||||||
matching_folders = search_entries_for_file(history_path, target_file)
|
|
||||||
|
|
||||||
# Output the matching folders
|
|
||||||
if matching_folders:
|
|
||||||
print(f"Found {target_file} in the following folders:")
|
|
||||||
for folder in matching_folders:
|
|
||||||
print(folder)
|
|
||||||
else:
|
|
||||||
print(f"No matches found for {target_file}.")
|
|
||||||
2
index.js
2
index.js
@@ -80,7 +80,7 @@ if (import.meta.url === `file://${process.argv[1]}`) {
|
|||||||
.command('init')
|
.command('init')
|
||||||
.description('Initialize a new project')
|
.description('Initialize a new project')
|
||||||
.action(() => {
|
.action(() => {
|
||||||
runInitCLI().catch(err => {
|
runInitCLI().catch((err) => {
|
||||||
console.error('Init failed:', err.message);
|
console.error('Init failed:', err.message);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
|
|
||||||
import TaskMasterMCPServer from "./src/index.js";
|
import TaskMasterMCPServer from './src/index.js';
|
||||||
import dotenv from "dotenv";
|
import dotenv from 'dotenv';
|
||||||
import logger from "./src/logger.js";
|
import logger from './src/logger.js';
|
||||||
|
|
||||||
// Load environment variables
|
// Load environment variables
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
@@ -14,12 +14,12 @@ async function startServer() {
|
|||||||
const server = new TaskMasterMCPServer();
|
const server = new TaskMasterMCPServer();
|
||||||
|
|
||||||
// Handle graceful shutdown
|
// Handle graceful shutdown
|
||||||
process.on("SIGINT", async () => {
|
process.on('SIGINT', async () => {
|
||||||
await server.stop();
|
await server.stop();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on("SIGTERM", async () => {
|
process.on('SIGTERM', async () => {
|
||||||
await server.stop();
|
await server.stop();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,9 @@ describe('ContextManager', () => {
|
|||||||
|
|
||||||
describe('getContext', () => {
|
describe('getContext', () => {
|
||||||
it('should create a new context when not in cache', async () => {
|
it('should create a new context when not in cache', async () => {
|
||||||
const context = await contextManager.getContext('test-id', { test: true });
|
const context = await contextManager.getContext('test-id', {
|
||||||
|
test: true
|
||||||
|
});
|
||||||
expect(context.id).toBe('test-id');
|
expect(context.id).toBe('test-id');
|
||||||
expect(context.metadata.test).toBe(true);
|
expect(context.metadata.test).toBe(true);
|
||||||
expect(contextManager.stats.misses).toBe(1);
|
expect(contextManager.stats.misses).toBe(1);
|
||||||
@@ -26,7 +28,9 @@ describe('ContextManager', () => {
|
|||||||
await contextManager.getContext('test-id', { test: true });
|
await contextManager.getContext('test-id', { test: true });
|
||||||
|
|
||||||
// Second call should hit cache
|
// Second call should hit cache
|
||||||
const context = await contextManager.getContext('test-id', { test: true });
|
const context = await contextManager.getContext('test-id', {
|
||||||
|
test: true
|
||||||
|
});
|
||||||
expect(context.id).toBe('test-id');
|
expect(context.id).toBe('test-id');
|
||||||
expect(context.metadata.test).toBe(true);
|
expect(context.metadata.test).toBe(true);
|
||||||
expect(contextManager.stats.hits).toBe(1);
|
expect(contextManager.stats.hits).toBe(1);
|
||||||
@@ -38,7 +42,7 @@ describe('ContextManager', () => {
|
|||||||
await contextManager.getContext('test-id', { test: true });
|
await contextManager.getContext('test-id', { test: true });
|
||||||
|
|
||||||
// Wait for TTL to expire
|
// Wait for TTL to expire
|
||||||
await new Promise(resolve => setTimeout(resolve, 1100));
|
await new Promise((resolve) => setTimeout(resolve, 1100));
|
||||||
|
|
||||||
// Should create new context
|
// Should create new context
|
||||||
await contextManager.getContext('test-id', { test: true });
|
await contextManager.getContext('test-id', { test: true });
|
||||||
@@ -50,7 +54,9 @@ describe('ContextManager', () => {
|
|||||||
describe('updateContext', () => {
|
describe('updateContext', () => {
|
||||||
it('should update existing context metadata', async () => {
|
it('should update existing context metadata', async () => {
|
||||||
await contextManager.getContext('test-id', { initial: true });
|
await contextManager.getContext('test-id', { initial: true });
|
||||||
const updated = await contextManager.updateContext('test-id', { updated: true });
|
const updated = await contextManager.updateContext('test-id', {
|
||||||
|
updated: true
|
||||||
|
});
|
||||||
|
|
||||||
expect(updated.metadata.initial).toBe(true);
|
expect(updated.metadata.initial).toBe(true);
|
||||||
expect(updated.metadata.updated).toBe(true);
|
expect(updated.metadata.updated).toBe(true);
|
||||||
|
|||||||
@@ -112,7 +112,8 @@ export class ContextManager {
|
|||||||
*/
|
*/
|
||||||
getCachedData(key) {
|
getCachedData(key) {
|
||||||
const cached = this.cache.get(key);
|
const cached = this.cache.get(key);
|
||||||
if (cached !== undefined) { // Check for undefined specifically, as null/false might be valid cached values
|
if (cached !== undefined) {
|
||||||
|
// Check for undefined specifically, as null/false might be valid cached values
|
||||||
this.stats.hits++;
|
this.stats.hits++;
|
||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,10 @@
|
|||||||
|
|
||||||
import { addDependency } from '../../../../scripts/modules/dependency-manager.js';
|
import { addDependency } from '../../../../scripts/modules/dependency-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for addDependency with error handling.
|
* Direct function wrapper for addDependency with error handling.
|
||||||
@@ -47,10 +50,18 @@ export async function addDependencyDirect(args, log) {
|
|||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Format IDs for the core function
|
// Format IDs for the core function
|
||||||
const taskId = args.id.includes && args.id.includes('.') ? args.id : parseInt(args.id, 10);
|
const taskId =
|
||||||
const dependencyId = args.dependsOn.includes && args.dependsOn.includes('.') ? args.dependsOn : parseInt(args.dependsOn, 10);
|
args.id.includes && args.id.includes('.')
|
||||||
|
? args.id
|
||||||
|
: parseInt(args.id, 10);
|
||||||
|
const dependencyId =
|
||||||
|
args.dependsOn.includes && args.dependsOn.includes('.')
|
||||||
|
? args.dependsOn
|
||||||
|
: parseInt(args.dependsOn, 10);
|
||||||
|
|
||||||
log.info(`Adding dependency: task ${taskId} will depend on ${dependencyId}`);
|
log.info(
|
||||||
|
`Adding dependency: task ${taskId} will depend on ${dependencyId}`
|
||||||
|
);
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { addSubtask } from '../../../../scripts/modules/task-manager.js';
|
import { addSubtask } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add a subtask to an existing task
|
* Add a subtask to an existing task
|
||||||
@@ -53,7 +56,7 @@ export async function addSubtaskDirect(args, log) {
|
|||||||
// Parse dependencies if provided
|
// Parse dependencies if provided
|
||||||
let dependencies = [];
|
let dependencies = [];
|
||||||
if (args.dependencies) {
|
if (args.dependencies) {
|
||||||
dependencies = args.dependencies.split(',').map(id => {
|
dependencies = args.dependencies.split(',').map((id) => {
|
||||||
// Handle both regular IDs and dot notation
|
// Handle both regular IDs and dot notation
|
||||||
return id.includes('.') ? id.trim() : parseInt(id.trim(), 10);
|
return id.includes('.') ? id.trim() : parseInt(id.trim(), 10);
|
||||||
});
|
});
|
||||||
@@ -74,7 +77,13 @@ export async function addSubtaskDirect(args, log) {
|
|||||||
// Case 1: Convert existing task to subtask
|
// Case 1: Convert existing task to subtask
|
||||||
if (existingTaskId) {
|
if (existingTaskId) {
|
||||||
log.info(`Converting task ${existingTaskId} to a subtask of ${parentId}`);
|
log.info(`Converting task ${existingTaskId} to a subtask of ${parentId}`);
|
||||||
const result = await addSubtask(tasksPath, parentId, existingTaskId, null, generateFiles);
|
const result = await addSubtask(
|
||||||
|
tasksPath,
|
||||||
|
parentId,
|
||||||
|
existingTaskId,
|
||||||
|
null,
|
||||||
|
generateFiles
|
||||||
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
@@ -99,7 +108,13 @@ export async function addSubtaskDirect(args, log) {
|
|||||||
dependencies: dependencies
|
dependencies: dependencies
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = await addSubtask(tasksPath, parentId, null, newSubtaskData, generateFiles);
|
const result = await addSubtask(
|
||||||
|
tasksPath,
|
||||||
|
parentId,
|
||||||
|
null,
|
||||||
|
newSubtaskData,
|
||||||
|
generateFiles
|
||||||
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|||||||
@@ -5,7 +5,19 @@
|
|||||||
|
|
||||||
import { addTask } from '../../../../scripts/modules/task-manager.js';
|
import { addTask } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
import {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getModelConfig
|
||||||
|
} from '../utils/ai-client-utils.js';
|
||||||
|
import {
|
||||||
|
_buildAddTaskPrompt,
|
||||||
|
parseTaskJsonResponse,
|
||||||
|
_handleAnthropicStream
|
||||||
|
} from '../../../../scripts/modules/ai-services.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for adding a new task with error handling.
|
* Direct function wrapper for adding a new task with error handling.
|
||||||
@@ -16,10 +28,12 @@ import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules
|
|||||||
* @param {string} [args.priority='medium'] - Task priority (high, medium, low)
|
* @param {string} [args.priority='medium'] - Task priority (high, medium, low)
|
||||||
* @param {string} [args.file] - Path to the tasks file
|
* @param {string} [args.file] - Path to the tasks file
|
||||||
* @param {string} [args.projectRoot] - Project root directory
|
* @param {string} [args.projectRoot] - Project root directory
|
||||||
|
* @param {boolean} [args.research] - Whether to use research capabilities for task creation
|
||||||
* @param {Object} log - Logger object
|
* @param {Object} log - Logger object
|
||||||
|
* @param {Object} context - Additional context (reportProgress, session)
|
||||||
* @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } }
|
* @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } }
|
||||||
*/
|
*/
|
||||||
export async function addTaskDirect(args, log) {
|
export async function addTaskDirect(args, log, context = {}) {
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
@@ -30,6 +44,7 @@ export async function addTaskDirect(args, log) {
|
|||||||
// Check required parameters
|
// Check required parameters
|
||||||
if (!args.prompt) {
|
if (!args.prompt) {
|
||||||
log.error('Missing required parameter: prompt');
|
log.error('Missing required parameter: prompt');
|
||||||
|
disableSilentMode();
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
@@ -43,10 +58,101 @@ export async function addTaskDirect(args, log) {
|
|||||||
const prompt = args.prompt;
|
const prompt = args.prompt;
|
||||||
const dependencies = Array.isArray(args.dependencies)
|
const dependencies = Array.isArray(args.dependencies)
|
||||||
? args.dependencies
|
? args.dependencies
|
||||||
: (args.dependencies ? String(args.dependencies).split(',').map(id => parseInt(id.trim(), 10)) : []);
|
: args.dependencies
|
||||||
|
? String(args.dependencies)
|
||||||
|
.split(',')
|
||||||
|
.map((id) => parseInt(id.trim(), 10))
|
||||||
|
: [];
|
||||||
const priority = args.priority || 'medium';
|
const priority = args.priority || 'medium';
|
||||||
|
|
||||||
log.info(`Adding new task with prompt: "${prompt}", dependencies: [${dependencies.join(', ')}], priority: ${priority}`);
|
log.info(
|
||||||
|
`Adding new task with prompt: "${prompt}", dependencies: [${dependencies.join(', ')}], priority: ${priority}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// Extract context parameters for advanced functionality
|
||||||
|
// Commenting out reportProgress extraction
|
||||||
|
// const { reportProgress, session } = context;
|
||||||
|
const { session } = context; // Keep session
|
||||||
|
|
||||||
|
// Initialize AI client with session environment
|
||||||
|
let localAnthropic;
|
||||||
|
try {
|
||||||
|
localAnthropic = getAnthropicClientForMCP(session, log);
|
||||||
|
} catch (error) {
|
||||||
|
log.error(`Failed to initialize Anthropic client: ${error.message}`);
|
||||||
|
disableSilentMode();
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'AI_CLIENT_ERROR',
|
||||||
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get model configuration from session
|
||||||
|
const modelConfig = getModelConfig(session);
|
||||||
|
|
||||||
|
// Read existing tasks to provide context
|
||||||
|
let tasksData;
|
||||||
|
try {
|
||||||
|
const fs = await import('fs');
|
||||||
|
tasksData = JSON.parse(fs.readFileSync(tasksPath, 'utf8'));
|
||||||
|
} catch (error) {
|
||||||
|
log.warn(`Could not read existing tasks for context: ${error.message}`);
|
||||||
|
tasksData = { tasks: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build prompts for AI
|
||||||
|
const { systemPrompt, userPrompt } = _buildAddTaskPrompt(
|
||||||
|
prompt,
|
||||||
|
tasksData.tasks
|
||||||
|
);
|
||||||
|
|
||||||
|
// Make the AI call using the streaming helper
|
||||||
|
let responseText;
|
||||||
|
try {
|
||||||
|
responseText = await _handleAnthropicStream(
|
||||||
|
localAnthropic,
|
||||||
|
{
|
||||||
|
model: modelConfig.model,
|
||||||
|
max_tokens: modelConfig.maxTokens,
|
||||||
|
temperature: modelConfig.temperature,
|
||||||
|
messages: [{ role: 'user', content: userPrompt }],
|
||||||
|
system: systemPrompt
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// reportProgress: context.reportProgress, // Commented out to prevent Cursor stroking out
|
||||||
|
mcpLog: log
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
log.error(`AI processing failed: ${error.message}`);
|
||||||
|
disableSilentMode();
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'AI_PROCESSING_ERROR',
|
||||||
|
message: `Failed to generate task with AI: ${error.message}`
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse the AI response
|
||||||
|
let taskDataFromAI;
|
||||||
|
try {
|
||||||
|
taskDataFromAI = parseTaskJsonResponse(responseText);
|
||||||
|
} catch (error) {
|
||||||
|
log.error(`Failed to parse AI response: ${error.message}`);
|
||||||
|
disableSilentMode();
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'RESPONSE_PARSING_ERROR',
|
||||||
|
message: `Failed to parse AI response: ${error.message}`
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Call the addTask function with 'json' outputFormat to prevent console output when called via MCP
|
// Call the addTask function with 'json' outputFormat to prevent console output when called via MCP
|
||||||
const newTaskId = await addTask(
|
const newTaskId = await addTask(
|
||||||
@@ -54,7 +160,12 @@ export async function addTaskDirect(args, log) {
|
|||||||
prompt,
|
prompt,
|
||||||
dependencies,
|
dependencies,
|
||||||
priority,
|
priority,
|
||||||
{ mcpLog: log },
|
{
|
||||||
|
// reportProgress, // Commented out
|
||||||
|
mcpLog: log,
|
||||||
|
session,
|
||||||
|
taskDataFromAI // Pass the parsed AI result
|
||||||
|
},
|
||||||
'json'
|
'json'
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,12 @@
|
|||||||
|
|
||||||
import { analyzeTaskComplexity } from '../../../../scripts/modules/task-manager.js';
|
import { analyzeTaskComplexity } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode,
|
||||||
|
isSilentMode,
|
||||||
|
readJSON
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
@@ -18,9 +23,12 @@ import path from 'path';
|
|||||||
* @param {boolean} [args.research] - Use Perplexity AI for research-backed complexity analysis
|
* @param {boolean} [args.research] - Use Perplexity AI for research-backed complexity analysis
|
||||||
* @param {string} [args.projectRoot] - Project root directory
|
* @param {string} [args.projectRoot] - Project root directory
|
||||||
* @param {Object} log - Logger object
|
* @param {Object} log - Logger object
|
||||||
|
* @param {Object} [context={}] - Context object containing session data
|
||||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||||
*/
|
*/
|
||||||
export async function analyzeTaskComplexityDirect(args, log) {
|
export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||||
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Analyzing task complexity with args: ${JSON.stringify(args)}`);
|
log.info(`Analyzing task complexity with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
@@ -33,6 +41,13 @@ export async function analyzeTaskComplexityDirect(args, log) {
|
|||||||
outputPath = path.join(args.projectRoot, outputPath);
|
outputPath = path.join(args.projectRoot, outputPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.info(`Analyzing task complexity from: ${tasksPath}`);
|
||||||
|
log.info(`Output report will be saved to: ${outputPath}`);
|
||||||
|
|
||||||
|
if (args.research) {
|
||||||
|
log.info('Using Perplexity AI for research-backed complexity analysis');
|
||||||
|
}
|
||||||
|
|
||||||
// Create options object for analyzeTaskComplexity
|
// Create options object for analyzeTaskComplexity
|
||||||
const options = {
|
const options = {
|
||||||
file: tasksPath,
|
file: tasksPath,
|
||||||
@@ -42,21 +57,42 @@ export async function analyzeTaskComplexityDirect(args, log) {
|
|||||||
research: args.research === true
|
research: args.research === true
|
||||||
};
|
};
|
||||||
|
|
||||||
log.info(`Analyzing task complexity from: ${tasksPath}`);
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
log.info(`Output report will be saved to: ${outputPath}`);
|
const wasSilent = isSilentMode();
|
||||||
|
if (!wasSilent) {
|
||||||
if (options.research) {
|
enableSilentMode();
|
||||||
log.info('Using Perplexity AI for research-backed complexity analysis');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Create a logWrapper that matches the expected mcpLog interface as specified in utilities.mdc
|
||||||
enableSilentMode();
|
const logWrapper = {
|
||||||
|
info: (message, ...args) => log.info(message, ...args),
|
||||||
|
warn: (message, ...args) => log.warn(message, ...args),
|
||||||
|
error: (message, ...args) => log.error(message, ...args),
|
||||||
|
debug: (message, ...args) => log.debug && log.debug(message, ...args),
|
||||||
|
success: (message, ...args) => log.info(message, ...args) // Map success to info
|
||||||
|
};
|
||||||
|
|
||||||
// Call the core function
|
try {
|
||||||
await analyzeTaskComplexity(options);
|
// Call the core function with session and logWrapper as mcpLog
|
||||||
|
await analyzeTaskComplexity(options, {
|
||||||
// Restore normal logging
|
session,
|
||||||
|
mcpLog: logWrapper // Use the wrapper instead of passing log directly
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
log.error(`Error in analyzeTaskComplexity: ${error.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'ANALYZE_ERROR',
|
||||||
|
message: `Error running complexity analysis: ${error.message}`
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
// Always restore normal logging in finally block, but only if we enabled it
|
||||||
|
if (!wasSilent) {
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Verify the report file was created
|
// Verify the report file was created
|
||||||
if (!fs.existsSync(outputPath)) {
|
if (!fs.existsSync(outputPath)) {
|
||||||
@@ -70,7 +106,26 @@ export async function analyzeTaskComplexityDirect(args, log) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Read the report file
|
// Read the report file
|
||||||
const report = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
|
let report;
|
||||||
|
try {
|
||||||
|
report = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
|
||||||
|
|
||||||
|
// Important: Handle different report formats
|
||||||
|
// The core function might return an array or an object with a complexityAnalysis property
|
||||||
|
const analysisArray = Array.isArray(report)
|
||||||
|
? report
|
||||||
|
: report.complexityAnalysis || [];
|
||||||
|
|
||||||
|
// Count tasks by complexity
|
||||||
|
const highComplexityTasks = analysisArray.filter(
|
||||||
|
(t) => t.complexityScore >= 8
|
||||||
|
).length;
|
||||||
|
const mediumComplexityTasks = analysisArray.filter(
|
||||||
|
(t) => t.complexityScore >= 5 && t.complexityScore < 8
|
||||||
|
).length;
|
||||||
|
const lowComplexityTasks = analysisArray.filter(
|
||||||
|
(t) => t.complexityScore < 5
|
||||||
|
).length;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
@@ -78,16 +133,28 @@ export async function analyzeTaskComplexityDirect(args, log) {
|
|||||||
message: `Task complexity analysis complete. Report saved to ${outputPath}`,
|
message: `Task complexity analysis complete. Report saved to ${outputPath}`,
|
||||||
reportPath: outputPath,
|
reportPath: outputPath,
|
||||||
reportSummary: {
|
reportSummary: {
|
||||||
taskCount: report.length,
|
taskCount: analysisArray.length,
|
||||||
highComplexityTasks: report.filter(t => t.complexityScore >= 8).length,
|
highComplexityTasks,
|
||||||
mediumComplexityTasks: report.filter(t => t.complexityScore >= 5 && t.complexityScore < 8).length,
|
mediumComplexityTasks,
|
||||||
lowComplexityTasks: report.filter(t => t.complexityScore < 5).length,
|
lowComplexityTasks
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
} catch (parseError) {
|
||||||
|
log.error(`Error parsing report file: ${parseError.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'REPORT_PARSE_ERROR',
|
||||||
|
message: `Error parsing complexity report: ${parseError.message}`
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
|
if (isSilentMode()) {
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
}
|
||||||
|
|
||||||
log.error(`Error in analyzeTaskComplexityDirect: ${error.message}`);
|
log.error(`Error in analyzeTaskComplexityDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { clearSubtasks } from '../../../../scripts/modules/task-manager.js';
|
import { clearSubtasks } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -27,7 +30,8 @@ export async function clearSubtasksDirect(args, log) {
|
|||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Either task IDs with id parameter or all parameter must be provided'
|
message:
|
||||||
|
'Either task IDs with id parameter or all parameter must be provided'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -61,7 +65,7 @@ export async function clearSubtasksDirect(args, log) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
taskIds = data.tasks.map(t => t.id).join(',');
|
taskIds = data.tasks.map((t) => t.id).join(',');
|
||||||
} else {
|
} else {
|
||||||
// Use the provided task IDs
|
// Use the provided task IDs
|
||||||
taskIds = args.id;
|
taskIds = args.id;
|
||||||
@@ -80,12 +84,12 @@ export async function clearSubtasksDirect(args, log) {
|
|||||||
|
|
||||||
// Read the updated data to provide a summary
|
// Read the updated data to provide a summary
|
||||||
const updatedData = JSON.parse(fs.readFileSync(tasksPath, 'utf8'));
|
const updatedData = JSON.parse(fs.readFileSync(tasksPath, 'utf8'));
|
||||||
const taskIdArray = taskIds.split(',').map(id => parseInt(id.trim(), 10));
|
const taskIdArray = taskIds.split(',').map((id) => parseInt(id.trim(), 10));
|
||||||
|
|
||||||
// Build a summary of what was done
|
// Build a summary of what was done
|
||||||
const clearedTasksCount = taskIdArray.length;
|
const clearedTasksCount = taskIdArray.length;
|
||||||
const taskSummary = taskIdArray.map(id => {
|
const taskSummary = taskIdArray.map((id) => {
|
||||||
const task = updatedData.tasks.find(t => t.id === id);
|
const task = updatedData.tasks.find((t) => t.id === id);
|
||||||
return task ? { id, title: task.title } : { id, title: 'Task not found' };
|
return task ? { id, title: task.title } : { id, title: 'Task not found' };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,11 @@
|
|||||||
* Direct function implementation for displaying complexity analysis report
|
* Direct function implementation for displaying complexity analysis report
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { readComplexityReport, enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
readComplexityReport,
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
@@ -24,12 +28,16 @@ export async function complexityReportDirect(args, log) {
|
|||||||
try {
|
try {
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.warn(`Tasks file not found, using current directory: ${error.message}`);
|
log.warn(
|
||||||
|
`Tasks file not found, using current directory: ${error.message}`
|
||||||
|
);
|
||||||
// Continue with default or specified report path
|
// Continue with default or specified report path
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get report file path from args or use default
|
// Get report file path from args or use default
|
||||||
const reportPath = args.file || path.join(process.cwd(), 'scripts', 'task-complexity-report.json');
|
const reportPath =
|
||||||
|
args.file ||
|
||||||
|
path.join(process.cwd(), 'scripts', 'task-complexity-report.json');
|
||||||
|
|
||||||
log.info(`Looking for complexity report at: ${reportPath}`);
|
log.info(`Looking for complexity report at: ${reportPath}`);
|
||||||
|
|
||||||
@@ -87,14 +95,18 @@ export async function complexityReportDirect(args, log) {
|
|||||||
actionFn: coreActionFn,
|
actionFn: coreActionFn,
|
||||||
log
|
log
|
||||||
});
|
});
|
||||||
log.info(`complexityReportDirect completed. From cache: ${result.fromCache}`);
|
log.info(
|
||||||
|
`complexityReportDirect completed. From cache: ${result.fromCache}`
|
||||||
|
);
|
||||||
return result; // Returns { success, data/error, fromCache }
|
return result; // Returns { success, data/error, fromCache }
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Catch unexpected errors from getCachedOrExecute itself
|
// Catch unexpected errors from getCachedOrExecute itself
|
||||||
// Ensure silent mode is disabled
|
// Ensure silent mode is disabled
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Unexpected error during getCachedOrExecute for complexityReport: ${error.message}`);
|
log.error(
|
||||||
|
`Unexpected error during getCachedOrExecute for complexityReport: ${error.message}`
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
|
|||||||
@@ -3,8 +3,15 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { expandAllTasks } from '../../../../scripts/modules/task-manager.js';
|
import { expandAllTasks } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode,
|
||||||
|
isSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
|
import { getAnthropicClientForMCP } from '../utils/ai-client-utils.js';
|
||||||
|
import path from 'path';
|
||||||
|
import fs from 'fs';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Expand all pending tasks with subtasks
|
* Expand all pending tasks with subtasks
|
||||||
@@ -16,12 +23,19 @@ import { findTasksJsonPath } from '../utils/path-utils.js';
|
|||||||
* @param {string} [args.file] - Path to the tasks file
|
* @param {string} [args.file] - Path to the tasks file
|
||||||
* @param {string} [args.projectRoot] - Project root directory
|
* @param {string} [args.projectRoot] - Project root directory
|
||||||
* @param {Object} log - Logger object
|
* @param {Object} log - Logger object
|
||||||
|
* @param {Object} context - Context object containing session
|
||||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||||
*/
|
*/
|
||||||
export async function expandAllTasksDirect(args, log) {
|
export async function expandAllTasksDirect(args, log, context = {}) {
|
||||||
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Expanding all tasks with args: ${JSON.stringify(args)}`);
|
log.info(`Expanding all tasks with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
|
// Enable silent mode early to prevent any console output
|
||||||
|
enableSilentMode();
|
||||||
|
|
||||||
|
try {
|
||||||
// Find the tasks.json path
|
// Find the tasks.json path
|
||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
@@ -31,10 +45,31 @@ export async function expandAllTasksDirect(args, log) {
|
|||||||
const additionalContext = args.prompt || '';
|
const additionalContext = args.prompt || '';
|
||||||
const forceFlag = args.force === true;
|
const forceFlag = args.force === true;
|
||||||
|
|
||||||
log.info(`Expanding all tasks with ${numSubtasks || 'default'} subtasks each...`);
|
log.info(
|
||||||
|
`Expanding all tasks with ${numSubtasks || 'default'} subtasks each...`
|
||||||
|
);
|
||||||
|
|
||||||
if (useResearch) {
|
if (useResearch) {
|
||||||
log.info('Using Perplexity AI for research-backed subtask generation');
|
log.info('Using Perplexity AI for research-backed subtask generation');
|
||||||
|
|
||||||
|
// Initialize AI client for research-backed expansion
|
||||||
|
try {
|
||||||
|
await getAnthropicClientForMCP(session, log);
|
||||||
|
} catch (error) {
|
||||||
|
// Ensure silent mode is disabled before returning error
|
||||||
|
disableSilentMode();
|
||||||
|
|
||||||
|
log.error(`Failed to initialize AI client: ${error.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'AI_CLIENT_ERROR',
|
||||||
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (additionalContext) {
|
if (additionalContext) {
|
||||||
log.info(`Additional context: "${additionalContext}"`);
|
log.info(`Additional context: "${additionalContext}"`);
|
||||||
}
|
}
|
||||||
@@ -42,37 +77,42 @@ export async function expandAllTasksDirect(args, log) {
|
|||||||
log.info('Force regeneration of subtasks is enabled');
|
log.info('Force regeneration of subtasks is enabled');
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
// Call the core function with session context for AI operations
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// and outputFormat as 'json' to prevent UI elements
|
||||||
enableSilentMode();
|
const result = await expandAllTasks(
|
||||||
|
tasksPath,
|
||||||
|
numSubtasks,
|
||||||
|
useResearch,
|
||||||
|
additionalContext,
|
||||||
|
forceFlag,
|
||||||
|
{ mcpLog: log, session },
|
||||||
|
'json' // Use JSON output format to prevent UI elements
|
||||||
|
);
|
||||||
|
|
||||||
// Call the core function
|
// The expandAllTasks function now returns a result object
|
||||||
await expandAllTasks(numSubtasks, useResearch, additionalContext, forceFlag);
|
|
||||||
|
|
||||||
// Restore normal logging
|
|
||||||
disableSilentMode();
|
|
||||||
|
|
||||||
// The expandAllTasks function doesn't have a return value, so we'll create our own success response
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: "Successfully expanded all pending tasks with subtasks",
|
message: 'Successfully expanded all pending tasks with subtasks',
|
||||||
details: {
|
details: {
|
||||||
numSubtasks: numSubtasks,
|
numSubtasks: numSubtasks,
|
||||||
research: useResearch,
|
research: useResearch,
|
||||||
prompt: additionalContext,
|
prompt: additionalContext,
|
||||||
force: forceFlag
|
force: forceFlag,
|
||||||
|
tasksExpanded: result.expandedCount,
|
||||||
|
totalEligibleTasks: result.tasksToExpand
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} finally {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Restore normal logging in finally block to ensure it runs even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
throw error; // Rethrow to be caught by outer catch block
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Ensure silent mode is disabled
|
// Ensure silent mode is disabled if an error occurs
|
||||||
|
if (isSilentMode()) {
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
}
|
||||||
|
|
||||||
log.error(`Error in expandAllTasksDirect: ${error.message}`);
|
log.error(`Error in expandAllTasksDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -4,8 +4,18 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { expandTask } from '../../../../scripts/modules/task-manager.js';
|
import { expandTask } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { readJSON, writeJSON, enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
readJSON,
|
||||||
|
writeJSON,
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode,
|
||||||
|
isSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
|
import {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getModelConfig
|
||||||
|
} from '../utils/ai-client-utils.js';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
|
||||||
@@ -14,25 +24,62 @@ import fs from 'fs';
|
|||||||
*
|
*
|
||||||
* @param {Object} args - Command arguments
|
* @param {Object} args - Command arguments
|
||||||
* @param {Object} log - Logger object
|
* @param {Object} log - Logger object
|
||||||
|
* @param {Object} context - Context object containing session and reportProgress
|
||||||
* @returns {Promise<Object>} - Task expansion result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
|
* @returns {Promise<Object>} - Task expansion result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
|
||||||
*/
|
*/
|
||||||
export async function expandTaskDirect(args, log) {
|
export async function expandTaskDirect(args, log, context = {}) {
|
||||||
|
const { session } = context;
|
||||||
|
|
||||||
|
// Log session root data for debugging
|
||||||
|
log.info(
|
||||||
|
`Session data in expandTaskDirect: ${JSON.stringify({
|
||||||
|
hasSession: !!session,
|
||||||
|
sessionKeys: session ? Object.keys(session) : [],
|
||||||
|
roots: session?.roots,
|
||||||
|
rootsStr: JSON.stringify(session?.roots)
|
||||||
|
})}`
|
||||||
|
);
|
||||||
|
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
// Find the tasks path first
|
// If a direct file path is provided, use it directly
|
||||||
|
if (args.file && fs.existsSync(args.file)) {
|
||||||
|
log.info(
|
||||||
|
`[expandTaskDirect] Using explicitly provided tasks file: ${args.file}`
|
||||||
|
);
|
||||||
|
tasksPath = args.file;
|
||||||
|
} else {
|
||||||
|
// Find the tasks path through standard logic
|
||||||
|
log.info(
|
||||||
|
`[expandTaskDirect] No direct file path provided or file not found at ${args.file}, searching using findTasksJsonPath`
|
||||||
|
);
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Tasks file not found: ${error.message}`);
|
log.error(
|
||||||
|
`[expandTaskDirect] Error during tasksPath determination: ${error.message}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// Include session roots information in error
|
||||||
|
const sessionRootsInfo = session
|
||||||
|
? `\nSession.roots: ${JSON.stringify(session.roots)}\n` +
|
||||||
|
`Current Working Directory: ${process.cwd()}\n` +
|
||||||
|
`Args.projectRoot: ${args.projectRoot}\n` +
|
||||||
|
`Args.file: ${args.file}\n`
|
||||||
|
: '\nSession object not available';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'FILE_NOT_FOUND_ERROR',
|
code: 'FILE_NOT_FOUND_ERROR',
|
||||||
message: error.message
|
message: `Error determining tasksPath: ${error.message}${sessionRootsInfo}`
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.info(`[expandTaskDirect] Determined tasksPath: ${tasksPath}`);
|
||||||
|
|
||||||
// Validate task ID
|
// Validate task ID
|
||||||
const taskId = args.id ? parseInt(args.id, 10) : null;
|
const taskId = args.id ? parseInt(args.id, 10) : null;
|
||||||
if (!taskId) {
|
if (!taskId) {
|
||||||
@@ -51,26 +98,56 @@ export async function expandTaskDirect(args, log) {
|
|||||||
const numSubtasks = args.num ? parseInt(args.num, 10) : undefined;
|
const numSubtasks = args.num ? parseInt(args.num, 10) : undefined;
|
||||||
const useResearch = args.research === true;
|
const useResearch = args.research === true;
|
||||||
const additionalContext = args.prompt || '';
|
const additionalContext = args.prompt || '';
|
||||||
const force = args.force === true;
|
|
||||||
|
// Initialize AI client if needed (for expandTask function)
|
||||||
|
try {
|
||||||
|
// This ensures the AI client is available by checking it
|
||||||
|
if (useResearch) {
|
||||||
|
log.info('Verifying AI client for research-backed expansion');
|
||||||
|
await getAnthropicClientForMCP(session, log);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
log.error(`Failed to initialize AI client: ${error.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'AI_CLIENT_ERROR',
|
||||||
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Expanding task ${taskId} into ${numSubtasks || 'default'} subtasks. Research: ${useResearch}, Force: ${force}`);
|
log.info(
|
||||||
|
`[expandTaskDirect] Expanding task ${taskId} into ${numSubtasks || 'default'} subtasks. Research: ${useResearch}`
|
||||||
|
);
|
||||||
|
|
||||||
// Read tasks data
|
// Read tasks data
|
||||||
|
log.info(`[expandTaskDirect] Attempting to read JSON from: ${tasksPath}`);
|
||||||
const data = readJSON(tasksPath);
|
const data = readJSON(tasksPath);
|
||||||
|
log.info(
|
||||||
|
`[expandTaskDirect] Result of readJSON: ${data ? 'Data read successfully' : 'readJSON returned null or undefined'}`
|
||||||
|
);
|
||||||
|
|
||||||
if (!data || !data.tasks) {
|
if (!data || !data.tasks) {
|
||||||
|
log.error(
|
||||||
|
`[expandTaskDirect] readJSON failed or returned invalid data for path: ${tasksPath}`
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INVALID_TASKS_FILE',
|
code: 'INVALID_TASKS_FILE',
|
||||||
message: `No valid tasks found in ${tasksPath}`
|
message: `No valid tasks found in ${tasksPath}. readJSON returned: ${JSON.stringify(data)}`
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the specific task
|
// Find the specific task
|
||||||
const task = data.tasks.find(t => t.id === taskId);
|
log.info(`[expandTaskDirect] Searching for task ID ${taskId} in data`);
|
||||||
|
const task = data.tasks.find((t) => t.id === taskId);
|
||||||
|
log.info(`[expandTaskDirect] Task found: ${task ? 'Yes' : 'No'}`);
|
||||||
|
|
||||||
if (!task) {
|
if (!task) {
|
||||||
return {
|
return {
|
||||||
@@ -98,6 +175,20 @@ export async function expandTaskDirect(args, log) {
|
|||||||
// Check for existing subtasks
|
// Check for existing subtasks
|
||||||
const hasExistingSubtasks = task.subtasks && task.subtasks.length > 0;
|
const hasExistingSubtasks = task.subtasks && task.subtasks.length > 0;
|
||||||
|
|
||||||
|
// If the task already has subtasks, just return it (matching core behavior)
|
||||||
|
if (hasExistingSubtasks) {
|
||||||
|
log.info(`Task ${taskId} already has ${task.subtasks.length} subtasks`);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
task,
|
||||||
|
subtasksAdded: 0,
|
||||||
|
hasExistingSubtasks
|
||||||
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Keep a copy of the task before modification
|
// Keep a copy of the task before modification
|
||||||
const originalTask = JSON.parse(JSON.stringify(task));
|
const originalTask = JSON.parse(JSON.stringify(task));
|
||||||
|
|
||||||
@@ -121,22 +212,32 @@ export async function expandTaskDirect(args, log) {
|
|||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Call expandTask
|
// Call expandTask with session context to ensure AI client is properly initialized
|
||||||
const result = await expandTask(taskId, numSubtasks, useResearch, additionalContext);
|
const result = await expandTask(
|
||||||
|
tasksPath,
|
||||||
|
taskId,
|
||||||
|
numSubtasks,
|
||||||
|
useResearch,
|
||||||
|
additionalContext,
|
||||||
|
{ mcpLog: log, session } // Only pass mcpLog and session, NOT reportProgress
|
||||||
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
// Read the updated data
|
// Read the updated data
|
||||||
const updatedData = readJSON(tasksPath);
|
const updatedData = readJSON(tasksPath);
|
||||||
const updatedTask = updatedData.tasks.find(t => t.id === taskId);
|
const updatedTask = updatedData.tasks.find((t) => t.id === taskId);
|
||||||
|
|
||||||
// Calculate how many subtasks were added
|
// Calculate how many subtasks were added
|
||||||
const subtasksAdded = updatedTask.subtasks ?
|
const subtasksAdded = updatedTask.subtasks
|
||||||
updatedTask.subtasks.length - subtasksCountBefore : 0;
|
? updatedTask.subtasks.length - subtasksCountBefore
|
||||||
|
: 0;
|
||||||
|
|
||||||
// Return the result
|
// Return the result
|
||||||
log.info(`Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks`);
|
log.info(
|
||||||
|
`Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks`
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { fixDependenciesCommand } from '../../../../scripts/modules/dependency-manager.js';
|
import { fixDependenciesCommand } from '../../../../scripts/modules/dependency-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -4,7 +4,10 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { generateTaskFiles } from '../../../../scripts/modules/task-manager.js';
|
import { generateTaskFiles } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
@@ -69,7 +72,8 @@ export async function generateTaskFilesDirect(args, log) {
|
|||||||
message: `Successfully generated task files`,
|
message: `Successfully generated task files`,
|
||||||
tasksPath,
|
tasksPath,
|
||||||
outputDir,
|
outputDir,
|
||||||
taskFiles: 'Individual task files have been generated in the output directory'
|
taskFiles:
|
||||||
|
'Individual task files have been generated in the output directory'
|
||||||
},
|
},
|
||||||
fromCache: false // This operation always modifies state and should never be cached
|
fromCache: false // This operation always modifies state and should never be cached
|
||||||
};
|
};
|
||||||
@@ -80,7 +84,10 @@ export async function generateTaskFilesDirect(args, log) {
|
|||||||
log.error(`Error generating task files: ${error.message}`);
|
log.error(`Error generating task files: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'GENERATE_TASKS_ERROR', message: error.message || 'Unknown error generating task files' },
|
error: {
|
||||||
|
code: 'GENERATE_TASKS_ERROR',
|
||||||
|
message: error.message || 'Unknown error generating task files'
|
||||||
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,10 @@
|
|||||||
import { listTasks } from '../../../../scripts/modules/task-manager.js';
|
import { listTasks } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for listTasks with error handling and caching.
|
* Direct function wrapper for listTasks with error handling and caching.
|
||||||
@@ -24,11 +27,19 @@ export async function listTasksDirect(args, log) {
|
|||||||
if (error.code === 'TASKS_FILE_NOT_FOUND') {
|
if (error.code === 'TASKS_FILE_NOT_FOUND') {
|
||||||
log.error(`Tasks file not found: ${error.message}`);
|
log.error(`Tasks file not found: ${error.message}`);
|
||||||
// Return the error structure expected by the calling tool/handler
|
// Return the error structure expected by the calling tool/handler
|
||||||
return { success: false, error: { code: error.code, message: error.message }, fromCache: false };
|
return {
|
||||||
|
success: false,
|
||||||
|
error: { code: error.code, message: error.message },
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
}
|
}
|
||||||
log.error(`Unexpected error finding tasks file: ${error.message}`);
|
log.error(`Unexpected error finding tasks file: ${error.message}`);
|
||||||
// Re-throw for outer catch or return structured error
|
// Re-throw for outer catch or return structured error
|
||||||
return { success: false, error: { code: 'FIND_TASKS_PATH_ERROR', message: error.message }, fromCache: false };
|
return {
|
||||||
|
success: false,
|
||||||
|
error: { code: 'FIND_TASKS_PATH_ERROR', message: error.message },
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate cache key *after* finding tasksPath
|
// Generate cache key *after* finding tasksPath
|
||||||
@@ -42,26 +53,46 @@ export async function listTasksDirect(args, log) {
|
|||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
log.info(`Executing core listTasks function for path: ${tasksPath}, filter: ${statusFilter}, subtasks: ${withSubtasks}`);
|
log.info(
|
||||||
const resultData = listTasks(tasksPath, statusFilter, withSubtasks, 'json');
|
`Executing core listTasks function for path: ${tasksPath}, filter: ${statusFilter}, subtasks: ${withSubtasks}`
|
||||||
|
);
|
||||||
|
const resultData = listTasks(
|
||||||
|
tasksPath,
|
||||||
|
statusFilter,
|
||||||
|
withSubtasks,
|
||||||
|
'json'
|
||||||
|
);
|
||||||
|
|
||||||
if (!resultData || !resultData.tasks) {
|
if (!resultData || !resultData.tasks) {
|
||||||
log.error('Invalid or empty response from listTasks core function');
|
log.error('Invalid or empty response from listTasks core function');
|
||||||
return { success: false, error: { code: 'INVALID_CORE_RESPONSE', message: 'Invalid or empty response from listTasks core function' } };
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'INVALID_CORE_RESPONSE',
|
||||||
|
message: 'Invalid or empty response from listTasks core function'
|
||||||
}
|
}
|
||||||
log.info(`Core listTasks function retrieved ${resultData.tasks.length} tasks`);
|
};
|
||||||
|
}
|
||||||
|
log.info(
|
||||||
|
`Core listTasks function retrieved ${resultData.tasks.length} tasks`
|
||||||
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
return { success: true, data: resultData };
|
return { success: true, data: resultData };
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Core listTasks function failed: ${error.message}`);
|
log.error(`Core listTasks function failed: ${error.message}`);
|
||||||
return { success: false, error: { code: 'LIST_TASKS_CORE_ERROR', message: error.message || 'Failed to list tasks' } };
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'LIST_TASKS_CORE_ERROR',
|
||||||
|
message: error.message || 'Failed to list tasks'
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -74,10 +105,16 @@ export async function listTasksDirect(args, log) {
|
|||||||
});
|
});
|
||||||
log.info(`listTasksDirect completed. From cache: ${result.fromCache}`);
|
log.info(`listTasksDirect completed. From cache: ${result.fromCache}`);
|
||||||
return result; // Returns { success, data/error, fromCache }
|
return result; // Returns { success, data/error, fromCache }
|
||||||
} catch(error) {
|
} catch (error) {
|
||||||
// Catch unexpected errors from getCachedOrExecute itself (though unlikely)
|
// Catch unexpected errors from getCachedOrExecute itself (though unlikely)
|
||||||
log.error(`Unexpected error during getCachedOrExecute for listTasks: ${error.message}`);
|
log.error(
|
||||||
|
`Unexpected error during getCachedOrExecute for listTasks: ${error.message}`
|
||||||
|
);
|
||||||
console.error(error.stack);
|
console.error(error.stack);
|
||||||
return { success: false, error: { code: 'CACHE_UTIL_ERROR', message: error.message }, fromCache: false };
|
return {
|
||||||
|
success: false,
|
||||||
|
error: { code: 'CACHE_UTIL_ERROR', message: error.message },
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,10 @@ import { findNextTask } from '../../../../scripts/modules/task-manager.js';
|
|||||||
import { readJSON } from '../../../../scripts/modules/utils.js';
|
import { readJSON } from '../../../../scripts/modules/utils.js';
|
||||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for finding the next task to work on with error handling and caching.
|
* Direct function wrapper for finding the next task to work on with error handling and caching.
|
||||||
@@ -60,11 +63,14 @@ export async function nextTaskDirect(args, log) {
|
|||||||
const nextTask = findNextTask(data.tasks);
|
const nextTask = findNextTask(data.tasks);
|
||||||
|
|
||||||
if (!nextTask) {
|
if (!nextTask) {
|
||||||
log.info('No eligible next task found. All tasks are either completed or have unsatisfied dependencies');
|
log.info(
|
||||||
|
'No eligible next task found. All tasks are either completed or have unsatisfied dependencies'
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: 'No eligible next task found. All tasks are either completed or have unsatisfied dependencies',
|
message:
|
||||||
|
'No eligible next task found. All tasks are either completed or have unsatisfied dependencies',
|
||||||
nextTask: null,
|
nextTask: null,
|
||||||
allTasks: data.tasks
|
allTasks: data.tasks
|
||||||
}
|
}
|
||||||
@@ -75,7 +81,9 @@ export async function nextTaskDirect(args, log) {
|
|||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
// Return the next task data with the full tasks array for reference
|
// Return the next task data with the full tasks array for reference
|
||||||
log.info(`Successfully found next task ${nextTask.id}: ${nextTask.title}`);
|
log.info(
|
||||||
|
`Successfully found next task ${nextTask.id}: ${nextTask.title}`
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
@@ -109,7 +117,9 @@ export async function nextTaskDirect(args, log) {
|
|||||||
return result; // Returns { success, data/error, fromCache }
|
return result; // Returns { success, data/error, fromCache }
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Catch unexpected errors from getCachedOrExecute itself
|
// Catch unexpected errors from getCachedOrExecute itself
|
||||||
log.error(`Unexpected error during getCachedOrExecute for nextTask: ${error.message}`);
|
log.error(
|
||||||
|
`Unexpected error during getCachedOrExecute for nextTask: ${error.message}`
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
|
|||||||
@@ -7,22 +7,49 @@ import path from 'path';
|
|||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { parsePRD } from '../../../../scripts/modules/task-manager.js';
|
import { parsePRD } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
import {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getModelConfig
|
||||||
|
} from '../utils/ai-client-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for parsing PRD documents and generating tasks.
|
* Direct function wrapper for parsing PRD documents and generating tasks.
|
||||||
*
|
*
|
||||||
* @param {Object} args - Command arguments containing input, numTasks or tasks, and output options.
|
* @param {Object} args - Command arguments containing input, numTasks or tasks, and output options.
|
||||||
* @param {Object} log - Logger object.
|
* @param {Object} log - Logger object.
|
||||||
|
* @param {Object} context - Context object containing session data.
|
||||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||||
*/
|
*/
|
||||||
export async function parsePRDDirect(args, log) {
|
export async function parsePRDDirect(args, log, context = {}) {
|
||||||
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Parsing PRD document with args: ${JSON.stringify(args)}`);
|
log.info(`Parsing PRD document with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Check required parameters
|
// Initialize AI client for PRD parsing
|
||||||
|
let aiClient;
|
||||||
|
try {
|
||||||
|
aiClient = getAnthropicClientForMCP(session, log);
|
||||||
|
} catch (error) {
|
||||||
|
log.error(`Failed to initialize AI client: ${error.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'AI_CLIENT_ERROR',
|
||||||
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parameter validation and path resolution
|
||||||
if (!args.input) {
|
if (!args.input) {
|
||||||
const errorMessage = 'No input file specified. Please provide an input PRD document path.';
|
const errorMessage =
|
||||||
|
'No input file specified. Please provide an input PRD document path.';
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -33,12 +60,16 @@ export async function parsePRDDirect(args, log) {
|
|||||||
|
|
||||||
// Resolve input path (relative to project root if provided)
|
// Resolve input path (relative to project root if provided)
|
||||||
const projectRoot = args.projectRoot || process.cwd();
|
const projectRoot = args.projectRoot || process.cwd();
|
||||||
const inputPath = path.isAbsolute(args.input) ? args.input : path.resolve(projectRoot, args.input);
|
const inputPath = path.isAbsolute(args.input)
|
||||||
|
? args.input
|
||||||
|
: path.resolve(projectRoot, args.input);
|
||||||
|
|
||||||
// Determine output path
|
// Determine output path
|
||||||
let outputPath;
|
let outputPath;
|
||||||
if (args.output) {
|
if (args.output) {
|
||||||
outputPath = path.isAbsolute(args.output) ? args.output : path.resolve(projectRoot, args.output);
|
outputPath = path.isAbsolute(args.output)
|
||||||
|
? args.output
|
||||||
|
: path.resolve(projectRoot, args.output);
|
||||||
} else {
|
} else {
|
||||||
// Default to tasks/tasks.json in the project root
|
// Default to tasks/tasks.json in the project root
|
||||||
outputPath = path.resolve(projectRoot, 'tasks', 'tasks.json');
|
outputPath = path.resolve(projectRoot, 'tasks', 'tasks.json');
|
||||||
@@ -58,29 +89,55 @@ export async function parsePRDDirect(args, log) {
|
|||||||
// Parse number of tasks - handle both string and number values
|
// Parse number of tasks - handle both string and number values
|
||||||
let numTasks = 10; // Default
|
let numTasks = 10; // Default
|
||||||
if (args.numTasks) {
|
if (args.numTasks) {
|
||||||
numTasks = typeof args.numTasks === 'string' ? parseInt(args.numTasks, 10) : args.numTasks;
|
numTasks =
|
||||||
|
typeof args.numTasks === 'string'
|
||||||
|
? parseInt(args.numTasks, 10)
|
||||||
|
: args.numTasks;
|
||||||
if (isNaN(numTasks)) {
|
if (isNaN(numTasks)) {
|
||||||
numTasks = 10; // Fallback to default if parsing fails
|
numTasks = 10; // Fallback to default if parsing fails
|
||||||
log.warn(`Invalid numTasks value: ${args.numTasks}. Using default: 10`);
|
log.warn(`Invalid numTasks value: ${args.numTasks}. Using default: 10`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Preparing to parse PRD from ${inputPath} and output to ${outputPath} with ${numTasks} tasks`);
|
log.info(
|
||||||
|
`Preparing to parse PRD from ${inputPath} and output to ${outputPath} with ${numTasks} tasks`
|
||||||
|
);
|
||||||
|
|
||||||
|
// Create the logger wrapper for proper logging in the core function
|
||||||
|
const logWrapper = {
|
||||||
|
info: (message, ...args) => log.info(message, ...args),
|
||||||
|
warn: (message, ...args) => log.warn(message, ...args),
|
||||||
|
error: (message, ...args) => log.error(message, ...args),
|
||||||
|
debug: (message, ...args) => log.debug && log.debug(message, ...args),
|
||||||
|
success: (message, ...args) => log.info(message, ...args) // Map success to info
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get model config from session
|
||||||
|
const modelConfig = getModelConfig(session);
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
try {
|
||||||
// Execute core parsePRD function (which is not async but we'll await it to maintain consistency)
|
// Execute core parsePRD function with AI client
|
||||||
await parsePRD(inputPath, outputPath, numTasks);
|
await parsePRD(
|
||||||
|
inputPath,
|
||||||
// Restore normal logging
|
outputPath,
|
||||||
disableSilentMode();
|
numTasks,
|
||||||
|
{
|
||||||
|
mcpLog: logWrapper,
|
||||||
|
session
|
||||||
|
},
|
||||||
|
aiClient,
|
||||||
|
modelConfig
|
||||||
|
);
|
||||||
|
|
||||||
// Since parsePRD doesn't return a value but writes to a file, we'll read the result
|
// Since parsePRD doesn't return a value but writes to a file, we'll read the result
|
||||||
// to return it to the caller
|
// to return it to the caller
|
||||||
if (fs.existsSync(outputPath)) {
|
if (fs.existsSync(outputPath)) {
|
||||||
const tasksData = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
|
const tasksData = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
|
||||||
log.info(`Successfully parsed PRD and generated ${tasksData.tasks?.length || 0} tasks`);
|
log.info(
|
||||||
|
`Successfully parsed PRD and generated ${tasksData.tasks?.length || 0} tasks`
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
@@ -100,6 +157,10 @@ export async function parsePRDDirect(args, log) {
|
|||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
// Always restore normal logging
|
||||||
|
disableSilentMode();
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
@@ -107,7 +168,10 @@ export async function parsePRDDirect(args, log) {
|
|||||||
log.error(`Error parsing PRD: ${error.message}`);
|
log.error(`Error parsing PRD: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'PARSE_PRD_ERROR', message: error.message || 'Unknown error parsing PRD' },
|
error: {
|
||||||
|
code: 'PARSE_PRD_ERROR',
|
||||||
|
message: error.message || 'Unknown error parsing PRD'
|
||||||
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { removeDependency } from '../../../../scripts/modules/dependency-manager.js';
|
import { removeDependency } from '../../../../scripts/modules/dependency-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove a dependency from a task
|
* Remove a dependency from a task
|
||||||
@@ -45,10 +48,18 @@ export async function removeDependencyDirect(args, log) {
|
|||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Format IDs for the core function
|
// Format IDs for the core function
|
||||||
const taskId = args.id.includes && args.id.includes('.') ? args.id : parseInt(args.id, 10);
|
const taskId =
|
||||||
const dependencyId = args.dependsOn.includes && args.dependsOn.includes('.') ? args.dependsOn : parseInt(args.dependsOn, 10);
|
args.id.includes && args.id.includes('.')
|
||||||
|
? args.id
|
||||||
|
: parseInt(args.id, 10);
|
||||||
|
const dependencyId =
|
||||||
|
args.dependsOn.includes && args.dependsOn.includes('.')
|
||||||
|
? args.dependsOn
|
||||||
|
: parseInt(args.dependsOn, 10);
|
||||||
|
|
||||||
log.info(`Removing dependency: task ${taskId} no longer depends on ${dependencyId}`);
|
log.info(
|
||||||
|
`Removing dependency: task ${taskId} no longer depends on ${dependencyId}`
|
||||||
|
);
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { removeSubtask } from '../../../../scripts/modules/task-manager.js';
|
import { removeSubtask } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove a subtask from its parent task
|
* Remove a subtask from its parent task
|
||||||
@@ -29,7 +32,8 @@ export async function removeSubtaskDirect(args, log) {
|
|||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Subtask ID is required and must be in format "parentId.subtaskId"'
|
message:
|
||||||
|
'Subtask ID is required and must be in format "parentId.subtaskId"'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -54,9 +58,16 @@ export async function removeSubtaskDirect(args, log) {
|
|||||||
// Determine if we should generate files
|
// Determine if we should generate files
|
||||||
const generateFiles = !args.skipGenerate;
|
const generateFiles = !args.skipGenerate;
|
||||||
|
|
||||||
log.info(`Removing subtask ${args.id} (convertToTask: ${convertToTask}, generateFiles: ${generateFiles})`);
|
log.info(
|
||||||
|
`Removing subtask ${args.id} (convertToTask: ${convertToTask}, generateFiles: ${generateFiles})`
|
||||||
|
);
|
||||||
|
|
||||||
const result = await removeSubtask(tasksPath, args.id, convertToTask, generateFiles);
|
const result = await removeSubtask(
|
||||||
|
tasksPath,
|
||||||
|
args.id,
|
||||||
|
convertToTask,
|
||||||
|
generateFiles
|
||||||
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|||||||
@@ -4,7 +4,10 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { removeTask } from '../../../../scripts/modules/task-manager.js';
|
import { removeTask } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -5,7 +5,11 @@
|
|||||||
|
|
||||||
import { setTaskStatus } from '../../../../scripts/modules/task-manager.js';
|
import { setTaskStatus } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode,
|
||||||
|
isSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for setTaskStatus with error handling.
|
* Direct function wrapper for setTaskStatus with error handling.
|
||||||
@@ -20,7 +24,8 @@ export async function setTaskStatusDirect(args, log) {
|
|||||||
|
|
||||||
// Check required parameters
|
// Check required parameters
|
||||||
if (!args.id) {
|
if (!args.id) {
|
||||||
const errorMessage = 'No task ID specified. Please provide a task ID to update.';
|
const errorMessage =
|
||||||
|
'No task ID specified. Please provide a task ID to update.';
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -30,7 +35,8 @@ export async function setTaskStatusDirect(args, log) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!args.status) {
|
if (!args.status) {
|
||||||
const errorMessage = 'No status specified. Please provide a new status value.';
|
const errorMessage =
|
||||||
|
'No status specified. Please provide a new status value.';
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -58,26 +64,22 @@ export async function setTaskStatusDirect(args, log) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Execute core setTaskStatus function
|
// Execute core setTaskStatus function
|
||||||
// We need to handle the arguments correctly - this function expects tasksPath, taskIdInput, newStatus
|
|
||||||
const taskId = args.id;
|
const taskId = args.id;
|
||||||
const newStatus = args.status;
|
const newStatus = args.status;
|
||||||
|
|
||||||
log.info(`Setting task ${taskId} status to "${newStatus}"`);
|
log.info(`Setting task ${taskId} status to "${newStatus}"`);
|
||||||
|
|
||||||
// Call the core function
|
// Call the core function with proper silent mode handling
|
||||||
|
let result;
|
||||||
|
enableSilentMode(); // Enable silent mode before calling core function
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Call the core function
|
||||||
enableSilentMode();
|
await setTaskStatus(tasksPath, taskId, newStatus, { mcpLog: log });
|
||||||
|
|
||||||
await setTaskStatus(tasksPath, taskId, newStatus);
|
|
||||||
|
|
||||||
// Restore normal logging
|
|
||||||
disableSilentMode();
|
|
||||||
|
|
||||||
log.info(`Successfully set task ${taskId} status to ${newStatus}`);
|
log.info(`Successfully set task ${taskId} status to ${newStatus}`);
|
||||||
|
|
||||||
// Return success data
|
// Return success data
|
||||||
return {
|
result = {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully updated task ${taskId} status to "${newStatus}"`,
|
message: `Successfully updated task ${taskId} status to "${newStatus}"`,
|
||||||
@@ -88,21 +90,34 @@ export async function setTaskStatusDirect(args, log) {
|
|||||||
fromCache: false // This operation always modifies state and should never be cached
|
fromCache: false // This operation always modifies state and should never be cached
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
log.error(`Error setting task status: ${error.message}`);
|
||||||
|
result = {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'SET_STATUS_ERROR',
|
||||||
|
message: error.message || 'Unknown error setting task status'
|
||||||
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
// ALWAYS restore normal logging in finally block
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
// Ensure silent mode is disabled if there was an uncaught error in the outer try block
|
||||||
|
if (isSilentMode()) {
|
||||||
|
disableSilentMode();
|
||||||
|
}
|
||||||
|
|
||||||
log.error(`Error setting task status: ${error.message}`);
|
log.error(`Error setting task status: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'SET_STATUS_ERROR', message: error.message || 'Unknown error setting task status' },
|
error: {
|
||||||
fromCache: false
|
code: 'SET_STATUS_ERROR',
|
||||||
};
|
message: error.message || 'Unknown error setting task status'
|
||||||
}
|
},
|
||||||
} catch (error) {
|
|
||||||
log.error(`Error setting task status: ${error.message}`);
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
error: { code: 'SET_STATUS_ERROR', message: error.message || 'Unknown error setting task status' },
|
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,10 @@ import { findTaskById } from '../../../../scripts/modules/utils.js';
|
|||||||
import { readJSON } from '../../../../scripts/modules/utils.js';
|
import { readJSON } from '../../../../scripts/modules/utils.js';
|
||||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for showing task details with error handling and caching.
|
* Direct function wrapper for showing task details with error handling and caching.
|
||||||
@@ -123,7 +126,9 @@ export async function showTaskDirect(args, log) {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Catch unexpected errors from getCachedOrExecute itself
|
// Catch unexpected errors from getCachedOrExecute itself
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
log.error(`Unexpected error during getCachedOrExecute for showTask: ${error.message}`);
|
log.error(
|
||||||
|
`Unexpected error during getCachedOrExecute for showTask: ${error.message}`
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
|
|||||||
@@ -4,23 +4,34 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { updateSubtaskById } from '../../../../scripts/modules/task-manager.js';
|
import { updateSubtaskById } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
|
import {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getPerplexityClientForMCP
|
||||||
|
} from '../utils/ai-client-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for updateSubtaskById with error handling.
|
* Direct function wrapper for updateSubtaskById with error handling.
|
||||||
*
|
*
|
||||||
* @param {Object} args - Command arguments containing id, prompt, useResearch and file path options.
|
* @param {Object} args - Command arguments containing id, prompt, useResearch and file path options.
|
||||||
* @param {Object} log - Logger object.
|
* @param {Object} log - Logger object.
|
||||||
|
* @param {Object} context - Context object containing session data.
|
||||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||||
*/
|
*/
|
||||||
export async function updateSubtaskByIdDirect(args, log) {
|
export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
||||||
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Check required parameters
|
// Check required parameters
|
||||||
if (!args.id) {
|
if (!args.id) {
|
||||||
const errorMessage = 'No subtask ID specified. Please provide a subtask ID to update.';
|
const errorMessage =
|
||||||
|
'No subtask ID specified. Please provide a subtask ID to update.';
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -30,7 +41,8 @@ export async function updateSubtaskByIdDirect(args, log) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!args.prompt) {
|
if (!args.prompt) {
|
||||||
const errorMessage = 'No prompt specified. Please provide a prompt with information to add to the subtask.';
|
const errorMessage =
|
||||||
|
'No prompt specified. Please provide a prompt with information to add to the subtask.';
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -41,8 +53,19 @@ export async function updateSubtaskByIdDirect(args, log) {
|
|||||||
|
|
||||||
// Validate subtask ID format
|
// Validate subtask ID format
|
||||||
const subtaskId = args.id;
|
const subtaskId = args.id;
|
||||||
if (typeof subtaskId !== 'string' || !subtaskId.includes('.')) {
|
if (typeof subtaskId !== 'string' && typeof subtaskId !== 'number') {
|
||||||
const errorMessage = `Invalid subtask ID format: ${subtaskId}. Subtask ID must be in format "parentId.subtaskId" (e.g., "5.2").`;
|
const errorMessage = `Invalid subtask ID type: ${typeof subtaskId}. Subtask ID must be a string or number.`;
|
||||||
|
log.error(errorMessage);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: { code: 'INVALID_SUBTASK_ID_TYPE', message: errorMessage },
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const subtaskIdStr = String(subtaskId);
|
||||||
|
if (!subtaskIdStr.includes('.')) {
|
||||||
|
const errorMessage = `Invalid subtask ID format: ${subtaskIdStr}. Subtask ID must be in format "parentId.subtaskId" (e.g., "5.2").`;
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -67,14 +90,57 @@ export async function updateSubtaskByIdDirect(args, log) {
|
|||||||
// Get research flag
|
// Get research flag
|
||||||
const useResearch = args.research === true;
|
const useResearch = args.research === true;
|
||||||
|
|
||||||
log.info(`Updating subtask with ID ${subtaskId} with prompt "${args.prompt}" and research: ${useResearch}`);
|
log.info(
|
||||||
|
`Updating subtask with ID ${subtaskIdStr} with prompt "${args.prompt}" and research: ${useResearch}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// Initialize the appropriate AI client based on research flag
|
||||||
|
try {
|
||||||
|
if (useResearch) {
|
||||||
|
// Initialize Perplexity client
|
||||||
|
await getPerplexityClientForMCP(session);
|
||||||
|
} else {
|
||||||
|
// Initialize Anthropic client
|
||||||
|
await getAnthropicClientForMCP(session);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
log.error(`AI client initialization error: ${error.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'AI_CLIENT_ERROR',
|
||||||
|
message: error.message || 'Failed to initialize AI client'
|
||||||
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
|
// Create a logger wrapper object to handle logging without breaking the mcpLog[level] calls
|
||||||
|
// This ensures outputFormat is set to 'json' while still supporting proper logging
|
||||||
|
const logWrapper = {
|
||||||
|
info: (message) => log.info(message),
|
||||||
|
warn: (message) => log.warn(message),
|
||||||
|
error: (message) => log.error(message),
|
||||||
|
debug: (message) => log.debug && log.debug(message),
|
||||||
|
success: (message) => log.info(message) // Map success to info if needed
|
||||||
|
};
|
||||||
|
|
||||||
// Execute core updateSubtaskById function
|
// Execute core updateSubtaskById function
|
||||||
const updatedSubtask = await updateSubtaskById(tasksPath, subtaskId, args.prompt, useResearch);
|
// Pass both session and logWrapper as mcpLog to ensure outputFormat is 'json'
|
||||||
|
const updatedSubtask = await updateSubtaskById(
|
||||||
|
tasksPath,
|
||||||
|
subtaskIdStr,
|
||||||
|
args.prompt,
|
||||||
|
useResearch,
|
||||||
|
{
|
||||||
|
session,
|
||||||
|
mcpLog: logWrapper
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
@@ -85,7 +151,8 @@ export async function updateSubtaskByIdDirect(args, log) {
|
|||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'SUBTASK_UPDATE_FAILED',
|
code: 'SUBTASK_UPDATE_FAILED',
|
||||||
message: 'Failed to update subtask. It may be marked as completed, or another error occurred.'
|
message:
|
||||||
|
'Failed to update subtask. It may be marked as completed, or another error occurred.'
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
@@ -95,9 +162,9 @@ export async function updateSubtaskByIdDirect(args, log) {
|
|||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully updated subtask with ID ${subtaskId}`,
|
message: `Successfully updated subtask with ID ${subtaskIdStr}`,
|
||||||
subtaskId,
|
subtaskId: subtaskIdStr,
|
||||||
parentId: subtaskId.split('.')[0],
|
parentId: subtaskIdStr.split('.')[0],
|
||||||
subtask: updatedSubtask,
|
subtask: updatedSubtask,
|
||||||
tasksPath,
|
tasksPath,
|
||||||
useResearch
|
useResearch
|
||||||
@@ -116,7 +183,10 @@ export async function updateSubtaskByIdDirect(args, log) {
|
|||||||
log.error(`Error updating subtask by ID: ${error.message}`);
|
log.error(`Error updating subtask by ID: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'UPDATE_SUBTASK_ERROR', message: error.message || 'Unknown error updating subtask' },
|
error: {
|
||||||
|
code: 'UPDATE_SUBTASK_ERROR',
|
||||||
|
message: error.message || 'Unknown error updating subtask'
|
||||||
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,22 +5,33 @@
|
|||||||
|
|
||||||
import { updateTaskById } from '../../../../scripts/modules/task-manager.js';
|
import { updateTaskById } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
import {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getPerplexityClientForMCP
|
||||||
|
} from '../utils/ai-client-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for updateTaskById with error handling.
|
* Direct function wrapper for updateTaskById with error handling.
|
||||||
*
|
*
|
||||||
* @param {Object} args - Command arguments containing id, prompt, useResearch and file path options.
|
* @param {Object} args - Command arguments containing id, prompt, useResearch and file path options.
|
||||||
* @param {Object} log - Logger object.
|
* @param {Object} log - Logger object.
|
||||||
|
* @param {Object} context - Context object containing session data.
|
||||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||||
*/
|
*/
|
||||||
export async function updateTaskByIdDirect(args, log) {
|
export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||||
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Check required parameters
|
// Check required parameters
|
||||||
if (!args.id) {
|
if (!args.id) {
|
||||||
const errorMessage = 'No task ID specified. Please provide a task ID to update.';
|
const errorMessage =
|
||||||
|
'No task ID specified. Please provide a task ID to update.';
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -30,7 +41,8 @@ export async function updateTaskByIdDirect(args, log) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!args.prompt) {
|
if (!args.prompt) {
|
||||||
const errorMessage = 'No prompt specified. Please provide a prompt with new information for the task update.';
|
const errorMessage =
|
||||||
|
'No prompt specified. Please provide a prompt with new information for the task update.';
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -78,16 +90,57 @@ export async function updateTaskByIdDirect(args, log) {
|
|||||||
// Get research flag
|
// Get research flag
|
||||||
const useResearch = args.research === true;
|
const useResearch = args.research === true;
|
||||||
|
|
||||||
log.info(`Updating task with ID ${taskId} with prompt "${args.prompt}" and research: ${useResearch}`);
|
// Initialize appropriate AI client based on research flag
|
||||||
|
let aiClient;
|
||||||
|
try {
|
||||||
|
if (useResearch) {
|
||||||
|
log.info('Using Perplexity AI for research-backed task update');
|
||||||
|
aiClient = await getPerplexityClientForMCP(session, log);
|
||||||
|
} else {
|
||||||
|
log.info('Using Claude AI for task update');
|
||||||
|
aiClient = getAnthropicClientForMCP(session, log);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
log.error(`Failed to initialize AI client: ${error.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'AI_CLIENT_ERROR',
|
||||||
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
`Updating task with ID ${taskId} with prompt "${args.prompt}" and research: ${useResearch}`
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Execute core updateTaskById function
|
// Create a logger wrapper that matches what updateTaskById expects
|
||||||
await updateTaskById(tasksPath, taskId, args.prompt, useResearch);
|
const logWrapper = {
|
||||||
|
info: (message) => log.info(message),
|
||||||
|
warn: (message) => log.warn(message),
|
||||||
|
error: (message) => log.error(message),
|
||||||
|
debug: (message) => log.debug && log.debug(message),
|
||||||
|
success: (message) => log.info(message) // Map success to info since many loggers don't have success
|
||||||
|
};
|
||||||
|
|
||||||
// Restore normal logging
|
// Execute core updateTaskById function with proper parameters
|
||||||
disableSilentMode();
|
await updateTaskById(
|
||||||
|
tasksPath,
|
||||||
|
taskId,
|
||||||
|
args.prompt,
|
||||||
|
useResearch,
|
||||||
|
{
|
||||||
|
mcpLog: logWrapper, // Use our wrapper object that has the expected method structure
|
||||||
|
session
|
||||||
|
},
|
||||||
|
'json'
|
||||||
|
);
|
||||||
|
|
||||||
// Since updateTaskById doesn't return a value but modifies the tasks file,
|
// Since updateTaskById doesn't return a value but modifies the tasks file,
|
||||||
// we'll return a success message
|
// we'll return a success message
|
||||||
@@ -102,13 +155,30 @@ export async function updateTaskByIdDirect(args, log) {
|
|||||||
fromCache: false // This operation always modifies state and should never be cached
|
fromCache: false // This operation always modifies state and should never be cached
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
log.error(`Error updating task by ID: ${error.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'UPDATE_TASK_ERROR',
|
||||||
|
message: error.message || 'Unknown error updating task'
|
||||||
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Ensure silent mode is disabled
|
||||||
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error updating task by ID: ${error.message}`);
|
log.error(`Error updating task by ID: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'UPDATE_TASK_ERROR', message: error.message || 'Unknown error updating task' },
|
error: {
|
||||||
|
code: 'UPDATE_TASK_ERROR',
|
||||||
|
message: error.message || 'Unknown error updating task'
|
||||||
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,23 +4,51 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { updateTasks } from '../../../../scripts/modules/task-manager.js';
|
import { updateTasks } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
|
import {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getPerplexityClientForMCP
|
||||||
|
} from '../utils/ai-client-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for updating tasks based on new context/prompt.
|
* Direct function wrapper for updating tasks based on new context/prompt.
|
||||||
*
|
*
|
||||||
* @param {Object} args - Command arguments containing fromId, prompt, useResearch and file path options.
|
* @param {Object} args - Command arguments containing fromId, prompt, useResearch and file path options.
|
||||||
* @param {Object} log - Logger object.
|
* @param {Object} log - Logger object.
|
||||||
|
* @param {Object} context - Context object containing session data.
|
||||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||||
*/
|
*/
|
||||||
export async function updateTasksDirect(args, log) {
|
export async function updateTasksDirect(args, log, context = {}) {
|
||||||
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Updating tasks with args: ${JSON.stringify(args)}`);
|
log.info(`Updating tasks with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
|
// Check for the common mistake of using 'id' instead of 'from'
|
||||||
|
if (args.id !== undefined && args.from === undefined) {
|
||||||
|
const errorMessage =
|
||||||
|
"You specified 'id' parameter but 'update' requires 'from' parameter. Use 'from' for this tool or use 'update_task' tool if you want to update a single task.";
|
||||||
|
log.error(errorMessage);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'PARAMETER_MISMATCH',
|
||||||
|
message: errorMessage,
|
||||||
|
suggestion:
|
||||||
|
"Use 'from' parameter instead of 'id', or use the 'update_task' tool for single task updates"
|
||||||
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Check required parameters
|
// Check required parameters
|
||||||
if (!args.from) {
|
if (!args.from) {
|
||||||
const errorMessage = 'No from ID specified. Please provide a task ID to start updating from.';
|
const errorMessage =
|
||||||
|
'No from ID specified. Please provide a task ID to start updating from.';
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -30,7 +58,8 @@ export async function updateTasksDirect(args, log) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!args.prompt) {
|
if (!args.prompt) {
|
||||||
const errorMessage = 'No prompt specified. Please provide a prompt with new context for task updates.';
|
const errorMessage =
|
||||||
|
'No prompt specified. Please provide a prompt with new context for task updates.';
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@@ -72,17 +101,41 @@ export async function updateTasksDirect(args, log) {
|
|||||||
// Get research flag
|
// Get research flag
|
||||||
const useResearch = args.research === true;
|
const useResearch = args.research === true;
|
||||||
|
|
||||||
log.info(`Updating tasks from ID ${fromId} with prompt "${args.prompt}" and research: ${useResearch}`);
|
// Initialize appropriate AI client based on research flag
|
||||||
|
let aiClient;
|
||||||
|
try {
|
||||||
|
if (useResearch) {
|
||||||
|
log.info('Using Perplexity AI for research-backed task updates');
|
||||||
|
aiClient = await getPerplexityClientForMCP(session, log);
|
||||||
|
} else {
|
||||||
|
log.info('Using Claude AI for task updates');
|
||||||
|
aiClient = getAnthropicClientForMCP(session, log);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
log.error(`Failed to initialize AI client: ${error.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'AI_CLIENT_ERROR',
|
||||||
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
`Updating tasks from ID ${fromId} with prompt "${args.prompt}" and research: ${useResearch}`
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Execute core updateTasks function
|
// Execute core updateTasks function, passing the AI client and session
|
||||||
await updateTasks(tasksPath, fromId, args.prompt, useResearch);
|
await updateTasks(tasksPath, fromId, args.prompt, useResearch, {
|
||||||
|
mcpLog: log,
|
||||||
// Restore normal logging
|
session
|
||||||
disableSilentMode();
|
});
|
||||||
|
|
||||||
// Since updateTasks doesn't return a value but modifies the tasks file,
|
// Since updateTasks doesn't return a value but modifies the tasks file,
|
||||||
// we'll return a success message
|
// we'll return a success message
|
||||||
@@ -97,9 +150,18 @@ export async function updateTasksDirect(args, log) {
|
|||||||
fromCache: false // This operation always modifies state and should never be cached
|
fromCache: false // This operation always modifies state and should never be cached
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
log.error(`Error updating tasks: ${error.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'UPDATE_TASKS_ERROR',
|
||||||
|
message: error.message || 'Unknown error updating tasks'
|
||||||
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
throw error; // Rethrow to be caught by outer catch block
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Ensure silent mode is disabled
|
// Ensure silent mode is disabled
|
||||||
@@ -108,7 +170,10 @@ export async function updateTasksDirect(args, log) {
|
|||||||
log.error(`Error updating tasks: ${error.message}`);
|
log.error(`Error updating tasks: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'UPDATE_TASKS_ERROR', message: error.message || 'Unknown error updating tasks' },
|
error: {
|
||||||
|
code: 'UPDATE_TASKS_ERROR',
|
||||||
|
message: error.message || 'Unknown error updating tasks'
|
||||||
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { validateDependenciesCommand } from '../../../../scripts/modules/dependency-manager.js';
|
import { validateDependenciesCommand } from '../../../../scripts/modules/dependency-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -32,6 +32,15 @@ import { removeTaskDirect } from './direct-functions/remove-task.js';
|
|||||||
// Re-export utility functions
|
// Re-export utility functions
|
||||||
export { findTasksJsonPath } from './utils/path-utils.js';
|
export { findTasksJsonPath } from './utils/path-utils.js';
|
||||||
|
|
||||||
|
// Re-export AI client utilities
|
||||||
|
export {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getPerplexityClientForMCP,
|
||||||
|
getModelConfig,
|
||||||
|
getBestAvailableAIModel,
|
||||||
|
handleClaudeError
|
||||||
|
} from './utils/ai-client-utils.js';
|
||||||
|
|
||||||
// Use Map for potential future enhancements like introspection or dynamic dispatch
|
// Use Map for potential future enhancements like introspection or dynamic dispatch
|
||||||
export const directFunctions = new Map([
|
export const directFunctions = new Map([
|
||||||
['listTasksDirect', listTasksDirect],
|
['listTasksDirect', listTasksDirect],
|
||||||
|
|||||||
@@ -26,10 +26,13 @@ const DEFAULT_MODEL_CONFIG = {
|
|||||||
export function getAnthropicClientForMCP(session, log = console) {
|
export function getAnthropicClientForMCP(session, log = console) {
|
||||||
try {
|
try {
|
||||||
// Extract API key from session.env or fall back to environment variables
|
// Extract API key from session.env or fall back to environment variables
|
||||||
const apiKey = session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY;
|
const apiKey =
|
||||||
|
session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY;
|
||||||
|
|
||||||
if (!apiKey) {
|
if (!apiKey) {
|
||||||
throw new Error('ANTHROPIC_API_KEY not found in session environment or process.env');
|
throw new Error(
|
||||||
|
'ANTHROPIC_API_KEY not found in session environment or process.env'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize and return a new Anthropic client
|
// Initialize and return a new Anthropic client
|
||||||
@@ -55,10 +58,13 @@ export function getAnthropicClientForMCP(session, log = console) {
|
|||||||
export async function getPerplexityClientForMCP(session, log = console) {
|
export async function getPerplexityClientForMCP(session, log = console) {
|
||||||
try {
|
try {
|
||||||
// Extract API key from session.env or fall back to environment variables
|
// Extract API key from session.env or fall back to environment variables
|
||||||
const apiKey = session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY;
|
const apiKey =
|
||||||
|
session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY;
|
||||||
|
|
||||||
if (!apiKey) {
|
if (!apiKey) {
|
||||||
throw new Error('PERPLEXITY_API_KEY not found in session environment or process.env');
|
throw new Error(
|
||||||
|
'PERPLEXITY_API_KEY not found in session environment or process.env'
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dynamically import OpenAI (it may not be used in all contexts)
|
// Dynamically import OpenAI (it may not be used in all contexts)
|
||||||
@@ -100,13 +106,19 @@ export function getModelConfig(session, defaults = DEFAULT_MODEL_CONFIG) {
|
|||||||
* @returns {Promise<Object>} Selected model info with type and client
|
* @returns {Promise<Object>} Selected model info with type and client
|
||||||
* @throws {Error} If no AI models are available
|
* @throws {Error} If no AI models are available
|
||||||
*/
|
*/
|
||||||
export async function getBestAvailableAIModel(session, options = {}, log = console) {
|
export async function getBestAvailableAIModel(
|
||||||
|
session,
|
||||||
|
options = {},
|
||||||
|
log = console
|
||||||
|
) {
|
||||||
const { requiresResearch = false, claudeOverloaded = false } = options;
|
const { requiresResearch = false, claudeOverloaded = false } = options;
|
||||||
|
|
||||||
// Test case: When research is needed but no Perplexity, use Claude
|
// Test case: When research is needed but no Perplexity, use Claude
|
||||||
if (requiresResearch &&
|
if (
|
||||||
|
requiresResearch &&
|
||||||
!(session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY) &&
|
!(session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY) &&
|
||||||
(session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)) {
|
(session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)
|
||||||
|
) {
|
||||||
try {
|
try {
|
||||||
log.warn('Perplexity not available for research, using Claude');
|
log.warn('Perplexity not available for research, using Claude');
|
||||||
const client = getAnthropicClientForMCP(session, log);
|
const client = getAnthropicClientForMCP(session, log);
|
||||||
@@ -118,7 +130,10 @@ export async function getBestAvailableAIModel(session, options = {}, log = conso
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Regular path: Perplexity for research when available
|
// Regular path: Perplexity for research when available
|
||||||
if (requiresResearch && (session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY)) {
|
if (
|
||||||
|
requiresResearch &&
|
||||||
|
(session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY)
|
||||||
|
) {
|
||||||
try {
|
try {
|
||||||
const client = await getPerplexityClientForMCP(session, log);
|
const client = await getPerplexityClientForMCP(session, log);
|
||||||
return { type: 'perplexity', client };
|
return { type: 'perplexity', client };
|
||||||
@@ -129,19 +144,29 @@ export async function getBestAvailableAIModel(session, options = {}, log = conso
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Test case: Claude for overloaded scenario
|
// Test case: Claude for overloaded scenario
|
||||||
if (claudeOverloaded && (session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)) {
|
if (
|
||||||
|
claudeOverloaded &&
|
||||||
|
(session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)
|
||||||
|
) {
|
||||||
try {
|
try {
|
||||||
log.warn('Claude is overloaded but no alternatives are available. Proceeding with Claude anyway.');
|
log.warn(
|
||||||
|
'Claude is overloaded but no alternatives are available. Proceeding with Claude anyway.'
|
||||||
|
);
|
||||||
const client = getAnthropicClientForMCP(session, log);
|
const client = getAnthropicClientForMCP(session, log);
|
||||||
return { type: 'claude', client };
|
return { type: 'claude', client };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Claude not available despite being overloaded: ${error.message}`);
|
log.error(
|
||||||
|
`Claude not available despite being overloaded: ${error.message}`
|
||||||
|
);
|
||||||
throw new Error('No AI models available');
|
throw new Error('No AI models available');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Default case: Use Claude when available and not overloaded
|
// Default case: Use Claude when available and not overloaded
|
||||||
if (!claudeOverloaded && (session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)) {
|
if (
|
||||||
|
!claudeOverloaded &&
|
||||||
|
(session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)
|
||||||
|
) {
|
||||||
try {
|
try {
|
||||||
const client = getAnthropicClientForMCP(session, log);
|
const client = getAnthropicClientForMCP(session, log);
|
||||||
return { type: 'claude', client };
|
return { type: 'claude', client };
|
||||||
|
|||||||
@@ -33,11 +33,19 @@ class AsyncOperationManager {
|
|||||||
this.log(operationId, 'info', `Operation added.`);
|
this.log(operationId, 'info', `Operation added.`);
|
||||||
|
|
||||||
// Start execution in the background (don't await here)
|
// Start execution in the background (don't await here)
|
||||||
this._runOperation(operationId, operationFn, args, context).catch(err => {
|
this._runOperation(operationId, operationFn, args, context).catch((err) => {
|
||||||
// Catch unexpected errors during the async execution setup itself
|
// Catch unexpected errors during the async execution setup itself
|
||||||
this.log(operationId, 'error', `Critical error starting operation: ${err.message}`, { stack: err.stack });
|
this.log(
|
||||||
|
operationId,
|
||||||
|
'error',
|
||||||
|
`Critical error starting operation: ${err.message}`,
|
||||||
|
{ stack: err.stack }
|
||||||
|
);
|
||||||
operation.status = 'failed';
|
operation.status = 'failed';
|
||||||
operation.error = { code: 'MANAGER_EXECUTION_ERROR', message: err.message };
|
operation.error = {
|
||||||
|
code: 'MANAGER_EXECUTION_ERROR',
|
||||||
|
message: err.message
|
||||||
|
};
|
||||||
operation.endTime = Date.now();
|
operation.endTime = Date.now();
|
||||||
|
|
||||||
// Move to completed operations
|
// Move to completed operations
|
||||||
@@ -67,7 +75,8 @@ class AsyncOperationManager {
|
|||||||
// The direct function needs to be adapted if it needs reportProgress
|
// The direct function needs to be adapted if it needs reportProgress
|
||||||
// We pass the original context's log, plus our wrapped reportProgress
|
// We pass the original context's log, plus our wrapped reportProgress
|
||||||
const result = await operationFn(args, operation.log, {
|
const result = await operationFn(args, operation.log, {
|
||||||
reportProgress: (progress) => this._handleProgress(operationId, progress),
|
reportProgress: (progress) =>
|
||||||
|
this._handleProgress(operationId, progress),
|
||||||
mcpLog: operation.log, // Pass log as mcpLog if direct fn expects it
|
mcpLog: operation.log, // Pass log as mcpLog if direct fn expects it
|
||||||
session: operation.session
|
session: operation.session
|
||||||
});
|
});
|
||||||
@@ -75,15 +84,31 @@ class AsyncOperationManager {
|
|||||||
operation.status = result.success ? 'completed' : 'failed';
|
operation.status = result.success ? 'completed' : 'failed';
|
||||||
operation.result = result.success ? result.data : null;
|
operation.result = result.success ? result.data : null;
|
||||||
operation.error = result.success ? null : result.error;
|
operation.error = result.success ? null : result.error;
|
||||||
this.log(operationId, 'info', `Operation finished with status: ${operation.status}`);
|
this.log(
|
||||||
|
operationId,
|
||||||
|
'info',
|
||||||
|
`Operation finished with status: ${operation.status}`
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.log(operationId, 'error', `Operation failed with error: ${error.message}`, { stack: error.stack });
|
this.log(
|
||||||
|
operationId,
|
||||||
|
'error',
|
||||||
|
`Operation failed with error: ${error.message}`,
|
||||||
|
{ stack: error.stack }
|
||||||
|
);
|
||||||
operation.status = 'failed';
|
operation.status = 'failed';
|
||||||
operation.error = { code: 'OPERATION_EXECUTION_ERROR', message: error.message };
|
operation.error = {
|
||||||
|
code: 'OPERATION_EXECUTION_ERROR',
|
||||||
|
message: error.message
|
||||||
|
};
|
||||||
} finally {
|
} finally {
|
||||||
operation.endTime = Date.now();
|
operation.endTime = Date.now();
|
||||||
this.emit('statusChanged', { operationId, status: operation.status, result: operation.result, error: operation.error });
|
this.emit('statusChanged', {
|
||||||
|
operationId,
|
||||||
|
status: operation.status,
|
||||||
|
result: operation.result,
|
||||||
|
error: operation.error
|
||||||
|
});
|
||||||
|
|
||||||
// Move to completed operations if done or failed
|
// Move to completed operations if done or failed
|
||||||
if (operation.status === 'completed' || operation.status === 'failed') {
|
if (operation.status === 'completed' || operation.status === 'failed') {
|
||||||
@@ -108,7 +133,7 @@ class AsyncOperationManager {
|
|||||||
startTime: operation.startTime,
|
startTime: operation.startTime,
|
||||||
endTime: operation.endTime,
|
endTime: operation.endTime,
|
||||||
result: operation.result,
|
result: operation.result,
|
||||||
error: operation.error,
|
error: operation.error
|
||||||
};
|
};
|
||||||
|
|
||||||
this.completedOperations.set(operationId, completedData);
|
this.completedOperations.set(operationId, completedData);
|
||||||
@@ -117,8 +142,9 @@ class AsyncOperationManager {
|
|||||||
// Trim completed operations if exceeding maximum
|
// Trim completed operations if exceeding maximum
|
||||||
if (this.completedOperations.size > this.maxCompletedOperations) {
|
if (this.completedOperations.size > this.maxCompletedOperations) {
|
||||||
// Get the oldest operation (sorted by endTime)
|
// Get the oldest operation (sorted by endTime)
|
||||||
const oldest = [...this.completedOperations.entries()]
|
const oldest = [...this.completedOperations.entries()].sort(
|
||||||
.sort((a, b) => a[1].endTime - b[1].endTime)[0];
|
(a, b) => a[1].endTime - b[1].endTime
|
||||||
|
)[0];
|
||||||
|
|
||||||
if (oldest) {
|
if (oldest) {
|
||||||
this.completedOperations.delete(oldest[0]);
|
this.completedOperations.delete(oldest[0]);
|
||||||
@@ -137,9 +163,17 @@ class AsyncOperationManager {
|
|||||||
try {
|
try {
|
||||||
// Use the reportProgress function captured from the original context
|
// Use the reportProgress function captured from the original context
|
||||||
operation.reportProgress(progress);
|
operation.reportProgress(progress);
|
||||||
this.log(operationId, 'debug', `Reported progress: ${JSON.stringify(progress)}`);
|
this.log(
|
||||||
} catch(err) {
|
operationId,
|
||||||
this.log(operationId, 'warn', `Failed to report progress: ${err.message}`);
|
'debug',
|
||||||
|
`Reported progress: ${JSON.stringify(progress)}`
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
this.log(
|
||||||
|
operationId,
|
||||||
|
'warn',
|
||||||
|
`Failed to report progress: ${err.message}`
|
||||||
|
);
|
||||||
// Don't stop the operation, just log the reporting failure
|
// Don't stop the operation, just log the reporting failure
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -160,7 +194,7 @@ class AsyncOperationManager {
|
|||||||
startTime: operation.startTime,
|
startTime: operation.startTime,
|
||||||
endTime: operation.endTime,
|
endTime: operation.endTime,
|
||||||
result: operation.result,
|
result: operation.result,
|
||||||
error: operation.error,
|
error: operation.error
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,7 +239,7 @@ class AsyncOperationManager {
|
|||||||
|
|
||||||
emit(eventName, data) {
|
emit(eventName, data) {
|
||||||
if (this.listeners.has(eventName)) {
|
if (this.listeners.has(eventName)) {
|
||||||
this.listeners.get(eventName).forEach(listener => listener(data));
|
this.listeners.get(eventName).forEach((listener) => listener(data));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,11 @@
|
|||||||
* @returns {Promise<any>} The result of the actionFn.
|
* @returns {Promise<any>} The result of the actionFn.
|
||||||
*/
|
*/
|
||||||
export async function withSessionEnv(sessionEnv, actionFn) {
|
export async function withSessionEnv(sessionEnv, actionFn) {
|
||||||
if (!sessionEnv || typeof sessionEnv !== 'object' || Object.keys(sessionEnv).length === 0) {
|
if (
|
||||||
|
!sessionEnv ||
|
||||||
|
typeof sessionEnv !== 'object' ||
|
||||||
|
Object.keys(sessionEnv).length === 0
|
||||||
|
) {
|
||||||
// If no sessionEnv is provided, just run the action directly
|
// If no sessionEnv is provided, just run the action directly
|
||||||
return await actionFn();
|
return await actionFn();
|
||||||
}
|
}
|
||||||
@@ -40,4 +44,4 @@ export async function withSessionEnv(sessionEnv, actionFn) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -100,7 +100,10 @@ export function findTasksJsonPath(args, log) {
|
|||||||
projectRoot,
|
projectRoot,
|
||||||
currentDir: process.cwd(),
|
currentDir: process.cwd(),
|
||||||
serverDir: path.dirname(process.argv[1]),
|
serverDir: path.dirname(process.argv[1]),
|
||||||
possibleProjectRoot: path.resolve(path.dirname(process.argv[1]), '../..'),
|
possibleProjectRoot: path.resolve(
|
||||||
|
path.dirname(process.argv[1]),
|
||||||
|
'../..'
|
||||||
|
),
|
||||||
lastFoundProjectRoot,
|
lastFoundProjectRoot,
|
||||||
searchedPaths: error.message
|
searchedPaths: error.message
|
||||||
};
|
};
|
||||||
@@ -117,17 +120,25 @@ export function findTasksJsonPath(args, log) {
|
|||||||
log.info(`Trying last known project root: ${lastFoundProjectRoot}`);
|
log.info(`Trying last known project root: ${lastFoundProjectRoot}`);
|
||||||
try {
|
try {
|
||||||
// Use the cached root
|
// Use the cached root
|
||||||
const tasksPath = findTasksJsonInDirectory(lastFoundProjectRoot, args.file, log);
|
const tasksPath = findTasksJsonInDirectory(
|
||||||
|
lastFoundProjectRoot,
|
||||||
|
args.file,
|
||||||
|
log
|
||||||
|
);
|
||||||
return tasksPath; // Return if found in cached root
|
return tasksPath; // Return if found in cached root
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.info(`Task file not found in last known project root, continuing search.`);
|
log.info(
|
||||||
|
`Task file not found in last known project root, continuing search.`
|
||||||
|
);
|
||||||
// Continue with search if not found in cache
|
// Continue with search if not found in cache
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Start search from current directory (most common CLI scenario)
|
// 3. Start search from current directory (most common CLI scenario)
|
||||||
const startDir = process.cwd();
|
const startDir = process.cwd();
|
||||||
log.info(`Searching for tasks.json starting from current directory: ${startDir}`);
|
log.info(
|
||||||
|
`Searching for tasks.json starting from current directory: ${startDir}`
|
||||||
|
);
|
||||||
|
|
||||||
// Try to find tasks.json by walking up the directory tree from cwd
|
// Try to find tasks.json by walking up the directory tree from cwd
|
||||||
try {
|
try {
|
||||||
@@ -146,7 +157,7 @@ export function findTasksJsonPath(args, log) {
|
|||||||
* @returns {boolean} - True if the directory contains any project markers
|
* @returns {boolean} - True if the directory contains any project markers
|
||||||
*/
|
*/
|
||||||
function hasProjectMarkers(dirPath) {
|
function hasProjectMarkers(dirPath) {
|
||||||
return PROJECT_MARKERS.some(marker => {
|
return PROJECT_MARKERS.some((marker) => {
|
||||||
const markerPath = path.join(dirPath, marker);
|
const markerPath = path.join(dirPath, marker);
|
||||||
// Check if the marker exists as either a file or directory
|
// Check if the marker exists as either a file or directory
|
||||||
return fs.existsSync(markerPath);
|
return fs.existsSync(markerPath);
|
||||||
@@ -179,7 +190,11 @@ function findTasksJsonInDirectory(dirPath, explicitFilePath, log) {
|
|||||||
|
|
||||||
// Find the first existing path
|
// Find the first existing path
|
||||||
for (const p of possiblePaths) {
|
for (const p of possiblePaths) {
|
||||||
if (fs.existsSync(p)) {
|
log.info(`Checking if exists: ${p}`);
|
||||||
|
const exists = fs.existsSync(p);
|
||||||
|
log.info(`Path ${p} exists: ${exists}`);
|
||||||
|
|
||||||
|
if (exists) {
|
||||||
log.info(`Found tasks file at: ${p}`);
|
log.info(`Found tasks file at: ${p}`);
|
||||||
// Store the project root for future use
|
// Store the project root for future use
|
||||||
lastFoundProjectRoot = dirPath;
|
lastFoundProjectRoot = dirPath;
|
||||||
@@ -188,7 +203,9 @@ function findTasksJsonInDirectory(dirPath, explicitFilePath, log) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If no file was found, throw an error
|
// If no file was found, throw an error
|
||||||
const error = new Error(`Tasks file not found in any of the expected locations relative to ${dirPath}: ${possiblePaths.join(', ')}`);
|
const error = new Error(
|
||||||
|
`Tasks file not found in any of the expected locations relative to ${dirPath}: ${possiblePaths.join(', ')}`
|
||||||
|
);
|
||||||
error.code = 'TASKS_FILE_NOT_FOUND';
|
error.code = 'TASKS_FILE_NOT_FOUND';
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -226,13 +243,17 @@ function findTasksJsonWithParentSearch(startDir, explicitFilePath, log) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Tasks file not found in ${currentDir}, searching in parent directory: ${parentDir}`);
|
log.info(
|
||||||
|
`Tasks file not found in ${currentDir}, searching in parent directory: ${parentDir}`
|
||||||
|
);
|
||||||
currentDir = parentDir;
|
currentDir = parentDir;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we've searched all the way to the root and found nothing
|
// If we've searched all the way to the root and found nothing
|
||||||
const error = new Error(`Tasks file not found in ${startDir} or any parent directory.`);
|
const error = new Error(
|
||||||
|
`Tasks file not found in ${startDir} or any parent directory.`
|
||||||
|
);
|
||||||
error.code = 'TASKS_FILE_NOT_FOUND';
|
error.code = 'TASKS_FILE_NOT_FOUND';
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -258,7 +279,11 @@ function findTasksWithNpmConsideration(startDir, log) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
// Check standard locations in home dir
|
// Check standard locations in home dir
|
||||||
return findTasksJsonInDirectory(path.join(homeDir, '.task-master'), null, log);
|
return findTasksJsonInDirectory(
|
||||||
|
path.join(homeDir, '.task-master'),
|
||||||
|
null,
|
||||||
|
log
|
||||||
|
);
|
||||||
} catch (thirdError) {
|
} catch (thirdError) {
|
||||||
// If all approaches fail, throw the original error
|
// If all approaches fail, throw the original error
|
||||||
throw error;
|
throw error;
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { FastMCP } from "fastmcp";
|
import { FastMCP } from 'fastmcp';
|
||||||
import path from "path";
|
import path from 'path';
|
||||||
import dotenv from "dotenv";
|
import dotenv from 'dotenv';
|
||||||
import { fileURLToPath } from "url";
|
import { fileURLToPath } from 'url';
|
||||||
import fs from "fs";
|
import fs from 'fs';
|
||||||
import logger from "./logger.js";
|
import logger from './logger.js';
|
||||||
import { registerTaskMasterTools } from "./tools/index.js";
|
import { registerTaskMasterTools } from './tools/index.js';
|
||||||
import { asyncOperationManager } from './core/utils/async-manager.js';
|
import { asyncOperationManager } from './core/utils/async-manager.js';
|
||||||
|
|
||||||
// Load environment variables
|
// Load environment variables
|
||||||
@@ -20,12 +20,12 @@ const __dirname = path.dirname(__filename);
|
|||||||
class TaskMasterMCPServer {
|
class TaskMasterMCPServer {
|
||||||
constructor() {
|
constructor() {
|
||||||
// Get version from package.json using synchronous fs
|
// Get version from package.json using synchronous fs
|
||||||
const packagePath = path.join(__dirname, "../../package.json");
|
const packagePath = path.join(__dirname, '../../package.json');
|
||||||
const packageJson = JSON.parse(fs.readFileSync(packagePath, "utf8"));
|
const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
|
||||||
|
|
||||||
this.options = {
|
this.options = {
|
||||||
name: "Task Master MCP Server",
|
name: 'Task Master MCP Server',
|
||||||
version: packageJson.version,
|
version: packageJson.version
|
||||||
};
|
};
|
||||||
|
|
||||||
this.server = new FastMCP(this.options);
|
this.server = new FastMCP(this.options);
|
||||||
@@ -69,9 +69,10 @@ class TaskMasterMCPServer {
|
|||||||
await this.init();
|
await this.init();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start the FastMCP server
|
// Start the FastMCP server with increased timeout
|
||||||
await this.server.start({
|
await this.server.start({
|
||||||
transportType: "stdio",
|
transportType: 'stdio',
|
||||||
|
timeout: 120000 // 2 minutes timeout (in milliseconds)
|
||||||
});
|
});
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import chalk from "chalk";
|
import chalk from 'chalk';
|
||||||
|
import { isSilentMode } from '../../scripts/modules/utils.js';
|
||||||
|
|
||||||
// Define log levels
|
// Define log levels
|
||||||
const LOG_LEVELS = {
|
const LOG_LEVELS = {
|
||||||
@@ -6,12 +7,12 @@ const LOG_LEVELS = {
|
|||||||
info: 1,
|
info: 1,
|
||||||
warn: 2,
|
warn: 2,
|
||||||
error: 3,
|
error: 3,
|
||||||
success: 4,
|
success: 4
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get log level from environment or default to info
|
// Get log level from environment or default to info
|
||||||
const LOG_LEVEL = process.env.LOG_LEVEL
|
const LOG_LEVEL = process.env.LOG_LEVEL
|
||||||
? LOG_LEVELS[process.env.LOG_LEVEL.toLowerCase()] ?? LOG_LEVELS.info
|
? (LOG_LEVELS[process.env.LOG_LEVEL.toLowerCase()] ?? LOG_LEVELS.info)
|
||||||
: LOG_LEVELS.info;
|
: LOG_LEVELS.info;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,42 +21,57 @@ const LOG_LEVEL = process.env.LOG_LEVEL
|
|||||||
* @param {...any} args - Arguments to log
|
* @param {...any} args - Arguments to log
|
||||||
*/
|
*/
|
||||||
function log(level, ...args) {
|
function log(level, ...args) {
|
||||||
|
// Skip logging if silent mode is enabled
|
||||||
|
if (isSilentMode()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Use text prefixes instead of emojis
|
// Use text prefixes instead of emojis
|
||||||
const prefixes = {
|
const prefixes = {
|
||||||
debug: chalk.gray("[DEBUG]"),
|
debug: chalk.gray('[DEBUG]'),
|
||||||
info: chalk.blue("[INFO]"),
|
info: chalk.blue('[INFO]'),
|
||||||
warn: chalk.yellow("[WARN]"),
|
warn: chalk.yellow('[WARN]'),
|
||||||
error: chalk.red("[ERROR]"),
|
error: chalk.red('[ERROR]'),
|
||||||
success: chalk.green("[SUCCESS]"),
|
success: chalk.green('[SUCCESS]')
|
||||||
};
|
};
|
||||||
|
|
||||||
if (LOG_LEVELS[level] !== undefined && LOG_LEVELS[level] >= LOG_LEVEL) {
|
if (LOG_LEVELS[level] !== undefined && LOG_LEVELS[level] >= LOG_LEVEL) {
|
||||||
const prefix = prefixes[level] || "";
|
const prefix = prefixes[level] || '';
|
||||||
let coloredArgs = args;
|
let coloredArgs = args;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
switch(level) {
|
switch (level) {
|
||||||
case "error":
|
case 'error':
|
||||||
coloredArgs = args.map(arg => typeof arg === 'string' ? chalk.red(arg) : arg);
|
coloredArgs = args.map((arg) =>
|
||||||
|
typeof arg === 'string' ? chalk.red(arg) : arg
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
case "warn":
|
case 'warn':
|
||||||
coloredArgs = args.map(arg => typeof arg === 'string' ? chalk.yellow(arg) : arg);
|
coloredArgs = args.map((arg) =>
|
||||||
|
typeof arg === 'string' ? chalk.yellow(arg) : arg
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
case "success":
|
case 'success':
|
||||||
coloredArgs = args.map(arg => typeof arg === 'string' ? chalk.green(arg) : arg);
|
coloredArgs = args.map((arg) =>
|
||||||
|
typeof arg === 'string' ? chalk.green(arg) : arg
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
case "info":
|
case 'info':
|
||||||
coloredArgs = args.map(arg => typeof arg === 'string' ? chalk.blue(arg) : arg);
|
coloredArgs = args.map((arg) =>
|
||||||
|
typeof arg === 'string' ? chalk.blue(arg) : arg
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
case "debug":
|
case 'debug':
|
||||||
coloredArgs = args.map(arg => typeof arg === 'string' ? chalk.gray(arg) : arg);
|
coloredArgs = args.map((arg) =>
|
||||||
|
typeof arg === 'string' ? chalk.gray(arg) : arg
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
// default: use original args (no color)
|
// default: use original args (no color)
|
||||||
}
|
}
|
||||||
} catch (colorError) {
|
} catch (colorError) {
|
||||||
// Fallback if chalk fails on an argument
|
// Fallback if chalk fails on an argument
|
||||||
// Use console.error here for internal logger errors, separate from normal logging
|
// Use console.error here for internal logger errors, separate from normal logging
|
||||||
console.error("Internal Logger Error applying chalk color:", colorError);
|
console.error('Internal Logger Error applying chalk color:', colorError);
|
||||||
coloredArgs = args;
|
coloredArgs = args;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,15 +88,18 @@ function log(level, ...args) {
|
|||||||
* @returns {Object} Logger object with info, error, debug, warn, and success methods
|
* @returns {Object} Logger object with info, error, debug, warn, and success methods
|
||||||
*/
|
*/
|
||||||
export function createLogger() {
|
export function createLogger() {
|
||||||
const createLogMethod = (level) => (...args) => log(level, ...args);
|
const createLogMethod =
|
||||||
|
(level) =>
|
||||||
|
(...args) =>
|
||||||
|
log(level, ...args);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
debug: createLogMethod("debug"),
|
debug: createLogMethod('debug'),
|
||||||
info: createLogMethod("info"),
|
info: createLogMethod('info'),
|
||||||
warn: createLogMethod("warn"),
|
warn: createLogMethod('warn'),
|
||||||
error: createLogMethod("error"),
|
error: createLogMethod('error'),
|
||||||
success: createLogMethod("success"),
|
success: createLogMethod('success'),
|
||||||
log: log, // Also expose the raw log function
|
log: log // Also expose the raw log function
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool for adding a dependency to a task
|
* Tool for adding a dependency to a task
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { addDependencyDirect } from "../core/task-master-core.js";
|
import { addDependencyDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the addDependency tool with the MCP server
|
* Register the addDependency tool with the MCP server
|
||||||
@@ -17,17 +17,29 @@ import { addDependencyDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerAddDependencyTool(server) {
|
export function registerAddDependencyTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "add_dependency",
|
name: 'add_dependency',
|
||||||
description: "Add a dependency relationship between two tasks",
|
description: 'Add a dependency relationship between two tasks',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("ID of task that will depend on another task"),
|
id: z.string().describe('ID of task that will depend on another task'),
|
||||||
dependsOn: z.string().describe("ID of task that will become a dependency"),
|
dependsOn: z
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
.string()
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
.describe('ID of task that will become a dependency'),
|
||||||
|
file: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Adding dependency for task ${args.id} to depend on ${args.dependsOn}`);
|
log.info(
|
||||||
|
`Adding dependency for task ${args.id} to depend on ${args.dependsOn}`
|
||||||
|
);
|
||||||
reportProgress({ progress: 0 });
|
reportProgress({ progress: 0 });
|
||||||
|
|
||||||
// Get project root using the utility function
|
// Get project root using the utility function
|
||||||
@@ -40,10 +52,14 @@ export function registerAddDependencyTool(server) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Call the direct function with the resolved rootFolder
|
// Call the direct function with the resolved rootFolder
|
||||||
const result = await addDependencyDirect({
|
const result = await addDependencyDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log, { reportProgress, mcpLog: log, session});
|
},
|
||||||
|
log,
|
||||||
|
{ reportProgress, mcpLog: log, session }
|
||||||
|
);
|
||||||
|
|
||||||
reportProgress({ progress: 100 });
|
reportProgress({ progress: 100 });
|
||||||
|
|
||||||
@@ -60,6 +76,6 @@ export function registerAddDependencyTool(server) {
|
|||||||
log.error(`Error in addDependency tool: ${error.message}`);
|
log.error(`Error in addDependency tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool for adding subtasks to existing tasks
|
* Tool for adding subtasks to existing tasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { addSubtaskDirect } from "../core/task-master-core.js";
|
import { addSubtaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the addSubtask tool with the MCP server
|
* Register the addSubtask tool with the MCP server
|
||||||
@@ -17,19 +17,48 @@ import { addSubtaskDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerAddSubtaskTool(server) {
|
export function registerAddSubtaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "add_subtask",
|
name: 'add_subtask',
|
||||||
description: "Add a subtask to an existing task",
|
description: 'Add a subtask to an existing task',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("Parent task ID (required)"),
|
id: z.string().describe('Parent task ID (required)'),
|
||||||
taskId: z.string().optional().describe("Existing task ID to convert to subtask"),
|
taskId: z
|
||||||
title: z.string().optional().describe("Title for the new subtask (when creating a new subtask)"),
|
.string()
|
||||||
description: z.string().optional().describe("Description for the new subtask"),
|
.optional()
|
||||||
details: z.string().optional().describe("Implementation details for the new subtask"),
|
.describe('Existing task ID to convert to subtask'),
|
||||||
status: z.string().optional().describe("Status for the new subtask (default: 'pending')"),
|
title: z
|
||||||
dependencies: z.string().optional().describe("Comma-separated list of dependency IDs for the new subtask"),
|
.string()
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
.optional()
|
||||||
skipGenerate: z.boolean().optional().describe("Skip regenerating task files"),
|
.describe('Title for the new subtask (when creating a new subtask)'),
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
description: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Description for the new subtask'),
|
||||||
|
details: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Implementation details for the new subtask'),
|
||||||
|
status: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe("Status for the new subtask (default: 'pending')"),
|
||||||
|
dependencies: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Comma-separated list of dependency IDs for the new subtask'),
|
||||||
|
file: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
|
skipGenerate: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Skip regenerating task files'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
try {
|
try {
|
||||||
@@ -42,10 +71,14 @@ export function registerAddSubtaskTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await addSubtaskDirect({
|
const result = await addSubtaskDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log, { reportProgress, mcpLog: log, session});
|
},
|
||||||
|
log,
|
||||||
|
{ reportProgress, mcpLog: log, session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Subtask added successfully: ${result.data.message}`);
|
log.info(`Subtask added successfully: ${result.data.message}`);
|
||||||
@@ -58,6 +91,6 @@ export function registerAddSubtaskTool(server) {
|
|||||||
log.error(`Error in addSubtask tool: ${error.message}`);
|
log.error(`Error in addSubtask tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,63 +3,71 @@
|
|||||||
* Tool to add a new task using AI
|
* Tool to add a new task using AI
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
createContentResponse,
|
createContentResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession,
|
||||||
} from "./utils.js";
|
executeTaskMasterCommand,
|
||||||
import { addTaskDirect } from "../core/task-master-core.js";
|
handleApiResult
|
||||||
|
} from './utils.js';
|
||||||
|
import { addTaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the add-task tool with the MCP server
|
* Register the addTask tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
* @param {AsyncOperationManager} asyncManager - The async operation manager instance.
|
|
||||||
*/
|
*/
|
||||||
export function registerAddTaskTool(server, asyncManager) {
|
export function registerAddTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "add_task",
|
name: 'add_task',
|
||||||
description: "Starts adding a new task using AI in the background.",
|
description: 'Add a new task using AI',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
prompt: z.string().describe("Description of the task to add"),
|
prompt: z.string().describe('Description of the task to add'),
|
||||||
dependencies: z.string().optional().describe("Comma-separated list of task IDs this task depends on"),
|
dependencies: z
|
||||||
priority: z.string().optional().describe("Task priority (high, medium, low)"),
|
.string()
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
.optional()
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
.describe('Comma-separated list of task IDs this task depends on'),
|
||||||
|
priority: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Task priority (high, medium, low)'),
|
||||||
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Root directory of the project'),
|
||||||
|
research: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Whether to use research capabilities for task creation')
|
||||||
}),
|
}),
|
||||||
execute: async (args, context) => {
|
execute: async (args, { log, reportProgress, session }) => {
|
||||||
const { log, reportProgress, session } = context;
|
|
||||||
try {
|
try {
|
||||||
log.info(`MCP add_task request received with prompt: \"${args.prompt}\"`);
|
log.info(`Starting add-task with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
if (!args.prompt) {
|
|
||||||
return createErrorResponse("Prompt is required for add_task.", "VALIDATION_ERROR");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// Get project root from session
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const directArgs = {
|
// Call the direct function
|
||||||
projectRoot: rootFolder,
|
const result = await addTaskDirect(
|
||||||
...args
|
{
|
||||||
};
|
...args,
|
||||||
|
projectRoot: rootFolder
|
||||||
const operationId = asyncManager.addOperation(addTaskDirect, directArgs, context);
|
},
|
||||||
|
log,
|
||||||
log.info(`Started background operation for add_task. Operation ID: ${operationId}`);
|
{ reportProgress, session }
|
||||||
|
);
|
||||||
return createContentResponse({
|
|
||||||
message: "Add task operation started successfully.",
|
|
||||||
operationId: operationId
|
|
||||||
});
|
|
||||||
|
|
||||||
|
// Return the result
|
||||||
|
return handleApiResult(result, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error initiating add_task operation: ${error.message}`, { stack: error.stack });
|
log.error(`Error in add-task tool: ${error.message}`);
|
||||||
return createErrorResponse(`Failed to start add task operation: ${error.message}`, "ADD_TASK_INIT_ERROR");
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool for analyzing task complexity and generating recommendations
|
* Tool for analyzing task complexity and generating recommendations
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { analyzeTaskComplexityDirect } from "../core/task-master-core.js";
|
import { analyzeTaskComplexityDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the analyze tool with the MCP server
|
* Register the analyze tool with the MCP server
|
||||||
@@ -17,20 +17,48 @@ import { analyzeTaskComplexityDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerAnalyzeTool(server) {
|
export function registerAnalyzeTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "analyze_project_complexity",
|
name: 'analyze_project_complexity',
|
||||||
description: "Analyze task complexity and generate expansion recommendations",
|
description:
|
||||||
|
'Analyze task complexity and generate expansion recommendations',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
output: z.string().optional().describe("Output file path for the report (default: scripts/task-complexity-report.json)"),
|
output: z
|
||||||
model: z.string().optional().describe("LLM model to use for analysis (defaults to configured model)"),
|
.string()
|
||||||
threshold: z.union([z.number(), z.string()]).optional().describe("Minimum complexity score to recommend expansion (1-10) (default: 5)"),
|
.optional()
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
.describe(
|
||||||
research: z.boolean().optional().describe("Use Perplexity AI for research-backed complexity analysis"),
|
'Output file path for the report (default: scripts/task-complexity-report.json)'
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
),
|
||||||
|
model: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'LLM model to use for analysis (defaults to configured model)'
|
||||||
|
),
|
||||||
|
threshold: z
|
||||||
|
.union([z.number(), z.string()])
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Minimum complexity score to recommend expansion (1-10) (default: 5)'
|
||||||
|
),
|
||||||
|
file: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
|
research: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Use Perplexity AI for research-backed complexity analysis'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Analyzing task complexity with args: ${JSON.stringify(args)}`);
|
log.info(
|
||||||
// await reportProgress({ progress: 0 });
|
`Analyzing task complexity with args: ${JSON.stringify(args)}`
|
||||||
|
);
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
@@ -39,18 +67,24 @@ export function registerAnalyzeTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await analyzeTaskComplexityDirect({
|
const result = await analyzeTaskComplexityDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log,
|
||||||
// await reportProgress({ progress: 100 });
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Task complexity analysis complete: ${result.data.message}`);
|
log.info(`Task complexity analysis complete: ${result.data.message}`);
|
||||||
log.info(`Report summary: ${JSON.stringify(result.data.reportSummary)}`);
|
log.info(
|
||||||
|
`Report summary: ${JSON.stringify(result.data.reportSummary)}`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to analyze task complexity: ${result.error.message}`);
|
log.error(
|
||||||
|
`Failed to analyze task complexity: ${result.error.message}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error analyzing task complexity');
|
return handleApiResult(result, log, 'Error analyzing task complexity');
|
||||||
@@ -58,6 +92,6 @@ export function registerAnalyzeTool(server) {
|
|||||||
log.error(`Error in analyze tool: ${error.message}`);
|
log.error(`Error in analyze tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool for clearing subtasks from parent tasks
|
* Tool for clearing subtasks from parent tasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { clearSubtasksDirect } from "../core/task-master-core.js";
|
import { clearSubtasksDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the clearSubtasks tool with the MCP server
|
* Register the clearSubtasks tool with the MCP server
|
||||||
@@ -17,16 +17,29 @@ import { clearSubtasksDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerClearSubtasksTool(server) {
|
export function registerClearSubtasksTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "clear_subtasks",
|
name: 'clear_subtasks',
|
||||||
description: "Clear subtasks from specified tasks",
|
description: 'Clear subtasks from specified tasks',
|
||||||
parameters: z.object({
|
parameters: z
|
||||||
id: z.string().optional().describe("Task IDs (comma-separated) to clear subtasks from"),
|
.object({
|
||||||
all: z.boolean().optional().describe("Clear subtasks from all tasks"),
|
id: z
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
.string()
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
.optional()
|
||||||
}).refine(data => data.id || data.all, {
|
.describe('Task IDs (comma-separated) to clear subtasks from'),
|
||||||
|
all: z.boolean().optional().describe('Clear subtasks from all tasks'),
|
||||||
|
file: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.refine((data) => data.id || data.all, {
|
||||||
message: "Either 'id' or 'all' parameter must be provided",
|
message: "Either 'id' or 'all' parameter must be provided",
|
||||||
path: ["id", "all"]
|
path: ['id', 'all']
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
try {
|
try {
|
||||||
@@ -40,10 +53,14 @@ export function registerClearSubtasksTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await clearSubtasksDirect({
|
const result = await clearSubtasksDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log, { reportProgress, mcpLog: log, session});
|
},
|
||||||
|
log,
|
||||||
|
{ reportProgress, mcpLog: log, session }
|
||||||
|
);
|
||||||
|
|
||||||
reportProgress({ progress: 100 });
|
reportProgress({ progress: 100 });
|
||||||
|
|
||||||
@@ -58,6 +75,6 @@ export function registerClearSubtasksTool(server) {
|
|||||||
log.error(`Error in clearSubtasks tool: ${error.message}`);
|
log.error(`Error in clearSubtasks tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool for displaying the complexity analysis report
|
* Tool for displaying the complexity analysis report
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { complexityReportDirect } from "../core/task-master-core.js";
|
import { complexityReportDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the complexityReport tool with the MCP server
|
* Register the complexityReport tool with the MCP server
|
||||||
@@ -17,15 +17,27 @@ import { complexityReportDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerComplexityReportTool(server) {
|
export function registerComplexityReportTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "complexity_report",
|
name: 'complexity_report',
|
||||||
description: "Display the complexity analysis report in a readable format",
|
description: 'Display the complexity analysis report in a readable format',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
file: z.string().optional().describe("Path to the report file (default: scripts/task-complexity-report.json)"),
|
file: z
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Path to the report file (default: scripts/task-complexity-report.json)'
|
||||||
|
),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Getting complexity report with args: ${JSON.stringify(args)}`);
|
log.info(
|
||||||
|
`Getting complexity report with args: ${JSON.stringify(args)}`
|
||||||
|
);
|
||||||
// await reportProgress({ progress: 0 });
|
// await reportProgress({ progress: 0 });
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
@@ -35,24 +47,37 @@ export function registerComplexityReportTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await complexityReportDirect({
|
const result = await complexityReportDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully retrieved complexity report${result.fromCache ? ' (from cache)' : ''}`);
|
log.info(
|
||||||
|
`Successfully retrieved complexity report${result.fromCache ? ' (from cache)' : ''}`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to retrieve complexity report: ${result.error.message}`);
|
log.error(
|
||||||
|
`Failed to retrieve complexity report: ${result.error.message}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error retrieving complexity report');
|
return handleApiResult(
|
||||||
|
result,
|
||||||
|
log,
|
||||||
|
'Error retrieving complexity report'
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in complexity-report tool: ${error.message}`);
|
log.error(`Error in complexity-report tool: ${error.message}`);
|
||||||
return createErrorResponse(`Failed to retrieve complexity report: ${error.message}`);
|
return createErrorResponse(
|
||||||
|
`Failed to retrieve complexity report: ${error.message}`
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool for expanding all pending tasks with subtasks
|
* Tool for expanding all pending tasks with subtasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { expandAllTasksDirect } from "../core/task-master-core.js";
|
import { expandAllTasksDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the expandAll tool with the MCP server
|
* Register the expandAll tool with the MCP server
|
||||||
@@ -17,20 +17,43 @@ import { expandAllTasksDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerExpandAllTool(server) {
|
export function registerExpandAllTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "expand_all",
|
name: 'expand_all',
|
||||||
description: "Expand all pending tasks into subtasks",
|
description: 'Expand all pending tasks into subtasks',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
num: z.union([z.number(), z.string()]).optional().describe("Number of subtasks to generate for each task"),
|
num: z
|
||||||
research: z.boolean().optional().describe("Enable Perplexity AI for research-backed subtask generation"),
|
.string()
|
||||||
prompt: z.string().optional().describe("Additional context to guide subtask generation"),
|
.optional()
|
||||||
force: z.boolean().optional().describe("Force regeneration of subtasks for tasks that already have them"),
|
.describe('Number of subtasks to generate for each task'),
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
research: z
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Enable Perplexity AI for research-backed subtask generation'
|
||||||
|
),
|
||||||
|
prompt: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Additional context to guide subtask generation'),
|
||||||
|
force: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Force regeneration of subtasks for tasks that already have them'
|
||||||
|
),
|
||||||
|
file: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Expanding all tasks with args: ${JSON.stringify(args)}`);
|
log.info(`Expanding all tasks with args: ${JSON.stringify(args)}`);
|
||||||
// await reportProgress({ progress: 0 });
|
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
@@ -39,17 +62,21 @@ export function registerExpandAllTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await expandAllTasksDirect({
|
const result = await expandAllTasksDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log,
|
||||||
// await reportProgress({ progress: 100 });
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully expanded all tasks: ${result.data.message}`);
|
log.info(`Successfully expanded all tasks: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to expand all tasks: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
|
`Failed to expand all tasks: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error expanding all tasks');
|
return handleApiResult(result, log, 'Error expanding all tasks');
|
||||||
@@ -57,6 +84,6 @@ export function registerExpandAllTool(server) {
|
|||||||
log.error(`Error in expand-all tool: ${error.message}`);
|
log.error(`Error in expand-all tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,15 @@
|
|||||||
* Tool to expand a task into subtasks
|
* Tool to expand a task into subtasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { expandTaskDirect } from "../core/task-master-core.js";
|
import { expandTaskDirect } from '../core/task-master-core.js';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the expand-task tool with the MCP server
|
* Register the expand-task tool with the MCP server
|
||||||
@@ -17,27 +19,35 @@ import { expandTaskDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerExpandTaskTool(server) {
|
export function registerExpandTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "expand_task",
|
name: 'expand_task',
|
||||||
description: "Expand a task into subtasks for detailed implementation",
|
description: 'Expand a task into subtasks for detailed implementation',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("ID of task to expand"),
|
id: z.string().describe('ID of task to expand'),
|
||||||
num: z.union([z.number(), z.string()]).optional().describe("Number of subtasks to generate"),
|
num: z
|
||||||
research: z.boolean().optional().describe("Use Perplexity AI for research-backed generation"),
|
.union([z.string(), z.number()])
|
||||||
prompt: z.string().optional().describe("Additional context for subtask generation"),
|
.optional()
|
||||||
force: z.boolean().optional().describe("Force regeneration even for tasks that already have subtasks"),
|
.describe('Number of subtasks to generate'),
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
research: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Use Perplexity AI for research-backed generation'),
|
||||||
|
prompt: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Additional context for subtask generation'),
|
||||||
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: current working directory)"
|
'Root directory of the project (default: current working directory)'
|
||||||
),
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, reportProgress, session }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Expanding task with args: ${JSON.stringify(args)}`);
|
log.info(`Starting expand-task with args: ${JSON.stringify(args)}`);
|
||||||
// await reportProgress({ progress: 0 });
|
|
||||||
|
|
||||||
|
// Get project root from session
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
@@ -45,24 +55,36 @@ export function registerExpandTaskTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await expandTaskDirect({
|
log.info(`Project root resolved to: ${rootFolder}`);
|
||||||
projectRoot: rootFolder,
|
|
||||||
...args
|
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// Check for tasks.json in the standard locations
|
||||||
|
const tasksJsonPath = path.join(rootFolder, 'tasks', 'tasks.json');
|
||||||
|
|
||||||
if (result.success) {
|
if (fs.existsSync(tasksJsonPath)) {
|
||||||
log.info(`Successfully expanded task with ID ${args.id}`);
|
log.info(`Found tasks.json at ${tasksJsonPath}`);
|
||||||
|
// Add the file parameter directly to args
|
||||||
|
args.file = tasksJsonPath;
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to expand task: ${result.error?.message || 'Unknown error'}`);
|
log.warn(`Could not find tasks.json at ${tasksJsonPath}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Call direct function with only session in the context, not reportProgress
|
||||||
|
// Use the pattern recommended in the MCP guidelines
|
||||||
|
const result = await expandTaskDirect(
|
||||||
|
{
|
||||||
|
...args,
|
||||||
|
projectRoot: rootFolder
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ session }
|
||||||
|
); // Only pass session, NOT reportProgress
|
||||||
|
|
||||||
|
// Return the result
|
||||||
return handleApiResult(result, log, 'Error expanding task');
|
return handleApiResult(result, log, 'Error expanding task');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in expand task tool: ${error.message}`);
|
log.error(`Error in expand task tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool for automatically fixing invalid task dependencies
|
* Tool for automatically fixing invalid task dependencies
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { fixDependenciesDirect } from "../core/task-master-core.js";
|
import { fixDependenciesDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the fixDependencies tool with the MCP server
|
* Register the fixDependencies tool with the MCP server
|
||||||
@@ -17,11 +17,16 @@ import { fixDependenciesDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerFixDependenciesTool(server) {
|
export function registerFixDependenciesTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "fix_dependencies",
|
name: 'fix_dependencies',
|
||||||
description: "Fix invalid dependencies in tasks automatically",
|
description: 'Fix invalid dependencies in tasks automatically',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
try {
|
try {
|
||||||
@@ -35,10 +40,14 @@ export function registerFixDependenciesTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await fixDependenciesDirect({
|
const result = await fixDependenciesDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log, { reportProgress, mcpLog: log, session});
|
},
|
||||||
|
log,
|
||||||
|
{ reportProgress, mcpLog: log, session }
|
||||||
|
);
|
||||||
|
|
||||||
await reportProgress({ progress: 100 });
|
await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool to generate individual task files from tasks.json
|
* Tool to generate individual task files from tasks.json
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { generateTaskFilesDirect } from "../core/task-master-core.js";
|
import { generateTaskFilesDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the generate tool with the MCP server
|
* Register the generate tool with the MCP server
|
||||||
@@ -17,17 +17,21 @@ import { generateTaskFilesDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerGenerateTool(server) {
|
export function registerGenerateTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "generate",
|
name: 'generate',
|
||||||
description: "Generates individual task files in tasks/ directory based on tasks.json",
|
description:
|
||||||
|
'Generates individual task files in tasks/ directory based on tasks.json',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
output: z.string().optional().describe("Output directory (default: same directory as tasks file)"),
|
output: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Output directory (default: same directory as tasks file)'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: current working directory)"
|
'Root directory of the project (default: current working directory)'
|
||||||
),
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
try {
|
try {
|
||||||
@@ -41,17 +45,22 @@ export function registerGenerateTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await generateTaskFilesDirect({
|
const result = await generateTaskFilesDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully generated task files: ${result.data.message}`);
|
log.info(`Successfully generated task files: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to generate task files: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
|
`Failed to generate task files: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error generating task files');
|
return handleApiResult(result, log, 'Error generating task files');
|
||||||
@@ -59,6 +68,6 @@ export function registerGenerateTool(server) {
|
|||||||
log.error(`Error in generate tool: ${error.message}`);
|
log.error(`Error in generate tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -10,9 +10,10 @@ import { createErrorResponse, createContentResponse } from './utils.js'; // Assu
|
|||||||
export function registerGetOperationStatusTool(server, asyncManager) {
|
export function registerGetOperationStatusTool(server, asyncManager) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: 'get_operation_status',
|
name: 'get_operation_status',
|
||||||
description: 'Retrieves the status and result/error of a background operation.',
|
description:
|
||||||
|
'Retrieves the status and result/error of a background operation.',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
operationId: z.string().describe('The ID of the operation to check.'),
|
operationId: z.string().describe('The ID of the operation to check.')
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log }) => {
|
execute: async (args, { log }) => {
|
||||||
try {
|
try {
|
||||||
@@ -32,11 +33,15 @@ export function registerGetOperationStatusTool(server, asyncManager) {
|
|||||||
|
|
||||||
log.info(`Status for ${operationId}: ${status.status}`);
|
log.info(`Status for ${operationId}: ${status.status}`);
|
||||||
return createContentResponse(status);
|
return createContentResponse(status);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in get_operation_status tool: ${error.message}`, { stack: error.stack });
|
log.error(`Error in get_operation_status tool: ${error.message}`, {
|
||||||
return createErrorResponse(`Failed to get operation status: ${error.message}`, 'GET_STATUS_ERROR');
|
stack: error.stack
|
||||||
|
});
|
||||||
|
return createErrorResponse(
|
||||||
|
`Failed to get operation status: ${error.message}`,
|
||||||
|
'GET_STATUS_ERROR'
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool to get task details by ID
|
* Tool to get task details by ID
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { showTaskDirect } from "../core/task-master-core.js";
|
import { showTaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Custom processor function that removes allTasks from the response
|
* Custom processor function that removes allTasks from the response
|
||||||
@@ -35,26 +35,30 @@ function processTaskResponse(data) {
|
|||||||
*/
|
*/
|
||||||
export function registerShowTaskTool(server) {
|
export function registerShowTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "get_task",
|
name: 'get_task',
|
||||||
description: "Get detailed information about a specific task",
|
description: 'Get detailed information about a specific task',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("Task ID to get"),
|
id: z.string().describe('Task ID to get'),
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: current working directory)"
|
'Root directory of the project (default: current working directory)'
|
||||||
),
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
// Log the session right at the start of execute
|
// Log the session right at the start of execute
|
||||||
log.info(`Session object received in execute: ${JSON.stringify(session)}`); // Use JSON.stringify for better visibility
|
log.info(
|
||||||
|
`Session object received in execute: ${JSON.stringify(session)}`
|
||||||
|
); // Use JSON.stringify for better visibility
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Getting task details for ID: ${args.id}`);
|
log.info(`Getting task details for ID: ${args.id}`);
|
||||||
|
|
||||||
log.info(`Session object received in execute: ${JSON.stringify(session)}`); // Use JSON.stringify for better visibility
|
log.info(
|
||||||
|
`Session object received in execute: ${JSON.stringify(session)}`
|
||||||
|
); // Use JSON.stringify for better visibility
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
@@ -64,29 +68,41 @@ export function registerShowTaskTool(server) {
|
|||||||
} else if (!rootFolder) {
|
} else if (!rootFolder) {
|
||||||
// Ensure we always have *some* root, even if session failed and args didn't provide one
|
// Ensure we always have *some* root, even if session failed and args didn't provide one
|
||||||
rootFolder = process.cwd();
|
rootFolder = process.cwd();
|
||||||
log.warn(`Session and args failed to provide root, using CWD: ${rootFolder}`);
|
log.warn(
|
||||||
|
`Session and args failed to provide root, using CWD: ${rootFolder}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Attempting to use project root: ${rootFolder}`); // Log the final resolved root
|
log.info(`Attempting to use project root: ${rootFolder}`); // Log the final resolved root
|
||||||
|
|
||||||
log.info(`Root folder: ${rootFolder}`); // Log the final resolved root
|
log.info(`Root folder: ${rootFolder}`); // Log the final resolved root
|
||||||
const result = await showTaskDirect({
|
const result = await showTaskDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log);
|
},
|
||||||
|
log
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully retrieved task details for ID: ${args.id}${result.fromCache ? ' (from cache)' : ''}`);
|
log.info(
|
||||||
|
`Successfully retrieved task details for ID: ${args.id}${result.fromCache ? ' (from cache)' : ''}`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to get task: ${result.error.message}`);
|
log.error(`Failed to get task: ${result.error.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use our custom processor function to remove allTasks from the response
|
// Use our custom processor function to remove allTasks from the response
|
||||||
return handleApiResult(result, log, 'Error retrieving task details', processTaskResponse);
|
return handleApiResult(
|
||||||
|
result,
|
||||||
|
log,
|
||||||
|
'Error retrieving task details',
|
||||||
|
processTaskResponse
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in get-task tool: ${error.message}\n${error.stack}`); // Add stack trace
|
log.error(`Error in get-task tool: ${error.message}\n${error.stack}`); // Add stack trace
|
||||||
return createErrorResponse(`Failed to get task: ${error.message}`);
|
return createErrorResponse(`Failed to get task: ${error.message}`);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool to get all tasks from Task Master
|
* Tool to get all tasks from Task Master
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { listTasksDirect } from "../core/task-master-core.js";
|
import { listTasksDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the getTasks tool with the MCP server
|
* Register the getTasks tool with the MCP server
|
||||||
@@ -17,21 +17,32 @@ import { listTasksDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerListTasksTool(server) {
|
export function registerListTasksTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "get_tasks",
|
name: 'get_tasks',
|
||||||
description: "Get all tasks from Task Master, optionally filtering by status and including subtasks.",
|
description:
|
||||||
|
'Get all tasks from Task Master, optionally filtering by status and including subtasks.',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
status: z.string().optional().describe("Filter tasks by status (e.g., 'pending', 'done')"),
|
status: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe("Filter tasks by status (e.g., 'pending', 'done')"),
|
||||||
withSubtasks: z
|
withSubtasks: z
|
||||||
.boolean()
|
.boolean()
|
||||||
.optional()
|
.optional()
|
||||||
.describe("Include subtasks nested within their parent tasks in the response"),
|
.describe(
|
||||||
file: z.string().optional().describe("Path to the tasks file (relative to project root or absolute)"),
|
'Include subtasks nested within their parent tasks in the response'
|
||||||
|
),
|
||||||
|
file: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Path to the tasks file (relative to project root or absolute)'
|
||||||
|
),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: automatically detected from session or CWD)"
|
'Root directory of the project (default: automatically detected from session or CWD)'
|
||||||
),
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
try {
|
try {
|
||||||
@@ -45,20 +56,25 @@ export function registerListTasksTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await listTasksDirect({
|
const result = await listTasksDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
log.info(`Retrieved ${result.success ? (result.data?.tasks?.length || 0) : 0} tasks${result.fromCache ? ' (from cache)' : ''}`);
|
log.info(
|
||||||
|
`Retrieved ${result.success ? result.data?.tasks?.length || 0 : 0} tasks${result.fromCache ? ' (from cache)' : ''}`
|
||||||
|
);
|
||||||
return handleApiResult(result, log, 'Error getting tasks');
|
return handleApiResult(result, log, 'Error getting tasks');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error getting tasks: ${error.message}`);
|
log.error(`Error getting tasks: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,32 +3,31 @@
|
|||||||
* Export all Task Master CLI tools for MCP server
|
* Export all Task Master CLI tools for MCP server
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { registerListTasksTool } from "./get-tasks.js";
|
import { registerListTasksTool } from './get-tasks.js';
|
||||||
import logger from "../logger.js";
|
import logger from '../logger.js';
|
||||||
import { registerSetTaskStatusTool } from "./set-task-status.js";
|
import { registerSetTaskStatusTool } from './set-task-status.js';
|
||||||
import { registerParsePRDTool } from "./parse-prd.js";
|
import { registerParsePRDTool } from './parse-prd.js';
|
||||||
import { registerUpdateTool } from "./update.js";
|
import { registerUpdateTool } from './update.js';
|
||||||
import { registerUpdateTaskTool } from "./update-task.js";
|
import { registerUpdateTaskTool } from './update-task.js';
|
||||||
import { registerUpdateSubtaskTool } from "./update-subtask.js";
|
import { registerUpdateSubtaskTool } from './update-subtask.js';
|
||||||
import { registerGenerateTool } from "./generate.js";
|
import { registerGenerateTool } from './generate.js';
|
||||||
import { registerShowTaskTool } from "./get-task.js";
|
import { registerShowTaskTool } from './get-task.js';
|
||||||
import { registerNextTaskTool } from "./next-task.js";
|
import { registerNextTaskTool } from './next-task.js';
|
||||||
import { registerExpandTaskTool } from "./expand-task.js";
|
import { registerExpandTaskTool } from './expand-task.js';
|
||||||
import { registerAddTaskTool } from "./add-task.js";
|
import { registerAddTaskTool } from './add-task.js';
|
||||||
import { registerAddSubtaskTool } from "./add-subtask.js";
|
import { registerAddSubtaskTool } from './add-subtask.js';
|
||||||
import { registerRemoveSubtaskTool } from "./remove-subtask.js";
|
import { registerRemoveSubtaskTool } from './remove-subtask.js';
|
||||||
import { registerAnalyzeTool } from "./analyze.js";
|
import { registerAnalyzeTool } from './analyze.js';
|
||||||
import { registerClearSubtasksTool } from "./clear-subtasks.js";
|
import { registerClearSubtasksTool } from './clear-subtasks.js';
|
||||||
import { registerExpandAllTool } from "./expand-all.js";
|
import { registerExpandAllTool } from './expand-all.js';
|
||||||
import { registerRemoveDependencyTool } from "./remove-dependency.js";
|
import { registerRemoveDependencyTool } from './remove-dependency.js';
|
||||||
import { registerValidateDependenciesTool } from "./validate-dependencies.js";
|
import { registerValidateDependenciesTool } from './validate-dependencies.js';
|
||||||
import { registerFixDependenciesTool } from "./fix-dependencies.js";
|
import { registerFixDependenciesTool } from './fix-dependencies.js';
|
||||||
import { registerComplexityReportTool } from "./complexity-report.js";
|
import { registerComplexityReportTool } from './complexity-report.js';
|
||||||
import { registerAddDependencyTool } from "./add-dependency.js";
|
import { registerAddDependencyTool } from './add-dependency.js';
|
||||||
import { registerRemoveTaskTool } from './remove-task.js';
|
import { registerRemoveTaskTool } from './remove-task.js';
|
||||||
import { registerInitializeProjectTool } from './initialize-project.js';
|
import { registerInitializeProjectTool } from './initialize-project.js';
|
||||||
import { asyncOperationManager } from '../core/utils/async-manager.js';
|
import { asyncOperationManager } from '../core/utils/async-manager.js';
|
||||||
import { registerGetOperationStatusTool } from './get-operation-status.js';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register all Task Master tools with the MCP server
|
* Register all Task Master tools with the MCP server
|
||||||
@@ -61,7 +60,6 @@ export function registerTaskMasterTools(server, asyncManager) {
|
|||||||
registerAddDependencyTool(server);
|
registerAddDependencyTool(server);
|
||||||
registerRemoveTaskTool(server);
|
registerRemoveTaskTool(server);
|
||||||
registerInitializeProjectTool(server);
|
registerInitializeProjectTool(server);
|
||||||
registerGetOperationStatusTool(server, asyncManager);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(`Error registering Task Master tools: ${error.message}`);
|
logger.error(`Error registering Task Master tools: ${error.message}`);
|
||||||
throw error;
|
throw error;
|
||||||
@@ -71,5 +69,5 @@ export function registerTaskMasterTools(server, asyncManager) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
registerTaskMasterTools,
|
registerTaskMasterTools
|
||||||
};
|
};
|
||||||
@@ -1,33 +1,66 @@
|
|||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import { execSync } from 'child_process';
|
import { execSync } from 'child_process';
|
||||||
import { createContentResponse, createErrorResponse } from "./utils.js"; // Only need response creators
|
import { createContentResponse, createErrorResponse } from './utils.js'; // Only need response creators
|
||||||
|
|
||||||
export function registerInitializeProjectTool(server) {
|
export function registerInitializeProjectTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "initialize_project", // snake_case for tool name
|
name: 'initialize_project', // snake_case for tool name
|
||||||
description: "Initializes a new Task Master project structure in the current working directory by running 'task-master init'.",
|
description:
|
||||||
|
"Initializes a new Task Master project structure in the current working directory by running 'task-master init'.",
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
projectName: z.string().optional().describe("The name for the new project."),
|
projectName: z
|
||||||
projectDescription: z.string().optional().describe("A brief description for the project."),
|
.string()
|
||||||
projectVersion: z.string().optional().describe("The initial version for the project (e.g., '0.1.0')."),
|
.optional()
|
||||||
|
.describe('The name for the new project.'),
|
||||||
|
projectDescription: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('A brief description for the project.'),
|
||||||
|
projectVersion: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe("The initial version for the project (e.g., '0.1.0')."),
|
||||||
authorName: z.string().optional().describe("The author's name."),
|
authorName: z.string().optional().describe("The author's name."),
|
||||||
skipInstall: z.boolean().optional().default(false).describe("Skip installing dependencies automatically."),
|
skipInstall: z
|
||||||
addAliases: z.boolean().optional().default(false).describe("Add shell aliases (tm, taskmaster) to shell config file."),
|
.boolean()
|
||||||
yes: z.boolean().optional().default(false).describe("Skip prompts and use default values or provided arguments."),
|
.optional()
|
||||||
|
.default(false)
|
||||||
|
.describe('Skip installing dependencies automatically.'),
|
||||||
|
addAliases: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.default(false)
|
||||||
|
.describe('Add shell aliases (tm, taskmaster) to shell config file.'),
|
||||||
|
yes: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.default(false)
|
||||||
|
.describe('Skip prompts and use default values or provided arguments.')
|
||||||
// projectRoot is not needed here as 'init' works on the current directory
|
// projectRoot is not needed here as 'init' works on the current directory
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log }) => { // Destructure context to get log
|
execute: async (args, { log }) => {
|
||||||
|
// Destructure context to get log
|
||||||
try {
|
try {
|
||||||
log.info(`Executing initialize_project with args: ${JSON.stringify(args)}`);
|
log.info(
|
||||||
|
`Executing initialize_project with args: ${JSON.stringify(args)}`
|
||||||
|
);
|
||||||
|
|
||||||
// Construct the command arguments carefully
|
// Construct the command arguments carefully
|
||||||
// Using npx ensures it uses the locally installed version if available, or fetches it
|
// Using npx ensures it uses the locally installed version if available, or fetches it
|
||||||
let command = 'npx task-master init';
|
let command = 'npx task-master init';
|
||||||
const cliArgs = [];
|
const cliArgs = [];
|
||||||
if (args.projectName) cliArgs.push(`--name "${args.projectName.replace(/"/g, '\\"')}"`); // Escape quotes
|
if (args.projectName)
|
||||||
if (args.projectDescription) cliArgs.push(`--description "${args.projectDescription.replace(/"/g, '\\"')}"`);
|
cliArgs.push(`--name "${args.projectName.replace(/"/g, '\\"')}"`); // Escape quotes
|
||||||
if (args.projectVersion) cliArgs.push(`--version "${args.projectVersion.replace(/"/g, '\\"')}"`);
|
if (args.projectDescription)
|
||||||
if (args.authorName) cliArgs.push(`--author "${args.authorName.replace(/"/g, '\\"')}"`);
|
cliArgs.push(
|
||||||
|
`--description "${args.projectDescription.replace(/"/g, '\\"')}"`
|
||||||
|
);
|
||||||
|
if (args.projectVersion)
|
||||||
|
cliArgs.push(
|
||||||
|
`--version "${args.projectVersion.replace(/"/g, '\\"')}"`
|
||||||
|
);
|
||||||
|
if (args.authorName)
|
||||||
|
cliArgs.push(`--author "${args.authorName.replace(/"/g, '\\"')}"`);
|
||||||
if (args.skipInstall) cliArgs.push('--skip-install');
|
if (args.skipInstall) cliArgs.push('--skip-install');
|
||||||
if (args.addAliases) cliArgs.push('--aliases');
|
if (args.addAliases) cliArgs.push('--aliases');
|
||||||
if (args.yes) cliArgs.push('--yes');
|
if (args.yes) cliArgs.push('--yes');
|
||||||
@@ -38,20 +71,24 @@ export function registerInitializeProjectTool(server) {
|
|||||||
|
|
||||||
// Execute the command in the current working directory of the server process
|
// Execute the command in the current working directory of the server process
|
||||||
// Capture stdout/stderr. Use a reasonable timeout (e.g., 5 minutes)
|
// Capture stdout/stderr. Use a reasonable timeout (e.g., 5 minutes)
|
||||||
const output = execSync(command, { encoding: 'utf8', stdio: 'pipe', timeout: 300000 });
|
const output = execSync(command, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
stdio: 'pipe',
|
||||||
|
timeout: 300000
|
||||||
|
});
|
||||||
|
|
||||||
log.info(`Initialization output:\n${output}`);
|
log.info(`Initialization output:\n${output}`);
|
||||||
|
|
||||||
// Return a standard success response manually
|
// Return a standard success response manually
|
||||||
return createContentResponse(
|
return createContentResponse(
|
||||||
"Project initialized successfully.",
|
'Project initialized successfully.',
|
||||||
{ output: output } // Include output in the data payload
|
{ output: output } // Include output in the data payload
|
||||||
);
|
);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Catch errors from execSync or timeouts
|
// Catch errors from execSync or timeouts
|
||||||
const errorMessage = `Project initialization failed: ${error.message}`;
|
const errorMessage = `Project initialization failed: ${error.message}`;
|
||||||
const errorDetails = error.stderr?.toString() || error.stdout?.toString() || error.message; // Provide stderr/stdout if available
|
const errorDetails =
|
||||||
|
error.stderr?.toString() || error.stdout?.toString() || error.message; // Provide stderr/stdout if available
|
||||||
log.error(`${errorMessage}\nDetails: ${errorDetails}`);
|
log.error(`${errorMessage}\nDetails: ${errorDetails}`);
|
||||||
|
|
||||||
// Return a standard error response manually
|
// Return a standard error response manually
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool to find the next task to work on
|
* Tool to find the next task to work on
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { nextTaskDirect } from "../core/task-master-core.js";
|
import { nextTaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the next-task tool with the MCP server
|
* Register the next-task tool with the MCP server
|
||||||
@@ -17,16 +17,17 @@ import { nextTaskDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerNextTaskTool(server) {
|
export function registerNextTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "next_task",
|
name: 'next_task',
|
||||||
description: "Find the next task to work on based on dependencies and status",
|
description:
|
||||||
|
'Find the next task to work on based on dependencies and status',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: current working directory)"
|
'Root directory of the project (default: current working directory)'
|
||||||
),
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
try {
|
try {
|
||||||
@@ -40,17 +41,24 @@ export function registerNextTaskTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await nextTaskDirect({
|
const result = await nextTaskDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully found next task: ${result.data?.task?.id || 'No available tasks'}`);
|
log.info(
|
||||||
|
`Successfully found next task: ${result.data?.task?.id || 'No available tasks'}`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to find next task: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
|
`Failed to find next task: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error finding next task');
|
return handleApiResult(result, log, 'Error finding next task');
|
||||||
@@ -58,6 +66,6 @@ export function registerNextTaskTool(server) {
|
|||||||
log.error(`Error in nextTask tool: ${error.message}`);
|
log.error(`Error in nextTask tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool to parse PRD document and generate tasks
|
* Tool to parse PRD document and generate tasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { parsePRDDirect } from "../core/task-master-core.js";
|
import { parsePRDDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the parsePRD tool with the MCP server
|
* Register the parsePRD tool with the MCP server
|
||||||
@@ -17,21 +17,40 @@ import { parsePRDDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerParsePRDTool(server) {
|
export function registerParsePRDTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "parse_prd",
|
name: 'parse_prd',
|
||||||
description: "Parse a Product Requirements Document (PRD) or text file to automatically generate initial tasks.",
|
description:
|
||||||
|
'Parse a Product Requirements Document (PRD) or text file to automatically generate initial tasks.',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
input: z.string().default("tasks/tasks.json").describe("Path to the PRD document file (relative to project root or absolute)"),
|
input: z
|
||||||
numTasks: z.string().optional().describe("Approximate number of top-level tasks to generate (default: 10)"),
|
.string()
|
||||||
output: z.string().optional().describe("Output path for tasks.json file (relative to project root or absolute, default: tasks/tasks.json)"),
|
.default('tasks/tasks.json')
|
||||||
force: z.boolean().optional().describe("Allow overwriting an existing tasks.json file."),
|
.describe(
|
||||||
|
'Path to the PRD document file (relative to project root or absolute)'
|
||||||
|
),
|
||||||
|
numTasks: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Approximate number of top-level tasks to generate (default: 10)'
|
||||||
|
),
|
||||||
|
output: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Output path for tasks.json file (relative to project root or absolute, default: tasks/tasks.json)'
|
||||||
|
),
|
||||||
|
force: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Allow overwriting an existing tasks.json file.'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: automatically detected from session or CWD)"
|
'Root directory of the project (default: automatically detected from session or CWD)'
|
||||||
),
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Parsing PRD with args: ${JSON.stringify(args)}`);
|
log.info(`Parsing PRD with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
@@ -42,17 +61,21 @@ export function registerParsePRDTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await parsePRDDirect({
|
const result = await parsePRDDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log,
|
||||||
// await reportProgress({ progress: 100 });
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully parsed PRD: ${result.data.message}`);
|
log.info(`Successfully parsed PRD: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to parse PRD: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
|
`Failed to parse PRD: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error parsing PRD');
|
return handleApiResult(result, log, 'Error parsing PRD');
|
||||||
@@ -60,6 +83,6 @@ export function registerParsePRDTool(server) {
|
|||||||
log.error(`Error in parse-prd tool: ${error.message}`);
|
log.error(`Error in parse-prd tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool for removing a dependency from a task
|
* Tool for removing a dependency from a task
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { removeDependencyDirect } from "../core/task-master-core.js";
|
import { removeDependencyDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the removeDependency tool with the MCP server
|
* Register the removeDependency tool with the MCP server
|
||||||
@@ -17,17 +17,27 @@ import { removeDependencyDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerRemoveDependencyTool(server) {
|
export function registerRemoveDependencyTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "remove_dependency",
|
name: 'remove_dependency',
|
||||||
description: "Remove a dependency from a task",
|
description: 'Remove a dependency from a task',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("Task ID to remove dependency from"),
|
id: z.string().describe('Task ID to remove dependency from'),
|
||||||
dependsOn: z.string().describe("Task ID to remove as a dependency"),
|
dependsOn: z.string().describe('Task ID to remove as a dependency'),
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
file: z
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Removing dependency for task ${args.id} from ${args.dependsOn} with args: ${JSON.stringify(args)}`);
|
log.info(
|
||||||
|
`Removing dependency for task ${args.id} from ${args.dependsOn} with args: ${JSON.stringify(args)}`
|
||||||
|
);
|
||||||
// await reportProgress({ progress: 0 });
|
// await reportProgress({ progress: 0 });
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
@@ -37,10 +47,13 @@ export function registerRemoveDependencyTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await removeDependencyDirect({
|
const result = await removeDependencyDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool for removing subtasks from parent tasks
|
* Tool for removing subtasks from parent tasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { removeSubtaskDirect } from "../core/task-master-core.js";
|
import { removeSubtaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the removeSubtask tool with the MCP server
|
* Register the removeSubtask tool with the MCP server
|
||||||
@@ -17,14 +17,34 @@ import { removeSubtaskDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerRemoveSubtaskTool(server) {
|
export function registerRemoveSubtaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "remove_subtask",
|
name: 'remove_subtask',
|
||||||
description: "Remove a subtask from its parent task",
|
description: 'Remove a subtask from its parent task',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("Subtask ID to remove in format 'parentId.subtaskId' (required)"),
|
id: z
|
||||||
convert: z.boolean().optional().describe("Convert the subtask to a standalone task instead of deleting it"),
|
.string()
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
.describe(
|
||||||
skipGenerate: z.boolean().optional().describe("Skip regenerating task files"),
|
"Subtask ID to remove in format 'parentId.subtaskId' (required)"
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
),
|
||||||
|
convert: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Convert the subtask to a standalone task instead of deleting it'
|
||||||
|
),
|
||||||
|
file: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
|
skipGenerate: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Skip regenerating task files'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
try {
|
try {
|
||||||
@@ -38,10 +58,13 @@ export function registerRemoveSubtaskTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await removeSubtaskDirect({
|
const result = await removeSubtaskDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
@@ -56,6 +79,6 @@ export function registerRemoveSubtaskTool(server) {
|
|||||||
log.error(`Error in removeSubtask tool: ${error.message}`);
|
log.error(`Error in removeSubtask tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool to remove a task by ID
|
* Tool to remove a task by ID
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { removeTaskDirect } from "../core/task-master-core.js";
|
import { removeTaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the remove-task tool with the MCP server
|
* Register the remove-task tool with the MCP server
|
||||||
@@ -17,18 +17,23 @@ import { removeTaskDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerRemoveTaskTool(server) {
|
export function registerRemoveTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "remove_task",
|
name: 'remove_task',
|
||||||
description: "Remove a task or subtask permanently from the tasks list",
|
description: 'Remove a task or subtask permanently from the tasks list',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("ID of the task or subtask to remove (e.g., '5' or '5.2')"),
|
id: z
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
.string()
|
||||||
|
.describe("ID of the task or subtask to remove (e.g., '5' or '5.2')"),
|
||||||
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: current working directory)"
|
'Root directory of the project (default: current working directory)'
|
||||||
),
|
),
|
||||||
confirm: z.boolean().optional().describe("Whether to skip confirmation prompt (default: false)")
|
confirm: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Whether to skip confirmation prompt (default: false)')
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session }) => {
|
execute: async (args, { log, session }) => {
|
||||||
try {
|
try {
|
||||||
@@ -43,17 +48,22 @@ export function registerRemoveTaskTool(server) {
|
|||||||
} else if (!rootFolder) {
|
} else if (!rootFolder) {
|
||||||
// Ensure we have a default if nothing else works
|
// Ensure we have a default if nothing else works
|
||||||
rootFolder = process.cwd();
|
rootFolder = process.cwd();
|
||||||
log.warn(`Session and args failed to provide root, using CWD: ${rootFolder}`);
|
log.warn(
|
||||||
|
`Session and args failed to provide root, using CWD: ${rootFolder}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Using project root: ${rootFolder}`);
|
log.info(`Using project root: ${rootFolder}`);
|
||||||
|
|
||||||
// Assume client has already handled confirmation if needed
|
// Assume client has already handled confirmation if needed
|
||||||
const result = await removeTaskDirect({
|
const result = await removeTaskDirect(
|
||||||
|
{
|
||||||
id: args.id,
|
id: args.id,
|
||||||
file: args.file,
|
file: args.file,
|
||||||
projectRoot: rootFolder
|
projectRoot: rootFolder
|
||||||
}, log);
|
},
|
||||||
|
log
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully removed task: ${args.id}`);
|
log.info(`Successfully removed task: ${args.id}`);
|
||||||
@@ -66,6 +76,6 @@ export function registerRemoveTaskTool(server) {
|
|||||||
log.error(`Error in remove-task tool: ${error.message}`);
|
log.error(`Error in remove-task tool: ${error.message}`);
|
||||||
return createErrorResponse(`Failed to remove task: ${error.message}`);
|
return createErrorResponse(`Failed to remove task: ${error.message}`);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool to set the status of a task
|
* Tool to set the status of a task
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { setTaskStatusDirect } from "../core/task-master-core.js";
|
import { setTaskStatusDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the setTaskStatus tool with the MCP server
|
* Register the setTaskStatus tool with the MCP server
|
||||||
@@ -17,28 +17,32 @@ import { setTaskStatusDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerSetTaskStatusTool(server) {
|
export function registerSetTaskStatusTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "set_task_status",
|
name: 'set_task_status',
|
||||||
description: "Set the status of one or more tasks or subtasks.",
|
description: 'Set the status of one or more tasks or subtasks.',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z
|
id: z
|
||||||
.string()
|
.string()
|
||||||
.describe("Task ID or subtask ID (e.g., '15', '15.2'). Can be comma-separated for multiple updates."),
|
.describe(
|
||||||
|
"Task ID or subtask ID (e.g., '15', '15.2'). Can be comma-separated for multiple updates."
|
||||||
|
),
|
||||||
status: z
|
status: z
|
||||||
.string()
|
.string()
|
||||||
.describe("New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."),
|
.describe(
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
"New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."
|
||||||
|
),
|
||||||
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: automatically detected)"
|
'Root directory of the project (default: automatically detected)'
|
||||||
),
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Setting status of task(s) ${args.id} to: ${args.status}`);
|
log.info(`Setting status of task(s) ${args.id} to: ${args.status}`);
|
||||||
// await reportProgress({ progress: 0 });
|
|
||||||
|
|
||||||
|
// Get project root from session
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
@@ -46,24 +50,34 @@ export function registerSetTaskStatusTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await setTaskStatusDirect({
|
// Call the direct function with the project root
|
||||||
projectRoot: rootFolder,
|
const result = await setTaskStatusDirect(
|
||||||
...args
|
{
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
...args,
|
||||||
|
projectRoot: rootFolder
|
||||||
// await reportProgress({ progress: 100 });
|
},
|
||||||
|
log
|
||||||
|
);
|
||||||
|
|
||||||
|
// Log the result
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully updated status for task(s) ${args.id} to "${args.status}": ${result.data.message}`);
|
log.info(
|
||||||
|
`Successfully updated status for task(s) ${args.id} to "${args.status}": ${result.data.message}`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to update task status: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
|
`Failed to update task status: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Format and return the result
|
||||||
return handleApiResult(result, log, 'Error setting task status');
|
return handleApiResult(result, log, 'Error setting task status');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in setTaskStatus tool: ${error.message}`);
|
log.error(`Error in setTaskStatus tool: ${error.message}`);
|
||||||
return createErrorResponse(`Error setting task status: ${error.message}`);
|
return createErrorResponse(
|
||||||
|
`Error setting task status: ${error.message}`
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool to append additional information to a specific subtask
|
* Tool to append additional information to a specific subtask
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { updateSubtaskByIdDirect } from "../core/task-master-core.js";
|
import { updateSubtaskByIdDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the update-subtask tool with the MCP server
|
* Register the update-subtask tool with the MCP server
|
||||||
@@ -17,24 +17,31 @@ import { updateSubtaskByIdDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerUpdateSubtaskTool(server) {
|
export function registerUpdateSubtaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "update_subtask",
|
name: 'update_subtask',
|
||||||
description: "Appends additional information to a specific subtask without replacing existing content",
|
description:
|
||||||
|
'Appends additional information to a specific subtask without replacing existing content',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("ID of the subtask to update in format \"parentId.subtaskId\" (e.g., \"5.2\")"),
|
id: z
|
||||||
prompt: z.string().describe("Information to add to the subtask"),
|
.string()
|
||||||
research: z.boolean().optional().describe("Use Perplexity AI for research-backed updates"),
|
.describe(
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
'ID of the subtask to update in format "parentId.subtaskId" (e.g., "5.2")'
|
||||||
|
),
|
||||||
|
prompt: z.string().describe('Information to add to the subtask'),
|
||||||
|
research: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Use Perplexity AI for research-backed updates'),
|
||||||
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: current working directory)"
|
'Root directory of the project (default: current working directory)'
|
||||||
),
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
||||||
// await reportProgress({ progress: 0 });
|
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
@@ -43,17 +50,21 @@ export function registerUpdateSubtaskTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await updateSubtaskByIdDirect({
|
const result = await updateSubtaskByIdDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log,
|
||||||
// await reportProgress({ progress: 100 });
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully updated subtask with ID ${args.id}`);
|
log.info(`Successfully updated subtask with ID ${args.id}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to update subtask: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
|
`Failed to update subtask: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error updating subtask');
|
return handleApiResult(result, log, 'Error updating subtask');
|
||||||
@@ -61,6 +72,6 @@ export function registerUpdateSubtaskTool(server) {
|
|||||||
log.error(`Error in update_subtask tool: ${error.message}`);
|
log.error(`Error in update_subtask tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool to update a single task by ID with new information
|
* Tool to update a single task by ID with new information
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { updateTaskByIdDirect } from "../core/task-master-core.js";
|
import { updateTaskByIdDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the update-task tool with the MCP server
|
* Register the update-task tool with the MCP server
|
||||||
@@ -17,24 +17,31 @@ import { updateTaskByIdDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerUpdateTaskTool(server) {
|
export function registerUpdateTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "update_task",
|
name: 'update_task',
|
||||||
description: "Updates a single task by ID with new information or context provided in the prompt.",
|
description:
|
||||||
|
'Updates a single task by ID with new information or context provided in the prompt.',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.union([z.number(), z.string()]).describe("ID of the task or subtask (e.g., '15', '15.2') to update"),
|
id: z
|
||||||
prompt: z.string().describe("New information or context to incorporate into the task"),
|
.string()
|
||||||
research: z.boolean().optional().describe("Use Perplexity AI for research-backed updates"),
|
.describe("ID of the task or subtask (e.g., '15', '15.2') to update"),
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
prompt: z
|
||||||
|
.string()
|
||||||
|
.describe('New information or context to incorporate into the task'),
|
||||||
|
research: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Use Perplexity AI for research-backed updates'),
|
||||||
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: current working directory)"
|
'Root directory of the project (default: current working directory)'
|
||||||
),
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
||||||
// await reportProgress({ progress: 0 });
|
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
@@ -43,17 +50,21 @@ export function registerUpdateTaskTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await updateTaskByIdDirect({
|
const result = await updateTaskByIdDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log,
|
||||||
// await reportProgress({ progress: 100 });
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully updated task with ID ${args.id}`);
|
log.info(`Successfully updated task with ID ${args.id}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to update task: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
|
`Failed to update task: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error updating task');
|
return handleApiResult(result, log, 'Error updating task');
|
||||||
@@ -61,6 +72,6 @@ export function registerUpdateTaskTool(server) {
|
|||||||
log.error(`Error in update_task tool: ${error.message}`);
|
log.error(`Error in update_task tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool to update tasks based on new context/prompt
|
* Tool to update tasks based on new context/prompt
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { updateTasksDirect } from "../core/task-master-core.js";
|
import { updateTasksDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the update tool with the MCP server
|
* Register the update tool with the MCP server
|
||||||
@@ -17,24 +17,33 @@ import { updateTasksDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerUpdateTool(server) {
|
export function registerUpdateTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "update",
|
name: 'update',
|
||||||
description: "Update multiple upcoming tasks (with ID >= 'from' ID) based on new context or changes provided in the prompt.",
|
description:
|
||||||
|
"Update multiple upcoming tasks (with ID >= 'from' ID) based on new context or changes provided in the prompt. Use 'update_task' instead for a single specific task.",
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
from: z.union([z.number(), z.string()]).describe("Task ID from which to start updating (inclusive)"),
|
from: z
|
||||||
prompt: z.string().describe("Explanation of changes or new context to apply"),
|
.string()
|
||||||
research: z.boolean().optional().describe("Use Perplexity AI for research-backed updates"),
|
.describe(
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
"Task ID from which to start updating (inclusive). IMPORTANT: This tool uses 'from', not 'id'"
|
||||||
|
),
|
||||||
|
prompt: z
|
||||||
|
.string()
|
||||||
|
.describe('Explanation of changes or new context to apply'),
|
||||||
|
research: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Use Perplexity AI for research-backed updates'),
|
||||||
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: current working directory)"
|
'Root directory of the project (default: current working directory)'
|
||||||
),
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Updating tasks with args: ${JSON.stringify(args)}`);
|
log.info(`Updating tasks with args: ${JSON.stringify(args)}`);
|
||||||
// await reportProgress({ progress: 0 });
|
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
@@ -43,17 +52,23 @@ export function registerUpdateTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await updateTasksDirect({
|
const result = await updateTasksDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
},
|
||||||
|
log,
|
||||||
// await reportProgress({ progress: 100 });
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully updated tasks from ID ${args.from}: ${result.data.message}`);
|
log.info(
|
||||||
|
`Successfully updated tasks from ID ${args.from}: ${result.data.message}`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to update tasks: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
|
`Failed to update tasks: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error updating tasks');
|
return handleApiResult(result, log, 'Error updating tasks');
|
||||||
@@ -61,6 +76,6 @@ export function registerUpdateTool(server) {
|
|||||||
log.error(`Error in update tool: ${error.message}`);
|
log.error(`Error in update tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,16 @@
|
|||||||
* Utility functions for Task Master CLI integration
|
* Utility functions for Task Master CLI integration
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { spawnSync } from "child_process";
|
import { spawnSync } from 'child_process';
|
||||||
import path from "path";
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { contextManager } from '../core/context-manager.js'; // Import the singleton
|
import { contextManager } from '../core/context-manager.js'; // Import the singleton
|
||||||
|
|
||||||
// Import path utilities to ensure consistent path resolution
|
// Import path utilities to ensure consistent path resolution
|
||||||
import { lastFoundProjectRoot, PROJECT_MARKERS } from '../core/utils/path-utils.js';
|
import {
|
||||||
|
lastFoundProjectRoot,
|
||||||
|
PROJECT_MARKERS
|
||||||
|
} from '../core/utils/path-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get normalized project root path
|
* Get normalized project root path
|
||||||
@@ -31,7 +34,9 @@ function getProjectRoot(projectRootRaw, log) {
|
|||||||
const absolutePath = path.isAbsolute(envRoot)
|
const absolutePath = path.isAbsolute(envRoot)
|
||||||
? envRoot
|
? envRoot
|
||||||
: path.resolve(process.cwd(), envRoot);
|
: path.resolve(process.cwd(), envRoot);
|
||||||
log.info(`Using project root from TASK_MASTER_PROJECT_ROOT environment variable: ${absolutePath}`);
|
log.info(
|
||||||
|
`Using project root from TASK_MASTER_PROJECT_ROOT environment variable: ${absolutePath}`
|
||||||
|
);
|
||||||
return absolutePath;
|
return absolutePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,23 +52,33 @@ function getProjectRoot(projectRootRaw, log) {
|
|||||||
|
|
||||||
// 3. If we have a last found project root from a tasks.json search, use that for consistency
|
// 3. If we have a last found project root from a tasks.json search, use that for consistency
|
||||||
if (lastFoundProjectRoot) {
|
if (lastFoundProjectRoot) {
|
||||||
log.info(`Using last known project root where tasks.json was found: ${lastFoundProjectRoot}`);
|
log.info(
|
||||||
|
`Using last known project root where tasks.json was found: ${lastFoundProjectRoot}`
|
||||||
|
);
|
||||||
return lastFoundProjectRoot;
|
return lastFoundProjectRoot;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Check if the current directory has any indicators of being a task-master project
|
// 4. Check if the current directory has any indicators of being a task-master project
|
||||||
const currentDir = process.cwd();
|
const currentDir = process.cwd();
|
||||||
if (PROJECT_MARKERS.some(marker => {
|
if (
|
||||||
|
PROJECT_MARKERS.some((marker) => {
|
||||||
const markerPath = path.join(currentDir, marker);
|
const markerPath = path.join(currentDir, marker);
|
||||||
return fs.existsSync(markerPath);
|
return fs.existsSync(markerPath);
|
||||||
})) {
|
})
|
||||||
log.info(`Using current directory as project root (found project markers): ${currentDir}`);
|
) {
|
||||||
|
log.info(
|
||||||
|
`Using current directory as project root (found project markers): ${currentDir}`
|
||||||
|
);
|
||||||
return currentDir;
|
return currentDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Default to current working directory but warn the user
|
// 5. Default to current working directory but warn the user
|
||||||
log.warn(`No task-master project detected in current directory. Using ${currentDir} as project root.`);
|
log.warn(
|
||||||
log.warn('Consider using --project-root to specify the correct project location or set TASK_MASTER_PROJECT_ROOT environment variable.');
|
`No task-master project detected in current directory. Using ${currentDir} as project root.`
|
||||||
|
);
|
||||||
|
log.warn(
|
||||||
|
'Consider using --project-root to specify the correct project location or set TASK_MASTER_PROJECT_ROOT environment variable.'
|
||||||
|
);
|
||||||
return currentDir;
|
return currentDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,21 +90,45 @@ function getProjectRoot(projectRootRaw, log) {
|
|||||||
*/
|
*/
|
||||||
function getProjectRootFromSession(session, log) {
|
function getProjectRootFromSession(session, log) {
|
||||||
try {
|
try {
|
||||||
|
// Add detailed logging of session structure
|
||||||
|
log.info(
|
||||||
|
`Session object: ${JSON.stringify({
|
||||||
|
hasSession: !!session,
|
||||||
|
hasRoots: !!session?.roots,
|
||||||
|
rootsType: typeof session?.roots,
|
||||||
|
isRootsArray: Array.isArray(session?.roots),
|
||||||
|
rootsLength: session?.roots?.length,
|
||||||
|
firstRoot: session?.roots?.[0],
|
||||||
|
hasRootsRoots: !!session?.roots?.roots,
|
||||||
|
rootsRootsType: typeof session?.roots?.roots,
|
||||||
|
isRootsRootsArray: Array.isArray(session?.roots?.roots),
|
||||||
|
rootsRootsLength: session?.roots?.roots?.length,
|
||||||
|
firstRootsRoot: session?.roots?.roots?.[0]
|
||||||
|
})}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// ALWAYS ensure we return a valid path for project root
|
||||||
|
const cwd = process.cwd();
|
||||||
|
|
||||||
// If we have a session with roots array
|
// If we have a session with roots array
|
||||||
if (session?.roots?.[0]?.uri) {
|
if (session?.roots?.[0]?.uri) {
|
||||||
const rootUri = session.roots[0].uri;
|
const rootUri = session.roots[0].uri;
|
||||||
|
log.info(`Found rootUri in session.roots[0].uri: ${rootUri}`);
|
||||||
const rootPath = rootUri.startsWith('file://')
|
const rootPath = rootUri.startsWith('file://')
|
||||||
? decodeURIComponent(rootUri.slice(7))
|
? decodeURIComponent(rootUri.slice(7))
|
||||||
: rootUri;
|
: rootUri;
|
||||||
|
log.info(`Decoded rootPath: ${rootPath}`);
|
||||||
return rootPath;
|
return rootPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we have a session with roots.roots array (different structure)
|
// If we have a session with roots.roots array (different structure)
|
||||||
if (session?.roots?.roots?.[0]?.uri) {
|
if (session?.roots?.roots?.[0]?.uri) {
|
||||||
const rootUri = session.roots.roots[0].uri;
|
const rootUri = session.roots.roots[0].uri;
|
||||||
|
log.info(`Found rootUri in session.roots.roots[0].uri: ${rootUri}`);
|
||||||
const rootPath = rootUri.startsWith('file://')
|
const rootPath = rootUri.startsWith('file://')
|
||||||
? decodeURIComponent(rootUri.slice(7))
|
? decodeURIComponent(rootUri.slice(7))
|
||||||
: rootUri;
|
: rootUri;
|
||||||
|
log.info(`Decoded rootPath: ${rootPath}`);
|
||||||
return rootPath;
|
return rootPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,33 +142,28 @@ function getProjectRootFromSession(session, log) {
|
|||||||
const projectRoot = serverPath.substring(0, mcpServerIndex - 1); // -1 to remove trailing slash
|
const projectRoot = serverPath.substring(0, mcpServerIndex - 1); // -1 to remove trailing slash
|
||||||
|
|
||||||
// Verify this looks like our project root by checking for key files/directories
|
// Verify this looks like our project root by checking for key files/directories
|
||||||
if (fs.existsSync(path.join(projectRoot, '.cursor')) ||
|
if (
|
||||||
|
fs.existsSync(path.join(projectRoot, '.cursor')) ||
|
||||||
fs.existsSync(path.join(projectRoot, 'mcp-server')) ||
|
fs.existsSync(path.join(projectRoot, 'mcp-server')) ||
|
||||||
fs.existsSync(path.join(projectRoot, 'package.json'))) {
|
fs.existsSync(path.join(projectRoot, 'package.json'))
|
||||||
|
) {
|
||||||
|
log.info(`Found project root from server path: ${projectRoot}`);
|
||||||
return projectRoot;
|
return projectRoot;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we get here, we'll try process.cwd() but only if it's not "/"
|
// ALWAYS ensure we return a valid path as a last resort
|
||||||
const cwd = process.cwd();
|
log.info(`Using current working directory as ultimate fallback: ${cwd}`);
|
||||||
if (cwd !== '/') {
|
|
||||||
return cwd;
|
return cwd;
|
||||||
}
|
|
||||||
|
|
||||||
// Last resort: try to derive from the server path we found earlier
|
|
||||||
if (serverPath) {
|
|
||||||
const mcpServerIndex = serverPath.indexOf('mcp-server');
|
|
||||||
return mcpServerIndex !== -1 ? serverPath.substring(0, mcpServerIndex - 1) : cwd;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error('Could not determine project root');
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// If we have a server path, use it as a basis for project root
|
// If we have a server path, use it as a basis for project root
|
||||||
const serverPath = process.argv[1];
|
const serverPath = process.argv[1];
|
||||||
if (serverPath && serverPath.includes('mcp-server')) {
|
if (serverPath && serverPath.includes('mcp-server')) {
|
||||||
const mcpServerIndex = serverPath.indexOf('mcp-server');
|
const mcpServerIndex = serverPath.indexOf('mcp-server');
|
||||||
return mcpServerIndex !== -1 ? serverPath.substring(0, mcpServerIndex - 1) : process.cwd();
|
return mcpServerIndex !== -1
|
||||||
|
? serverPath.substring(0, mcpServerIndex - 1)
|
||||||
|
: process.cwd();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only use cwd if it's not "/"
|
// Only use cwd if it's not "/"
|
||||||
@@ -146,7 +180,12 @@ function getProjectRootFromSession(session, log) {
|
|||||||
* @param {Function} processFunction - Optional function to process successful result data
|
* @param {Function} processFunction - Optional function to process successful result data
|
||||||
* @returns {Object} - Standardized MCP response object
|
* @returns {Object} - Standardized MCP response object
|
||||||
*/
|
*/
|
||||||
function handleApiResult(result, log, errorPrefix = 'API error', processFunction = processMCPResponseData) {
|
function handleApiResult(
|
||||||
|
result,
|
||||||
|
log,
|
||||||
|
errorPrefix = 'API error',
|
||||||
|
processFunction = processMCPResponseData
|
||||||
|
) {
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
const errorMsg = result.error?.message || `Unknown ${errorPrefix}`;
|
const errorMsg = result.error?.message || `Unknown ${errorPrefix}`;
|
||||||
// Include cache status in error logs
|
// Include cache status in error logs
|
||||||
@@ -155,7 +194,9 @@ function handleApiResult(result, log, errorPrefix = 'API error', processFunction
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Process the result data if needed
|
// Process the result data if needed
|
||||||
const processedData = processFunction ? processFunction(result.data) : result.data;
|
const processedData = processFunction
|
||||||
|
? processFunction(result.data)
|
||||||
|
: result.data;
|
||||||
|
|
||||||
// Log success including cache status
|
// Log success including cache status
|
||||||
log.info(`Successfully completed operation. From cache: ${result.fromCache}`); // Add success log with cache status
|
log.info(`Successfully completed operation. From cache: ${result.fromCache}`); // Add success log with cache status
|
||||||
@@ -171,18 +212,20 @@ function handleApiResult(result, log, errorPrefix = 'API error', processFunction
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Execute a Task Master CLI command using child_process
|
* Executes a task-master CLI command synchronously.
|
||||||
* @param {string} command - The command to execute
|
* @param {string} command - The command to execute (e.g., 'add-task')
|
||||||
* @param {Object} log - The logger object from FastMCP
|
* @param {Object} log - Logger instance
|
||||||
* @param {Array} args - Arguments for the command
|
* @param {Array} args - Arguments for the command
|
||||||
* @param {string|undefined} projectRootRaw - Optional raw project root path (will be normalized internally)
|
* @param {string|undefined} projectRootRaw - Optional raw project root path (will be normalized internally)
|
||||||
|
* @param {Object|null} customEnv - Optional object containing environment variables to pass to the child process
|
||||||
* @returns {Object} - The result of the command execution
|
* @returns {Object} - The result of the command execution
|
||||||
*/
|
*/
|
||||||
function executeTaskMasterCommand(
|
function executeTaskMasterCommand(
|
||||||
command,
|
command,
|
||||||
log,
|
log,
|
||||||
args = [],
|
args = [],
|
||||||
projectRootRaw = null
|
projectRootRaw = null,
|
||||||
|
customEnv = null // Changed from session to customEnv
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
// Normalize project root internally using the getProjectRoot utility
|
// Normalize project root internally using the getProjectRoot utility
|
||||||
@@ -199,18 +242,24 @@ function executeTaskMasterCommand(
|
|||||||
|
|
||||||
// Common options for spawn
|
// Common options for spawn
|
||||||
const spawnOptions = {
|
const spawnOptions = {
|
||||||
encoding: "utf8",
|
encoding: 'utf8',
|
||||||
cwd: cwd,
|
cwd: cwd,
|
||||||
|
// Merge process.env with customEnv, giving precedence to customEnv
|
||||||
|
env: { ...process.env, ...(customEnv || {}) }
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Log the environment being passed (optional, for debugging)
|
||||||
|
// log.info(`Spawn options env: ${JSON.stringify(spawnOptions.env)}`);
|
||||||
|
|
||||||
// Execute the command using the global task-master CLI or local script
|
// Execute the command using the global task-master CLI or local script
|
||||||
// Try the global CLI first
|
// Try the global CLI first
|
||||||
let result = spawnSync("task-master", fullArgs, spawnOptions);
|
let result = spawnSync('task-master', fullArgs, spawnOptions);
|
||||||
|
|
||||||
// If global CLI is not available, try fallback to the local script
|
// If global CLI is not available, try fallback to the local script
|
||||||
if (result.error && result.error.code === "ENOENT") {
|
if (result.error && result.error.code === 'ENOENT') {
|
||||||
log.info("Global task-master not found, falling back to local script");
|
log.info('Global task-master not found, falling back to local script');
|
||||||
result = spawnSync("node", ["scripts/dev.js", ...fullArgs], spawnOptions);
|
// Pass the same spawnOptions (including env) to the fallback
|
||||||
|
result = spawnSync('node', ['scripts/dev.js', ...fullArgs], spawnOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.error) {
|
if (result.error) {
|
||||||
@@ -223,7 +272,7 @@ function executeTaskMasterCommand(
|
|||||||
? result.stderr.trim()
|
? result.stderr.trim()
|
||||||
: result.stdout
|
: result.stdout
|
||||||
? result.stdout.trim()
|
? result.stdout.trim()
|
||||||
: "Unknown error";
|
: 'Unknown error';
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Command failed with exit code ${result.status}: ${errorOutput}`
|
`Command failed with exit code ${result.status}: ${errorOutput}`
|
||||||
);
|
);
|
||||||
@@ -232,13 +281,13 @@ function executeTaskMasterCommand(
|
|||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
stdout: result.stdout,
|
stdout: result.stdout,
|
||||||
stderr: result.stderr,
|
stderr: result.stderr
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error executing task-master command: ${error.message}`);
|
log.error(`Error executing task-master command: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: error.message,
|
error: error.message
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -280,9 +329,13 @@ async function getCachedOrExecute({ cacheKey, actionFn, log }) {
|
|||||||
const { fromCache, ...resultToCache } = result;
|
const { fromCache, ...resultToCache } = result;
|
||||||
contextManager.setCachedData(cacheKey, resultToCache);
|
contextManager.setCachedData(cacheKey, resultToCache);
|
||||||
} else if (!result.success) {
|
} else if (!result.success) {
|
||||||
log.warn(`Action failed for cache key ${cacheKey}. Result not cached. Error: ${result.error?.message}`);
|
log.warn(
|
||||||
|
`Action failed for cache key ${cacheKey}. Result not cached. Error: ${result.error?.message}`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
log.warn(`Action for cache key ${cacheKey} succeeded but returned no data. Result not cached.`);
|
log.warn(
|
||||||
|
`Action for cache key ${cacheKey} succeeded but returned no data. Result not cached.`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return the fresh result, indicating it wasn't from cache
|
// Return the fresh result, indicating it wasn't from cache
|
||||||
@@ -299,7 +352,10 @@ async function getCachedOrExecute({ cacheKey, actionFn, log }) {
|
|||||||
* @param {string[]} fieldsToRemove - An array of field names to remove.
|
* @param {string[]} fieldsToRemove - An array of field names to remove.
|
||||||
* @returns {Object|Array} - The processed data with specified fields removed.
|
* @returns {Object|Array} - The processed data with specified fields removed.
|
||||||
*/
|
*/
|
||||||
function processMCPResponseData(taskOrData, fieldsToRemove = ['details', 'testStrategy']) {
|
function processMCPResponseData(
|
||||||
|
taskOrData,
|
||||||
|
fieldsToRemove = ['details', 'testStrategy']
|
||||||
|
) {
|
||||||
if (!taskOrData) {
|
if (!taskOrData) {
|
||||||
return taskOrData;
|
return taskOrData;
|
||||||
}
|
}
|
||||||
@@ -313,7 +369,7 @@ function processMCPResponseData(taskOrData, fieldsToRemove = ['details', 'testSt
|
|||||||
const processedTask = { ...task };
|
const processedTask = { ...task };
|
||||||
|
|
||||||
// Remove specified fields from the task
|
// Remove specified fields from the task
|
||||||
fieldsToRemove.forEach(field => {
|
fieldsToRemove.forEach((field) => {
|
||||||
delete processedTask[field];
|
delete processedTask[field];
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -332,14 +388,23 @@ function processMCPResponseData(taskOrData, fieldsToRemove = ['details', 'testSt
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Check if the input is a data structure containing a 'tasks' array (like from listTasks)
|
// Check if the input is a data structure containing a 'tasks' array (like from listTasks)
|
||||||
if (typeof taskOrData === 'object' && taskOrData !== null && Array.isArray(taskOrData.tasks)) {
|
if (
|
||||||
|
typeof taskOrData === 'object' &&
|
||||||
|
taskOrData !== null &&
|
||||||
|
Array.isArray(taskOrData.tasks)
|
||||||
|
) {
|
||||||
return {
|
return {
|
||||||
...taskOrData, // Keep other potential fields like 'stats', 'filter'
|
...taskOrData, // Keep other potential fields like 'stats', 'filter'
|
||||||
tasks: processArrayOfTasks(taskOrData.tasks),
|
tasks: processArrayOfTasks(taskOrData.tasks)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// Check if the input is likely a single task object (add more checks if needed)
|
// Check if the input is likely a single task object (add more checks if needed)
|
||||||
else if (typeof taskOrData === 'object' && taskOrData !== null && 'id' in taskOrData && 'title' in taskOrData) {
|
else if (
|
||||||
|
typeof taskOrData === 'object' &&
|
||||||
|
taskOrData !== null &&
|
||||||
|
'id' in taskOrData &&
|
||||||
|
'title' in taskOrData
|
||||||
|
) {
|
||||||
return processSingleTask(taskOrData);
|
return processSingleTask(taskOrData);
|
||||||
}
|
}
|
||||||
// Check if the input is an array of tasks directly (less common but possible)
|
// Check if the input is an array of tasks directly (less common but possible)
|
||||||
@@ -361,11 +426,12 @@ function createContentResponse(content) {
|
|||||||
return {
|
return {
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
type: "text",
|
type: 'text',
|
||||||
text: typeof content === 'object' ?
|
text:
|
||||||
// Format JSON nicely with indentation
|
typeof content === 'object'
|
||||||
JSON.stringify(content, null, 2) :
|
? // Format JSON nicely with indentation
|
||||||
// Keep other content types as-is
|
JSON.stringify(content, null, 2)
|
||||||
|
: // Keep other content types as-is
|
||||||
String(content)
|
String(content)
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -381,7 +447,7 @@ export function createErrorResponse(errorMessage) {
|
|||||||
return {
|
return {
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
type: "text",
|
type: 'text',
|
||||||
text: `Error: ${errorMessage}`
|
text: `Error: ${errorMessage}`
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -397,5 +463,5 @@ export {
|
|||||||
executeTaskMasterCommand,
|
executeTaskMasterCommand,
|
||||||
getCachedOrExecute,
|
getCachedOrExecute,
|
||||||
processMCPResponseData,
|
processMCPResponseData,
|
||||||
createContentResponse,
|
createContentResponse
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool for validating task dependencies
|
* Tool for validating task dependencies
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { validateDependenciesDirect } from "../core/task-master-core.js";
|
import { validateDependenciesDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the validateDependencies tool with the MCP server
|
* Register the validateDependencies tool with the MCP server
|
||||||
@@ -17,11 +17,17 @@ import { validateDependenciesDirect } from "../core/task-master-core.js";
|
|||||||
*/
|
*/
|
||||||
export function registerValidateDependenciesTool(server) {
|
export function registerValidateDependenciesTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "validate_dependencies",
|
name: 'validate_dependencies',
|
||||||
description: "Check tasks for dependency issues (like circular references or links to non-existent tasks) without making changes.",
|
description:
|
||||||
|
'Check tasks for dependency issues (like circular references or links to non-existent tasks) without making changes.',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
try {
|
try {
|
||||||
@@ -35,15 +41,21 @@ export function registerValidateDependenciesTool(server) {
|
|||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await validateDependenciesDirect({
|
const result = await validateDependenciesDirect(
|
||||||
|
{
|
||||||
projectRoot: rootFolder,
|
projectRoot: rootFolder,
|
||||||
...args
|
...args
|
||||||
}, log, { reportProgress, mcpLog: log, session});
|
},
|
||||||
|
log,
|
||||||
|
{ reportProgress, mcpLog: log, session }
|
||||||
|
);
|
||||||
|
|
||||||
await reportProgress({ progress: 100 });
|
await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully validated dependencies: ${result.data.message}`);
|
log.info(
|
||||||
|
`Successfully validated dependencies: ${result.data.message}`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to validate dependencies: ${result.error.message}`);
|
log.error(`Failed to validate dependencies: ${result.error.message}`);
|
||||||
}
|
}
|
||||||
@@ -53,6 +65,6 @@ export function registerValidateDependenciesTool(server) {
|
|||||||
log.error(`Error in validateDependencies tool: ${error.message}`);
|
log.error(`Error in validateDependencies tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -16,7 +16,9 @@ try {
|
|||||||
|
|
||||||
if (fs.existsSync(mcpPath)) {
|
if (fs.existsSync(mcpPath)) {
|
||||||
console.error('mcp.json file found');
|
console.error('mcp.json file found');
|
||||||
console.error(`File content: ${JSON.stringify(JSON.parse(fs.readFileSync(mcpPath, 'utf8')), null, 2)}`);
|
console.error(
|
||||||
|
`File content: ${JSON.stringify(JSON.parse(fs.readFileSync(mcpPath, 'utf8')), null, 2)}`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
console.error('mcp.json file not found');
|
console.error('mcp.json file not found');
|
||||||
}
|
}
|
||||||
@@ -27,7 +29,9 @@ try {
|
|||||||
|
|
||||||
// Check if env property exists
|
// Check if env property exists
|
||||||
if (config.env) {
|
if (config.env) {
|
||||||
console.error(`Config.env exists with keys: ${Object.keys(config.env).join(', ')}`);
|
console.error(
|
||||||
|
`Config.env exists with keys: ${Object.keys(config.env).join(', ')}`
|
||||||
|
);
|
||||||
|
|
||||||
// Print each env var value (careful with sensitive values)
|
// Print each env var value (careful with sensitive values)
|
||||||
for (const [key, value] of Object.entries(config.env)) {
|
for (const [key, value] of Object.entries(config.env)) {
|
||||||
|
|||||||
50
package-lock.json
generated
50
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "task-master-ai",
|
"name": "task-master-ai",
|
||||||
"version": "0.10.0",
|
"version": "0.10.1",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "task-master-ai",
|
"name": "task-master-ai",
|
||||||
"version": "0.10.0",
|
"version": "0.10.1",
|
||||||
"license": "MIT WITH Commons-Clause",
|
"license": "MIT WITH Commons-Clause",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@anthropic-ai/sdk": "^0.39.0",
|
"@anthropic-ai/sdk": "^0.39.0",
|
||||||
@@ -32,7 +32,8 @@
|
|||||||
"bin": {
|
"bin": {
|
||||||
"task-master": "bin/task-master.js",
|
"task-master": "bin/task-master.js",
|
||||||
"task-master-init": "bin/task-master-init.js",
|
"task-master-init": "bin/task-master-init.js",
|
||||||
"task-master-mcp": "mcp-server/server.js"
|
"task-master-mcp": "mcp-server/server.js",
|
||||||
|
"task-master-mcp-server": "mcp-server/server.js"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@changesets/changelog-github": "^0.5.1",
|
"@changesets/changelog-github": "^0.5.1",
|
||||||
@@ -41,6 +42,7 @@
|
|||||||
"jest": "^29.7.0",
|
"jest": "^29.7.0",
|
||||||
"jest-environment-node": "^29.7.0",
|
"jest-environment-node": "^29.7.0",
|
||||||
"mock-fs": "^5.5.0",
|
"mock-fs": "^5.5.0",
|
||||||
|
"prettier": "^3.5.3",
|
||||||
"supertest": "^7.1.0"
|
"supertest": "^7.1.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -607,6 +609,22 @@
|
|||||||
"semver": "^7.5.3"
|
"semver": "^7.5.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@changesets/apply-release-plan/node_modules/prettier": {
|
||||||
|
"version": "2.8.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz",
|
||||||
|
"integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"prettier": "bin-prettier.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.13.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@changesets/apply-release-plan/node_modules/semver": {
|
"node_modules/@changesets/apply-release-plan/node_modules/semver": {
|
||||||
"version": "7.7.1",
|
"version": "7.7.1",
|
||||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz",
|
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz",
|
||||||
@@ -929,6 +947,22 @@
|
|||||||
"prettier": "^2.7.1"
|
"prettier": "^2.7.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@changesets/write/node_modules/prettier": {
|
||||||
|
"version": "2.8.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz",
|
||||||
|
"integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"prettier": "bin-prettier.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.13.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@colors/colors": {
|
"node_modules/@colors/colors": {
|
||||||
"version": "1.5.0",
|
"version": "1.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
|
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
|
||||||
@@ -6621,16 +6655,16 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/prettier": {
|
"node_modules/prettier": {
|
||||||
"version": "2.8.8",
|
"version": "3.5.3",
|
||||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz",
|
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.5.3.tgz",
|
||||||
"integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==",
|
"integrity": "sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"bin": {
|
"bin": {
|
||||||
"prettier": "bin-prettier.js"
|
"prettier": "bin/prettier.cjs"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10.13.0"
|
"node": ">=14"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/prettier/prettier?sponsor=1"
|
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user