feat(research): Adds MCP tool for command

- New MCP Tool: research tool enables AI-powered research with project context
- Context Integration: Supports task IDs, file paths, custom context, and project tree
- Fuzzy Task Discovery: Automatically finds relevant tasks using semantic search
- Token Management: Detailed token counting and breakdown by context type
- Multiple Detail Levels: Support for low, medium, and high detail research responses
- Telemetry Integration: Full cost tracking and usage analytics
- Direct Function: researchDirect with comprehensive parameter validation
- Silent Mode: Prevents console output interference with MCP JSON responses
- Error Handling: Robust error handling with proper MCP response formatting

This completes subtasks 94.5 (Direct Function) and 94.6 (MCP Tool) for the research command implementation, providing a powerful research interface for integrated development environments like Cursor.

Updated documentation across taskmaster.mdc, README.md, command-reference.md, examples.md, tutorial.md, and docs/README.md to highlight research capabilities and usage patterns.
This commit is contained in:
Eyal Toledano
2025-05-25 20:16:48 -04:00
parent 1e020023ed
commit 023f51c579
11 changed files with 454 additions and 3 deletions

View File

@@ -0,0 +1,17 @@
---
'task-master-ai': minor
---
Add comprehensive `research` MCP tool for AI-powered research queries
- **New MCP Tool**: `research` tool enables AI-powered research with project context
- **Context Integration**: Supports task IDs, file paths, custom context, and project tree
- **Fuzzy Task Discovery**: Automatically finds relevant tasks using semantic search
- **Token Management**: Detailed token counting and breakdown by context type
- **Multiple Detail Levels**: Support for low, medium, and high detail research responses
- **Telemetry Integration**: Full cost tracking and usage analytics
- **Direct Function**: `researchDirect` with comprehensive parameter validation
- **Silent Mode**: Prevents console output interference with MCP JSON responses
- **Error Handling**: Robust error handling with proper MCP response formatting
This completes subtasks 94.5 (Direct Function) and 94.6 (MCP Tool) for the research command implementation, providing a powerful research interface for integrated development environments like Cursor.

View File

@@ -366,6 +366,43 @@ This document provides a detailed reference for interacting with Taskmaster, cov
--- ---
## AI-Powered Research
### 25. Research (`research`)
* **MCP Tool:** `research`
* **CLI Command:** `task-master research [options]`
* **Description:** `Perform AI-powered research queries with project context to get fresh, up-to-date information beyond the AI's knowledge cutoff.`
* **Key Parameters/Options:**
* `query`: `Required. Research query/prompt (e.g., "What are the latest best practices for React Query v5?").` (CLI: `[query]` positional or `-q, --query <text>`)
* `taskIds`: `Comma-separated list of task/subtask IDs for context (e.g., "15,16.2,17").` (CLI: `-i, --id <ids>`)
* `filePaths`: `Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md").` (CLI: `-f, --files <paths>`)
* `customContext`: `Additional custom context text to include in the research.` (CLI: `-c, --context <text>`)
* `includeProjectTree`: `Include project file tree structure in context (default: false).` (CLI: `--tree`)
* `detailLevel`: `Detail level for the research response: 'low', 'medium', 'high' (default: medium).` (CLI: `--detail <level>`)
* `projectRoot`: `The directory of the project. Must be an absolute path.` (CLI: Determined automatically)
* **Usage:** **This is a POWERFUL tool that agents should use FREQUENTLY** to:
* Get fresh information beyond knowledge cutoff dates
* Research latest best practices, library updates, security patches
* Find implementation examples for specific technologies
* Validate approaches against current industry standards
* Get contextual advice based on project files and tasks
* **When to Consider Using Research:**
* **Before implementing any task** - Research current best practices
* **When encountering new technologies** - Get up-to-date implementation guidance (libraries, apis, etc)
* **For security-related tasks** - Find latest security recommendations
* **When updating dependencies** - Research breaking changes and migration guides
* **For performance optimization** - Get current performance best practices
* **When debugging complex issues** - Research known solutions and workarounds
* **Research + Action Pattern:**
* Use `research` to gather fresh information
* Use `update_subtask` to commit findings with timestamps
* Use `update_task` to incorporate research into task details
* Use `add_task` with research flag for informed task creation
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. The research provides FRESH data beyond the AI's training cutoff, making it invaluable for current best practices and recent developments.
---
## File Management ## File Management
### 24. Generate Task Files (`generate`) ### 24. Generate Task Files (`generate`)

View File

@@ -132,6 +132,8 @@ Use your AI assistant to:
- Implement a task: `Can you help me implement task 3?` - Implement a task: `Can you help me implement task 3?`
- View multiple tasks: `Can you show me tasks 1, 3, and 5?` - View multiple tasks: `Can you show me tasks 1, 3, and 5?`
- Expand a task: `Can you help me expand task 4?` - Expand a task: `Can you help me expand task 4?`
- **Research fresh information**: `Research the latest best practices for implementing JWT authentication with Node.js`
- **Research with context**: `Research React Query v5 migration strategies for our current API implementation in src/api.js`
[More examples on how to use Task Master in chat](docs/examples.md) [More examples on how to use Task Master in chat](docs/examples.md)
@@ -177,6 +179,9 @@ task-master next
# Show specific task(s) - supports comma-separated IDs # Show specific task(s) - supports comma-separated IDs
task-master show 1,3,5 task-master show 1,3,5
# Research fresh information with project context
task-master research "What are the latest best practices for JWT authentication?"
# Generate task files # Generate task files
task-master generate task-master generate
``` ```

View File

@@ -9,7 +9,7 @@ Welcome to the Task Master documentation. Use the links below to navigate to the
## Reference ## Reference
- [Command Reference](command-reference.md) - Complete list of all available commands (including new multi-task viewing) - [Command Reference](command-reference.md) - Complete list of all available commands (including research and multi-task viewing)
- [Task Structure](task-structure.md) - Understanding the task format and features - [Task Structure](task-structure.md) - Understanding the task format and features
## Examples & Licensing ## Examples & Licensing

View File

@@ -280,3 +280,42 @@ task-master models --setup
``` ```
Configuration is stored in `.taskmasterconfig` in your project root. API keys are still managed via `.env` or MCP configuration. Use `task-master models` without flags to see available built-in models. Use `--setup` for a guided experience. Configuration is stored in `.taskmasterconfig` in your project root. API keys are still managed via `.env` or MCP configuration. Use `task-master models` without flags to see available built-in models. Use `--setup` for a guided experience.
## Research Fresh Information
```bash
# Perform AI-powered research with fresh, up-to-date information
task-master research "What are the latest best practices for JWT authentication in Node.js?"
# Research with specific task context
task-master research "How to implement OAuth 2.0?" --id=15,16
# Research with file context for code-aware suggestions
task-master research "How can I optimize this API implementation?" --files=src/api.js,src/auth.js
# Research with custom context and project tree
task-master research "Best practices for error handling" --context="We're using Express.js" --tree
# Research with different detail levels
task-master research "React Query v5 migration guide" --detail=high
# Save research results to a file
task-master research "Database optimization techniques" --save=research/db-optimization.md
```
**The research command is a powerful tool that provides:**
- **Fresh information beyond AI knowledge cutoffs**
- **Project-aware context** from your tasks and files
- **Automatic task discovery** using fuzzy search
- **Multiple detail levels** (low, medium, high)
- **Token counting and cost tracking**
- **Interactive follow-up questions**
**Use research frequently to:**
- Get current best practices before implementing features
- Research new technologies and libraries
- Find solutions to complex problems
- Validate your implementation approaches
- Stay updated with latest security recommendations

View File

@@ -123,3 +123,56 @@ Please add a new task to implement user profile image uploads using Cloudinary,
``` ```
(Agent runs: `task-master add-task --prompt="Implement user profile image uploads using Cloudinary" --research`) (Agent runs: `task-master add-task --prompt="Implement user profile image uploads using Cloudinary" --research`)
## Research-Driven Development
### Getting Fresh Information
```
Research the latest best practices for implementing JWT authentication in Node.js applications.
```
(Agent runs: `task-master research "Latest best practices for JWT authentication in Node.js"`)
### Research with Project Context
```
I'm working on task 15 which involves API optimization. Can you research current best practices for our specific implementation?
```
(Agent runs: `task-master research "API optimization best practices" --id=15 --files=src/api.js`)
### Research Before Implementation
```
Before I implement task 8 (React Query integration), can you research the latest React Query v5 patterns and any breaking changes?
```
(Agent runs: `task-master research "React Query v5 patterns and breaking changes" --id=8`)
### Research and Update Pattern
```
Research the latest security recommendations for Express.js applications and update our authentication task with the findings.
```
(Agent runs:
1. `task-master research "Latest Express.js security recommendations" --id=12`
2. `task-master update-subtask --id=12.3 --prompt="Updated with latest security findings: [research results]"`)
### Research for Debugging
```
I'm having issues with our WebSocket implementation in task 20. Can you research common WebSocket problems and solutions?
```
(Agent runs: `task-master research "Common WebSocket implementation problems and solutions" --id=20 --files=src/websocket.js`)
### Research Technology Comparisons
```
We need to choose between Redis and Memcached for caching. Can you research the current recommendations for our use case?
```
(Agent runs: `task-master research "Redis vs Memcached 2024 comparison for session caching" --tree`)

View File

@@ -443,3 +443,55 @@ Can you analyze the complexity of our tasks to help me understand which ones nee
``` ```
Can you show me the complexity report in a more readable format? Can you show me the complexity report in a more readable format?
``` ```
### Research-Driven Development
Task Master includes a powerful research tool that provides fresh, up-to-date information beyond the AI's knowledge cutoff. This is particularly valuable for:
#### Getting Current Best Practices
```
Before implementing task 5 (authentication), research the latest JWT security recommendations.
```
The agent will execute:
```bash
task-master research "Latest JWT security recommendations 2024" --id=5
```
#### Research with Project Context
```
Research React Query v5 migration strategies for our current API implementation.
```
The agent will execute:
```bash
task-master research "React Query v5 migration strategies" --files=src/api.js,src/hooks.js
```
#### Research and Update Pattern
A powerful workflow is to research first, then update tasks with findings:
```
Research the latest Node.js performance optimization techniques and update task 12 with the findings.
```
The agent will:
1. Run research: `task-master research "Node.js performance optimization 2024" --id=12`
2. Update the task: `task-master update-subtask --id=12.2 --prompt="Updated with latest performance findings: [research results]"`
#### When to Use Research
- **Before implementing any new technology**
- **When encountering security-related tasks**
- **For performance optimization tasks**
- **When debugging complex issues**
- **Before making architectural decisions**
- **When updating dependencies**
The research tool automatically includes relevant project context and provides fresh information that can significantly improve implementation quality.

View File

@@ -0,0 +1,159 @@
/**
* research.js
* Direct function implementation for AI-powered research queries
*/
import { performResearch } from '../../../../scripts/modules/task-manager.js';
import {
enableSilentMode,
disableSilentMode
} from '../../../../scripts/modules/utils.js';
import { createLogWrapper } from '../../tools/utils.js';
/**
* Direct function wrapper for performing AI-powered research with project context.
*
* @param {Object} args - Command arguments
* @param {string} args.query - Research query/prompt (required)
* @param {string} [args.taskIds] - Comma-separated list of task/subtask IDs for context
* @param {string} [args.filePaths] - Comma-separated list of file paths for context
* @param {string} [args.customContext] - Additional custom context text
* @param {boolean} [args.includeProjectTree=false] - Include project file tree in context
* @param {string} [args.detailLevel='medium'] - Detail level: 'low', 'medium', 'high'
* @param {string} [args.projectRoot] - Project root path
* @param {Object} log - Logger object
* @param {Object} context - Additional context (session)
* @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } }
*/
export async function researchDirect(args, log, context = {}) {
// Destructure expected args
const {
query,
taskIds,
filePaths,
customContext,
includeProjectTree = false,
detailLevel = 'medium',
projectRoot
} = args;
const { session } = context; // Destructure session from context
// Enable silent mode to prevent console logs from interfering with JSON response
enableSilentMode();
// Create logger wrapper using the utility
const mcpLog = createLogWrapper(log);
try {
// Check required parameters
if (!query || typeof query !== 'string' || query.trim().length === 0) {
log.error('Missing or invalid required parameter: query');
disableSilentMode();
return {
success: false,
error: {
code: 'MISSING_PARAMETER',
message:
'The query parameter is required and must be a non-empty string'
}
};
}
// Parse comma-separated task IDs if provided
const parsedTaskIds = taskIds
? taskIds
.split(',')
.map((id) => id.trim())
.filter((id) => id.length > 0)
: [];
// Parse comma-separated file paths if provided
const parsedFilePaths = filePaths
? filePaths
.split(',')
.map((path) => path.trim())
.filter((path) => path.length > 0)
: [];
// Validate detail level
const validDetailLevels = ['low', 'medium', 'high'];
if (!validDetailLevels.includes(detailLevel)) {
log.error(`Invalid detail level: ${detailLevel}`);
disableSilentMode();
return {
success: false,
error: {
code: 'INVALID_PARAMETER',
message: `Detail level must be one of: ${validDetailLevels.join(', ')}`
}
};
}
log.info(
`Performing research query: "${query.substring(0, 100)}${query.length > 100 ? '...' : ''}", ` +
`taskIds: [${parsedTaskIds.join(', ')}], ` +
`filePaths: [${parsedFilePaths.join(', ')}], ` +
`detailLevel: ${detailLevel}, ` +
`includeProjectTree: ${includeProjectTree}, ` +
`projectRoot: ${projectRoot}`
);
// Prepare options for the research function
const researchOptions = {
taskIds: parsedTaskIds,
filePaths: parsedFilePaths,
customContext: customContext || '',
includeProjectTree,
detailLevel,
projectRoot
};
// Prepare context for the research function
const researchContext = {
session,
mcpLog,
commandName: 'research',
outputType: 'mcp'
};
// Call the performResearch function
const result = await performResearch(
query.trim(),
researchOptions,
researchContext,
'json', // outputFormat - use 'json' to suppress CLI UI
false // allowFollowUp - disable for MCP calls
);
// Restore normal logging
disableSilentMode();
return {
success: true,
data: {
query: result.query,
result: result.result,
contextSize: result.contextSize,
contextTokens: result.contextTokens,
tokenBreakdown: result.tokenBreakdown,
systemPromptTokens: result.systemPromptTokens,
userPromptTokens: result.userPromptTokens,
totalInputTokens: result.totalInputTokens,
detailLevel: result.detailLevel,
telemetryData: result.telemetryData
}
};
} catch (error) {
// Make sure to restore normal logging even if there's an error
disableSilentMode();
log.error(`Error in researchDirect: ${error.message}`);
return {
success: false,
error: {
code: error.code || 'RESEARCH_ERROR',
message: error.message
}
};
}
}

View File

@@ -31,6 +31,7 @@ import { removeTaskDirect } from './direct-functions/remove-task.js';
import { initializeProjectDirect } from './direct-functions/initialize-project.js'; import { initializeProjectDirect } from './direct-functions/initialize-project.js';
import { modelsDirect } from './direct-functions/models.js'; import { modelsDirect } from './direct-functions/models.js';
import { moveTaskDirect } from './direct-functions/move-task.js'; import { moveTaskDirect } from './direct-functions/move-task.js';
import { researchDirect } from './direct-functions/research.js';
// Re-export utility functions // Re-export utility functions
export { findTasksJsonPath } from './utils/path-utils.js'; export { findTasksJsonPath } from './utils/path-utils.js';
@@ -62,7 +63,8 @@ export const directFunctions = new Map([
['removeTaskDirect', removeTaskDirect], ['removeTaskDirect', removeTaskDirect],
['initializeProjectDirect', initializeProjectDirect], ['initializeProjectDirect', initializeProjectDirect],
['modelsDirect', modelsDirect], ['modelsDirect', modelsDirect],
['moveTaskDirect', moveTaskDirect] ['moveTaskDirect', moveTaskDirect],
['researchDirect', researchDirect]
]); ]);
// Re-export all direct function implementations // Re-export all direct function implementations
@@ -92,5 +94,6 @@ export {
removeTaskDirect, removeTaskDirect,
initializeProjectDirect, initializeProjectDirect,
modelsDirect, modelsDirect,
moveTaskDirect moveTaskDirect,
researchDirect
}; };

View File

@@ -29,6 +29,7 @@ import { registerRemoveTaskTool } from './remove-task.js';
import { registerInitializeProjectTool } from './initialize-project.js'; import { registerInitializeProjectTool } from './initialize-project.js';
import { registerModelsTool } from './models.js'; import { registerModelsTool } from './models.js';
import { registerMoveTaskTool } from './move-task.js'; import { registerMoveTaskTool } from './move-task.js';
import { registerResearchTool } from './research.js';
/** /**
* Register all Task Master tools with the MCP server * Register all Task Master tools with the MCP server
@@ -74,6 +75,9 @@ export function registerTaskMasterTools(server) {
registerRemoveDependencyTool(server); registerRemoveDependencyTool(server);
registerValidateDependenciesTool(server); registerValidateDependenciesTool(server);
registerFixDependenciesTool(server); registerFixDependenciesTool(server);
// Group 7: AI-Powered Features
registerResearchTool(server);
} 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;

View File

@@ -0,0 +1,82 @@
/**
* tools/research.js
* Tool to perform AI-powered research queries with project context
*/
import { z } from 'zod';
import {
createErrorResponse,
handleApiResult,
withNormalizedProjectRoot
} from './utils.js';
import { researchDirect } from '../core/task-master-core.js';
/**
* Register the research tool with the MCP server
* @param {Object} server - FastMCP server instance
*/
export function registerResearchTool(server) {
server.addTool({
name: 'research',
description: 'Perform AI-powered research queries with project context',
parameters: z.object({
query: z.string().describe('Research query/prompt (required)'),
taskIds: z
.string()
.optional()
.describe(
'Comma-separated list of task/subtask IDs for context (e.g., "15,16.2,17")'
),
filePaths: z
.string()
.optional()
.describe(
'Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md")'
),
customContext: z
.string()
.optional()
.describe('Additional custom context text to include in the research'),
includeProjectTree: z
.boolean()
.optional()
.describe(
'Include project file tree structure in context (default: false)'
),
detailLevel: z
.enum(['low', 'medium', 'high'])
.optional()
.describe('Detail level for the research response (default: medium)'),
projectRoot: z
.string()
.describe('The directory of the project. Must be an absolute path.')
}),
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
log.info(
`Starting research with query: "${args.query.substring(0, 100)}${args.query.length > 100 ? '...' : ''}"`
);
// Call the direct function
const result = await researchDirect(
{
query: args.query,
taskIds: args.taskIds,
filePaths: args.filePaths,
customContext: args.customContext,
includeProjectTree: args.includeProjectTree || false,
detailLevel: args.detailLevel || 'medium',
projectRoot: args.projectRoot
},
log,
{ session }
);
return handleApiResult(result, log);
} catch (error) {
log.error(`Error in research tool: ${error.message}`);
return createErrorResponse(error.message);
}
})
});
}