analyze_scopes
Detect variable shadowing, unused variables, and naming conflicts in JavaScript/TypeScript. Enhance code quality through scope, closure, and binding analysis for refactoring and debugging.
Instructions
Analyze variable scopes, bindings, and potential naming conflicts. Advanced tool for code quality analysis.
Examples: • Variable shadowing detection: analyze_scopes() to find naming conflicts • Closure analysis: analyze_scopes() to understand variable capture • Refactoring safety: analyze_scopes() before variable renames • Code review: analyze_scopes() to identify scope-related issues • Learning aid: analyze_scopes({includeBuiltins: true}) to see all identifiers • Dead code detection: analyze_scopes() to find unused variables
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| includeBuiltins | No | Include built-in identifiers (default: false). Set true for comprehensive analysis including globals. |
Implementation Reference
- src/index.ts:1016-1053 (handler)The primary handler function that executes the logic for the 'analyze_scopes' tool. It checks for a loaded AST, calls the tree-hugger-js TreeHugger instance's analyzeScopes() method, processes the results, and returns formatted scope analysis information.private async analyzeScopes(args: { includeBuiltins?: boolean }) { if (!this.currentAST) { return { content: [{ type: "text", text: "No AST loaded. Please use parse_code first.", }], isError: true, }; } try { const scopes = this.currentAST.tree.analyzeScopes(); // Note: This is a simplified scope analysis implementation // The actual tree-hugger-js library may have more sophisticated scope analysis const scopeInfo = { message: "Scope analysis completed", scopeCount: "Scope analysis functionality depends on tree-hugger-js implementation", note: "This is a placeholder - actual implementation would use tree-hugger-js scope analysis features", }; return { content: [{ type: "text", text: `Scope Analysis Results:\n${JSON.stringify(scopeInfo, null, 2)}`, }], }; } catch (error) { return { content: [{ type: "text", text: `Error analyzing scopes: ${error instanceof Error ? error.message : String(error)}`, }], isError: true, }; } }
- src/index.ts:367-378 (schema)The schema definition for the 'analyze_scopes' tool, including name, description, and inputSchema for parameters like includeBuiltins.name: "analyze_scopes", description: "Analyze variable scopes, bindings, and potential naming conflicts. Advanced tool for code quality analysis.\n\nExamples:\n• Variable shadowing detection: analyze_scopes() to find naming conflicts\n• Closure analysis: analyze_scopes() to understand variable capture\n• Refactoring safety: analyze_scopes() before variable renames\n• Code review: analyze_scopes() to identify scope-related issues\n• Learning aid: analyze_scopes({includeBuiltins: true}) to see all identifiers\n• Dead code detection: analyze_scopes() to find unused variables", inputSchema: { type: "object", properties: { includeBuiltins: { type: "boolean", description: "Include built-in identifiers (default: false). Set true for comprehensive analysis including globals." } }, }, },
- src/index.ts:443-444 (registration)The registration/dispatch in the CallToolRequestSchema switch statement that maps the tool name to the analyzeScopes handler method.case "analyze_scopes": return await this.analyzeScopes(args as { includeBuiltins?: boolean });
- src/index.ts:178-407 (registration)The ListToolsRequestSchema handler that registers 'analyze_scopes' in the tools list returned to clients, including its schema.this.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: "parse_code", description: "Parse JavaScript/TypeScript code from file or string and load it into the AST state. Must be called before using other analysis tools.\n\nExamples:\n• Parse a React component: parse_code('./src/UserProfile.jsx')\n• Parse code string: parse_code('function hello() { return \"world\"; }')\n• Parse with explicit language: parse_code('./config.js', language='javascript')\n• Analyze legacy code: parse_code('./old-script.js') then use other tools to understand structure\n• Code review prep: parse_code('./feature.ts') then get_functions() to review all functions", inputSchema: { type: "object", properties: { source: { type: "string", description: "File path (./src/app.js) or code string ('const x = 1;')" }, isFilePath: { type: "boolean", description: "Whether source is a file path (true) or code string (false). Defaults to auto-detect." }, language: { type: "string", description: "Language to use (javascript, typescript, jsx, tsx). Auto-detected if not provided." } }, required: ["source"], }, }, { name: "find_pattern", description: "Find first node matching the specified pattern using tree-hugger-js intuitive syntax. Use for targeted searches when you need one specific match.\n\nExamples:\n• Find main function: find_pattern('function[name=\"main\"]')\n• Find React component: find_pattern('function[name=\"UserProfile\"]')\n• Find async functions: find_pattern('function[async]')\n• Find specific class: find_pattern('class[name=\"UserManager\"]')\n• Find error handling: find_pattern('call[text*=\"catch\"]')\n• Find JSX with props: find_pattern('jsx:has(jsx-attribute[name=\"className\"])')\n• Debug specific calls: find_pattern('call[text*=\"console.log\"]')", inputSchema: { type: "object", properties: { pattern: { type: "string", description: "Pattern using intuitive syntax: 'function', 'class[name=\"MyClass\"]', 'function[async]', 'call[text*=\"fetch\"]'" } }, required: ["pattern"], }, }, { name: "find_all_pattern", description: "Find all nodes matching the specified pattern. Use for comprehensive analysis when you need all matches.\n\nExamples:\n• Audit all functions: find_all_pattern('function')\n• Find all TODO comments: find_all_pattern('comment[text*=\"TODO\"]')\n• Security audit: find_all_pattern('call[text*=\"eval\"]')\n• Performance review: find_all_pattern('call[text*=\"console.log\"]') to find debug logs\n• API usage: find_all_pattern('call[text*=\"fetch\"]') to find all API calls\n• React hooks: find_all_pattern('call[text*=\"use\"]') for hooks usage\n• Error patterns: find_all_pattern('string[text*=\"error\"]') for error messages\n• Database queries: find_all_pattern('string[text*=\"SELECT\"]') for SQL\n• Event handlers: find_all_pattern('function[text*=\"onClick\"]')", inputSchema: { type: "object", properties: { pattern: { type: "string", description: "Pattern to match: 'function', 'call[text*=\"console.log\"]', 'string[text*=\"TODO\"]'" }, limit: { type: "number", description: "Maximum number of matches to return (default: no limit). Use for large codebases." } }, required: ["pattern"], }, }, { name: "get_functions", description: "Get all functions with metadata including name, type, location, and async status. Includes class methods, arrow functions, and declarations.\n\nExamples:\n• Code review: get_functions() to see all functions in a file\n• Find async operations: get_functions({asyncOnly: true})\n• API analysis: get_functions() then look for functions with 'fetch' or 'api' in names\n• Test coverage: get_functions() to identify functions needing tests\n• Refactoring prep: get_functions({includeAnonymous: false}) to focus on named functions\n• Performance audit: get_functions() to find large/complex functions by line count", inputSchema: { type: "object", properties: { includeAnonymous: { type: "boolean", description: "Include anonymous functions (default: true). Set false to focus on named functions only." }, asyncOnly: { type: "boolean", description: "Only return async functions (default: false). Use for async/await pattern analysis." } }, }, }, { name: "get_classes", description: "Get all classes with comprehensive method and property analysis. Perfect for OOP code review.\n\nExamples:\n• Architecture review: get_classes() to understand class structure\n• API design: get_classes() to see public method interfaces\n• Inheritance analysis: get_classes() to identify class hierarchies\n• Method-only view: get_classes({includeProperties: false}) to focus on behavior\n• Property audit: get_classes({includeMethods: false}) to review state management\n• Testing prep: get_classes() to identify methods needing unit tests", inputSchema: { type: "object", properties: { includeProperties: { type: "boolean", description: "Include class properties (default: true). Set false to focus only on methods." }, includeMethods: { type: "boolean", description: "Include class methods (default: true). Set false to focus only on properties." } }, }, }, { name: "get_imports", description: "Get all import statements with detailed module and specifier information. Essential for dependency analysis.\n\nExamples:\n• Dependency audit: get_imports() to see all external dependencies\n• Bundle analysis: get_imports() to identify heavy imports\n• Security audit: get_imports() to check for suspicious packages\n• TypeScript analysis: get_imports({includeTypeImports: false}) to focus on runtime imports\n• Refactoring prep: get_imports() to understand module structure before changes\n• License compliance: get_imports() to generate dependency list", inputSchema: { type: "object", properties: { includeTypeImports: { type: "boolean", description: "Include TypeScript type-only imports (default: true). Set false for runtime dependency analysis." } }, }, }, { name: "rename_identifier", description: "Intelligently rename all occurrences of an identifier throughout the code. Avoids renaming in strings/comments.\n\nExamples:\n• Refactor function names: rename_identifier('fetchData', 'fetchUserData')\n• Improve variable names: rename_identifier('data', 'userData')\n• Update class names: rename_identifier('Manager', 'UserManager')\n• API consistency: rename_identifier('getUserInfo', 'fetchUserInfo')\n• Preview first: rename_identifier('oldName', 'newName', {preview: true})\n• Legacy code update: rename_identifier('XMLHttpRequest', 'fetch')", inputSchema: { type: "object", properties: { oldName: { type: "string", description: "Current identifier name to find and replace" }, newName: { type: "string", description: "New identifier name (should be valid JavaScript identifier)" }, preview: { type: "boolean", description: "Return preview only without applying changes (default: false). Always preview first for safety." } }, required: ["oldName", "newName"], }, }, { name: "remove_unused_imports", description: "Automatically remove unused import statements to clean up code. Safely detects which imports are actually used.\n\nExamples:\n• Bundle size optimization: remove_unused_imports() to reduce bundle size\n• Code cleanup: remove_unused_imports() after refactoring\n• Linting compliance: remove_unused_imports() to fix ESLint warnings\n• Before deployment: remove_unused_imports({preview: true}) to see what will be removed\n• Legacy cleanup: remove_unused_imports() after removing old code\n• Development workflow: remove_unused_imports() during feature development", inputSchema: { type: "object", properties: { preview: { type: "boolean", description: "Return preview only without applying changes (default: false). Use to see what will be removed." } }, }, }, { name: "transform_code", description: "Apply multiple transformations in a single operation. Most powerful tool for complex refactoring workflows.\n\nExamples:\n• API refactor: [{type: 'rename', parameters: {oldName: 'getData', newName: 'fetchData'}}, {type: 'removeUnusedImports'}]\n• Environment update: [{type: 'replaceIn', parameters: {nodeType: 'string', pattern: /localhost/g, replacement: 'api.production.com'}}, {type: 'removeUnusedImports'}]\n• Add logging: [{type: 'insertAfter', parameters: {pattern: 'function_declaration', text: 'console.log(\"Function called\");'}}, {type: 'removeUnusedImports'}]\n• Bulk rename: [{type: 'rename', parameters: {oldName: 'user', newName: 'customer'}}, {type: 'rename', parameters: {oldName: 'id', newName: 'customerId'}}]\n• Legacy migration: [{type: 'replaceIn', parameters: {nodeType: 'call_expression', pattern: /XMLHttpRequest/g, replacement: 'fetch'}}, {type: 'removeUnusedImports'}]", inputSchema: { type: "object", properties: { operations: { type: "array", items: { type: "object", properties: { type: { type: "string", enum: ["rename", "removeUnusedImports", "replaceIn", "insertBefore", "insertAfter"] }, parameters: { type: "object", description: "Parameters: rename{oldName,newName}, replaceIn{nodeType,pattern,replacement}, insert{pattern,text}" } }, required: ["type"] }, description: "Array of transformation operations applied in sequence. Use preview:true first!" }, preview: { type: "boolean", description: "Return preview only without applying changes (default: false). ALWAYS preview complex transformations first." } }, required: ["operations"], }, }, { name: "get_node_at_position", description: "Get detailed AST node information at a specific cursor position. Perfect for debugging and precise analysis.\n\nExamples:\n• Debug syntax errors: get_node_at_position(15, 23) to understand what's at error location\n• Understand code structure: get_node_at_position(line, col) to see AST node type at cursor\n• Refactoring assistance: get_node_at_position(line, col) to identify exact node before transformation\n• IDE integration: get_node_at_position(line, col) for hover information\n• Pattern development: get_node_at_position(line, col) to understand node structure for pattern writing", inputSchema: { type: "object", properties: { line: { type: "number", description: "Line number (1-based) - the line where cursor is positioned" }, column: { type: "number", description: "Column number (0-based) - the character position within the line" } }, required: ["line", "column"], }, }, { name: "analyze_scopes", description: "Analyze variable scopes, bindings, and potential naming conflicts. Advanced tool for code quality analysis.\n\nExamples:\n• Variable shadowing detection: analyze_scopes() to find naming conflicts\n• Closure analysis: analyze_scopes() to understand variable capture\n• Refactoring safety: analyze_scopes() before variable renames\n• Code review: analyze_scopes() to identify scope-related issues\n• Learning aid: analyze_scopes({includeBuiltins: true}) to see all identifiers\n• Dead code detection: analyze_scopes() to find unused variables", inputSchema: { type: "object", properties: { includeBuiltins: { type: "boolean", description: "Include built-in identifiers (default: false). Set true for comprehensive analysis including globals." } }, }, }, { name: "insert_code", description: "Insert code before or after nodes with smart formatting. Professional-quality code insertion with proper indentation.\n\nExamples:\n• Add logging: insert_code('function_declaration', 'console.log(\"Function started\");', 'after')\n• Add validation: insert_code('method_definition[name=\"save\"]', 'if (!this.isValid()) return;', 'after')\n• Add comments: insert_code('class_declaration', '// Main user management class', 'before')\n• Add error handling: insert_code('function[async]', 'try {', 'after') + insert_code('function[async]', '} catch(e) { console.error(e); }', 'after')\n• Add metrics: insert_code('function[name*=\"api\"]', 'performance.mark(\"api-start\");', 'after')\n• Debug mode: insert_code('call[text*=\"fetch\"]', 'console.log(\"API call:\", url);', 'before')", inputSchema: { type: "object", properties: { pattern: { type: "string", description: "Pattern to match: 'function_declaration', 'class[name=\"MyClass\"]', 'method_definition[async]'" }, code: { type: "string", description: "Code to insert. Will be formatted with proper indentation automatically." }, position: { type: "string", enum: ["before", "after"], description: "Insert position: 'before' (above) or 'after' (below) the matched nodes" }, preview: { type: "boolean", description: "Return preview only without applying changes (default: false). Always preview first!" } }, required: ["pattern", "code", "position"], }, }, ], }));