Skip to main content
Glama
Stefan-Nitu

mcp-refactor-typescript

by Stefan-Nitu

NPM Version NPM Downloads CI Status MIT Licensed

MCP Refactor TypeScript

A Model Context Protocol (MCP) server that provides comprehensive TypeScript/JavaScript refactoring capabilities powered by the TypeScript compiler. Perform complex code transformations with compiler-grade accuracy and type-safety.

Overview

MCP Refactor TypeScript exposes TypeScript's powerful refactoring engine through the Model Context Protocol, enabling AI assistants and other MCP clients to perform sophisticated code transformations that would be impossible or error-prone to do manually.

Key Features:

  • Type-Aware Refactoring - Uses TypeScript's compiler for accurate, safe transformations

  • Cross-File Support - Automatically updates imports, exports, and references across your entire codebase

  • Safe - Preview mode for all destructive operations

  • Detailed Reporting - See exactly what changed with file paths and line numbers

Related MCP server: TypeScript Tools MCP

Installation

npm install -g mcp-refactor-typescript

The package will be globally installed and available as mcp-refactor-typescript.

From Source

git clone https://github.com/Stefan-Nitu/mcp-refactor-typescript.git
cd mcp-refactor-typescript
bun install
bun run build

⚠️ Requires Bun v1.3.8+ (development) and Node.js v18+ (runtime)

Quick Start

With Claude Desktop

Add to your Claude Desktop configuration file:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "mcp-refactor-typescript": {
      "command": "npx",
      "args": ["-y", "mcp-refactor-typescript"]
    }
  }
}

Or if installed globally:

{
  "mcpServers": {
    "mcp-refactor-typescript": {
      "command": "mcp-refactor-typescript"
    }
  }
}

Restart Claude Desktop and you'll have access to all refactoring tools.

With MCP Inspector

Test the server interactively:

npx @modelcontextprotocol/inspector npx -y mcp-refactor-typescript

Or if installed globally:

npx @modelcontextprotocol/inspector mcp-refactor-typescript

Open http://localhost:5173 to explore available tools and test refactoring operations.

Available Tools (v2.0)

The server exposes 4 grouped tools with 15 operations total. Each tool has a specific domain and uses the operation parameter to specify the action.

Tool Groups

Tool

Operations

Use When

file_operations

rename_file, move_file, batch_move_files

Renaming/moving files, reorganizing code structure

code_quality

organize_imports, fix_all, remove_unused

Before commits, after refactoring, cleanup tasks

refactoring

rename, extract_function, extract_constant, extract_variable, infer_return_type

Renaming symbols, reducing duplication, improving structure

workspace

find_references, refactor_module, cleanup_codebase, restart_tsserver

Understanding impact, large-scale refactoring, TypeScript issues

Operations Reference

Operation

Tool

Description

rename_file

file_operations

Rename file in-place with automatic import path updates

move_file

file_operations

Move file to different directory with import updates

batch_move_files

file_operations

Move multiple files atomically

organize_imports

code_quality

Sort and remove unused imports (preserves side-effects)

fix_all

code_quality

Apply all available TypeScript quick fixes

remove_unused

code_quality

Remove unused variables and imports safely

rename

refactoring

Rename symbols across all files with automatic import/export updates

extract_function

refactoring

Extract code to function with auto-detected parameters/types

extract_constant

refactoring

Extract magic numbers/strings to named constants

extract_variable

refactoring

Extract expressions to local variables

infer_return_type

refactoring

Add return type annotations automatically

find_references

workspace

Find all usages with type-aware analysis

refactor_module

workspace

Complete workflow: move + organize + fix

cleanup_codebase

workspace

Clean entire codebase (organize + optionally delete unused)

restart_tsserver

workspace

Restart TypeScript server for fresh project state

📖 Detailed Documentation: See docs/OPERATIONS.md for full examples, best practices, and workflow patterns for each operation. Also available via MCP resource operations://catalog.

Response Format

All tools return structured JSON:

{
  "tool": "refactoring",
  "operation": "rename",
  "status": "success" | "error",
  "message": "Human-readable summary",
  "data": {
    "filesChanged": ["list", "of", "modified", "files"],
    "changes": [
      {
        "file": "filename.ts",
        "path": "/absolute/path/filename.ts",
        "edits": [
          {
            "line": 42,
            "column": 10,
            "old": "oldText",
            "new": "newText"
          }
        ]
      }
    ]
  },
  "preview": {  // Only when preview: true
    "filesAffected": 5,
    "estimatedTime": "< 1s",
    "command": "Run again with preview: false to apply changes"
  },
  "nextActions": [  // Suggested follow-up operations
    "organize_imports - Clean up import statements",
    "fix_all - Fix any type errors"
  ]
}

Example Usage

Rename a symbol

{
  "tool": "refactoring",
  "params": {
    "operation": "rename",
    "filePath": "src/user.ts",
    "line": 10,
    "text": "getUser",
    "name": "getUserProfile",
    "preview": false
  }
}

Organize imports

{
  "tool": "code_quality",
  "params": {
    "operation": "organize_imports",
    "filePath": "src/index.ts"
  }
}

Extract function

{
  "tool": "refactoring",
  "params": {
    "operation": "extract_function",
    "filePath": "src/calculate.ts",
    "line": 15,
    "text": "x + y",
    "name": "addNumbers"
  }
}

Find references

{
  "tool": "workspace",
  "params": {
    "operation": "find_references",
    "filePath": "src/utils.ts",
    "line": 5,
    "text": "helper"
  }
}

Advanced Usage

Preview Mode

All destructive operations support preview mode:

{
  "filePath": "src/user.ts",
  "line": 10,
  "column": 5,
  "name": "getUserProfile",
  "preview": true
}

Returns what would change without modifying any files.

Entry Points for Cleanup

Required when deleteUnusedFiles: true - prevents accidental deletion with wrong defaults.

Safe mode (organize imports only) uses automatic defaults. Aggressive mode requires explicit entry points:

{
  "operation": "cleanup_codebase",
  "directory": "src",
  "deleteUnusedFiles": true,
  "entrypoints": [
    "src/main\\.ts$",       // Main entry point
    "src/cli\\.ts$",        // CLI entry
    ".*\\.test\\.ts$",      // Test files (auto-included in defaults)
    "scripts/.*\\.ts$"      // Script files
  ]
}

⚠️ Files not reachable from entry points will be DELETED. Always use preview: true first.

Batch Operations

Move multiple files atomically:

{
  "files": [
    "src/utils/string.ts",
    "src/utils/number.ts",
    "src/utils/array.ts"
  ],
  "targetFolder": "src/lib"
}

All imports update automatically, all files move together or not at all.

Development

Project Structure

mcp-refactor-typescript/
├── src/
│   ├── index.ts                     # MCP server entry point
│   ├── operation-name.ts            # Operation name enum (single source of truth)
│   ├── registry.ts                  # Operation registry
│   ├── operations/                  # Refactoring operations
│   │   ├── rename.ts               # Rename operation
│   │   ├── move-file.ts            # Move file operation
│   │   ├── extract-function.ts     # Extract function operation
│   │   └── ...                     # Other operations
│   ├── language-servers/
│   │   └── typescript/             # TypeScript server client
│   │       ├── tsserver-client.ts  # Direct tsserver communication
│   │       └── tsserver-types.ts   # Protocol type definitions
│   └── utils/
│       ├── logger.ts               # Pino logger (stderr only)
│       └── validation-error.ts     # Zod error formatting
├── test/
│   └── fixtures/                   # Test TypeScript files
└── docs/                           # Architecture & testing docs

Testing

# Run all tests
bun test

# Run specific test file
bun test --filter rename

# Run in watch mode
bun test --watch

# Type checking
bun run typecheck

# Linting
bun run lint

Test Coverage

  • Integration tests covering all operations

  • Unit tests for validation, error handling, and edge cases

  • E2E tests for server startup and initialization

  • All tests use real TypeScript compiler (no mocks)

Requirements

  • Node.js >= 18.0.0

  • TypeScript project with tsconfig.json

  • Valid TypeScript/JavaScript files

  • ESM module resolution (.js extensions in imports)

Your project does not need TypeScript installed — the server ships its own. When your project does have one, that copy is used instead so refactors match the language version you compile with. Projects on TypeScript 7 fall back to the bundled TypeScript 5, because TypeScript 7 no longer ships the tsserver this server drives.

Architecture

The server uses TypeScript's native tsserver for all refactoring operations:

  1. Server Starts: Detects TypeScript files and starts tsserver

  2. Indexing: TypeScript indexes project files (1-5 seconds for most projects)

  3. Operations: Each tool sends protocol messages to tsserver

  4. Results: Changes are returned as structured JSON with full details

Key Design Decisions:

  • Direct tsserver communication (not VS Code LSP)

  • One tsserver instance shared across all operations

  • All logging to stderr (MCP protocol compliance)

See docs/ARCHITECTURE.md for detailed architecture information.

Documentation

Troubleshooting

TypeScript Server Not Starting

If operations fail with "TypeScript server not running":

  1. Check that you have TypeScript files in your project

  2. Verify tsconfig.json exists and is valid

  3. Run restart_tsserver tool to force a restart

  4. Check logs in stderr for detailed error messages

Incomplete References

If find_references or rename misses some usages:

  1. Wait for TypeScript to finish indexing (check for "Project loaded" in logs)

  2. Ensure all files are included in tsconfig.json

  3. Fix any TypeScript errors that might prevent analysis

  4. Use restart_tsserver after making project configuration changes

Import Paths Not Updating

If move_file doesn't update some imports:

  1. Ensure imports use .js extensions (ESM requirement)

  2. Check that moved file is part of TypeScript project

  3. Verify tsconfig.json module resolution settings

  4. Look for dynamic imports that TypeScript can't analyze

Contributing

  1. Fork the repository

  2. Create a feature branch

  3. Write tests first (TDD approach)

  4. Implement the feature

  5. Ensure all tests pass (bun test)

  6. Run linting (bun run lint)

  7. Submit a pull request

License

MIT

Available Tools

4 tools
code_qualityCode QualityA

Fix ALL TypeScript errors + organize imports + remove unused (<1s, 20+ issues).

vs Manual: Compiler-verified, preserves side-effects, finds hidden issues.

Use when: After refactoring or before commits. Use proactively.

ParametersJSON Schema
NameRequiredDescriptionDefault
operationYes
filePathYes
previewNo

TDQS

A3.5/5.0
Behavior3/5

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

Annotations already set readOnlyHint=false and destructiveHint=false. The description adds that the tool is fast (<1s) and finds hidden issues, but does not explain the modify-in-place behavior or potential side-effects beyond preserving side-effects. It adds some value but not extensive.

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

Conciseness5/5

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

Extremely concise: two short lines that front-load the action and rationale. No wasted words. Every sentence adds value.

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 3 parameters, no output schema, and sibling tools like refactoring, the description covers purpose and when-to-use but lacks parameter documentation and return value info. It is somewhat incomplete for an agent to fully understand usage.

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

Parameters2/5

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

Schema description coverage is 0%, so the description must compensate. The description mentions operations (fix all, organize imports, remove unused) which map to the operation enum, but does not explain the filePath or preview parameters. Without these, an agent may not use the tool correctly.

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

Purpose4/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: fixing TypeScript errors, organizing imports, and removing unused code. It uses specific verbs and resources. However, it could better distinguish from sibling tools like refactoring, which might have overlapping capabilities.

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?

Explicit usage guidance is provided: 'Use when: After refactoring or before commits. Use proactively.' This helps the agent decide when to invoke. It also compares to manual process. No explicit when-not to use, but the context is clear.

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

file_operationsFile OperationsA

Rename/move TypeScript files - auto-updates ALL imports (<1s, 47 refs across 12 files).

vs Edit/Bash: They break imports. This catches dynamic imports, mocks, re-exports.

Use when: Renaming/moving TS/JS files. Always use this, not mv/Edit.

ParametersJSON Schema
NameRequiredDescriptionDefault
operationYes
sourcePathNo
nameNo
destinationPathNo
filesNo
targetFolderNo
previewNo

TDQS

A4.5/5.0
Behavior5/5

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

Annotations indicate non-read-only and non-destructive behavior. The description adds critical behavioral context: auto-updates all imports, handles dynamic imports/mocks/re-exports, and provides speed and scope metrics (<1s, 47 refs across 12 files). No contradiction with annotations.

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

Conciseness5/5

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

The description is exceptionally concise: two sentences plus a usage line, front-loaded with the most important info. Every sentence adds unique value—function, contrast with alternatives, and explicit usage advice—with no wasted words.

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 7 parameters (1 required) and no output schema, the description covers the primary use case and performance but omits details on parameter combinations (e.g., when to use sourcePath+name vs files+targetFolder) and the preview parameter. It addresses key behavioral aspects but lacks full completeness for a tool of moderate complexity.

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?

With 0% schema description coverage for 7 parameters, the description should compensate but only indirectly hints at parameters (e.g., 'Rename/move' implies operation, '47 refs' suggests batch moves). It does not explicitly describe individual parameters or their relationships, leaving gaps.

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 explicitly states the tool renames/moves TypeScript files and auto-updates imports, providing a specific verb and resource. It distinguishes itself from Edit/Bash by highlighting import-breaking behavior, and the performance metrics add clarity.

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

Usage Guidelines5/5

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

The description includes a clear directive: 'Use when: Renaming/moving TS/JS files. Always use this, not mv/Edit.' It also contrasts with Edit/Bash, explaining when not to use those alternatives, making the usage context explicit.

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

refactoringRefactoringA

Rename symbols, extract functions, or move symbols to files (auto-updates imports).

vs Edit: Updates ALL refs (imports, JSDoc, dynamic imports). Impossible by hand.

Use when: Renaming, extracting, or moving symbols between files. Always use this.

ParametersJSON Schema
NameRequiredDescriptionDefault
operationYes
filePathYes
lineYes
textYes
nameNo
destinationPathNo
previewNo

TDQS

A4.2/5.0
Behavior4/5

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

Annotations (readOnlyHint=false, destructiveHint=false) are complemented by description that says tool 'Updates ALL refs (imports, JSDoc, dynamic imports). Impossible by hand.' This adds useful behavioral context beyond annotations.

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

Conciseness5/5

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

Concise four-sentence description, front-loaded with main actions, each sentence adds value. No redundancy.

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?

Covers purpose and usage well, but lacks details on return values, preview behavior, and error handling. Given 7 parameters and no output schema, more completeness would be beneficial.

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

Parameters2/5

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

With 0% schema coverage, the description does not explain individual parameters like 'line', 'text', 'destinationPath', etc. It only mentions operations and vague inputs, insufficient for agent to use correctly.

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 does renaming, extracting, and moving of symbols with automatic import updates. It distinguishes itself from an 'Edit' tool, providing differentiation from a sibling-like action.

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

Usage Guidelines5/5

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

Explicitly states when to use: 'Rename, extracting, or moving symbols between files. Always use this.' Also contrasts with 'Edit' tool, giving clear contextual guidance.

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

workspaceWorkspaceA
Destructive

Find references (type-aware) | Cleanup | Move+organize+fix | Restart tsserver.

vs grep: Finds dynamic imports, JSDoc, type-only imports grep misses. ⚠️ Can DELETE.

Use when: Before renaming/refactoring. Use find_references first to see impact.

ParametersJSON Schema
NameRequiredDescriptionDefault
operationYes
filePathNo
lineNo
textNo
sourcePathNo
destinationPathNo
directoryNo
deleteUnusedFilesNo
entrypointsNo
previewNo

TDQS

A3.8/5.0
Behavior5/5

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

The description warns '⚠️ Can DELETE,' which aligns with the destructiveHint annotation and adds emphasis. It also explains advantages over grep (dynamic imports, JSDoc, type-only imports), providing behavioral context beyond annotations.

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 very concise: three lines covering operations, comparison, and usage. It is front-loaded with key actions. Minor improvement possible by adding parameter hints without bloating.

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

Completeness2/5

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

Given 10 parameters, no output schema, and multi-operation nature, the description lacks detail on operation-specific parameter usage, return values, and example invocations. Significant gaps exist.

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

Parameters1/5

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

Schema description coverage is 0%, so the description carries full burden. It mentions operations but provides no explanation of parameters like filePath, line, text, etc., leaving the agent without guidance on how to construct valid invocations.

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

Purpose4/5

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

The description clearly lists four distinct operations (find references, cleanup, move+organize+fix, restart tsserver) with a comparison to grep, indicating specific type-aware behavior. It does not explicitly differentiate from sibling tools, but the purpose is specific enough.

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

Usage Guidelines5/5

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

The description explicitly states 'Use when: Before renaming/refactoring. Use find_references first to see impact.' This gives clear usage context and a recommended order of operations, fully satisfying the dimension.

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

TDQS

A3.9/5.0
Disambiguation4/5

Tools have mostly distinct purposes: code_quality for fixing errors/organizing, file_operations for file moves, refactoring for symbol renaming/extraction, workspace for finding references and cleanup. Some overlap exists (e.g., workspace cleanup may overlap with code_quality), but descriptions clarify when to use each.

Naming Consistency3/5

All names use lowercase snake_case, but the pattern is inconsistent: code_quality (noun_quality) vs file_operations (noun_operations) vs refactoring (gerund) vs workspace (single noun). No verb_noun pattern, making it less predictable for agents.

Tool Count5/5

With 4 tools, the surface is well-scoped for a TypeScript refactoring server. Each tool covers a key area (code quality, file operations, symbol refactoring, workspace queries) without unnecessary bloat.

Completeness4/5

Core refactoring workflows are covered: error fixing, file renaming, symbol manipulation, and referencing. Minor gaps like formatting or running typechecker are absent, but the set is sufficient for common refactoring tasks.

Maintenance

ActivitySlowing
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    C
    maintenance
    An MCP server that enables AI agents to move TypeScript files and directories while automatically updating all affected imports using a persistent tsserver instance. This ensures atomic, error-free refactoring that maintains project integrity without manual intervention or wasted tokens.
    2
    29
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    A lightweight MCP server that provides 40 tools for TypeScript/JavaScript refactoring and code intelligence, directly mapping to TypeScript's tsserver protocol commands for accurate structural changes and workspace analysis.
    40
    34
    3
    MIT

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/Stefan-Nitu/mcp-refactor-typescript'

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