claudemaster
Version:
Task management MCP server optimized for Claude Code - no API keys required
644 lines (526 loc) • 19.4 kB
JavaScript
/**
* claudemaster-initialization.js
* Initialize Claudemaster for Claude Code projects
*/
import { z } from 'zod';
import { mkdirSync, writeFileSync, existsSync } from 'fs';
import { join } from 'path';
import TaskEngine from '../core/task-engine.js';
import { getProjectTemplate } from '../core/claude-templates.js';
export function registerInitializeClaudemasterTool(server) {
server.addTool({
name: 'initialize_claudemaster',
description: 'Initialize Claudemaster task management for a Claude Code project. Creates necessary directories, configuration, and starter templates.',
parameters: z.object({
projectRoot: z.string().describe('Absolute path to project root directory'),
projectType: z.enum(['react_app', 'node_api', 'full_stack', 'general']).default('general').describe('Type of project for optimized setup'),
projectName: z.string().optional().describe('Name of the project'),
includeExamples: z.boolean().default(true).describe('Include example PRD and tasks'),
createStarterTasks: z.boolean().default(true).describe('Create initial starter tasks based on project type')
}),
execute: async (args) => {
try {
const { projectRoot, projectType, projectName, includeExamples, createStarterTasks } = args;
// Create directory structure
const structure = createDirectoryStructure(projectRoot);
// Initialize task engine
const taskEngine = new TaskEngine(projectRoot);
// Create configuration files
const configFiles = createConfigurationFiles(projectRoot, projectType, projectName);
// Create example PRD if requested
let exampleFiles = [];
if (includeExamples) {
exampleFiles = createExampleFiles(projectRoot, projectType);
}
// Create starter tasks if requested
let starterTasks = [];
if (createStarterTasks) {
starterTasks = createStarterTasks ? await createInitialTasks(taskEngine, projectType) : [];
}
// Create Claude Code integration files
const integrationFiles = createClaudeCodeIntegration(projectRoot, projectType);
return {
success: true,
message: `Claudemaster initialized successfully for ${projectType} project`,
structure: {
directoriesCreated: structure,
configurationFiles: configFiles,
exampleFiles: exampleFiles,
integrationFiles: integrationFiles
},
projectSetup: {
projectType,
projectName: projectName || 'Untitled Project',
tasksCreated: starterTasks.length,
starterTasks: starterTasks.slice(0, 3) // Show first 3 tasks
},
nextSteps: getNextSteps(projectType, includeExamples),
claudeCodeInstructions: {
setup: [
'Claudemaster is now initialized and ready to use',
'Your project structure has been created in .taskmaster/',
includeExamples ? 'Review the example PRD in .taskmaster/docs/example_prd.txt' : 'Create your PRD in .taskmaster/docs/prd.txt',
'Use claude_guided_prd_parsing to convert your PRD into tasks'
],
recommendedWorkflow: [
'1. Create or update your PRD document',
'2. Use claude_guided_prd_parsing to generate tasks',
'3. Use get_next_task to see what to work on',
'4. Use project_health_check to monitor progress'
]
}
};
} catch (error) {
return {
success: false,
error: error.message,
troubleshooting: [
'Ensure the project root directory is writable',
'Check that the path is absolute and valid',
'Make sure you have sufficient permissions'
]
};
}
}
});
}
function createDirectoryStructure(projectRoot) {
const directories = [
'.taskmaster',
'.taskmaster/docs',
'.taskmaster/templates',
'.taskmaster/exports',
'.taskmaster/archive'
];
const created = [];
for (const dir of directories) {
const fullPath = join(projectRoot, dir);
if (!existsSync(fullPath)) {
mkdirSync(fullPath, { recursive: true });
created.push(dir);
}
}
return created;
}
function createConfigurationFiles(projectRoot, projectType, projectName) {
const configFiles = [];
// Create Claudemaster config
const claudemasterConfig = {
projectName: projectName || 'Untitled Project',
projectType,
version: '1.0.0',
createdAt: new Date().toISOString(),
settings: {
defaultPriority: 'medium',
maxSubtasks: 10,
autoGenerateIds: true,
trackTimeEstimates: true
},
claudeCodeIntegration: {
enabled: true,
autoSuggestions: true,
intelligentBreakdown: true,
contextualHelp: true
}
};
const configPath = join(projectRoot, '.taskmaster', 'claudemaster.json');
writeFileSync(configPath, JSON.stringify(claudemasterConfig, null, 2));
configFiles.push('claudemaster.json');
// Create .gitignore for taskmaster directory
const gitignorePath = join(projectRoot, '.taskmaster', '.gitignore');
const gitignoreContent = `# Temporary files
*.tmp
*.temp
# Export files (optional - you may want to track these)
exports/*.json
exports/*.csv
# Archive files (usually you don't want to track these)
archive/
`;
writeFileSync(gitignorePath, gitignoreContent);
configFiles.push('.gitignore');
return configFiles;
}
function createExampleFiles(projectRoot, projectType) {
const exampleFiles = [];
// Create example PRD based on project type
const prdContent = generateExamplePRD(projectType);
const prdPath = join(projectRoot, '.taskmaster', 'docs', 'example_prd.txt');
writeFileSync(prdPath, prdContent);
exampleFiles.push('docs/example_prd.txt');
// Create README for the taskmaster directory
const readmeContent = generateClaudemasterReadme(projectType);
const readmePath = join(projectRoot, '.taskmaster', 'README.md');
writeFileSync(readmePath, readmeContent);
exampleFiles.push('README.md');
// Create template for PRD
const prdTemplate = generatePRDTemplate();
const templatePath = join(projectRoot, '.taskmaster', 'templates', 'prd_template.txt');
writeFileSync(templatePath, prdTemplate);
exampleFiles.push('templates/prd_template.txt');
return exampleFiles;
}
async function createInitialTasks(taskEngine, projectType) {
const template = getProjectTemplate(projectType);
if (!template || !template.defaultTasks) {
return [];
}
const tasks = [];
for (const taskData of template.defaultTasks) {
const task = taskEngine.addTask({
...taskData,
status: 'pending',
createdBy: 'claudemaster_initialization'
});
tasks.push(task);
}
return tasks;
}
function createClaudeCodeIntegration(projectRoot, projectType) {
const integrationFiles = [];
// Create a .mcp.json template for project-level MCP configuration
const mcpConfig = {
"mcpServers": {
"claudemaster": {
"command": "npx",
"args": ["-y", "claudemaster"],
"description": "Claudemaster task management optimized for Claude Code"
}
}
};
const mcpConfigPath = join(projectRoot, '.mcp.json.template');
writeFileSync(mcpConfigPath, JSON.stringify(mcpConfig, null, 2));
integrationFiles.push('.mcp.json.template');
// Create Claude Code workspace suggestions
const workspaceSuggestions = generateWorkspaceSuggestions(projectType);
const suggestionsPath = join(projectRoot, '.taskmaster', 'claude_code_setup.md');
writeFileSync(suggestionsPath, workspaceSuggestions);
integrationFiles.push('claude_code_setup.md');
return integrationFiles;
}
function generateExamplePRD(projectType) {
const prdTemplates = {
react_app: `# React Application PRD
## Project Overview
Build a modern React application with the following features:
## Core Features
1. User authentication and authorization
2. Dashboard with data visualization
3. CRUD operations for main entities
4. Responsive design for mobile and desktop
5. State management with Redux/Zustand
6. API integration
## Technical Requirements
- React 18+ with hooks
- TypeScript for type safety
- Modern CSS (Tailwind/Styled Components)
- Unit and integration testing
- Performance optimization
- Accessibility compliance
## User Stories
1. As a user, I want to register and login securely
2. As a user, I want to view my dashboard with relevant data
3. As a user, I want to create, read, update, and delete records
4. As a user, I want the app to work well on mobile devices
## Success Criteria
- Page load times under 3 seconds
- 95%+ test coverage
- Mobile-responsive design
- Accessible to WCAG 2.1 standards`,
node_api: `# Node.js API PRD
## Project Overview
Develop a RESTful API with Node.js and Express for [your application domain].
## Core Features
1. User authentication with JWT
2. CRUD endpoints for main resources
3. Database integration (PostgreSQL/MongoDB)
4. Input validation and sanitization
5. Error handling and logging
6. API documentation
7. Rate limiting and security
## Technical Requirements
- Node.js 18+ with Express
- TypeScript for type safety
- Database ORM (Prisma/Mongoose)
- Comprehensive testing
- Docker containerization
- CI/CD pipeline
## API Endpoints
1. Authentication: POST /auth/login, POST /auth/register
2. Users: GET/POST/PUT/DELETE /users
3. Main Resource: GET/POST/PUT/DELETE /[resource]
4. Health check: GET /health
## Success Criteria
- Response times under 500ms
- 99%+ uptime
- Comprehensive error handling
- Complete API documentation`,
full_stack: `# Full-Stack Application PRD
## Project Overview
Build a complete full-stack application with modern frontend and robust backend.
## Core Features
1. Modern React frontend with TypeScript
2. Node.js/Express API backend
3. Database integration and management
4. User authentication and authorization
5. Real-time features (WebSocket/Socket.io)
6. File upload and management
7. Admin panel and user dashboard
## Technical Requirements
Frontend:
- React 18+ with TypeScript
- State management (Redux Toolkit/Zustand)
- Modern UI framework (Material-UI/Tailwind)
- Testing with Vitest/Jest
Backend:
- Node.js with Express and TypeScript
- Database (PostgreSQL with Prisma)
- Authentication with JWT
- Real-time capabilities
DevOps:
- Docker containerization
- CI/CD pipeline
- Environment management
- Monitoring and logging
## Success Criteria
- Full type safety across frontend and backend
- 95%+ test coverage
- Mobile-responsive design
- Scalable architecture`,
general: `# Project Requirements Document
## Project Overview
[Describe your project goals and objectives]
## Core Features
1. [Feature 1 description]
2. [Feature 2 description]
3. [Feature 3 description]
## Technical Requirements
- [Technical requirement 1]
- [Technical requirement 2]
- [Technical requirement 3]
## User Stories
1. As a [user type], I want [goal] so that [benefit]
2. As a [user type], I want [goal] so that [benefit]
## Success Criteria
- [Measurable success criterion 1]
- [Measurable success criterion 2]
- [Measurable success criterion 3]
## Timeline and Milestones
- Phase 1: [Timeline and deliverables]
- Phase 2: [Timeline and deliverables]
- Phase 3: [Timeline and deliverables]`
};
return prdTemplates[projectType] || prdTemplates.general;
}
function generateClaudemasterReadme(projectType) {
return `# Claudemaster Project
This directory contains your Claudemaster task management files optimized for Claude Code.
## Structure
- **docs/**: Project documentation and PRD files
- **templates/**: Reusable templates for common documents
- **exports/**: Generated reports and exports
- **archive/**: Completed or archived tasks
- **claudemaster.json**: Project configuration
## Getting Started with Claude Code
1. **Create your PRD**: Edit \`docs/prd.txt\` or use the template in \`templates/prd_template.txt\`
2. **Parse your PRD**: Use Claude Code with:
\`\`\`
Use claude_guided_prd_parsing to analyze my PRD and create tasks
\`\`\`
3. **Start working**: Use:
\`\`\`
What's the next task I should work on?
\`\`\`
## Available Claude Code Commands
- \`initialize_claudemaster\`: Initialize project (already done!)
- \`claude_guided_prd_parsing\`: Convert PRD to structured tasks
- \`get_next_task\`: Get recommended next task
- \`analyze_project_complexity\`: Analyze and optimize your project
- \`claude_guided_task_expansion\`: Break down complex tasks
- \`project_health_check\`: Comprehensive project analysis
## Project Type: ${projectType}
${getProjectTypeSpecificInstructions(projectType)}
## Tips for Claude Code Integration
1. Be specific when asking for help: "Help me implement the authentication system from task 3"
2. Use context: "Based on our React project, how should I structure the components?"
3. Ask for breakdowns: "This task seems complex, can you break it down?"
4. Request implementation plans: "Create a detailed plan for implementing the API endpoints"
Happy coding with Claude Code and Claudemaster! 🚀
`;
}
function getProjectTypeSpecificInstructions(projectType) {
const instructions = {
react_app: `
### React App Specific Tips:
- Use "Analyze this React component structure" for architecture reviews
- Ask "How should I organize my React hooks?" for state management
- Request "Create a component testing strategy" for test planning`,
node_api: `
### Node.js API Specific Tips:
- Use "Review this API endpoint design" for architecture validation
- Ask "How should I structure my Express middleware?" for organization
- Request "Create a database schema plan" for data modeling`,
full_stack: `
### Full-Stack Specific Tips:
- Use "Plan the frontend-backend integration" for architecture alignment
- Ask "How should I share types between frontend and backend?" for type safety
- Request "Create a deployment strategy" for DevOps planning`,
general: `
### General Development Tips:
- Use specific, context-rich questions for better assistance
- Break down complex problems into smaller, manageable tasks
- Regularly ask for code reviews and architecture feedback`
};
return instructions[projectType] || instructions.general;
}
function generatePRDTemplate() {
return `# Project Requirements Document Template
## Project Overview
[Provide a clear, concise description of what you're building and why]
## Goals and Objectives
- [Primary goal 1]
- [Primary goal 2]
- [Primary goal 3]
## Core Features
1. **[Feature Name]**
- Description: [What this feature does]
- User benefit: [Why users need this]
- Acceptance criteria: [How to know it's done]
2. **[Feature Name]**
- Description: [What this feature does]
- User benefit: [Why users need this]
- Acceptance criteria: [How to know it's done]
## Technical Requirements
- **Technology Stack**: [Frontend, backend, database, etc.]
- **Performance**: [Load times, concurrent users, etc.]
- **Security**: [Authentication, data protection, etc.]
- **Scalability**: [Expected growth, capacity planning]
- **Compatibility**: [Browsers, devices, platforms]
## User Stories
1. As a [user type], I want [goal] so that [benefit]
2. As a [user type], I want [goal] so that [benefit]
3. As a [user type], I want [goal] so that [benefit]
## Success Criteria
- [Measurable success metric 1]
- [Measurable success metric 2]
- [Measurable success metric 3]
## Constraints and Assumptions
- **Budget**: [Budget constraints]
- **Timeline**: [Key deadlines and milestones]
- **Resources**: [Team size, skills available]
- **Technical**: [Existing systems, limitations]
## Risks and Mitigation
1. **Risk**: [Potential risk]
- **Impact**: [What happens if this occurs]
- **Mitigation**: [How to prevent or handle]
## Future Considerations
- [Potential features or improvements for later phases]
- [Scalability considerations]
- [Integration possibilities]
`;
}
function generateWorkspaceSuggestions(projectType) {
return `# Claude Code Setup for Claudemaster
## MCP Configuration
To enable Claudemaster in Claude Code, add this to your Claude Code configuration:
\`\`\`json
{
"mcpServers": {
"claudemaster": {
"command": "npx",
"args": ["-y", "claudemaster"]
}
}
}
\`\`\`
## Recommended Claude Code Workflow
### 1. Project Setup
\`\`\`
Initialize Claudemaster for my ${projectType} project
\`\`\`
### 2. Requirements Analysis
\`\`\`
Help me parse my PRD and create structured tasks
\`\`\`
### 3. Development Planning
\`\`\`
What's the next task I should work on?
Break down this complex task into subtasks
Analyze the complexity of my project tasks
\`\`\`
### 4. Implementation Guidance
\`\`\`
Create an implementation plan for [task name]
Help me implement [specific feature]
Review my approach for [component/module]
\`\`\`
### 5. Progress Monitoring
\`\`\`
Check my project health and progress
What tasks are blocking other work?
Suggest optimizations for my development workflow
\`\`\`
## Project-Specific Commands
${getProjectSpecificCommands(projectType)}
## Best Practices with Claude Code
1. **Be Specific**: Instead of "help with the frontend", say "help me implement the user authentication component in React"
2. **Provide Context**: Share relevant code, file structures, or previous decisions when asking for help
3. **Iterative Development**: Use Claudemaster to break down work into small, manageable chunks
4. **Regular Check-ins**: Periodically run project health checks to stay on track
5. **Document Decisions**: Ask Claude Code to help document architectural decisions and patterns
Happy coding! 🚀
`;
}
function getProjectSpecificCommands(projectType) {
const commands = {
react_app: `
### React App Commands
\`\`\`
Help me design the React component architecture
Create a state management strategy for my app
Plan the routing structure for my React app
Design a testing strategy for React components
\`\`\``,
node_api: `
### Node.js API Commands
\`\`\`
Help me design RESTful API endpoints
Create a database schema for my Node.js app
Plan error handling and logging for my API
Design authentication and authorization flow
\`\`\``,
full_stack: `
### Full-Stack Commands
\`\`\`
Plan the integration between frontend and backend
Create a shared type system for full-stack TypeScript
Design the deployment strategy for my full-stack app
Plan data flow between React frontend and Node.js backend
\`\`\``,
general: `
### General Development Commands
\`\`\`
Help me plan the architecture for [your project type]
Create a testing strategy for my application
Design error handling and logging approach
Plan the deployment and DevOps workflow
\`\`\``
};
return commands[projectType] || commands.general;
}
function getNextSteps(projectType, includeExamples) {
const steps = [
'Review the created directory structure in .taskmaster/',
includeExamples ? 'Examine the example PRD in docs/example_prd.txt' : 'Create your PRD in docs/prd.txt',
'Use claude_guided_prd_parsing to convert your PRD into tasks',
'Run get_next_task to see what to work on first',
'Use project_health_check periodically to monitor progress'
];
const projectSpecificSteps = {
react_app: ['Set up your React development environment', 'Plan your component architecture with Claude Code'],
node_api: ['Set up your Node.js development environment', 'Design your database schema with Claude Code'],
full_stack: ['Set up both frontend and backend development environments', 'Plan your full-stack architecture with Claude Code'],
general: ['Set up your development environment', 'Plan your project architecture with Claude Code']
};
return [...steps, ...projectSpecificSteps[projectType] || projectSpecificSteps.general];
}