Skip to main content
Glama
Tree-Hugger-JS MCP Server

Tree-Hugger-JS MCP Server

by qckfx

Tree-Hugger-JS MCP Server

An MCP (Model Context Protocol) server that provides AI agents with powerful JavaScript/TypeScript code analysis and transformation capabilities using the tree-hugger-js library.

Features

🔍 Code Analysis

  • Parse JavaScript, TypeScript, JSX, and TSX files or code strings

  • Find patterns using intuitive syntax (e.g., function, class[name="MyClass"])

  • Extract functions, classes, imports with detailed metadata

  • Navigate AST nodes and analyze code structure

  • Get nodes at specific positions

🔧 Code Transformation

  • Rename identifiers throughout code

  • Remove unused imports

  • Chain multiple transformations

  • Insert code before/after patterns

  • Preview transformations before applying

📊 Code Intelligence

  • Scope analysis and variable binding

  • Pattern matching with CSS-like selectors

  • Support for async functions, classes, methods

  • TypeScript type import handling

Related MCP server: ts-mcp

Installation & Usage

Try immediately with npx - no installation required:

# Use with Claude Code or any MCP client
npx tree-hugger-js-mcp

📦 Global Installation

# Install globally for repeated use
npm install -g tree-hugger-js-mcp

# Then run anywhere
tree-hugger-js-mcp

🔧 Development Setup

# Clone and build from source
git clone https://github.com/qckfx/tree-hugger-js-mcp.git
cd tree-hugger-js-mcp
npm install
npm run build
npm start

MCP Client Configuration

Using with Claude Code

Add to your MCP client configuration:

{
  "mcpServers": {
    "tree-hugger-js": {
      "command": "npx",
      "args": ["tree-hugger-js-mcp"]
    }
  }
}

Alternative Configurations

{
  "mcpServers": {
    "tree-hugger-js": {
      // If installed globally
      "command": "tree-hugger-js-mcp"
      
      // Or if built from source
      "command": "node",
      "args": ["/path/to/tree-hugger-js-mcp/build/index.js"]
    }
  }
}

Tools

Code Analysis Tools

parse_code

Parse JavaScript/TypeScript code from file or string.

Parameters:

  • source (string): File path or code string to parse

  • isFilePath (boolean, optional): Whether source is a file path (auto-detected if not provided)

  • language (string, optional): Language to use (javascript, typescript, jsx, tsx)

Example:

// Parse a file
await callTool("parse_code", { 
  source: "./src/app.js",
  isFilePath: true 
});

// Parse code string
await callTool("parse_code", { 
  source: "function hello() { console.log('world'); }" 
});

find_pattern

Find first node matching a pattern.

Parameters:

  • pattern (string): Pattern to match using tree-hugger-js syntax

Examples:

// Find any function
await callTool("find_pattern", { pattern: "function" });

// Find async functions
await callTool("find_pattern", { pattern: "function[async]" });

// Find class by name
await callTool("find_pattern", { pattern: "class[name='MyClass']" });

find_all_pattern

Find all nodes matching a pattern.

Parameters:

  • pattern (string): Pattern to match

  • limit (number, optional): Maximum matches to return

get_functions

Get all functions with details.

Parameters:

  • includeAnonymous (boolean, optional): Include anonymous functions (default: true)

  • asyncOnly (boolean, optional): Only return async functions (default: false)

get_classes

Get all classes with methods and properties.

Parameters:

  • includeProperties (boolean, optional): Include class properties (default: true)

  • includeMethods (boolean, optional): Include class methods (default: true)

get_imports

Get all import statements.

Parameters:

  • includeTypeImports (boolean, optional): Include TypeScript type-only imports (default: true)

Code Transformation Tools

rename_identifier

Rename all occurrences of an identifier.

Parameters:

  • oldName (string): Current identifier name

  • newName (string): New identifier name

  • preview (boolean, optional): Return preview only (default: false)

Example:

await callTool("rename_identifier", {
  oldName: "fetchData",
  newName: "fetchUserData",
  preview: true
});

remove_unused_imports

Remove unused import statements.

Parameters:

  • preview (boolean, optional): Return preview only (default: false)

transform_code

Apply multiple transformations in sequence.

Parameters:

  • operations (array): Array of transformation operations

  • preview (boolean, optional): Return preview only (default: false)

Example:

await callTool("transform_code", {
  operations: [
    { type: "rename", parameters: { oldName: "oldFunc", newName: "newFunc" } },
    { type: "removeUnusedImports" },
    { type: "replaceIn", parameters: { nodeType: "string", pattern: /localhost/g, replacement: "api.example.com" } }
  ],
  preview: true
});

insert_code

Insert code before or after nodes matching a pattern.

Parameters:

  • pattern (string): Pattern to match for insertion points

  • code (string): Code to insert

  • position (string): "before" or "after"

  • preview (boolean, optional): Return preview only (default: false)

Navigation Tools

get_node_at_position

Get AST node at specific line and column.

Parameters:

  • line (number): Line number (1-based)

  • column (number): Column number (0-based)

analyze_scopes

Analyze variable scopes and bindings.

Parameters:

  • includeBuiltins (boolean, optional): Include built-in identifiers (default: false)

Resources

The server provides three resources for accessing internal state:

ast://current

Current parsed AST state with metadata and statistics.

ast://analysis

Results from the most recent code analysis (functions, classes, imports).

ast://transforms

History of code transformations and available operations.

Pattern Syntax

Tree-hugger-js uses intuitive patterns instead of verbose tree-sitter node types:

Basic Patterns

  • function - Any function (declaration, expression, arrow, method)

  • class - Class declarations and expressions

  • string - String and template literals

  • import/export - Import/export statements

  • call - Function calls

  • loop - For, while, do-while loops

Attribute Selectors

  • [name="foo"] - Nodes with specific name

  • [async] - Async functions

  • [text*="test"] - Nodes containing text

CSS-like Selectors

  • class method - Methods inside classes

  • function > return - Return statements directly in functions

  • :has() and :not() pseudo-selectors

Examples

Basic Code Analysis

// Parse and analyze a React component
await callTool("parse_code", { source: "./components/UserProfile.jsx" });

// Get all functions
const functions = await callTool("get_functions", { asyncOnly: true });

// Find JSX elements
const jsxElements = await callTool("find_all_pattern", { pattern: "jsx" });

Code Refactoring

// Rename a function and remove unused imports
await callTool("transform_code", {
  operations: [
    { type: "rename", parameters: { oldName: "getUserData", newName: "fetchUserProfile" } },
    { type: "removeUnusedImports" }
  ]
});

Pattern Matching

// Find all async functions that call console.log
await callTool("find_all_pattern", { 
  pattern: "function[async]:has(call[text*='console.log'])" 
});

// Find classes with constructor methods
await callTool("find_all_pattern", { 
  pattern: "class:has(method[name='constructor'])" 
});

Development

# Install dependencies
npm install

# Build the project
npm run build

# Watch mode for development
npm run dev

# Test with MCP inspector
npm run inspector

Error Handling

The server provides detailed error messages and suggestions:

  • File not found errors for invalid file paths

  • Parse errors with helpful context

  • Pattern matching errors with suggestions

  • Transformation errors with rollback capability

License

MIT

Available Tools

12 tools
analyze_scopesA

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

Inputs: includeBuiltins.

find_all_patternA

Find all nodes matching the specified pattern. Use for comprehensive analysis when you need all matches.

Examples: • Audit all functions: find_all_pattern('function') • Find all TODO comments: find_all_pattern('comment[text*="TODO"]') • Security audit: find_all_pattern('call[text*="eval"]') • Performance review: find_all_pattern('call[text*="console.log"]') to find debug logs • API usage: find_all_pattern('call[text*="fetch"]') to find all API calls • React hooks: find_all_pattern('call[text*="use"]') for hooks usage • Error patterns: find_all_pattern('string[text*="error"]') for error messages • Database queries: find_all_pattern('string[text*="SELECT"]') for SQL • Event handlers: find_all_pattern('function[text*="onClick"]')

Inputs: pattern (required), limit.

find_patternA

Find first node matching the specified pattern using tree-hugger-js intuitive syntax. Use for targeted searches when you need one specific match.

Examples: • Find main function: find_pattern('function[name="main"]') • Find React component: find_pattern('function[name="UserProfile"]') • Find async functions: find_pattern('function[async]') • Find specific class: find_pattern('class[name="UserManager"]') • Find error handling: find_pattern('call[text*="catch"]') • Find JSX with props: find_pattern('jsx:has(jsx-attribute[name="className"])') • Debug specific calls: find_pattern('call[text*="console.log"]')

Inputs: pattern (required).

get_classesA

Get all classes with comprehensive method and property analysis. Perfect for OOP code review.

Examples: • Architecture review: get_classes() to understand class structure • API design: get_classes() to see public method interfaces • Inheritance analysis: get_classes() to identify class hierarchies • Method-only view: get_classes({includeProperties: false}) to focus on behavior • Property audit: get_classes({includeMethods: false}) to review state management • Testing prep: get_classes() to identify methods needing unit tests

Inputs: includeProperties, includeMethods.

get_functionsA

Get all functions with metadata including name, type, location, and async status. Includes class methods, arrow functions, and declarations.

Examples: • Code review: get_functions() to see all functions in a file • Find async operations: get_functions({asyncOnly: true}) • API analysis: get_functions() then look for functions with 'fetch' or 'api' in names • Test coverage: get_functions() to identify functions needing tests • Refactoring prep: get_functions({includeAnonymous: false}) to focus on named functions • Performance audit: get_functions() to find large/complex functions by line count

Inputs: includeAnonymous, asyncOnly.

get_importsA

Get all import statements with detailed module and specifier information. Essential for dependency analysis.

Examples: • Dependency audit: get_imports() to see all external dependencies • Bundle analysis: get_imports() to identify heavy imports • Security audit: get_imports() to check for suspicious packages • TypeScript analysis: get_imports({includeTypeImports: false}) to focus on runtime imports • Refactoring prep: get_imports() to understand module structure before changes • License compliance: get_imports() to generate dependency list

Inputs: includeTypeImports.

get_node_at_positionA

Get detailed AST node information at a specific cursor position. Perfect for debugging and precise analysis.

Examples: • Debug syntax errors: get_node_at_position(15, 23) to understand what's at error location • Understand code structure: get_node_at_position(line, col) to see AST node type at cursor • Refactoring assistance: get_node_at_position(line, col) to identify exact node before transformation • IDE integration: get_node_at_position(line, col) for hover information • Pattern development: get_node_at_position(line, col) to understand node structure for pattern writing

Inputs: line (required), column (required).

insert_codeA

Insert code before or after nodes with smart formatting. Professional-quality code insertion with proper indentation.

Examples: • Add logging: insert_code('function_declaration', 'console.log("Function started");', 'after') • Add validation: insert_code('method_definition[name="save"]', 'if (!this.isValid()) return;', 'after') • Add comments: insert_code('class_declaration', '// Main user management class', 'before') • Add error handling: insert_code('function[async]', 'try {', 'after') + insert_code('function[async]', '} catch(e) { console.error(e); }', 'after') • Add metrics: insert_code('function[name*="api"]', 'performance.mark("api-start");', 'after') • Debug mode: insert_code('call[text*="fetch"]', 'console.log("API call:", url);', 'before')

Inputs: pattern (required), code (required), position (required), preview.

parse_codeA

Parse JavaScript/TypeScript code from file or string and load it into the AST state. Must be called before using other analysis tools.

Examples: • Parse a React component: parse_code('./src/UserProfile.jsx') • Parse code string: parse_code('function hello() { return "world"; }') • Parse with explicit language: parse_code('./config.js', language='javascript') • Analyze legacy code: parse_code('./old-script.js') then use other tools to understand structure • Code review prep: parse_code('./feature.ts') then get_functions() to review all functions

Inputs: source (required), isFilePath, language.

remove_unused_importsA

Automatically remove unused import statements to clean up code. Safely detects which imports are actually used.

Examples: • Bundle size optimization: remove_unused_imports() to reduce bundle size • Code cleanup: remove_unused_imports() after refactoring • Linting compliance: remove_unused_imports() to fix ESLint warnings • Before deployment: remove_unused_imports({preview: true}) to see what will be removed • Legacy cleanup: remove_unused_imports() after removing old code • Development workflow: remove_unused_imports() during feature development

Inputs: preview.

rename_identifierA

Intelligently rename all occurrences of an identifier throughout the code. Avoids renaming in strings/comments.

Examples: • Refactor function names: rename_identifier('fetchData', 'fetchUserData') • Improve variable names: rename_identifier('data', 'userData') • Update class names: rename_identifier('Manager', 'UserManager') • API consistency: rename_identifier('getUserInfo', 'fetchUserInfo') • Preview first: rename_identifier('oldName', 'newName', {preview: true}) • Legacy code update: rename_identifier('XMLHttpRequest', 'fetch')

Inputs: oldName (required), newName (required), preview.

transform_codeA

Apply multiple transformations in a single operation. Most powerful tool for complex refactoring workflows.

Examples: • API refactor: [{type: 'rename', parameters: {oldName: 'getData', newName: 'fetchData'}}, {type: 'removeUnusedImports'}] • Environment update: [{type: 'replaceIn', parameters: {nodeType: 'string', pattern: /localhost/g, replacement: 'api.production.com'}}, {type: 'removeUnusedImports'}] • Add logging: [{type: 'insertAfter', parameters: {pattern: 'function_declaration', text: 'console.log("Function called");'}}, {type: 'removeUnusedImports'}] • Bulk rename: [{type: 'rename', parameters: {oldName: 'user', newName: 'customer'}}, {type: 'rename', parameters: {oldName: 'id', newName: 'customerId'}}] • Legacy migration: [{type: 'replaceIn', parameters: {nodeType: 'call_expression', pattern: /XMLHttpRequest/g, replacement: 'fetch'}}, {type: 'removeUnusedImports'}]

Inputs: operations (required), preview.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.1/5.0

    Scored across 12 tools

    Disambiguation4/5

    Most tools have distinct purposes, such as parse_code for loading code, get_functions for retrieving functions, and rename_identifier for refactoring. However, find_pattern and find_all_pattern overlap significantly in functionality, differing only in returning the first match versus all matches, which could cause confusion in selection. The other tools are well-differentiated, with clear boundaries like analyze_scopes for scope analysis and insert_code for code insertion.

    Naming Consistency5/5

    All tool names follow a consistent snake_case pattern with clear verb_noun structures, such as parse_code, get_functions, rename_identifier, and remove_unused_imports. There are no deviations in naming conventions, making the set predictable and easy to understand. The naming style is uniform throughout, enhancing readability and usability.

    Tool Count5/5

    With 12 tools, the count is well-scoped for a JavaScript/TypeScript AST analysis server, covering essential operations like parsing, querying, transforming, and refactoring code. Each tool serves a specific purpose, such as get_imports for dependency analysis and transform_code for complex workflows, without redundancy. The number aligns perfectly with the domain's complexity, providing comprehensive coverage without being overwhelming.

    Completeness5/5

    The toolset offers complete coverage for AST-based code analysis and manipulation, including parsing (parse_code), querying (e.g., get_functions, get_classes), transformation (e.g., insert_code, rename_identifier), and cleanup (remove_unused_imports). It supports full lifecycle operations from loading code to advanced refactoring with transform_code, leaving no obvious gaps. The domain of code analysis and refactoring is thoroughly addressed with tools for both analysis and modification.

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables AI assistants to navigate and edit TypeScript/JavaScript source by named declarations, reading symbols, imports, diagnostics, and replacing code via the TypeScript AST.
      -
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI coding agents to perform structural code operations on TypeScript/TSX projects—finding symbols and references and renaming them semantically while preserving source.
      27 npm
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      Enables LLM agents to explore JavaScript/TypeScript repositories through parsed syntax trees by returning compact file outlines, precise symbol definitions, and local dependency graphs. It keeps access read-only and sandboxed to chosen roots while using a bounded, flood-proof stdio transport.
      3
      MIT