insert_code
Insert formatted code before or after specific JavaScript/TypeScript nodes. Automatically handles indentation for adding logging, validation, comments, error handling, and metrics.
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 |
|---|---|---|---|
| code | Yes | Code to insert. Will be formatted with proper indentation automatically. | |
| pattern | Yes | Pattern to match: 'function_declaration', 'class[name="MyClass"]', 'method_definition[async]' | |
| 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 logic. It uses tree-hugger-js to transform the AST by inserting code before or after nodes matching the given pattern, with preview support and history logging.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:379-405 (registration)Tool registration in the ListToolsRequestSchema response, defining the tool name, description, 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 case in the CallToolRequestSchema switch statement that invokes the insertCode handler.case "insert_code": return await this.insertCode(args as { pattern: string; code: string; position: "before" | "after"; preview?: boolean });
- src/index.ts:382-402 (schema)Input schema definition for the insert_code tool, specifying parameters, types, descriptions, and required fields.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!" } },
- src/index.ts:159-159 (helper)Listed as an available transformation operation in the ast://transforms resource metadata."insert_code"