mcp-refactor-typescript

mcp-refactor-typescript

A 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.

Category
访问服务器

README

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)

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)

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

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选