Map Code
mapCodeInsert, replace, or append code snippets in files using name-based matching for functions, classes, and methods. Supports preview and file creation.
Instructions
Map/insert/replace code snippets into a file. Designed for AI code generation workflows.
How matching works:
Without focusLocations → code is ALWAYS appended to end of file (no matching attempted)
With focusLocations → TypeScript searches for matching declarations by NAME in the scope
Matching works for: functions, classes, methods, interfaces (nodes with a 'name' property)
Matching does NOT work for: const/let/var declarations (VariableStatement has no name)
When a match is found:
The range from first matching statement to last matching statement is REPLACED with new code
When no match is found:
Code is appended to the end of the scope (file or block)
Multiple contents limitation:
When providing multiple contents entries, only the FIRST entry's match is applied
To replace multiple named declarations, call mapCode once per declaration
Non-existent files:
tsserver opens a virtual file buffer for paths that don't exist on disk
Edits are returned and written as if the file exists, effectively creating it
Use preview=true first to verify the output before writing a new file
Usage patterns:
REPLACE a function: provide contents with same function name + focusLocations anywhere in file
ADD new code: omit focusLocations (always appends to end)
REPLACE const/var: NOT SUPPORTED by mapCode — use standard file editing instead
REPLACE multiple declarations: call mapCode separately for each one
CREATE a new file: provide the desired path and contents without focusLocations
Example - replacing function 'calculate' (focusLocations just needs to be in the file scope): contents: ["export function calculate(x: number) { return x * 2; }"] focusLocations: [[{ start: { line: 1, offset: 1 }, end: { line: 1, offset: 1 } }]]
Set preview=true to see edits without applying them.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| file | Yes | File path (absolute or relative to cwd) | |
| preview | Yes | If true, return edits without applying them | |
| contents | Yes | Code snippets to map into the file. Each is parsed independently. Functions/classes are matched by name. | |
| focusLocations | No | Required to enable name-based matching. Point anywhere in the file/block scope to search. Without this, code is always appended. |