MCP ts-morph Refactoring Tools
Инструменты рефакторинга MCP ts-morph
обзор
Этот сервер MCP использует ts-morph для выполнения операций рефакторинга для кодовых баз TypeScript и JavaScript. Он работает с расширениями редактора, такими как Cursor, позволяя переименовывать символы на основе AST, переименовывать файлы/папки и находить ссылки.
Related MCP server: TypeScript Rename Helper
Предоставленные функции
Этот сервер MCP предоставляет следующие функции рефакторинга: каждая функция использует ts-morph для анализа AST и внесения изменений, сохраняя при этом согласованность во всем проекте.
Переименование символов ( rename_symbol_by_tsmorph )
Что он делает : глобально переименовывает символ (функцию, переменную, класс, интерфейс и т. д.) в определенной позиции указанного файла во всем проекте.
Вариант использования : Вы хотите изменить имя функции или переменной, но на нее существует много ссылок, и изменить ее вручную будет сложно.
Требуемая информация : путь к проекту
tsconfig.json, путь к целевому файлу, положение символа (строка и столбец), текущее имя символа, новое имя символа
Переименование файла/папки ( rename_filesystem_entry_by_tsmorph )
Функция : переименовывает несколько указанных файлов и/или папок и автоматически обновляет пути во всех операторах
import/exportв проекте.Вариант использования : вы меняете структуру файла и хотите соответствующим образом изменить пути импорта. Если вы хотите переименовать/переместить несколько файлов/папок одновременно.
Требуемая информация : путь к
tsconfig.jsonпроекта, массив операций переименования (renames: { oldPath: string, newPath: string }[]).замечания :
Ссылки в основном разрешаются с использованием символьного разрешения.
Ссылки, содержащие псевдонимы путей (например,
@/), будут обновлены, но преобразованы в относительные пути .Импорты, ссылающиеся на файл индекса каталога (например,
../components) , обновляются до явного пути к файлу (например,../components/index.tsx) .Он также выполняет проверку на наличие конфликтов путей (дубликатов в существующих путях и внутри операции) перед операцией переименования.
Примечание (время выполнения): При работе с большим количеством файлов и папок одновременно или для очень больших проектов анализ и обновление ссылок может занять некоторое время.
ПРИМЕЧАНИЕ (известное ограничение): В настоящее время ссылки на экспорт по умолчанию формы
export default Identifier;могут быть обновлены некорректно.
Поиск ссылок ( find_references_by_tsmorph )
Что он делает : находит и выводит на экран определение символа в определенном месте указанного файла, а также все ссылки на него в проекте.
Вариант использования : Вы хотите знать, где используется функция или переменная. Вы хотите изучить область рефакторинга.
Требуемая информация : путь к
tsconfig.jsonпроекта, путь к целевому файлу, положение символа (строка, столбец).
Удалить псевдоним пути ( remove_path_alias_by_tsmorph )
Функция : Заменяет псевдонимы путей (например,
@/components) в операторахimport/exportв указанном файле или каталоге на относительные пути (например,../../components).Вариант использования : Вы хотите сделать свой проект более портативным или соответствовать определенным стандартам кодирования.
Требуемая информация :
tsconfig.jsonпуть к проекту, путь к файлу или каталогу для обработки.
Перемещение символов между файлами ( move_symbol_to_file_by_tsmorph )
Функция : Перемещает указанный символ (функцию, переменную, класс, интерфейс, псевдоним типа, перечисление) из текущего файла в другой указанный файл. Автоматически обновляйте ссылки по всему проекту (включая пути импорта/экспорта) по мере продвижения.
Вариант использования : вы хотите извлечь определенную функциональность в отдельный файл, чтобы реорганизовать свой код.
Требуемая информация : путь к
tsconfig.jsonпроекта, путь к исходному файлу, путь к целевому файлу, имя перемещаемого символа. При желании можно указать тип символа (declarationKindString), чтобы устранить неоднозначность символов с одинаковыми именами.Примечание : внутренние зависимости символа (другие объявления, используемые только внутри этого символа) перемещаются вместе с ним. Зависимости, на которые также ссылаются другие символы, оставшиеся в исходном файле, останутся в исходном файле, а
exportбудут добавлены по мере необходимости и импортированы в целевой файл.Примечание : символы, экспортированные
export defaultнельзя перемещать с помощью этого инструмента.
окружающая среда строительство
Для пользователей (при использовании как пакета npm)
Добавьте следующие настройки в mcp.json . При использовании команды npx будет автоматически использоваться последняя установленная вами версия.
{
"mcpServers": {
"mcp-tsmorph-refactor": { // 任意のサーバー名
"command": "npx",
"args": ["-y", "@sirosuzume/mcp-tsmorph-refactor"],
"env": {} // 必要に応じてロギング設定などを追加
}
}
}Для разработчиков (для локальной разработки и исполнения)
Если вы хотите запустить сервер локально из исходного кода, вам необходимо сначала его собрать.
# 依存関係のインストール (初回のみ)
pnpm install
# TypeScript コードのビルド
pnpm run buildПосле сборки вы можете запустить его непосредственно в node , установив следующее в mcp.json :
{
"mcpServers": {
"mcp-tsmorph-refactor-dev": { // 開発用など、別の名前を推奨
"command": "node",
// プロジェクトルートからの相対パスまたは絶対パス
"args": ["/path/to/your/local/repo/dist/index.js"],
"env": {
// 開発時のデバッグログ設定など
"LOG_LEVEL": "debug"
}
}
}
}Настройки ведения журнала (переменные среды)
Уровень выходных данных и место назначения журнала операций сервера можно контролировать с помощью следующих переменных среды. Установите его в блоке env mcp.json .
LOG_LEVEL: Устанавливает уровень детализации журнала.Доступные уровни:
fatal,error,warn,info(по умолчанию),debug,trace,silentПример:
"LOG_LEVEL": "debug"
LOG_OUTPUT: указывает место назначения вывода журнала.console(по умолчанию): выводит журнал на стандартный вывод. Если вы находитесь в среде разработки (NODE_ENV !== 'production') и у вас установленpino-pretty, вывод будет в формате pretty.file: Выводит журнал в указанный файл. Установите этот параметр, чтобы избежать влияния на клиентов MCP.Пример:
"LOG_OUTPUT": "file"
LOG_FILE_PATH: если дляLOG_OUTPUTзадано значениеfile, это указывает абсолютный путь к файлу журнала.По умолчанию:
[プロジェクトルート]/app.logПример:
"LOG_FILE_PATH": "/var/log/mcp-tsmorph.log"
Пример конфигурации (в mcp.json ):
// ... (mcp.json の他の設定)
"env": {
"LOG_LEVEL": "debug", // デバッグレベルのログを
"LOG_OUTPUT": "file", // ファイルに出力
"LOG_FILE_PATH": "/Users/yourname/logs/mcp-tsmorph.log" // ログファイルのパス指定
}
// ...Информация для разработчиков
Предпосылки
Node.js (версию см. в
.node-versionилиvoltaвpackage.json)pnpm (версию см. в поле
packageManagerвpackage.json)
настраивать
Клонируйте репозиторий и установите зависимости:
git clone https://github.com/sirosuzume/mcp-tsmorph-refactor.git
cd mcp-tsmorph-refactor
pnpm installСтроить
Компилирует код TypeScript в JavaScript.
pnpm buildАртефакты сборки выводятся в каталог dist .
тест
Запустите модульные тесты.
pnpm testЛинтинг и форматирование
Он статически анализирует и форматирует ваш код.
# Lintチェック
pnpm lint
# Lint修正
pnpm lint:fix
# フォーマット
pnpm formatИспользование отладочной оболочки
Если вы хотите подробно проверить последовательность запуска, стандартный ввод/вывод и вывод ошибок сервера MCP во время разработки, вы можете использовать mcp_launcher.js , который находится в каталоге scripts проекта.
Этот скрипт-оболочка запускает исходный процесс сервера MCP ( npx -y @sirosuzume/mcp-tsmorph-refactor ) как дочерний процесс и регистрирует информацию о запуске и вывод в файле .logs/mcp_launcher.log в корне проекта.
Как использовать:
В файле
mcp.jsonизмените конфигурацию сервераmcp-tsmorph-refactorследующим образом:Установите
commandна"node".В
argsукажите путь кscripts/mcp_launcher.js(например,["path/to/your_project_root/scripts/mcp_launcher.js"]). Вы также можете использовать путь относительно корня проекта (["scripts/mcp_launcher.js"]).
Пример конфигурации (
mcp.json):{ "mcpServers": { "mcp-tsmorph-refactor": { "command": "node", // scripts/mcp_launcher.js へのパス (プロジェクトルートからの相対パス or 絶対パス) "args": ["path/to/your_project_root/scripts/mcp_launcher.js"], "env": { // 元の環境変数設定はそのまま活かせます // 例: // "LOG_LEVEL": "trace", // "LOG_OUTPUT": "file", // "LOG_FILE_PATH": ".logs/mcp-ts-morph.log" } } // ... 他のサーバー設定 ... } }Перезапустите или перезагрузите клиент MCP (например, Cursor).
Убедитесь, что журнал выводится в
.logs/mcp_launcher.logв корне проекта. Вы также можете проверить журнал самого сервера MCP, если он настроен (например,.logs/mcp-ts-morph.log).
Использование этой оболочки может помочь вам диагностировать, почему ваш сервер MCP не запускается должным образом.
Публикация в npm
Этот пакет будет автоматически опубликован в npm через рабочий процесс GitHub Actions ( .github/workflows/release.yml ).
Предпосылки
Токен NPM: убедитесь, что у вас есть токен доступа npm с публичными разрешениями, установленными в секретах действий вашего репозитория (
Settings>Secrets and variables>Actions) с именемNPM_TOKEN.Обновите версию: перед публикацией обновите поле
versionвpackage.jsonв соответствии с семантическим версионированием (SemVer).
Как опубликовать
Чтобы запустить рабочий процесс релиза, используйте отправку тега Git.
Как: отправить тег Git (рекомендуется для релизов)
Предполагаемое использование: Регулярные выпуски версий (основные, второстепенные, исправленные). Git — рекомендуемый стандартный процесс выпуска, поскольку он обеспечивает четкое соответствие между историей и версиями.
Обновить версию: Измените
versionвpackage.json(например,0.3.0).Зафиксировать и отправить: зафиксировать изменения в
package.jsonи отправить их в основную ветку.Создать тег и отправить: создает тег Git (с префиксом
v), соответствующий версии, и отправляет его.git tag v0.3.0 git push origin v0.3.0Автоматизация: отправка тега запускает рабочий процесс
Release Package, который собирает, тестирует и публикует пакет в npm.Проверка: проверьте вкладку «Действия» для определения статуса рабочего процесса и проверьте пакет на npmjs.com.
Меры предосторожности
Согласованность версий: при запуске push-уведомления тега имя тега (например,
v0.3.0) должно точно соответствоватьversionвpackage.json(например,0.3.0). Если совпадений нет, рабочий процесс завершится неудачей.Предварительная проверка: хотя ваш рабочий процесс CI включает этапы сборки и тестирования, мы рекомендуем запускать
pnpm run buildиpnpm run testлокально перед обновлением версии, чтобы выявить потенциальные проблемы на ранней стадии.
лицензия
Данный проект выпущен под лицензией MIT. Подробную информацию смотрите в файле ЛИЦЕНЗИЯ .
Available Tools
8 toolschange_signature_by_tsmorphA
[ts-morph] Add, remove, or reorder parameters of a function/method/arrow-function and propagate the matching argument changes to every call site in the project.
When to use
Adding a required parameter to a function with many callers (LLM single-edit reliably misses some — this tool guarantees every call site is updated via the type checker).
Removing or reordering parameters of a function that is imported, re-exported, or accessed through a method chain.
Inserting a context-like first parameter (
ctx,logger, etc.) into existing helpers.
When NOT to use
Renaming a parameter — use
rename_symbol_by_tsmorphon the parameter identifier instead.Changing only the parameter's type annotation without changing arity — edit the source file directly.
Moving the function to another file — use
move_symbol_to_file_by_tsmorph.
Critical constraints
positionmust point at the function's name identifier (1-based line/column). Forconst foo = () => {}, point atfoo; forclass C { foo() {} }, point atfoo.functionNamemust match the identifier text at that position (sanity check).All paths (
tsconfigPath,targetFilePath) MUST be absolute.Spread arguments (
fn(...args)) at call sites cause the operation to fail when a change would modify arguments. Refactor those callers manually first, or limit changes to trailing optional/defaulted parameters with noargumentForCallers.Operations apply sequentially; later operations see the parameter list produced by earlier ones.
Operation semantics
add: Inserts a parameter at
index(default: end). IfargumentForCallersis provided, that exact text is inserted at the same index in every call site. If omitted, callers are left untouched (use only for trailing optional / defaulted parameters).remove: Removes the parameter at
index. Each call site with at least that many arguments drops the corresponding one. Calls passing fewer arguments are left untouched.reorder: Rebuilds the parameter list and every call site according to
newOrder. Fails if any call site does not pass exactly that many arguments (no way to safely reorder omitted optionals).
Tips
Run with
dryRun: truefirst when the function has many callers to preview the impacted files.For adding multiple parameters at once, list multiple
addoperations; theirindexvalues refer to the parameter list after prior operations in the same call have been applied.
Result
Returns the list of modified (or to-be-modified, in dryRun) file paths, plus status and processing time.
Inputs: tsconfigPath (required), targetFilePath (required), position (required), functionName (required), +2 more.
find_references_by_tsmorphA
[ts-morph] Locate the definition AND every reference of a symbol at a given position, project-wide. Read-only.
When to use
Assessing the blast radius of a planned refactor before changing anything.
Answering "who calls this function?" / "where is this type used?" precisely.
Prefer this over
grepfor identifier lookups: grep matches unrelated same-name tokens (different scopes, comments, strings), while this tool uses the type checker to return only true references.
When NOT to use
You just want a free-text search (comments, strings, doc files) -> use
grep.You already plan to rename -> skip straight to
rename_symbol_by_tsmorph(it computes the same set internally and supportsdryRun).
Critical constraints
positionmust land on the symbol identifier itself (1-based line/column, as shown by editors). A position on whitespace or another token will fail to resolve.All paths (
tsconfigPath,targetFilePath) MUST be absolute.
Result
Returns the definition (file path, line, column, source line) when found, followed by a numbered list of references with the same fields.
Inputs: tsconfigPath (required), targetFilePath (required), position (required).
find_unused_exports_by_tsmorphA
[ts-morph] List exports that have no references outside their declaring file across the project. Read-only.
When to use
Hunting for dead code candidates after a refactor or migration.
Auditing a module's surface area: which exports does nobody actually consume?
Pre-deletion safety check before manually removing exports — combine with
find_references_by_tsmorphto double-confirm.
When NOT to use
You want a single symbol's references — use
find_references_by_tsmorph.Single-file unused locals —
tsc --noUnusedLocalsis faster.
Detection scope
Reports:
export function/class/const/let/var/enum/interface/type ...(inline export keyword)export default function/class ...andexport default <Identifier>export = <Identifier>(CommonJS)
Detection algorithm
For each candidate identifier, findReferencesAsNodes() is run and the following references are excluded before deciding "unused":
References inside the SAME file as the declaration (internal use does not count).
References inside any
ExportDeclaration(pure re-export sites likeexport { x } from "./y"orexport *). This means a symbol re-exported only via a barrel — with nothing actually consuming the barrel — IS reported as unused.References in
node_modules.
If 0 references remain, the export is reported.
Known limitations (this tool returns CANDIDATES, not verdicts)
Static analysis cannot see:
Dynamic
require()/import()resolved from runtime strings.File-system / convention based routing (Next.js
page.tsx, Remix routes, etc.). Pass these asentryPoints.Symbols looked up via reflection or string keys.
Pure local re-exports (
export { x }withoutfrom) wherexis declared by a separateconst x = ...in the same file — this form is not enumerated.Mixed function + namespace declarations may be partially missed.
Workspace packages that publish built output: in a monorepo, when a scanned package's
package.jsonentry points (exports/main/module/types) resolve outside the scanned sources (e.g."exports": { ".": "./dist/index.js" }), imports from OTHER workspace packages resolve to the built files (or node_modules) instead of the scanned sources. Every export of such a package is then reported unused even when it IS consumed — a systematic false positive. The tool detects this shape and prepends a ⚠ package-level warning to the result; treat all candidates from a warned package as low confidence. Workaround: point that package'sexportsat source files for analysis, or verify each candidate withfind_references_by_tsmorph/textHits.
Default exports are high false-positive
export default <Identifier> / export = <Identifier> (shown with the [default] tag) are prone to FALSE POSITIVES: findReferencesAsNodes runs on the local identifier and often fails to connect to import Foo from "./mod" default-import sites. A default export reported here with textHits well above 0 is almost certainly actually used. Treat [default] candidates as low confidence and always confirm with find_references_by_tsmorph.
Always verify a candidate with find_references_by_tsmorph before deletion.
Options
tsconfigPath: absolute path totsconfig.json.entryPoints: list of absolute file paths whose exports should be skipped (treat as public API). Reference sites IN these files still count as "used" automatically.excludeFilePatterns: substrings; any file whose absolute pathincludes()a pattern is not scanned. Use this for test files (e.g.".test."), generated dirs, etc.maxResults: cap on number of reported entries. Default 100. When reached, scanning stops andtruncatedbecomes true — narrow scope with the filters above and retry.
Output modes (responseFormat)
"list"(default): one line per candidate (format below)."summary": aggregate counts for the WHOLE project — total, delete-safety split (deletable vs unexport-only), default-export count, and breakdowns by kind and by directory. On large repos the per-line list easily blows past the response size limit, so start with"summary"to see where dead code clusters, then narrow withentryPoints/excludeFilePatternsand switch to"list"for exact locations. (summaryscans the whole project regardless ofmaxResults.)
Result format (list mode)
A bullet list of candidates with file:line:column, symbol name, declaration kind, a [default] tag for default exports, textHits=N, and sameFileRefs=N.
sameFileRefs — decides delete vs. unexport (read this first)
Every reported export is, by definition, unreferenced OUTSIDE its declaring file. sameFileRefs tells you whether it is still used INSIDE that file (declaration itself and re-export sites excluded), which determines the safe action:
sameFileRefs=0: not used anywhere, including its own file → truly dead, safe to delete the whole declaration (combine withtextHits=0for highest confidence).sameFileRefs=1+: used within its own file → only theexportkeyword is unnecessary. Removeexport, but KEEP the declaration — deleting it breaks the in-file references.
Deleting every reported declaration blindly will break the build: the majority are often sameFileRefs=1+ (over-exported but internally used).
textHits — text-occurrence triage hint
textHits is the number of word-boundary occurrences of the export's name in OTHER source files (declaring file excluded — so it says nothing about same-file usage; use sameFileRefs for that):
textHits=0: no OTHER file mentions the name. Does NOT by itself mean deletable — still checksameFileRefs.textHits=1+: the name appears as a string literal, JSX tag, dynamicimport().then(m => m.X), or comment. Verify withfind_references_by_tsmorphbefore deleting. Short names (e.g.a,id) match incidentally — discount accordingly.
⚠ Package-level warnings
When a package that produced candidates publishes built output (see Known limitations), a ⚠ warnings block is prepended to the result (both list and summary modes) naming the package, its out-of-scan entry points, and how many candidates are affected. Those candidates are likely false positives.
Trailing line reports Scanned files: N and Truncated: bool.
Inputs: tsconfigPath (required), entryPoints, excludeFilePatterns, maxResults, +2 more.
get_type_at_position_by_tsmorphA
[ts-morph] Return the TypeChecker-inferred type at a specific position in a TypeScript/JavaScript file, plus the symbol and its declaration location.
When to use
Quickly verifying "what is the actual inferred type of this variable / expression / function?" without spawning
tscor running a full type check.Cheaper than
Read-ing the declaration file when all you need is the type signature.Before refactoring, to confirm what a value's actual shape is (especially helpful when types are inferred through multiple generics).
When NOT to use
Bulk type analysis across many positions — call
tscdirectly instead.Listing every reference of a symbol — use
find_references_by_tsmorph.
Critical constraints
positionis 1-based (line/column), matching what editors display.All paths (
tsconfigPath,targetFilePath) MUST be absolute.For function/method identifiers (where ALL declarations are signature-bearing) the type is rendered as a call-style
(arg: T) => Rtext taken directly from the declaration source, preserving rest..., optional?, default values, and destructuring patterns. Overloads are joined with&and the implementation signature is hidden.For function/namespace merges or other mixed symbols (function with extra properties), the raw TypeChecker text (e.g.
typeof fn) is returned to avoid silently dropping the property side of the type.For imported symbols the resolved (aliased) symbol's declaration location is reported, including barrel re-export chains (
export * from,export { x } from) which are recursively unwrapped.For built-in or third-party symbols (e.g.
console,Promise),declarationmay point insidenode_moduleslib.d.ts files.
Result fields
type: the inferred type text.nodeKind/nodeText: what the position landed on (Identifier, StringLiteral, etc., and the source text — truncated to 80 chars).symbol(optional): the resolved symbol's name and the kind of its first declaration.declaration(optional): file path + 1-based line/column of the first declaration.
Tips
Pointing at whitespace or a comment line returns a SourceFile/EndOfFileToken node and the file-level inferred type (e.g.
typeof import("...")) — this is NOT an error but is usually not what you want. ChecknodeKindin the response and re-target to the identifier.For function/namespace merges where the type returns as
typeof fn, inspect thedeclarationlocation to discover the merged namespace members.
Inputs: tsconfigPath (required), targetFilePath (required), position (required).
move_symbol_to_file_by_tsmorphA
[ts-morph] Move one top-level symbol (function, variable, class, interface, type, enum) from one file to another, carrying its internal-only dependencies and rewriting all imports/exports across the project.
When to use
Splitting a large file: move related symbols to a new file one by one.
Relocating a helper from a generic
utils.tsto a feature-specific module.Prefer this over manual cut-and-paste + import fixing. Manual moves frequently miss re-exports, leave stale imports, or fail to add the new export -- this tool handles all of that via the type checker.
When NOT to use
Renaming the file (without moving a single symbol out of it) ->
rename_filesystem_entry_by_tsmorph.Renaming a symbol in place ->
rename_symbol_by_tsmorph.The symbol you want to move is a
export default-> NOT SUPPORTED, refactor it to a named export first.
Critical constraints
ONE top-level symbol per call. To move N symbols, invoke the tool N times.
Default exports CANNOT be moved. Convert them to named exports beforehand.
If multiple top-level declarations share the same name (e.g., function + namespace), pass
declarationKindString(e.g.,"FunctionDeclaration","VariableStatement") to disambiguate.Internal dependency rules:
Dependencies used ONLY by the moved symbol travel with it.
Dependencies also used by other symbols in the source file stay put, gain
exportif missing, and are imported back into the destination file.
All paths (
tsconfigPath,originalFilePath,targetFilePath) MUST be absolute.targetFilePathmay point to a non-existent file; it will be created.
Tips
Run with
dryRun: truefirst when the source file has many co-dependencies to confirm what gets pulled along.
Result
Returns the list of modified (or to-be-modified, in dryRun) file paths, plus status and processing time.
Inputs: tsconfigPath (required), originalFilePath (required), targetFilePath (required), symbolToMove (required), +2 more.
remove_path_alias_by_tsmorphA
[ts-morph] Convert path-alias imports/exports (e.g., @/components/Button) to relative paths (../../components/Button) within a target file or directory.
When to use
Standardizing on relative paths for a subset of the codebase.
Preparing for a large
rename_filesystem_entry_by_tsmorphrun when you want to control alias rewriting explicitly (note:rename_filesystem_entry_by_tsmorphalready rewrites aliases to relative paths automatically; run this tool first only if you want the conversion to be a separate, reviewable commit).Prefer this over manual find/replace -- relative path computation is error-prone across nested directories.
When NOT to use
The project has no
pathsmapping intsconfig.json(this tool has nothing to do).You want to ADD aliases or change one alias to another (not supported).
Critical constraints
Aliases are read from the
pathsoption of the project'stsconfig.json. Only those aliases are resolved.targetPathmay be a single file OR a directory. Directory targets process every.ts/.tsxfile under it.All paths (
tsconfigPath,targetPath) MUST be absolute.
Tips
Run with
dryRun: truefirst when applying to a directory, to confirm the scope.
Result
Returns the list of modified (or to-be-modified, in dryRun) file paths, plus status and processing time.
Inputs: tsconfigPath (required), targetPath (required), dryRun.
rename_filesystem_entry_by_tsmorphA
[ts-morph] Rename or move one or more TypeScript/JavaScript files and/or folders, and automatically rewrite every import/export path that references them.
When to use
Renaming or moving any .ts/.tsx/.js/.jsx file or directory (single or batch).
Prefer this over
mv+ manual import fixing. This tool resolves references via the type checker, so it handles relative paths, path aliases (@/), and barrel imports (from '.',from '..') that grep cannot reliably find.Use batch mode (multiple entries in
renames) when reorganizing several files at once -- a single AST pass is much faster than running the tool repeatedly.
When NOT to use
Renaming a symbol inside a file ->
rename_symbol_by_tsmorph.Moving a single symbol (not the whole file) to another file ->
move_symbol_to_file_by_tsmorph.
Critical constraints
Path aliases in updated imports are REWRITTEN AS RELATIVE PATHS (e.g.,
@/foo->../foo). If you want to keep aliases, runremove_path_alias_by_tsmorphseparately beforehand, or accept the conversion.Barrel imports like
import X from '../components'are rewritten to point at the resolved index file (e.g.,'../components/index.tsx').Default exports declared via a bare identifier (
export default Foo;) may not be updated correctly. Default function/class declarations (export default function foo() {}) are handled.All paths (
tsconfigPath,oldPath,newPath) MUST be absolute.The tool refuses to run on path conflicts (target already exists, duplicate destinations).
Tips
Run with
dryRun: truefirst for any non-trivial rename to inspect the affected file list.timeoutSecondsdefaults to 120; raise it for very large projects or huge batch renames.
Result
Returns the list of modified (or to-be-modified, in dryRun) file paths, plus status and processing time. On timeout the operation is cancelled and an error is returned.
Inputs: tsconfigPath (required), renames (required), dryRun, timeoutSeconds.
rename_symbol_by_tsmorphA
[ts-morph] Type-aware rename of a TypeScript/JavaScript symbol (function, variable, class, type, interface, enum, etc.) across the entire project.
When to use
Renaming any symbol that may be imported, re-exported, or referenced in other files.
Prefer this over manual Edit + grep / sed. Identifier-based search misses re-exports, JSX attribute usage, and matches unrelated same-name tokens. This tool resolves references via the type checker, so it is both safer and faster.
Even for a "local-only" symbol, this tool is the correct default: it costs nothing extra and guarantees no missed reference.
When NOT to use
Renaming a file or folder (and updating imports to it) -> use
rename_filesystem_entry_by_tsmorph.Moving a symbol to a different file -> use
move_symbol_to_file_by_tsmorph.Just looking up where a symbol is used (no rename) -> use
find_references_by_tsmorph.
Critical constraints
positionmust point at the symbol's identifier (1-based line/column, as shown by editors). If the position lands on whitespace or a different token, the rename fails.symbolNamemust match the identifier text at that position; it is used as a sanity check.All paths (
tsconfigPath,targetFilePath) MUST be absolute.
Tips
Run with
dryRun: truefirst when the change spans many files, to preview the affected file list.
Result
Returns the list of modified (or to-be-modified, in dryRun) file paths, plus status and processing time.
Inputs: tsconfigPath (required), targetFilePath (required), position (required), symbolName (required), +2 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Each tool owns a clearly distinct operation—symbol rename, file rename/move, symbol move, signature change, reference lookup, type query, alias removal, and dead-export detection. The descriptions include explicit "When NOT to use" cross-references that route the agent to the correct counterpart, leaving no ambiguity between overlapping-sounding tools like rename_symbol vs. move_symbol vs. rename_filesystem_entry.
All 8 tools follow a consistent snake_case verb_noun_by_tsmorph pattern, with the shared suffix making the family instantly recognizable. Minor structural variations like move_symbol_to_file_by_tsmorph and get_type_at_position_by_tsmorph are still verb-first and follow the same morphological convention, so there is no real inconsistency.
8 tools is a well-scoped size for a refactoring toolkit. Each tool covers a distinct, frequently-needed refactoring or analysis operation with no redundancy or bloat, and the count is comfortably within the ideal 3–15 range.
The surface covers the major project-wide refactorings—rename symbol, rename/move files, move symbol, change signature, dead-code detection—plus read-only helpers for references and types. The only notable gap is the absence of extract/inline-style refactorings, but those aren't strongly implied by the server's stated purpose, so this is a minor rather than significant gap.
Maintenance
Related MCP Connectors
Stateless TS/JS compiler facts for agents: references, imports, impact. No repo index or OAuth.
Manage files and folders directly from your workspace. Read and write files, list directories, cre…
Ask a codebase what calls what: search, blast radius, paths between symbols, and diffs.
Coding agents in multi-service codebases routinely rebuild existing helpers, trust stale type definitions, and modify API contracts without knowing who consumes them. Carrick solves this by indexing your entire TypeScript ecosystem across service and repository boundaries. By integrating deeply with the TypeScript compiler, Carrick traces every route, type, and cross-service call while recording function behaviour so agents search by intent rather than name. Delivered via MCP for AI agents and LSP for IDEs, Carrick ensures models see existing endpoints and utilities before generating new code. The scanner is source-available and runs from your CLI or CI pipeline.
Related MCP Servers
- FlicenseAqualityDmaintenanceProvides code refactoring capabilities for TypeScript/JavaScript and Python through Language Server Protocol integration. Enables renaming symbols, extracting functions, finding references, and moving code between files via natural language commands.57-
- AlicenseAqualityDmaintenanceProvides compiler-grade TypeScript symbol renaming and file/directory move planning through the TypeScript Language Service, returning structured edit plans without modifying files.321 npmMIT
- AlicenseAqualityDmaintenanceProvides Python refactoring capabilities via the Rope library, enabling AI agents to perform safe, project-wide code transformations such as renaming symbols, moving modules, and extracting methods.1084 PyPI2MIT
- AlicenseAqualityBmaintenanceA TypeScript/JavaScript refactoring MCP server that uses the TypeScript compiler to perform safe, type-aware code transformations such as renaming, extracting functions, and organizing imports across your codebase.494 npm13MIT