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
| Name | Required | Description | Default |
|---|---|---|---|
| pattern | Yes | Pattern to match: 'function_declaration', 'class[name="MyClass"]', 'method_definition[async]' | |
| code | Yes | Code to insert. Will be formatted with proper indentation automatically. | |
| position | Yes | Insert position: 'before' (above) or 'after' (below) the matched nodes | |
| preview | No | Return preview only without applying changes (default: false). Always preview first! |
Implementation Reference
- src/index.ts:1055-1104 (handler)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, }; } }
- src/index.ts:382-404 (schema)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 });
- src/index.ts:1081-1085 (helper)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(), };