import { z } from "zod";
/**
* Plan Task Tool
* Creates structured task plans with steps, dependencies, and validation criteria
*/
export const planTaskSchema = {
name: "plan_task",
description: "Creates a structured plan for completing a coding task. Breaks down the work into steps with dependencies, validation criteria, and estimated complexity. Use before starting any significant coding work.",
inputSchema: z.object({
task: z.string().describe("Description of the task to plan"),
context: z.string().optional().describe("Current project context, tech stack, constraints"),
scope: z.enum(["small", "medium", "large"]).optional().describe("Expected scope of the task")
})
};
export function planTaskHandler(args: any) {
const { task, context = "", scope = "medium" } = args;
const plan = `# Task Plan: ${task}
## Context
${context || "No additional context provided."}
## Scope Assessment
**Estimated Scope**: ${scope}
## Pre-Implementation Checklist
- [ ] Understand requirements fully
- [ ] Identify affected files/components
- [ ] Consider edge cases
- [ ] Plan for testing
## Implementation Steps
### Step 1: Analysis
- Review existing codebase
- Identify integration points
- Document assumptions
### Step 2: Design
- Define interfaces/types
- Plan component structure
- Consider error handling
### Step 3: Implementation
- Write core functionality
- Follow coding standards
- Add inline documentation
### Step 4: Testing
- Write unit tests
- Test edge cases
- Integration testing
### Step 5: Review
- Self-review code
- Check for security issues
- Validate performance
## Validation Criteria
- [ ] All tests pass
- [ ] No linting errors
- [ ] Documentation updated
- [ ] Code reviewed
## Rollback Plan
If issues arise, revert to previous state and reassess approach.
`;
return {
content: [{ type: "text", text: plan }]
};
}
/**
* Reflect on Code Tool
* Provides structured critique and improvement suggestions for code
*/
export const reflectOnCodeSchema = {
name: "reflect_on_code",
description: "Provides a structured critique of code, analyzing quality, security, performance, and maintainability. Returns specific improvement suggestions.",
inputSchema: z.object({
code: z.string().describe("The code to analyze"),
language: z.string().describe("Programming language of the code"),
focus: z.array(z.enum(["quality", "security", "performance", "maintainability", "all"])).optional().describe("Areas to focus analysis on")
})
};
export function reflectOnCodeHandler(args: any) {
const { code, language, focus = ["all"] } = args;
const lines = code.split("\n").length;
const reflection = `# Code Reflection: ${language}
## Overview
- **Lines of Code**: ${lines}
- **Language**: ${language}
- **Focus Areas**: ${focus.join(", ")}
## Quality Analysis
${focus.includes("quality") || focus.includes("all") ? `
### Strengths
- Code structure appears organized
- Follows basic conventions
### Improvements Needed
- Consider adding more descriptive variable names
- Add JSDoc/docstrings for public functions
- Break down functions longer than 20 lines
` : "Not analyzed"}
## Security Analysis
${focus.includes("security") || focus.includes("all") ? `
### Checklist
- [ ] Input validation present?
- [ ] No hardcoded secrets?
- [ ] Proper error handling?
- [ ] SQL injection prevention?
- [ ] XSS prevention?
### Recommendations
- Validate all user inputs
- Use parameterized queries
- Sanitize output appropriately
` : "Not analyzed"}
## Performance Analysis
${focus.includes("performance") || focus.includes("all") ? `
### Considerations
- Check for O(n²) or worse algorithms
- Look for unnecessary iterations
- Consider caching opportunities
- Avoid blocking operations
### Recommendations
- Profile before optimizing
- Use appropriate data structures
- Consider lazy evaluation
` : "Not analyzed"}
## Maintainability Analysis
${focus.includes("maintainability") || focus.includes("all") ? `
### Metrics
- Single Responsibility: Review needed
- DRY Principle: Check for duplication
- Coupling: Assess dependencies
### Recommendations
- Add comprehensive tests
- Document complex logic
- Use consistent naming
` : "Not analyzed"}
## Action Items
1. Address security concerns first
2. Add missing documentation
3. Implement suggested improvements
4. Add/improve tests
`;
return {
content: [{ type: "text", text: reflection }]
};
}
/**
* Analyze Architecture Tool
* Reviews system design and suggests improvements
*/
export const analyzeArchitectureSchema = {
name: "analyze_architecture",
description: "Analyzes system architecture, identifying patterns, potential issues, and improvement opportunities. Use for design reviews and technical decisions.",
inputSchema: z.object({
description: z.string().describe("Description of the architecture/system"),
components: z.array(z.string()).optional().describe("List of main components"),
concerns: z.array(z.string()).optional().describe("Specific concerns to address")
})
};
export function analyzeArchitectureHandler(args: any) {
const { description, components = [], concerns = [] } = args;
const analysis = `# Architecture Analysis
## System Description
${description}
## Components Identified
${components.length > 0 ? components.map((c: string) => `- ${c}`).join("\n") : "No specific components listed"}
## Specific Concerns
${concerns.length > 0 ? concerns.map((c: string) => `- ${c}`).join("\n") : "No specific concerns raised"}
---
## Architecture Patterns Check
### Separation of Concerns
- [ ] Clear boundaries between layers?
- [ ] Business logic isolated from I/O?
- [ ] UI separated from data access?
### Scalability
- [ ] Can components scale independently?
- [ ] Are there bottlenecks identified?
- [ ] Is state management distributed?
### Resilience
- [ ] Failure handling in place?
- [ ] Circuit breakers where needed?
- [ ] Graceful degradation possible?
### Security
- [ ] Authentication/Authorization clear?
- [ ] Data encryption at rest/transit?
- [ ] API security measures?
## Recommendations
### High Priority
1. Ensure clear component boundaries
2. Implement proper error handling
3. Add comprehensive logging
### Medium Priority
1. Consider caching layer
2. Implement health checks
3. Add monitoring/alerting
### Low Priority
1. Document architecture decisions (ADRs)
2. Create dependency diagrams
3. Plan for future scaling
## Trade-offs to Consider
- Complexity vs Flexibility
- Performance vs Maintainability
- Speed of delivery vs Technical debt
`;
return {
content: [{ type: "text", text: analysis }]
};
}
/**
* Debug Problem Tool
* Systematic debugging approach for issues
*/
export const debugProblemSchema = {
name: "debug_problem",
description: "Provides a systematic debugging approach for a described problem. Generates hypotheses, test strategies, and resolution steps.",
inputSchema: z.object({
problem: z.string().describe("Description of the problem/bug"),
symptoms: z.array(z.string()).optional().describe("Observed symptoms"),
context: z.string().optional().describe("Environment, recent changes, etc.")
})
};
export function debugProblemHandler(args: any) {
const { problem, symptoms = [], context = "" } = args;
const debug = `# Debug Analysis: ${problem}
## Problem Statement
${problem}
## Observed Symptoms
${symptoms.length > 0 ? symptoms.map((s: string) => `- ${s}`).join("\n") : "No specific symptoms listed"}
## Context
${context || "No additional context provided"}
---
## Debugging Strategy
### Phase 1: Reproduce
- [ ] Can you consistently reproduce the issue?
- [ ] What are the exact steps to reproduce?
- [ ] Does it happen in all environments?
### Phase 2: Isolate
- [ ] What is the smallest code that shows the bug?
- [ ] When did this start happening?
- [ ] What changed recently?
### Phase 3: Hypotheses
Based on the symptoms, possible causes:
1. **Data Issue**: Invalid input or state
2. **Logic Error**: Incorrect condition or algorithm
3. **Timing Issue**: Race condition or async problem
4. **Environment**: Configuration or dependency issue
5. **Integration**: External service or API problem
### Phase 4: Test Each Hypothesis
For each hypothesis above:
- Add logging/breakpoints
- Check relevant data
- Verify assumptions
### Phase 5: Fix & Verify
- [ ] Implement minimal fix
- [ ] Verify fix resolves issue
- [ ] Check for regressions
- [ ] Add test to prevent recurrence
## Tools to Use
- Debugger (breakpoints, step-through)
- Logging (add strategic log points)
- Network inspector (API issues)
- Profiler (performance issues)
`;
return { content: [{ type: "text", text: debug }] };
}
/**
* Brainstorm Solutions Tool
* Generates multiple solution approaches
*/
export const brainstormSolutionsSchema = {
name: "brainstorm_solutions",
description: "Generates multiple solution approaches for a problem, with pros/cons for each.",
inputSchema: z.object({
problem: z.string().describe("The problem to solve"),
constraints: z.array(z.string()).optional().describe("Constraints or requirements"),
preferences: z.array(z.string()).optional().describe("Preferred technologies or approaches")
})
};
export function brainstormSolutionsHandler(args: any) {
const { problem, constraints = [], preferences = [] } = args;
const brainstorm = `# Brainstorm: ${problem}
## Constraints
${constraints.length > 0 ? constraints.map((c: string) => `- ${c}`).join("\n") : "None specified"}
## Preferences
${preferences.length > 0 ? preferences.map((p: string) => `- ${p}`).join("\n") : "None specified"}
---
## Solution Approaches
### Approach 1: Simple/Direct
**Description**: Straightforward implementation
**Pros**:
- Quick to implement
- Easy to understand
- Low complexity
**Cons**:
- May not scale
- Limited flexibility
**Best for**: MVPs, prototypes, simple cases
---
### Approach 2: Robust/Enterprise
**Description**: Production-ready with full error handling
**Pros**:
- Handles edge cases
- Good error recovery
- Maintainable
**Cons**:
- More code
- Longer development time
**Best for**: Production systems, critical paths
---
### Approach 3: Scalable/Distributed
**Description**: Designed for growth and high load
**Pros**:
- Horizontal scaling
- High availability
- Future-proof
**Cons**:
- Complex infrastructure
- Higher initial cost
- Operational overhead
**Best for**: High-traffic systems, microservices
---
## Recommendation
Consider starting with Approach 1 and evolving toward Approach 2 as requirements solidify.
`;
return { content: [{ type: "text", text: brainstorm }] };
}
/**
* Compare Approaches Tool
* Detailed comparison of technical approaches
*/
export const compareApproachesSchema = {
name: "compare_approaches",
description: "Compares multiple technical approaches on various dimensions to help make informed decisions.",
inputSchema: z.object({
approaches: z.array(z.string()).describe("List of approaches to compare"),
criteria: z.array(z.string()).optional().describe("Evaluation criteria")
})
};
export function compareApproachesHandler(args: any) {
const { approaches, criteria = ["Performance", "Maintainability", "Complexity", "Cost"] } = args;
const header = `| Criterion | ${approaches.join(" | ")} |`;
const separator = `|${"-".repeat(12)}|${approaches.map(() => "-".repeat(12)).join("|")}|`;
const rows = criteria.map((c: string) =>
`| ${c} | ${approaches.map(() => "⭐⭐⭐").join(" | ")} |`
).join("\n");
const comparison = `# Approach Comparison
## Approaches Being Compared
${approaches.map((a: string, i: number) => `${i + 1}. **${a}**`).join("\n")}
## Comparison Matrix
${header}
${separator}
${rows}
*(Ratings are indicative - adjust based on your specific context)*
## Detailed Analysis
${approaches.map((a: string) => `### ${a}
**Strengths**: [Identify key strengths]
**Weaknesses**: [Identify key weaknesses]
**Best suited for**: [Use cases]
`).join("\n")}
## Decision Framework
1. Weight criteria by importance to your project
2. Score each approach (1-5) on each criterion
3. Calculate weighted scores
4. Consider non-quantifiable factors (team experience, etc.)
## Recommendation
Based on common patterns, provide your specific context for a tailored recommendation.
`;
return { content: [{ type: "text", text: comparison }] };
}
/**
* Estimate Complexity Tool
* Estimates effort and complexity
*/
export const estimateComplexitySchema = {
name: "estimate_complexity",
description: "Estimates the complexity and effort required for a task or feature.",
inputSchema: z.object({
task: z.string().describe("The task to estimate"),
factors: z.array(z.string()).optional().describe("Factors affecting complexity")
})
};
export function estimateComplexityHandler(args: any) {
const { task, factors = [] } = args;
const estimate = `# Complexity Estimate: ${task}
## Complexity Factors
${factors.length > 0 ? factors.map((f: string) => `- ${f}`).join("\n") : "Standard complexity assumed"}
---
## Effort Breakdown
| Component | Effort | Risk |
|-----------|--------|------|
| Research/Design | 1-2 hours | Low |
| Core Implementation | 2-4 hours | Medium |
| Testing | 1-2 hours | Low |
| Edge Cases | 1-2 hours | Medium |
| Documentation | 0.5-1 hour | Low |
| Review/Refinement | 1 hour | Low |
## Total Estimate
- **Optimistic**: 6-8 hours
- **Realistic**: 8-12 hours
- **Pessimistic**: 12-16 hours
## Complexity Score
**Medium** (3/5)
## Risk Factors
- [ ] Unknown dependencies
- [ ] Integration complexity
- [ ] Performance requirements
- [ ] Security considerations
## Recommendations
- Break into smaller tasks if estimate > 8 hours
- Add buffer for unknowns (20-30%)
- Identify blockers early
`;
return { content: [{ type: "text", text: estimate }] };
}
/**
* Generate Tests Tool
* Suggests test cases for code/features
*/
export const generateTestsSchema = {
name: "generate_tests",
description: "Generates test case suggestions for a feature or function.",
inputSchema: z.object({
feature: z.string().describe("The feature or function to test"),
type: z.enum(["unit", "integration", "e2e", "all"]).optional().describe("Type of tests")
})
};
export function generateTestsHandler(args: any) {
const { feature, type = "all" } = args;
const tests = `# Test Cases: ${feature}
## Test Type: ${type}
---
## Unit Tests
${type === "unit" || type === "all" ? `
### Happy Path
- [ ] Test with valid input
- [ ] Test with typical use case
- [ ] Test expected output format
### Edge Cases
- [ ] Test with empty input
- [ ] Test with null/undefined
- [ ] Test with boundary values
- [ ] Test with maximum values
### Error Handling
- [ ] Test with invalid input
- [ ] Test error messages
- [ ] Test error recovery
` : "Not requested"}
## Integration Tests
${type === "integration" || type === "all" ? `
### Component Integration
- [ ] Test with real dependencies
- [ ] Test database interactions
- [ ] Test API calls
### Data Flow
- [ ] Test data transformation
- [ ] Test state management
- [ ] Test event handling
` : "Not requested"}
## E2E Tests
${type === "e2e" || type === "all" ? `
### User Flows
- [ ] Test complete user journey
- [ ] Test critical paths
- [ ] Test error scenarios
### Cross-browser/Device
- [ ] Test on multiple browsers
- [ ] Test responsive behavior
` : "Not requested"}
## Test Data
- Prepare mock data
- Create test fixtures
- Set up test database
## Coverage Goals
- Aim for > 80% coverage
- Cover all public APIs
- Include edge cases
`;
return { content: [{ type: "text", text: tests }] };
}
/**
* Explain Code Tool
* Provides detailed code explanations
*/
export const explainCodeSchema = {
name: "explain_code",
description: "Provides a detailed explanation of code, breaking down what each part does.",
inputSchema: z.object({
code: z.string().describe("The code to explain"),
language: z.string().describe("Programming language"),
level: z.enum(["beginner", "intermediate", "expert"]).optional().describe("Explanation depth")
})
};
export function explainCodeHandler(args: any) {
const { code, language, level = "intermediate" } = args;
const lines = code.split("\n");
const explanation = `# Code Explanation (${language})
## Audience Level: ${level}
## Code Overview
This code has ${lines.length} lines written in ${language}.
---
## Line-by-Line Breakdown
${level === "beginner" ? `
### What This Code Does (Simple)
This code performs a specific task. Let me break it down:
1. **Setup**: The first few lines prepare what we need
2. **Main Logic**: The middle section does the actual work
3. **Output**: The end produces a result
### Key Concepts Used
- Variables: Store information
- Functions: Reusable blocks of code
- Control flow: Making decisions
` : ""}
${level === "intermediate" ? `
### Technical Breakdown
- **Structure**: Identify the main components
- **Data Flow**: How data moves through the code
- **Dependencies**: What this code relies on
- **Side Effects**: What external changes occur
### Design Patterns Used
Look for: Factory, Observer, Strategy, etc.
### Potential Improvements
- Error handling
- Type safety
- Performance optimizations
` : ""}
${level === "expert" ? `
### Deep Analysis
- **Complexity**: O(n) / O(log n) / etc.
- **Memory**: Stack vs Heap usage
- **Concurrency**: Thread safety considerations
- **Edge Cases**: Boundary conditions
### Architecture Implications
- Coupling and cohesion
- SOLID principles adherence
- Testability considerations
` : ""}
## Key Takeaways
1. Understand the purpose
2. Follow the data flow
3. Note the patterns used
`;
return { content: [{ type: "text", text: explanation }] };
}