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 ctx = (context + " " + task).toLowerCase();
// Smart Context Detection
const tags = {
isFrontend: /react|vue|svelte|frontend|ui|css|component/.test(ctx),
isBackend: /api|server|backend|endpoint|express|fastapi/.test(ctx),
isDatabase: /db|database|sql|mongo|schema|migration/.test(ctx),
isAuth: /auth|login|jwt|token|security|oauth/.test(ctx),
isRefactor: /refactor|rewrite|clean|debt/.test(ctx),
};
// Dynamic Step Generation
const steps = [];
// Phase 1: Analysis
steps.push({ phase: "Analysis", task: "Review requirements and context" });
if (tags.isRefactor)
steps.push({ phase: "Analysis", task: "Audit existing code and tests" });
if (tags.isDatabase)
steps.push({ phase: "Analysis", task: "Review schema impacts" });
// Phase 2: Design
steps.push({ phase: "Design", task: "Plan interfaces and types" });
if (tags.isFrontend && tags.isBackend)
steps.push({ phase: "Design", task: "Define API contract" });
if (tags.isDatabase)
steps.push({ phase: "Design", task: "Draft database schema/migration" });
if (tags.isAuth)
steps.push({ phase: "Design", task: "Review security implications" });
// Phase 3: Implementation
if (tags.isBackend) {
steps.push({ phase: "Implementation", task: "Implement core logic/API" });
if (tags.isDatabase)
steps.push({ phase: "Implementation", task: "Run database migrations" });
}
if (tags.isFrontend) {
steps.push({ phase: "Implementation", task: "Build UI components" });
steps.push({ phase: "Implementation", task: "Integrate with API/State" });
}
if (!tags.isFrontend && !tags.isBackend) {
steps.push({ phase: "Implementation", task: "Implement strict logic" });
}
// Phase 4: Testing
steps.push({ phase: "Testing", task: "Write unit tests" });
if (tags.isRefactor)
steps.push({ phase: "Testing", task: "Verify no regressions" });
if (tags.isFrontend)
steps.push({
phase: "Testing",
task: "Verify responsiveness/accessibility",
});
if (scope === "large") {
steps.push({ phase: "Review", task: "Perform security audit" });
steps.push({ phase: "Review", task: "Performance profiling" });
}
steps.push({ phase: "Review", task: "Self-review and refactor" });
const plan = `# Smart Task Plan: ${task}
${tags.isRefactor ? "> 🛠️ **Refactoring Mode Detected**" : ""}
${tags.isAuth ? "> 🔒 **Security Context Detected**" : ""}
## Context
${context || "No additional context provided."}
## Scope Assessment
**Estimated Scope**: ${scope.toUpperCase()}
**Analyzed Tags**: ${
Object.entries(tags)
.filter(([, v]) => v)
.map(([k]) => k.replace("is", ""))
.join(", ") || "General"
}
## Execution Steps
${steps
.map(
(s, i) => `### ${i + 1}. ${s.phase}: ${s.task}
- [ ] ${s.task}
- [ ] verify output`,
)
.join("\n")}
## Validation Criteria
- [ ] All tests pass
- [ ] No linting errors
${tags.isAuth ? "- [ ] Security requirements met (No leaked secrets)" : ""}
${tags.isRefactor ? "- [ ] Functionality equivalent to before" : ""}
## Rollback Plan
- Reset to clean git state if verification fails.
`;
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");
const lineCount = lines.length;
const analysis: any = {
quality: [],
security: [],
performance: [],
maintainability: [],
};
// --- Quality Checks ---
if (focus.includes("quality") || focus.includes("all")) {
if (lineCount > 300) {
analysis.quality.push(
`- **File Size**: Code is quite long (${lineCount} lines). Consider splitting into smaller modules.`,
);
}
const longFunctions = lines.filter((l: string) =>
/function\s+\w+\s*\(/.test(l),
).length; // rough heuristic
if (code.includes("any") && language === "typescript") {
analysis.quality.push(
`- **Type Safety**: Avoid using \`any\`. Use specific types or generics.`,
);
}
if (!code.includes("/**") && !code.includes("///")) {
analysis.quality.push(
`- **Documentation**: No JSDoc/comments found. Document public functions.`,
);
}
}
// --- Security Checks ---
if (focus.includes("security") || focus.includes("all")) {
if (/eval\(|exec\(/.test(code)) {
analysis.security.push(
`- 🚨 **Critical**: Avoid \`eval()\` or \`exec()\`. This is a major security risk.`,
);
}
if (/innerHTML/.test(code)) {
analysis.security.push(
`- ⚠️ **XSS Risk**: \`innerHTML\` usage detected. Ensure content is sanitized.`,
);
}
if (/(api_?key|secret|password|token)\s*[:=]\s*["'][^"']+["']/.test(code)) {
analysis.security.push(
`- ⚠️ **Secrets**: Hardcoded secrets detected. Use environment variables.`,
);
}
}
// --- Performance Checks ---
if (focus.includes("performance") || focus.includes("all")) {
// Check for nested loops
let nestedLoops = 0;
for (let i = 0; i < lines.length; i++) {
if (/\bfor\b|\bwhile\b/.test(lines[i])) {
// Very basic lookahead for nesting
if (i + 1 < lines.length && /\bfor\b|\bwhile\b/.test(lines[i + 1])) {
nestedLoops++;
}
}
}
if (nestedLoops > 0) {
analysis.performance.push(
`- **Complexity**: Nested loops detected. Check for O(n²) complexity.`,
);
}
if (
code.includes("await") &&
lines.some((l: string) => l.includes("map") && l.includes("await"))
) {
analysis.performance.push(
`- **Async**: \`await\` inside \`map\` often results in serial execution. Use \`Promise.all\`.`,
);
}
}
// --- Maintainability Checks ---
if (focus.includes("maintainability") || focus.includes("all")) {
const todoCount = (code.match(/TODO|FIXME/g) || []).length;
if (todoCount > 3) {
analysis.maintainability.push(
`- **Debt**: ${todoCount} TODOs found. Consider addressing them.`,
);
}
if (
lineCount > 0 &&
analysis.quality.length === 0 &&
analysis.security.length === 0
) {
analysis.maintainability.push(
`- **Good**: Code appears clean and maintainable.`,
);
}
}
// Formatting Output
const formatSection = (title: string, items: string[]) => {
if (items.length === 0) return "";
return `## ${title} Analysis\n${items.join("\n")}\n`;
};
let reflection = `# Code Reflection (${language})\n\n`;
reflection += `**Lines**: ${lineCount}\n\n`;
if (focus.includes("quality") || focus.includes("all"))
reflection += formatSection(
"Quality",
analysis.quality.length
? analysis.quality
: ["- No major quality issues found."],
);
if (focus.includes("security") || focus.includes("all"))
reflection += formatSection(
"Security",
analysis.security.length
? analysis.security
: ["- No obvious security issues found."],
);
if (focus.includes("performance") || focus.includes("all"))
reflection += formatSection(
"Performance",
analysis.performance.length
? analysis.performance
: ["- No obvious performance bottlenecks found."],
);
if (focus.includes("maintainability") || focus.includes("all"))
reflection += formatSection(
"Maintainability",
analysis.maintainability.length
? analysis.maintainability
: ["- Maintainability looks good."],
);
reflection += `\n## Action Plan\n1. Review strictness level.\n2. Address any critical security warnings immediately.\n3. Run tests to verify logic.`;
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;
// Heuristic: Suggest perspectives based on problem keywords
const perspectives = [];
const p = problem.toLowerCase();
if (p.includes("user") || p.includes("client"))
perspectives.push("User-Centric (UX Focus)");
if (p.includes("data") || p.includes("scale"))
perspectives.push("Data-First (Scalability Focus)");
if (p.includes("money") || p.includes("budget"))
perspectives.push("Lean (Cost Focus)");
if (p.includes("security") || p.includes("auth"))
perspectives.push("Zero-Trust (Security Focus)");
if (perspectives.length === 0)
perspectives.push("General Engineering", "Product Mindset");
const brainstorm = `# Brainstorm: ${problem}
## Recommended Perspectives
${perspectives.map((p) => `- ${p}`).join("\n")}
## 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;
// Keyword-based heuristics
const highImpactKeywords = [
"database",
"auth",
"security",
"payment",
"crypto",
"legacy",
"refactor",
];
const mediumImpactKeywords = ["api", "cache", "ui", "form", "validation"];
const t = task.toLowerCase();
const detectedComplexity =
highImpactKeywords.filter((k) => t.includes(k)).length * 2 +
mediumImpactKeywords.filter((k) => t.includes(k)).length;
let baseHours = 4; // minimum
let riskLevel = "Low";
if (detectedComplexity > 3) {
baseHours = 16;
riskLevel = "High";
} else if (detectedComplexity > 1) {
baseHours = 8;
riskLevel = "Medium";
}
const estimate = `# Complexity Estimate: ${task}
## Complexity Factors
${factors.length > 0 ? factors.map((f: string) => `- ${f}`).join("\n") : "Standard complexity assumed"}
${detectedComplexity > 0 ? `- **Detected Keywords**: Found high/medium impact terms suggesting ${riskLevel} complexity.` : ""}
---
## Effort Breakdown
| Component | Effort | Risk |
|-----------|--------|------|
| Research/Design | ${Math.ceil(baseHours * 0.2)}-${Math.ceil(baseHours * 0.3)} hours | Low |
| Core Implementation | ${Math.ceil(baseHours * 0.4)}-${Math.ceil(baseHours * 0.6)} hours | ${riskLevel} |
| Testing | ${Math.ceil(baseHours * 0.2)}-${Math.ceil(baseHours * 0.3)} hours | Low |
| Edge Cases | ${Math.ceil(baseHours * 0.1)}-${Math.ceil(baseHours * 0.2)} hours | Medium |
| Documentation | ${Math.ceil(baseHours * 0.1)} hour | Low |
| Review/Refinement | 1 hour | Low |
## Total Estimate
- **Optimistic**: ${baseHours} hours
- **Realistic**: ${Math.ceil(baseHours * 1.5)} hours
- **Pessimistic**: ${baseHours * 2} hours
## Complexity Score
**${riskLevel}** (${detectedComplexity > 3 ? "5/5" : detectedComplexity > 1 ? "3/5" : "1/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 }] };
}