mcp-repl
Version:
MCP REPL with code execution, semantic code search, and comprehensive ast-grep integration
236 lines • 112 kB
JSON
{
"executenodejs": {
"name": "executenodejs",
"description": "**PRIMARY EXECUTION ENGINE** - Execute JavaScript code with Node.js. **ALWAYS USE THIS TOOL FIRST** for code testing, debugging, and investigation.\n\n**MANDATORY WORKING DIRECTORY:**\n• workingDirectory parameter is **REQUIRED** and **MUST BE SET** - specify the exact directory context\n• Each execution runs in the specified directory as its current working directory\n• Use absolute paths or relative paths from the working directory\n• Working directory affects: file operations, module resolution, process.cwd()\n• **ALWAYS provide this parameter** - execution will fail without it\n\n**AUTOMATIC RESPONSE TRUNCATION & OVERFLOW HANDLING:**\n• **25k Token Limit**: Responses exceeding ~25,000 tokens are automatically truncated\n• **Overflow Storage**: Excess content stored in `.call_overflow/` directory within workingDirectory\n• **Seamless Retrieval**: Use `retrieve_overflow` tool to access stored content chunks\n• **Preservation Guarantee**: Leading content always preserved, nothing lost permanently\n• **Clear Instructions**: Truncation notices provide exact steps to retrieve remaining content\n• **Example**: If truncated, response shows \"Use 'retrieve_overflow' tool with file: 'overflow_executenodejs_1234567890.json'\"\n\n**COMPREHENSIVE BATCHING CAPABILITIES:**\nThis tool can batch ALL of the following operations in a single call:\n• **File System Operations**: Reading, writing, analyzing multiple files simultaneously\n• **API Testing**: Multiple HTTP requests with Promise.allSettled() for parallel execution\n• **Data Processing**: Transform, validate, and analyze datasets in loops/maps\n• **Module Testing**: Import and test multiple modules or functions together\n• **Performance Analysis**: Benchmark multiple approaches in single execution\n• **Database Operations**: Multiple queries, transactions, schema analysis\n• **Configuration Management**: Read, validate, transform config files\n• **Code Generation**: Create multiple files, templates, or code structures\n• **Error Simulation**: Test multiple error scenarios and recovery patterns\n• **Integration Testing**: End-to-end workflows with multiple service calls\n\n**CRITICAL EFFICIENCY PRINCIPLES:**\n• **BATCH AGGRESSIVELY** - Combine 5-10 related operations in single calls (10x faster than individual calls)\n• **CONSOLIDATE LOGIC** - Group testing, validation, file ops, API calls, and analysis together\n• **USE LOOPS/ARRAYS** - Process multiple items, files, or tests simultaneously\n• **AVOID SEQUENTIAL CALLS** - Plan comprehensive solutions that accomplish multiple goals at once\n\n**ADVANCED BATCHING STRATEGIES:**\n```javascript\n// EXCELLENT: Complete workflow in single execution\nconst fs = require('fs');\nconst path = require('path');\nconst https = require('https');\n\n// Batch file analysis + API validation + performance testing\nconst files = ['config.js', 'utils.js', 'api.js'];\nconst apis = ['https://api1.com/health', 'https://api2.com/status'];\n\nconst results = {\n fileAnalysis: files.map(file => {\n const content = fs.readFileSync(path.join(__dirname, file), 'utf8');\n return {\n file,\n size: content.length,\n functions: (content.match(/function\\s+\\w+/g) || []).length,\n hasTests: content.includes('test(') || content.includes('it(')\n };\n }),\n apiHealth: await Promise.allSettled(apis.map(testEndpoint)),\n performance: measureExecutionTime(() => processLargeDataset())\n};\n\nconsole.log('Complete Analysis:', JSON.stringify(results, null, 2));\n```\n\n**REPLACE ALL EXTERNAL TOOLS:**\n• Instead of curl → use fetch(), https, or axios with batched requests\n• Instead of file commands → use fs module with parallel operations\n• Instead of grep/search → use JavaScript regex and string processing\n• Instead of multiple CLI tools → write unified JavaScript solutions\n• Instead of bash scripts → implement in JavaScript with full error handling\n\n**WORKING DIRECTORY FUNCTIONALITY:**\n• **Execution Context**: All file operations use workingDirectory as base\n• **Module Resolution**: Node.js resolves modules relative to workingDirectory\n• **Process CWD**: process.cwd() returns the specified workingDirectory\n• **Path Operations**: Relative paths are resolved from workingDirectory\n• **Child Processes**: Spawned processes inherit the working directory context\n• **File Globbing**: Glob patterns operate within the working directory scope\n\n**OUTPUT OPTIMIZATION STRATEGIES:**\n• Use console.log() strategically - only log essential results and summaries\n• Summarize large datasets instead of dumping raw data\n• Use JSON.stringify(obj, null, 2) for readable object inspection\n• Implement result filtering/truncation within your code\n• Return structured summaries rather than verbose logs\n• Group related outputs under clear headings\n\n**DEBUGGING METHODOLOGY:**\n1. **Hypothesis Formation** - Write code that tests specific assumptions\n2. **Batch Validation** - Test multiple scenarios simultaneously\n3. **Incremental Refinement** - Use results to guide next batch of tests\n4. **Comprehensive Coverage** - Ensure all edge cases tested in minimal calls\n5. **Error Boundary Testing** - Include error scenarios in batch operations\n\n**PERFORMANCE OPTIMIZATION:**\n• **Parallel Processing**: Use Promise.allSettled() for independent operations\n• **Stream Processing**: Handle large files with streams to avoid memory issues\n• **Caching Strategies**: Store repeated computations in variables\n• **Efficient Data Structures**: Use appropriate data structures for operations\n• **Memory Management**: Clean up large objects and close file handles",
"inputSchema": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "JavaScript code to execute - use for debugging, testing hypotheses, and investigation"
},
"timeout": {
"type": "number",
"description": "Optional timeout in milliseconds (default: 120000)"
},
"workingDirectory": {
"type": "string",
"description": "**MANDATORY WORKING DIRECTORY** - workingDirectory parameter is **REQUIRED** and **MUST BE SET**. Specify the exact directory path for code execution. All file operations, module resolution, and process.cwd() will use this directory as the base context. **ALWAYS provide this parameter** - execution will fail without it."
}
},
"required": [
"code",
"workingDirectory"
]
}
},
"executedeno": {
"name": "executedeno",
"description": "**TYPESCRIPT EXECUTION ENGINE** - Execute TypeScript/JavaScript with Deno runtime. **ALWAYS USE FOR TYPE-SAFE OPERATIONS** and when TypeScript validation is needed.\n\n**MANDATORY WORKING DIRECTORY:**\n• workingDirectory parameter is **REQUIRED** and **MUST BE SET** - specify the exact directory context\n• Each execution runs in the specified directory as its current working directory\n• Deno resolves imports and modules relative to the working directory\n• File permissions and access are scoped to the working directory context\n• **ALWAYS provide this parameter** - execution will fail without it\n\n**AUTOMATIC RESPONSE TRUNCATION & OVERFLOW HANDLING:**\n• **25k Token Limit**: Responses exceeding ~25,000 tokens are automatically truncated\n• **Overflow Storage**: Excess content stored in `.call_overflow/` directory within workingDirectory\n• **Seamless Retrieval**: Use `retrieve_overflow` tool to access stored content chunks\n• **Preservation Guarantee**: Leading content always preserved, nothing lost permanently\n• **Clear Instructions**: Truncation notices provide exact steps to retrieve remaining content\n• **Example**: If truncated, response shows \"Use 'retrieve_overflow' tool with file: 'overflow_executedeno_1234567890.json'\"\n\n**COMPREHENSIVE BATCHING CAPABILITIES:**\nThis tool can batch ALL of the following TypeScript/JavaScript operations:\n• **Type Checking**: Validate multiple TypeScript files and interfaces simultaneously\n• **Module Testing**: Import and test multiple TypeScript modules together\n• **API Integration**: Batch HTTP requests with full type safety and error handling\n• **File Processing**: Read, analyze, and transform multiple files with type validation\n• **Code Generation**: Generate TypeScript types, interfaces, and implementation files\n• **Schema Validation**: Validate multiple data structures against TypeScript interfaces\n• **Web Standards Testing**: Test Web APIs, fetch requests, and browser compatibility\n• **Performance Benchmarking**: Type-safe performance testing of multiple algorithms\n• **Configuration Parsing**: Validate and process multiple config files with types\n• **Security Analysis**: Type-safe validation of security patterns and implementations\n\n**ADVANCED BATCHING STRATEGIES:**\n```typescript\n// EXCELLENT: Complete TypeScript workflow\ninterface APIEndpoint { url: string; method: string; expectedStatus: number; }\ninterface FileAnalysis { path: string; valid: boolean; issues: string[]; }\n\n// Batch API testing + file validation + type checking\nconst endpoints: APIEndpoint[] = [\n { url: 'https://api1.com/health', method: 'GET', expectedStatus: 200 },\n { url: 'https://api2.com/status', method: 'GET', expectedStatus: 200 }\n];\n\nconst configFiles = ['config.ts', 'types.ts', 'utils.ts'];\n\nconst results = {\n apiTests: await Promise.allSettled(\n endpoints.map(async (endpoint): Promise<{ endpoint: APIEndpoint; success: boolean }> => {\n const response = await fetch(endpoint.url, { method: endpoint.method });\n return { endpoint, success: response.status === endpoint.expectedStatus };\n })\n ),\n fileAnalysis: configFiles.map((file): FileAnalysis => {\n try {\n const content = Deno.readTextFileSync(file);\n const issues: string[] = [];\n if (!content.includes('export')) issues.push('No exports found');\n if (content.includes('any')) issues.push('Uses any type');\n return { path: file, valid: issues.length === 0, issues };\n } catch (error) {\n return { path: file, valid: false, issues: [error.message] };\n }\n }),\n typeValidation: validateComplexTypes()\n};\n\nconsole.log('TypeScript Analysis:', Deno.inspect(results, { depth: 3 }));\n```\n\n**REPLACE ALL TYPESCRIPT TOOLS:**\n• Instead of tsc → use Deno's built-in TypeScript compilation with batch processing\n• Instead of separate test runners → use Deno.test() in comprehensive batched scenarios\n• Instead of external formatters → use Deno fmt programmatically on multiple files\n• Instead of multiple HTTP clients → use native fetch with full type safety\n• Instead of separate linters → use Deno lint with custom validation logic\n• Instead of webpack/bundlers → use Deno bundle with dependency analysis\n\n**TYPE-DRIVEN DEVELOPMENT PATTERNS:**\n• **Interface-First Design**: Define comprehensive interfaces for all batch operations\n• **Generic Batch Processing**: Create reusable typed functions for common patterns\n• **Union Type Handling**: Use discriminated unions for multiple operation types\n• **Type Guard Implementation**: Runtime validation with compile-time type safety\n• **Mapped Type Utilities**: Transform types programmatically for batch operations\n\n**WEB API & SECURITY OPTIMIZATION:**\n• **Batch HTTP Operations**: Promise.allSettled() with full type safety and error handling\n• **Stream Processing**: Use Web Streams API for efficient large data processing\n• **Caching Strategies**: Leverage Deno's built-in caching with type validation\n• **Permission Management**: Runs with --allow-all for comprehensive operations\n• **Security Validation**: Type-safe input validation and output sanitization\n\n**WORKING DIRECTORY FUNCTIONALITY:**\n• **Import Resolution**: TypeScript/JavaScript imports resolved relative to workingDirectory\n• **Type Definition Access**: .d.ts files and @types packages accessed from working directory\n• **File Operations**: All Deno file APIs operate within working directory context\n• **Module Cache**: Deno module cache scoped to working directory dependencies\n• **Configuration Files**: deno.json, import_map.json loaded from working directory\n\n**OUTPUT OPTIMIZATION FOR DENO:**\n• Use Deno.inspect() for superior object formatting with type information\n• Leverage built-in formatters and type-aware validators\n• Implement streaming for large data processing with type safety\n• Use structured logging with typed log entries\n• Return typed results with comprehensive error information\n\n**PERFORMANCE & EFFICIENCY:**\n• **Parallel Type Checking**: Validate multiple files simultaneously\n• **Concurrent API Testing**: Batch HTTP requests with proper error boundaries\n• **Memory Efficiency**: Use generators and iterators for large dataset processing\n• **Compilation Caching**: Leverage Deno's built-in compilation cache\n• **Dependency Optimization**: Analyze and optimize import graphs",
"inputSchema": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "JavaScript/TypeScript code to execute - use for debugging, testing hypotheses, and investigation"
},
"timeout": {
"type": "number",
"description": "Optional timeout in milliseconds (default: 120000)"
},
"workingDirectory": {
"type": "string",
"description": "**MANDATORY WORKING DIRECTORY** - workingDirectory parameter is **REQUIRED** and **MUST BE SET**. Specify the exact directory path for Deno execution. All imports, file operations, and type resolution occur relative to this directory. **ALWAYS provide this parameter** - execution will fail without it."
}
},
"required": [
"code",
"workingDirectory"
]
}
},
"searchcode": {
"name": "searchcode",
"description": "**INTELLIGENT CODE DISCOVERY** - AI-powered semantic search with structural understanding. **ALWAYS USE THIS FIRST** for code exploration before reading files or using other search tools.\n\n**MANDATORY WORKING DIRECTORY:**\n• workingDirectory parameter is **REQUIRED** - specify the exact codebase to search\n• Search operates within the specified directory and its subdirectories\n• AI indexing and semantic understanding scoped to working directory contents\n• All relative paths in results are relative to the working directory\n• **ALWAYS provide this parameter** - search will fail without it\n\n**AUTOMATIC RESPONSE TRUNCATION & OVERFLOW HANDLING:**\n• **25k Token Limit**: Responses exceeding ~25,000 tokens are automatically truncated\n• **Overflow Storage**: Excess content stored in `.call_overflow/` directory within workingDirectory\n• **Seamless Retrieval**: Use `retrieve_overflow` tool to access stored content chunks\n• **Preservation Guarantee**: Leading content always preserved, nothing lost permanently\n• **Clear Instructions**: Truncation notices provide exact steps to retrieve remaining content\n• **Example**: If truncated, response shows \"Use 'retrieve_overflow' tool with file: 'overflow_searchcode_1234567890.json'\"\n\n**COMPREHENSIVE BATCHING CAPABILITIES:**\nThis tool can efficiently batch ALL of the following search operations:\n• **Multi-Concept Queries**: Combine related concepts in single queries for comprehensive discovery\n• **Architecture Exploration**: Find multiple related patterns (controllers + models + views) simultaneously\n• **Security Auditing**: Batch searches for authentication, validation, and security patterns\n• **Feature Analysis**: Discover complete feature implementations across multiple files\n• **Integration Mapping**: Find API endpoints, database queries, and service integrations together\n• **Error Pattern Discovery**: Locate error handling, logging, and exception patterns in one search\n• **Performance Investigation**: Batch searches for bottlenecks, caching, and optimization opportunities\n• **Configuration Analysis**: Find environment variables, settings, and configuration patterns\n• **Dependency Mapping**: Discover import/export relationships and module dependencies\n• **Code Quality Assessment**: Batch searches for code smells, anti-patterns, and quality issues\n\n**ADVANCED QUERY STRATEGIES:**\n```\n// EXCELLENT: Comprehensive architecture discovery\n\"authentication middleware session management security validation JWT token\"\n\n// EXCELLENT: Complete feature investigation\n\"user registration email verification password reset database operations\"\n\n// EXCELLENT: Performance and error analysis\n\"database queries caching error handling logging performance optimization\"\n\n// EXCELLENT: Integration and API discovery\n\"REST API endpoints GraphQL resolvers database connections external services\"\n```\n\n**INTELLIGENT BATCHING TECHNIQUES:**\n• **Conceptual Grouping**: Combine semantically related terms to find complete implementations\n• **Layer-Aware Searching**: Include frontend, backend, and database terms in single queries\n• **Pattern-Based Discovery**: Search for architectural patterns, design patterns, and code structures\n• **Cross-Functional Analysis**: Find features that span multiple domains or services\n• **Technical Stack Exploration**: Discover technology-specific implementations and integrations\n\n**SEARCH SCOPE OPTIMIZATION:**\n• **folders parameter**: Target specific areas like \"src/api,src/services,src/models\" for backend analysis\n• **extensions parameter**: Focus on relevant technologies: \"js,ts,jsx,tsx\" for React, \"py,sql\" for Python/DB\n• **ignores parameter**: Exclude irrelevant areas: \"test,spec,node_modules,dist,build\" for production focus\n• **topK parameter**: Control result volume: 8-15 for exploration, 20-50 for comprehensive analysis\n\n**WORKING DIRECTORY FUNCTIONALITY:**\n• **Index Scope**: AI semantic indexing operates on all files within working directory\n• **Relationship Mapping**: Code relationships and dependencies mapped within directory context\n• **Structure Analysis**: Class hierarchies, function calls, and imports analyzed per directory\n• **Search Accuracy**: Results ranked by relevance within the specific codebase context\n• **Path Resolution**: All file paths in results are relative to the working directory\n\n**STRUCTURAL AWARENESS ADVANTAGES:**\n• **Function Discovery**: Finds functions with parameters, return types, and full context\n• **Class Analysis**: Discovers classes with inheritance, methods, and property relationships\n• **Module Understanding**: Maps imports, exports, and inter-module dependencies\n• **API Mapping**: Identifies REST endpoints, GraphQL resolvers, and service interfaces\n• **Database Integration**: Finds queries, models, and database interaction patterns\n• **Configuration Detection**: Locates environment variables, settings, and config patterns\n\n**EFFICIENT EXPLORATION WORKFLOWS:**\n1. **Initial Architecture Survey**: \"main entry points routing middleware database configuration\"\n2. **Feature Deep Dive**: \"user management authentication authorization permissions\"\n3. **Integration Analysis**: \"external API calls third party services webhooks\"\n4. **Security Assessment**: \"input validation sanitization authentication authorization\"\n5. **Performance Investigation**: \"database queries caching async operations bottlenecks\"\n6. **Error Handling Review**: \"try catch error handling logging exception management\"\n\n**RESULTS INTERPRETATION GUIDE:**\n• **High scores (>0.8)**: Directly relevant implementations, primary candidates\n• **Medium scores (0.6-0.8)**: Related functionality, secondary analysis targets\n• **Low scores (<0.6)**: Contextual relevance, background understanding\n• **Qualified names**: Full module/class/function paths show code organization\n• **Structure metadata**: Parameters, types, inheritance provide implementation details\n• **Documentation**: Extracted comments and docstrings provide usage context\n\n**OUTPUT OPTIMIZATION:**\n• **Focus on high-scoring matches** for immediate investigation\n• **Extract architectural insights** from result patterns\n• **Identify implementation clusters** across multiple files\n• **Map feature boundaries** using structural metadata\n• **Synthesize findings** rather than listing raw results",
"inputSchema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Semantic search query for code - use broad, conceptual terms for best results"
},
"folders": {
"type": "string",
"description": "Optional comma-separated list of folders to search within working directory"
},
"extensions": {
"type": "string",
"description": "Optional comma-separated list of file extensions to include (default: js,ts)"
},
"ignores": {
"type": "string",
"description": "Optional comma-separated list of patterns to ignore (default: node_modules)"
},
"topK": {
"type": "number",
"description": "Optional number of results to return (default: 8, recommended: 8-15 for exploration)"
},
"workingDirectory": {
"type": "string",
"description": "**MANDATORY WORKING DIRECTORY** - workingDirectory parameter is **REQUIRED** and **MUST BE SET**. Specify the exact directory path containing the codebase to search. All search operations are strictly scoped to this directory and its subdirectories. **ALWAYS provide this parameter** - search will fail without it."
}
},
"required": [
"query",
"workingDirectory"
]
}
},
"astgrep_search": {
"name": "astgrep_search",
"description": "**STRUCTURAL CODE ANALYSIS** - AST-based pattern matching for precise code discovery. **ALWAYS USE FOR STRUCTURAL PATTERN MATCHING** when you need exact syntactic matches.\n\n**MANDATORY WORKING DIRECTORY:**\n• workingDirectory parameter is **REQUIRED** - specify the exact codebase directory for AST analysis\n• AST parsing operates on all source files within the working directory tree\n• Pattern matching respects language-specific syntax within directory context\n• All file paths in results are relative to the working directory\n• **ALWAYS provide this parameter** - analysis will fail without it\n\n**AUTOMATIC RESPONSE TRUNCATION & OVERFLOW HANDLING:**\n• **25k Token Limit**: Responses exceeding ~25,000 tokens are automatically truncated\n• **Overflow Storage**: Excess content stored in `.call_overflow/` directory within workingDirectory\n• **Seamless Retrieval**: Use `retrieve_overflow` tool to access stored content chunks\n• **Preservation Guarantee**: Leading content always preserved, nothing lost permanently\n• **Clear Instructions**: Truncation notices provide exact steps to retrieve remaining content\n• **Example**: If truncated, response shows \"Use 'retrieve_overflow' tool with file: 'overflow_astgrep_search_1234567890.json'\"\n\n**COMPREHENSIVE STRUCTURAL BATCHING:**\nThis tool can efficiently batch ALL of the following AST pattern operations:\n• **Architecture Pattern Discovery**: Find controllers, models, views, and their relationships simultaneously\n• **Security Pattern Auditing**: Batch searches for authentication, authorization, input validation, and sanitization\n• **Error Handling Analysis**: Discover try/catch blocks, error throwing, and exception handling patterns\n• **Performance Pattern Investigation**: Find loops, recursive calls, database queries, and async operations\n• **API Pattern Mapping**: Locate REST endpoints, GraphQL resolvers, middleware, and route handlers\n• **Database Pattern Analysis**: Find ORM usage, query building, transactions, and connection patterns\n• **Configuration Pattern Discovery**: Locate environment variable usage, config objects, and settings\n• **Testing Pattern Identification**: Find test functions, mocks, assertions, and test utilities\n• **Import/Export Analysis**: Discover module dependencies, import patterns, and export structures\n• **Code Quality Pattern Detection**: Find code smells, anti-patterns, and structural inconsistencies\n\n**ADVANCED PATTERN STRATEGIES:**\n```\n// EXCELLENT: Comprehensive function analysis with error handling\nfunction $NAME($$$PARAMS) {\n try {\n $$$BODY\n } catch ($ERR) {\n $$$CATCH\n }\n}\n\n// EXCELLENT: Complete API endpoint pattern with middleware\n$ROUTER.$METHOD('$PATH', $$$MIDDLEWARE, async ($REQ, $RES) => {\n $$$BODY\n});\n\n// EXCELLENT: Database operation patterns with error handling\n$DB.$OPERATION($$$ARGS)\n .then($RESULT => $$$)\n .catch($ERROR => $$$);\n\n// EXCELLENT: React component patterns with hooks\nfunction $COMPONENT($PROPS) {\n const [$STATE, $SETTER] = useState($INITIAL);\n $$$BODY\n return $JSX;\n}\n```\n\n**META-VARIABLE MASTERY:**\n• **$VAR**: Captures single expressions, identifiers, or values\n• **$$$BODY**: Captures multiple statements or expressions\n• **$$VAR**: Captures statement sequences with specific patterns\n• **Named Captures**: Use descriptive names like $FUNCTION_NAME, $ERROR_TYPE\n• **Nested Patterns**: Combine meta-variables for complex structural matching\n\n**LANGUAGE-SPECIFIC BATCHING:**\n• **JavaScript/TypeScript**: async/await patterns, React hooks, Express middleware, Promise chains\n• **Python**: Class decorators, context managers, async generators, Django views\n• **Rust**: Ownership patterns, Result handling, trait implementations, macro usage\n• **Go**: Interface implementations, goroutine patterns, error handling, channel operations\n• **Java**: Annotation patterns, stream operations, exception handling, Spring components\n\n**WORKING DIRECTORY FUNCTIONALITY:**\n• **File Discovery**: Recursively finds all source files matching language patterns\n• **AST Parsing**: Parses files into abstract syntax trees within directory scope\n• **Pattern Matching**: Applies patterns across all parsed files in working directory\n• **Context Preservation**: Maintains file context and relationships within directory\n• **Path Resolution**: All results use paths relative to working directory\n\n**STRUCTURAL INVESTIGATION WORKFLOWS:**\n1. **API Architecture Mapping**: `$ROUTER.$METHOD` → `async function $HANDLER` → `await $DB.$QUERY`\n2. **Error Flow Analysis**: `try { $$$ } catch` → `throw new $ERROR` → `$LOGGER.$LEVEL`\n3. **Data Processing Chains**: `function $TRANSFORM($DATA)` → `return $RESULT` → `$PROCESS($OUTPUT)`\n4. **Security Validation**: `$AUTH.$VERIFY` → `if (!$PERMISSION)` → `throw $UNAUTHORIZED`\n5. **Performance Bottlenecks**: `for ($ITEM of $ARRAY)` → `await $OPERATION` → `$RESULT.push($VALUE)`\n\n**OUTPUT OPTIMIZATION STRATEGIES:**\n• **Context Control**: Use context parameter (3-5 lines) for surrounding code visibility\n• **Format Selection**: 'compact' for quick scanning, 'pretty' for detailed analysis\n• **Strictness Tuning**: 'smart' for flexible matching, 'ast' for precise structural requirements\n• **Pattern Density**: Focus on files with multiple pattern matches for comprehensive analysis\n• **Result Filtering**: Use paths parameter to limit search scope when needed\n\n**INTEGRATION WITH WORKFLOW:**\n• **Post-Semantic Search**: Use after `searchcode` to structurally validate semantic findings\n• **Pre-Refactoring**: Identify exact transformation targets before using `astgrep_replace`\n• **Rule Development**: Find problematic patterns to create `astgrep_lint` rules\n• **Analysis Preparation**: Locate complex scenarios for detailed `astgrep_analyze` investigation\n• **Batch Coordination**: Combine with other tools in `batch_execute` for comprehensive analysis\n\n**PERFORMANCE OPTIMIZATION:**\n• **Path Targeting**: Use paths parameter to limit search scope for large codebases\n• **Language Specification**: Always specify language for optimal parser selection\n• **Pattern Efficiency**: Design patterns that match intended structures without over-generalization\n• **Context Balance**: Use appropriate context lines - avoid excessive output\n• **Strictness Selection**: Choose appropriate strictness level for performance vs. accuracy balance",
"inputSchema": {
"type": "object",
"properties": {
"pattern": {
"type": "string",
"description": "AST pattern to search for using meta-variables (e.g., 'function $NAME($$$ARGS) { $$$ }')"
},
"language": {
"type": "string",
"description": "Programming language (javascript, typescript, python, rust, go, java, etc.) - required for proper AST parsing"
},
"paths": {
"type": "array",
"items": {
"type": "string"
},
"description": "Optional specific paths within working directory to search (defaults to entire working directory)"
},
"context": {
"type": "number",
"description": "Optional number of context lines to include around matches (default: 3, recommended: 3-5)"
},
"strictness": {
"type": "string",
"enum": [
"cst",
"smart",
"ast",
"relaxed"
],
"description": "Pattern matching strictness: 'smart' (recommended), 'ast' (precise), 'relaxed' (flexible)"
},
"outputFormat": {
"type": "string",
"enum": [
"compact",
"pretty"
],
"description": "Output format: 'compact' (scanning), 'pretty' (detailed analysis)"
},
"workingDirectory": {
"type": "string",
"description": "**MANDATORY WORKING DIRECTORY** - workingDirectory parameter is **REQUIRED** and **MUST BE SET**. Specify the exact directory path containing source code to analyze with AST patterns. All AST operations are strictly scoped to this directory. **ALWAYS provide this parameter** - analysis will fail without it."
}
},
"required": [
"pattern",
"workingDirectory"
]
}
},
"astgrep_replace": {
"name": "astgrep_replace",
"description": "**INTELLIGENT CODE TRANSFORMATION** - AST-based code rewriting with meta-variable substitution. **ALWAYS USE FOR SAFE, STRUCTURAL REFACTORING** after identifying patterns with search tools.\n\n**MANDATORY WORKING DIRECTORY:**\n• workingDirectory parameter is **REQUIRED** - specify the exact codebase directory for transformation\n• All transformations operate within the working directory and its subdirectories\n• File modifications are applied to files within the working directory context\n• Backup and safety checks are scoped to the working directory\n• **ALWAYS provide this parameter** - transformation will fail without it\n\n**AUTOMATIC RESPONSE TRUNCATION & OVERFLOW HANDLING:**\n• **25k Token Limit**: Responses exceeding ~25,000 tokens are automatically truncated\n• **Overflow Storage**: Excess content stored in `.call_overflow/` directory within workingDirectory\n• **Seamless Retrieval**: Use `retrieve_overflow` tool to access stored content chunks\n• **Preservation Guarantee**: Leading content always preserved, nothing lost permanently\n• **Clear Instructions**: Truncation notices provide exact steps to retrieve remaining content\n• **Example**: If truncated, response shows \"Use 'retrieve_overflow' tool with file: 'overflow_astgrep_replace_1234567890.json'\"\n\n**COMPREHENSIVE TRANSFORMATION BATCHING:**\nThis tool can efficiently batch ALL of the following code transformation operations:\n• **API Modernization**: Transform multiple endpoints with consistent error handling and response patterns\n• **Security Hardening**: Add input validation, output sanitization, and authentication across similar functions\n• **Performance Optimization**: Apply caching, async patterns, and database optimization to multiple operations\n• **Framework Migration**: Update component patterns, lifecycle methods, and API usage for new versions\n• **Code Standardization**: Enforce consistent logging, error handling, and formatting across codebase\n• **Legacy Modernization**: Convert callback patterns to async/await, update deprecated APIs\n• **Type Safety Enhancement**: Add TypeScript types, improve type annotations, fix type errors\n• **Testing Integration**: Add test coverage, update test patterns, improve assertion styles\n• **Configuration Management**: Update config patterns, environment variable usage, settings management\n• **Architecture Refactoring**: Apply design patterns, improve separation of concerns, enhance modularity\n\n**ADVANCED TRANSFORMATION STRATEGIES:**\n```\n// EXCELLENT: Comprehensive async modernization\nPATTERN: $OBJ.$METHOD($$$ARGS, function($ERR, $DATA) {\n if ($ERR) {\n $$$ERROR_HANDLING\n } else {\n $$$SUCCESS_HANDLING\n }\n})\nREPLACE: try {\n const $DATA = await $OBJ.$METHOD($$$ARGS);\n $$$SUCCESS_HANDLING\n} catch ($ERR) {\n $$$ERROR_HANDLING\n}\n\n// EXCELLENT: Security enhancement with validation\nPATTERN: app.$METHOD('$PATH', ($REQ, $RES) => {\n $$$BODY\n})\nREPLACE: app.$METHOD('$PATH', [\n validateInput,\n sanitizeInput,\n authenticate\n], async ($REQ, $RES) => {\n try {\n $$$BODY\n } catch (error) {\n logger.error('API Error:', error);\n return $RES.status(500).json({ error: 'Internal server error' });\n }\n});\n\n// EXCELLENT: Database optimization with caching\nPATTERN: $DB.query('$QUERY', $PARAMS)\nREPLACE: await cacheManager.getOrSet(\n `query:${hashQuery('$QUERY', $PARAMS)}`,\n () => $DB.query('$QUERY', $PARAMS),\n { ttl: 300 }\n)\n```\n\n**SAFETY-FIRST PROTOCOLS:**\n1. **Pre-transformation Analysis**: ALWAYS use `astgrep_search` to identify all affected code locations\n2. **Mandatory Dry-run**: Set `dryRun: true` to preview all changes before applying\n3. **Incremental Validation**: Apply transformations to small subsets and test thoroughly\n4. **Post-transformation Testing**: Use `executenodejs`/`executedeno` to verify functionality\n5. **Rollback Planning**: Ensure version control or backup strategies before major transformations\n\n**WORKING DIRECTORY FUNCTIONALITY:**\n• **File Discovery**: Recursively finds and transforms all matching files within working directory\n• **Pattern Application**: Applies transformations consistently across entire directory tree\n• **Safety Scoping**: Limits transformation impact to working directory boundaries\n• **Context Preservation**: Maintains file relationships and imports within directory structure\n• **Path Management**: All file operations use paths relative to working directory\n\n**COMPLEX TRANSFORMATION WORKFLOWS:**\n• **Complete Framework Migration**: Update imports, component patterns, lifecycle methods, and API calls\n• **Security Enhancement Suite**: Add authentication, validation, sanitization, and logging systematically\n• **Performance Optimization Campaign**: Apply caching, async patterns, query optimization across services\n• **Code Quality Standardization**: Implement consistent error handling, logging, and formatting patterns\n• **Legacy System Modernization**: Convert deprecated patterns to modern equivalents across entire codebase\n\n**META-VARIABLE MASTERY FOR TRANSFORMATIONS:**\n• **Preserve Structure**: Use `$$$BODY` to maintain existing code blocks in transformations\n• **Parameter Mapping**: Map `$PARAM1, $PARAM2` to maintain function signatures\n• **Context Transfer**: Use named meta-variables to transfer context between patterns\n• **Conditional Logic**: Preserve conditional structures while updating implementation\n• **Type Information**: Maintain type annotations and generic parameters in transformations\n\n**OUTPUT OPTIMIZATION & REPORTING:**\n• **Transformation Summary**: Report total files affected, lines changed, patterns matched\n• **Change Categories**: Group changes by type (security, performance, style, architecture)\n• **Impact Analysis**: Highlight critical changes that may affect system behavior\n• **Verification Checklist**: Provide specific testing recommendations for transformed code\n• **Diff Highlights**: Show key before/after examples for important transformations\n\n**MULTI-FILE COORDINATION STRATEGIES:**\n• **Import/Export Synchronization**: Update module dependencies and exports consistently\n• **Type Definition Updates**: Keep TypeScript definitions aligned with implementation changes\n• **Configuration File Updates**: Modify config files to match code transformations\n• **Test File Adaptation**: Update test files to match transformed implementation patterns\n• **Documentation Alignment**: Consider documentation updates needed for transformed code\n\n**ERROR PREVENTION & VALIDATION:**\n• **Pattern Testing**: Validate patterns match intended code before applying transformations\n• **Syntax Verification**: Ensure replacement patterns produce syntactically valid code\n• **Semantic Preservation**: Verify transformations maintain original code behavior\n• **Dependency Analysis**: Check that transformations don't break module dependencies\n• **Side Effect Assessment**: Consider impact on external code that depends on transformed functions",
"inputSchema": {
"type": "object",
"properties": {
"pattern": {
"type": "string",
"description": "AST pattern to match for transformation using meta-variables"
},
"replacement": {
"type": "string",
"description": "Replacement pattern with meta-variable substitutions"
},
"language": {
"type": "string",
"description": "Programming language for transformation (javascript, typescript, python, etc.)"
},
"paths": {
"type": "array",
"items": {
"type": "string"
},
"description": "Optional specific paths within working directory to transform"
},
"dryRun": {
"type": "boolean",
"description": "**RECOMMENDED** - Preview changes without applying (always use first)"
},
"interactive": {
"type": "boolean",
"description": "Enable interactive confirmation for each transformation"
},
"workingDirectory": {
"type": "string",
"description": "**MANDATORY WORKING DIRECTORY** - workingDirectory parameter is **REQUIRED** and **MUST BE SET**. Specify the exact directory path containing code to transform. All transformations are strictly scoped to this directory and its subdirectories. **ALWAYS provide this parameter** - transformation will fail without it."
}
},
"required": [
"pattern",
"replacement",
"workingDirectory"
]
}
},
"astgrep_lint": {
"name": "astgrep_lint",
"description": "**COMPREHENSIVE CODE QUALITY ENFORCEMENT** - YAML-based rule engine for structural code validation. **ALWAYS USE FOR SYSTEMATIC QUALITY ASSURANCE** across entire codebases.\n\n**MANDATORY WORKING DIRECTORY:**\n• workingDirectory parameter is **REQUIRED** - specify the exact codebase directory for quality analysis\n• Rule validation operates on all source files within the working directory tree\n• Quality metrics and violation reports are scoped to the working directory\n• All file paths in violation reports are relative to the working directory\n• **ALWAYS provide this parameter** - validation will fail without it\n\n**AUTOMATIC RESPONSE TRUNCATION & OVERFLOW HANDLING:**\n• **25k Token Limit**: Responses exceeding ~25,000 tokens are automatically truncated\n• **Overflow Storage**: Excess content stored in `.call_overflow/` directory within workingDirectory\n• **Seamless Retrieval**: Use `retrieve_overflow` tool to access stored content chunks\n• **Preservation Guarantee**: Leading content always preserved, nothing lost permanently\n• **Clear Instructions**: Truncation notices provide exact steps to retrieve remaining content\n• **Example**: If truncated, response shows \"Use 'retrieve_overflow' tool with file: 'overflow_astgrep_lint_1234567890.json'\"\n\n**COMPREHENSIVE QUALITY BATCHING:**\nThis tool can efficiently batch ALL of the following quality assurance operations:\n• **Security Vulnerability Scanning**: SQL injection, XSS, code injection, unsafe operations in one ruleset\n• **Performance Anti-pattern Detection**: N+1 queries, synchronous operations, memory leaks, inefficient algorithms\n• **Architecture Compliance Validation**: Layer violations, circular dependencies, improper coupling, design pattern violations\n• **Code Style Standardization**: Naming conventions, formatting consistency, comment standards, file organization\n• **Error Handling Assessment**: Missing try/catch, improper error propagation, silent failures, exception handling\n• **API Design Validation**: REST conventions, GraphQL best practices, middleware patterns, response formatting\n• **Database Interaction Quality**: Query optimization, transaction handling, connection management, ORM usage\n• **Testing Pattern Enforcement**: Test naming, assertion patterns, mock usage, coverage requirements\n• **Documentation Standards**: Function documentation, type annotations, README requirements, comment quality\n• **Dependency Management**: Import organization, unused dependencies, circular imports, version consistency\n\n**ADVANCED RULE ORCHESTRATION:**\n```yaml\n# EXCELLENT: Comprehensive security and performance ruleset\nrules:\n - id: security-comprehensive\n message: Critical security violations detected\n rule:\n any:\n # Code injection vulnerabilities\n - pattern: eval($EXPR)\n - pattern: new Function($ARGS)\n - pattern: $OBJ.innerHTML = $UNSAFE\n - pattern: document.write($CONTENT)\n # SQL injection patterns\n - pattern: $DB.query('$SQL' + $VAR)\n - pattern: $DB.raw($TEMPLATE + $INPUT)\n # XSS vulnerabilities\n - pattern: $ELEMENT.innerHTML = $USER_INPUT\n severity: error\n fix: Add input validation and use safe alternatives\n\n - id: performance-optimization\n message: Performance anti-patterns detected\n rule:\n any:\n # Inefficient loops\n - pattern: for ($ITEM of $ARRAY) { await $ASYNC_OP }\n - pattern: $ARRAY.forEach(async ($ITEM) => { await $OP })\n # N+1 query patterns\n - pattern: for ($ITEM of $ITEMS) { $DB.query($QUERY) }\n # Synchronous operations in async contexts\n - pattern: fs.readFileSync($PATH)\n severity: warning\n fix: Use Promise.all(), batch operations, or async alternatives\n\n - id: architecture-patterns\n message: Architecture compliance violations\n rule:\n any:\n # Direct database access from controllers\n - pattern: class $CONTROLLER { $METHOD() { $DB.query($$$) } }\n # Missing error boundaries\n - pattern: async function $NAME($$$) { $$$BODY }\n not: { has: { pattern: try { $$$ } catch { $$$ } } }\n severity: info\n fix: Use proper layering and error handling patterns\n```\n\n**WORKING DIRECTORY FUNCTIONALITY:**\n• **Recursive Analysis**: Scans all source files within working directory and subdirectories\n• **Rule Application**: Applies YAML rules consistently across entire directory structure\n• **Context Awareness**: Maintains file relationships and project structure during analysis\n• **Scope Management**: Limits analysis to working directory boundaries for focused results\n• **Report Generation**: Creates violation reports with paths relative to working directory\n\n**RULE DESIGN EXCELLENCE:**\n• **Multi-Pattern Rules**: Use `any`, `all`, `not` combinators for comprehensive coverage\n• **Severity Stratification**: Error (critical) → Warning (important) → Info (nice-to-have) → Hint (suggestions)\n• **Contextual Rules**: Include `has`, `inside`, `follows` for sophisticated pattern matching\n• **Fix Suggestions**: Provide actionable remediation guidance in rule messages\n• **Framework-Specific Rules**: Tailor rules to React, Express, Django, Spring, etc.\n\n**SYSTEMATIC VALIDATION WORKFLOWS:**\n1. **Critical Security Sweep**: Identify immediate security vulnerabilities requiring urgent fixes\n2. **Performance Bottleneck Analysis**: Find expensive operations and inefficient patterns\n3. **Architecture Compliance Check**: Validate adherence to design patterns and layering\n4. **Code Quality Assessment**: Review style, documentation, and maintainability issues\n5. **Framework Best Practices**: Ensure proper usage of libraries and frameworks\n6. **Testing Standards Validation**: Verify test quality and coverage patterns\n\n**OUTPUT OPTIMIZATION STRATEGIES:**\n• **JSON Format**: Use for programmatic processing, integration, and automated remediation\n• **Severity Filtering**: Focus on `error` level first, then `warning`, then `info`\n• **Rule Grouping**: Organize violations by rule ID for systematic fixing\n• **Path Filtering**: Use paths parameter to focus on specific modules or components\n• **Impact Summarization**: Provide high-level quality metrics and trend indicators\n\n**RULE EVOLUTION & MANAGEMENT:**\n• **Progressive Enhancement**: Start with critical rules, expand to comprehensive coverage\n• **False Positive Minimization**: Refine rules based on actual codebase patterns\n• **Team Collaboration**: Create shared rule libraries for consistent quality standards\n• **Continuous Improvement**: Regular rule review and effectiveness assessment\n• **Documentation Integration**: Link rules to coding standards and best practice guides\n\n**INTEGRATION WORKFLOWS:**\n• **Pre-commit Hooks**: Catch quality issues before code submission\n• **CI/CD Pipeline**: Automated quality gates with configurable failure thresholds\n• **Code Review Enhancement**: Systematic identification of review focus areas\n• **Refactoring Planning**: Identify improvement candidates and technical debt\n• **Onboarding Support**: Help new team members learn coding standards\n\n**REPORTING & ACTIONABILITY:**\n• **Priority Matrix**: Critical/High/Medium/Low classification for remediation planning\n• **Effort Estimation**: Assess complexity of fixes for project planning\n• **Trend Analysis**: Track quality improvements over time\n• **Team Metrics**: Individual and team quality performance indicators\n• **Compliance Reporting**: Generate reports for auditing and governance requirements",
"inputSchema": {
"type": "object",
"properties": {
"rules": {
"type": "string",
"description": "YAML rule content or path to rule file within working directory"
},
"paths": {
"type": "array",
"items": {
"type": "string"
},
"description": "Optional specific paths within working directory to validate"
},
"severity": {
"type": "string",
"enum": [
"error",
"warning",
"info",
"hint"
],
"description": "Minimum severity level to report (recommended: start with 'error')"
},
"format": {
"type": "string",
"enum": [
"json",
"text"
],
"description": "Output format: 'json' (programmatic), 'text' (human-readable)"
},
"workingDirectory": {
"type": "string",
"description": "**MANDATORY WORKING DIRECTORY** - workingDirectory parameter is **REQUIRED** and **MUST BE SET**. Specify the exact directory path containing code to validate with quality rules. All validation is strictly scoped to this directory. **ALWAYS provide this parameter** - validation will fail without it."
}
},
"required": [
"rules",
"workingDirectory"
]
}
},
"astgrep_analyze": {
"name": "astgrep_analyze",
"description": "**DEEP STRUCTURAL CODE INVESTIGATION** - AST exploration and pattern debugging tool. **ALWAYS USE FOR COMPLEX PATTERN ANALYSIS** and understanding intricate code structures.\n\n**MANDATORY WORKING DIRECTORY:**\n• workingDirectory parameter is **REQUIRED** - specify the exact codebase directory for AST analysis\n• AST parsing and analysis operate on source files within the working directory\n• Pattern debugging uses code examples found in the working directory\n• All analysis results are contextualized to the working directory structure\n• **ALWAYS provide this parameter** - analysis will fail without it\n\n**AUTOMATIC RESPONSE TRUNCATION & OVERFLOW HANDLING:**\n• **25k Token Limit**: Responses exceeding ~25,000 tokens are automatically truncated\n• **Overflow Storage**: Excess content stored in `.call_overflow/` directory within workingDirectory\n• **Seamless Retrieval**: Use `retrieve_overflow` tool to access stored content chunks\n• **Preservation Guarantee**: Leading content always preserved, nothing lost permanently\n• **Clear Instructions**: Truncation notices provide exact steps to retrieve remaining content\n• **Example**: If truncated, response shows \"Use 'retrieve_overflow' tool with file: 'overflow_astgrep_analyze_1234567890.json'\"\n\n**COMPREHENSIVE ANALYSIS BATCHING:**\nThis tool can efficiently batch ALL of the following structural analysis operations:\n• **Pattern Development & Debugging**: Test multiple pattern variations and refinements simultaneously\n• **AST Structure Exploration**: Analyze complex code constructs across multiple files and languages\n• **Meta-variable Validation**: Test meta-variable captures across diverse code examples\n• **Framework Pattern Analysis**: Deep-dive into React components, Express middleware, Django views\n• **Architecture Pattern Investigation**: Analyze design patterns, architectural decisions, code organization\n• **Performance Pattern Detection**: Identify performance bottlenecks and optimization opportunities\n• **Security Pattern Assessment**: Analyze se