Skip to main content
Glama
qckfx

Tree-Hugger-JS MCP Server

by qckfx

insert_code

Insert code snippets before or after specific JavaScript/TypeScript nodes with automatic formatting, enabling logging, validation, comments, error handling, and debugging additions.

Instructions

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')

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
patternYesPattern to match: 'function_declaration', 'class[name="MyClass"]', 'method_definition[async]'
codeYesCode to insert. Will be formatted with proper indentation automatically.
positionYesInsert position: 'before' (above) or 'after' (below) the matched nodes
previewNoReturn preview only without applying changes (default: false). Always preview first!

Implementation Reference

  • The core handler function that executes the insert_code tool. It uses the tree-hugger-js transform API to insert code before or after matching nodes based on the pattern, handles preview mode, updates the AST state, and logs the transformation.
    private async insertCode(args: { pattern: string; code: string; position: "before" | "after"; preview?: boolean }) {
      if (!this.currentAST) {
        return {
          content: [{
            type: "text",
            text: "No AST loaded. Please use parse_code first.",
          }],
          isError: true,
        };
      }
    
      try {
        const transformer = this.currentAST.tree.transform();
        const transformed = args.position === "before" 
          ? transformer.insertBefore(args.pattern, args.code)
          : transformer.insertAfter(args.pattern, args.code);
    
        const result = transformed.toString();
        
        if (!args.preview) {
          this.currentAST.sourceCode = result;
          this.currentAST.tree = parse(result);
          this.currentAST.timestamp = new Date();
        }
    
        const transformResult: TransformResult = {
          operation: "insert_code",
          parameters: { pattern: args.pattern, text: args.code },
          preview: result.slice(0, 500) + (result.length > 500 ? '...' : ''),
          timestamp: new Date(),
        };
        
        this.transformHistory.push(transformResult);
    
        return {
          content: [{
            type: "text",
            text: `${args.preview ? 'Preview: ' : ''}Inserted code ${args.position} pattern "${args.pattern}"\n\n${args.preview ? 'Preview:\n' : 'Result:\n'}${result}`,
          }],
        };
      } catch (error) {
        return {
          content: [{
            type: "text",
            text: `Error inserting code: ${error instanceof Error ? error.message : String(error)}`,
          }],
          isError: true,
        };
      }
    }
  • The input schema defining the parameters for the insert_code tool: pattern (string), code (string), position (enum: before/after), optional preview (boolean).
    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"],
    },
  • src/index.ts:379-405 (registration)
    Registration of the insert_code tool in the ListToolsRequestSchema handler, including name, detailed description with usage examples, and input schema.
    {
      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"],
      },
    },
  • src/index.ts:446-447 (registration)
    Dispatch registration in the CallToolRequestSchema switch statement that routes calls to the insertCode handler method.
    case "insert_code":
      return await this.insertCode(args as { pattern: string; code: string; position: "before" | "after"; preview?: boolean });
  • Helper code within the handler that creates a TransformResult record for the insert_code operation, used for history tracking.
      operation: "insert_code",
      parameters: { pattern: args.pattern, text: args.code },
      preview: result.slice(0, 500) + (result.length > 500 ? '...' : ''),
      timestamp: new Date(),
    };
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It adds value by describing 'smart formatting' and 'proper indentation automatically', and the 'preview' parameter hint ('Always preview first!') suggests safety considerations. However, it doesn't cover potential side effects, error handling, or mutation behavior beyond insertion, leaving gaps for a tool that modifies code.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded with a clear purpose statement, followed by useful examples. However, the examples are extensive (six bullet points), which could be streamlined—some are redundant (e.g., multiple 'after' insertion examples). Overall, it's efficient but slightly verbose in the example section.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of a code modification tool with no annotations and no output schema, the description is moderately complete. It covers the purpose and usage through examples but lacks details on return values, error cases, or integration with sibling tools. For a mutation tool, this leaves the agent with incomplete guidance on behavioral outcomes.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds minimal semantic context through examples (e.g., showing 'pattern' usage like 'function_declaration'), but doesn't provide additional meaning beyond what's in the schema. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('insert code before or after nodes') and resource ('nodes'), distinguishing it from siblings like 'remove_unused_imports' or 'rename_identifier' by focusing on code insertion rather than analysis or transformation. It emphasizes 'smart formatting' and 'professional-quality code insertion' as key differentiators.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context through examples (e.g., 'Add logging', 'Add validation'), implicitly guiding when to use this tool for inserting code snippets. However, it lacks explicit guidance on when not to use it or alternatives among siblings like 'transform_code' for more complex modifications, which would require the agent to infer based on the examples.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/qckfx/tree-hugger-js-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server