MCP Refactor TypeScript logo

MCP Refactor TypeScript

Community
Stefan-Nitu

A Model Context Protocol (MCP) server that provides comprehensive TypeScript/JavaScript refactoring capabilities powered by the TypeScript compiler. Perform complex code transformations with…

PublisherStefan-Nitu
Repositorymcp-refactor-typescript
LanguageTypeScript
Forks
8
Stars
12
Available tools
4
Transport typestdio
Categories
Links
  • Connect tools to AI workflows

    MCP Refactor TypeScript exposes MCP capabilities that can be used by compatible AI clients and agents.

  • 4 available tools

    Browse the callable actions below, including names and descriptions when provided by the server.

  • Ready-to-copy setup

    Use the installation snippets to configure this server in your preferred MCP client.

  • Open source signals

    12 stars and 8 forks from the linked repository.

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

Installation

Via npm (Recommended)

bash
npm install -g mcp-refactor-typescript

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

From Source

bash
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

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

Or if installed globally:

json
{
  "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:

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

Or if installed globally:

bash
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

ToolOperationsUse When
file_operationsrename_file, move_file, batch_move_filesRenaming/moving files, reorganizing code structure
code_qualityorganize_imports, fix_all, remove_unusedBefore commits, after refactoring, cleanup tasks
refactoringrename, extract_function, extract_constant, extract_variable, infer_return_typeRenaming symbols, reducing duplication, improving structure
workspacefind_references, refactor_module, cleanup_codebase, restart_tsserverUnderstanding impact, large-scale refactoring, TypeScript issues

Operations Reference

OperationToolDescription
rename_filefile_operationsRename file in-place with automatic import path updates
move_filefile_operationsMove file to different directory with import updates
batch_move_filesfile_operationsMove multiple files atomically
organize_importscode_qualitySort and remove unused imports (preserves side-effects)
fix_allcode_qualityApply all available TypeScript quick fixes
remove_unusedcode_qualityRemove unused variables and imports safely
renamerefactoringRename symbols across all files with automatic import/export updates
extract_functionrefactoringExtract code to function with auto-detected parameters/types
extract_constantrefactoringExtract magic numbers/strings to named constants
extract_variablerefactoringExtract expressions to local variables
infer_return_typerefactoringAdd return type annotations automatically
find_referencesworkspaceFind all usages with type-aware analysis
refactor_moduleworkspaceComplete workflow: move + organize + fix
cleanup_codebaseworkspaceClean entire codebase (organize + optionally delete unused)
restart_tsserverworkspaceRestart 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:

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

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

Organize imports

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

Extract function

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

Find references

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

Advanced Usage

Preview Mode

All destructive operations support preview mode:

json
{
  "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:

json
{
  "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:

json
{
  "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

bash
# 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

Related Projects

Installation

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

Available Tools

  • file_operations

    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.

  • code_quality

    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.

  • refactoring

    Rename symbols project-wide OR extract functions (auto-detects params/types/closures).

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

    Use when: Renaming variables/functions OR extracting code. Always use this.

  • workspace

    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.

Use MCP Refactor TypeScript MCP with multiple AI models

TypingMind connects MCP tools at the workspace level, so once MCP Refactor TypeScript is connected, you can use it with different AI models in TypingMind instead of setting it up separately for each model. This MCP runs locally through the TypingMind MCP connector on your device.

Setup guide to use the local connector

Use this when the MCP server needs access to local files, apps, or private resources on your computer.

1

Open the MCP settings

In TypingMind, go to Settings, Advanced Settings, then Model Context Protocol and choose Setup Connector.

  1. Open TypingMind in your browser.
  2. Click the Settings icon.
  3. Go to Advanced Settings.
  4. Open the Model Context Protocol section.
  5. Click Setup Connector and choose This Device.
TypingMind MCP connector setup screen with This Device selected
2

Run the connector command

Choose This Device, copy the command from TypingMind, and run it in Terminal. Keep the process running while you use MCP.

  1. Copy the setup command shown by TypingMind.
  2. Open Terminal on macOS or Windows Terminal on Windows.
  3. Paste and run the command.
  4. Approve the package install if Terminal asks you to proceed.
  5. Keep the Terminal window running while using MCP tools.
3

Add MCP Refactor TypeScript as a server

When the connector status is Ready, click Edit Servers and paste the MCP server configuration.

  1. Wait until the connector status shows Ready.
  2. Click Edit Servers.
  3. Paste the MCP Refactor TypeScript MCP server configuration.
  4. Save the server list.
  5. Refresh if you want to confirm the connector is still ready.
TypingMind MCP settings showing active server and Edit Servers button
{
  "mcpServers": {
    "mcp-refactor-typescript": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-refactor-typescript"
      ]
    }
  }
}
4

Use it across models

Save the server list, open Plugins, enable the MCP Refactor TypeScript MCP tools, then select any supported AI model in TypingMind and use the tools in chat or assign them to an AI agent.

  1. Open the Plugins page in TypingMind.
  2. Enable the MCP Refactor TypeScript MCP tools.
  3. Start a chat and choose the AI model you want to use.
  4. Use the MCP tools in chat or assign them to an AI agent.
  5. Switch to another AI model whenever needed without reconnecting MCP.
TypingMind chat using enabled MCP tools with a selected AI model
Can you use MCP Refactor TypeScript to help me with this task?
MCP Refactor TypeScript
Sure. I read it.
Here is what I found using MCP Refactor TypeScript.

Frequently asked questions

What is the MCP Refactor TypeScript MCP server used for?

MCP Refactor TypeScript is an MCP server that lets compatible AI clients connect to external tools and context. In TypingMind, you can add this MCP server once and make its tools available in your AI workspace.

Can I use MCP Refactor TypeScript MCP with multiple AI models in TypingMind?

Yes. TypingMind connects MCP tools at the workspace level, so you can use MCP Refactor TypeScript with different AI models such as Claude, ChatGPT, Gemini, or other models you have configured in TypingMind without setting up the MCP server separately for each model.

Why use MCP Refactor TypeScript MCP with TypingMind?

TypingMind is one of the best frontends for LLM chat because it brings multiple AI models, prompts, plugins, AI agents, API keys, and MCP tools into one workspace. With MCP Refactor TypeScript connected, you can use its MCP tools across your preferred models while keeping your chat workflow organized in TypingMind.

How do I connect MCP Refactor TypeScript MCP to TypingMind?

MCP Refactor TypeScript runs through the TypingMind local MCP connector. This is best when the MCP server needs access to local files, desktop apps, command-line tools, or private resources on your computer.

What tools does MCP Refactor TypeScript MCP provide in TypingMind?

MCP Refactor TypeScript exposes 4 MCP tools that can be enabled from the TypingMind Plugins page and used in chat or assigned to AI agents.

Do I need to share my API keys with TypingMind to use MCP Refactor TypeScript MCP?

No. TypingMind is local-first and lets you keep your model providers, API keys, prompts, and MCP configuration under your control. If MCP Refactor TypeScript requires authentication, add the required headers, OAuth settings, or local configuration for that MCP server when you create the connection.

operations-catalog

Detailed documentation for all refactoring operations with examples

Related MCP Servers

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇