Skip to main content
Glama
README.md
# refact-mcp

Read-only TypeScript architecture analysis and conservative, rollback-safe micro-refactoring tool with thin **CLI** and **MCP** interfaces.

## Positioning & Explicit Non-Goals (v1)

**What `refact-mcp` does:**
- Analyzes TypeScript repositories without executing target code: dependency graph, Tarjan SCC cycles, hotspot metrics, line-independent `SymbolId` index, semantic references, Public API snapshots, static blind spots (`ResidualUnknown`), and bottom-up micro-refactor plans.
- Applies conservative, fail-closed AST refactorings (`moveSymbol`, `renameSymbol`) inside an isolated temporary Git worktree, verified by multi-evidence gates (`TypeCheckGate`, `PublicApiGate`, and opt-in `ProjectTestGate`) before fast-forward merging back to the main branch—or rolling back cleanly on failure.

**Explicit v1 non-goals:**
- **TypeScript only**: No support for other languages; unsupported or ambiguous TypeScript syntax is rejected fail-closed rather than best-effort rewritten.
- **Not an OS security sandbox**: Git worktrees and sanitized child processes provide working-tree rollback isolation, not security confinement against malicious target code.
- **No mathematical proof of zero behavior change**: Passing typechecking, Public API comparison, and finite project tests provides multi-evidence confidence, not a formal proof.
- **No implicit execution or destructive Git operations**: Never runs `npm test`, `npm install`, lifecycle scripts, `git push`, or `git reset --hard` without explicit authorization.

---

## Requirements & Installation

- **Node.js `>= 22.0.0`**
- **Git** (required for write refactoring worktree transactions; read-only analysis works with or without Git)

```bash
# Local development / from source
git clone https://github.com/realcarsonterry/refact-mcp.git
cd refact-mcp
npm ci
npm run build

# Run CLI directly from build artifacts
node dist/composition/cliEntry.js --help
```

Or run via `npx` once published:

```bash
npx -y refact-mcp doctor .
```

---

## Quick Start

### 1. CLI Examples

```bash
# Workspace health & revision fingerprint (read-only)
refact-mcp doctor ./fixtures/messy-monolith

# Dependency graph, Tarjan cycles, hotspots & static unknowns (read-only)
refact-mcp analyze ./fixtures/messy-monolith --json

# Bottom-up micro-refactor plan isolating cycles and blocking unknowns (read-only)
refact-mcp plan ./fixtures/messy-monolith

# Verification gates (test execution blocked unless --allow-exec is explicitly passed)
refact-mcp verify ./fixtures/messy-monolith
refact-mcp verify ./fixtures/messy-monolith --allow-exec

# Dry-run preview of an atomic moveSymbol or renameSymbol (zero writes)
refact-mcp refactor move ./fixtures/messy-monolith \
  --symbol "sym:v1|src/godService.ts|function|buildCustomerNotice" \
  --to src/customerNotice.ts --dry-run

refact-mcp refactor rename ./fixtures/messy-monolith \
  --symbol "sym:v1|src/godService.ts|function|buildCustomerNotice" \
  --new-name formatCustomerNotice --dry-run

# Safely preview or register refact-mcp in a verified MCP client config
refact-mcp setup --client cursor --dry-run
refact-mcp setup --client claude --config-path /path/to/claude_desktop_config.json
```

### 2. MCP Server Configuration

`refact-mcp` exposes an MCP stdio server via `refact-mcp serve` (or the dedicated binary `refact-mcp-server`). `stdout` is 100% reserved for JSON-RPC frames; all logs go to `stderr`.

```json
{
  "mcpServers": {
    "refact-mcp": {
      "command": "npx",
      "args": ["-y", "refact-mcp", "serve"]
    }
  }
}
```

> Use `refact-mcp setup --client cursor --dry-run` (or `--client claude`) to preview config installation. `setup` refuses JSONC files containing comments/trailing commas, never silently overwrites a differing existing `refact-mcp` entry without `--overwrite-existing`, and backs up existing files before atomic replacement.

---

## CLI Commands & MCP Tools

### CLI Commands

| Command | Mode | Description |
|---|---|---|
| `doctor <workspace> [--tsconfig <path>] [--json]` | Read-only | Inspect workspace boundary, tsconfig, Git cleanliness, and revision fingerprint |
| `analyze <workspace> [--tsconfig <path>] [--json]` | Read-only | Compute dependency graph, Tarjan SCC cycles, hotspots, and static unknowns |
| `plan <workspace> [--tsconfig <path>] [--json]` | Read-only | Generate conservative bottom-up refactor plan isolating cycles and blocking unknowns |
| `verify <workspace> [--tsconfig <path>] [--allow-exec] [--json]` | Read-only (opt-in test exec) | Run multi-evidence verification gates (`project_tests` requires `--allow-exec`) |
| `refactor move <workspace> --symbol <id> --to <path> [...]` | Write (supports `--dry-run`) | Rollback-safe Git worktree `moveSymbol` (`--no-reexport`, `--allow-exec`, `--expected-revision`, `--approve-unknown`, `--commit-message`, `--json`) |
| `refactor rename <workspace> --symbol <id> --new-name <name> [...]` | Write (supports `--dry-run`) | Rollback-safe Git worktree `renameSymbol` (`--allow-exec`, `--expected-revision`, `--approve-unknown`, `--commit-message`, `--json`) |
| `setup --client <name> [--dry-run] [--config-path <path>] [--overwrite-existing] [--json]` | Config write (supports `--dry-run`) | Safely register `refact-mcp` in verified MCP client configs (`claude`, `cursor`) |
| `serve` | MCP stdio | Start MCP stdio server |

### MCP Tools

| Tool | Mode | Key Parameters |
|---|---|---|
| `open_workspace` | Read-only | `workspacePath`, `tsconfigPath?` |
| `get_dependency_summary` | Read-only | `workspacePath`, `tsconfigPath?`, `topHotspotsLimit?`, `includeEdges?` |
| `list_symbols` | Read-only | `workspacePath`, `tsconfigPath?`, `file?`, `kind?`, `exportedOnly?`, `offset?`, `limit?` |
| `find_references` | Read-only | `workspacePath`, `symbolId`, `tsconfigPath?`, `includeDeclaration?` |
| `list_unknowns` | Read-only | `workspacePath`, `tsconfigPath?`, `severity?`, `file?`, `offset?`, `limit?` |
| `generate_refactor_plan` | Read-only | `workspacePath`, `tsconfigPath?` |
| `apply_safe_refactor_step` | Write (`dryRun?`) | `workspacePath`, `operation` (`moveSymbol` \| `renameSymbol`), `symbolId`, `targetFile?`, `preserveReExport?`, `newName?`, `dryRun?`, `expectedRevision?`, `commitMessage?`, `allowProjectTestExecution?`, `testExecutionReason?`, `approvedUnknowns?` |
| `get_evidence` | Read-only | `evidenceId?`, `offset?`, `limit?` |

An agent workflow skill matching these exact tools is shipped at [.agents/skills/monolith-refactor/SKILL.md](./.agents/skills/monolith-refactor/SKILL.md).

---

## Architecture Overview

`refact-mcp` enforces unidirectional layering, zero cycles, `public.ts`-only cross-module encapsulation, and function/file complexity limits via `dependency-cruiser` + ESLint (`npm run lint:arch && npm run lint`).

```mermaid
flowchart LR
  composition["composition/ (wiring root)"] --> cli["adapters/cli"]
  composition --> mcp["adapters/mcp"]
  composition --> workflows["workflows/ (orchestration + evidence + setup)"]
  composition --> modules["modules/*/public.ts"]
  composition --> platform["platform/ (fs, process, git-cli, ts-project, config)"]
  cli --> workflows
  mcp --> workflows
  workflows -. "narrow ports" .-> modules
  modules --> platform
  modules --> shared["shared/ (zero-dep value objects)"]
  platform --> shared
```

See [ARCHITECTURE.md](./ARCHITECTURE.md) for the complete module graph and dependency rules.

---

## Supported AST Transformations

- **`moveSymbol`**: Top-level named `function`, `interface`, `type`, and pure single-identifier `const`. Refuses private dependencies (never auto-adds `export`), module mutable state, position-sensitive semantics (`import.meta`, `__dirname`, `eval`, dynamic `import()`), top-level side effects, overloads, declaration merging, classes, default exports, and cycle introduction.
- **`renameSymbol`**: Top-level named `function`, `class`, `interface`, `type`, and single-identifier variable via TypeScript Language Service semantic rename locations. Preserves import/export aliases, object property shorthands (`{ foo }` -> `{ foo: newName }`), and namespace destructuring while refusing scope shadowing/capture, dynamic reflection, and unapproved Public API breaks.

Full support and fail-closed rejection matrix: [docs/supported-transformations.md](./docs/supported-transformations.md).

---

## Verification States & Decisions

Each verification gate (`typecheck`, `public_api`, `project_tests`) reports one of 5 honest states:

| Gate State | Meaning |
|---|---|
| `passed` | Gate executed and met all pass criteria |
| `failed` | Regression detected (new TS diagnostics, Public API removal/change, or non-zero test exit) |
| `skipped` | Gate intentionally not applicable (e.g., `public_api` in standalone `verify` without a baseline) |
| `needs_approval` | Requires explicit execution authorization (`--allow-exec` / `allowProjectTestExecution: true`) |
| `inconclusive` | Environment/fingerprint mismatch or unexpected error prevented a reliable verdict |

Aggregated verification decisions:
- `safe_to_commit`: All required gates `passed` (never masks `skipped`/`needs_approval`/`inconclusive` as `passed`).
- `blocked`: At least one gate `failed`.
- `requires_human_approval`: No gate failed, but at least one required gate is `needs_approval`.
- `inconclusive`: No gate failed, but a required gate is `inconclusive` or could not complete.

---

## Worktree Dependencies, Security Risks & Recovery

- **Worktree dependency resolution**: Worktrees do not symlink `node_modules/` from your main workspace to avoid cache/file leakage. Read [docs/adr/ADR-0001-worktree-dependencies.md](./docs/adr/ADR-0001-worktree-dependencies.md) for the three explicit strategies (`none`, `node-path-readonly`, `explicit-install`).
- **Security model & static blind spots**: Read [docs/security-and-limitations.md](./docs/security-and-limitations.md) and [SECURITY.md](./SECURITY.md).
- **Manual recovery** (stale worktrees or `committed_with_cleanup_warning`): Read [docs/worktree-recovery.md](./docs/worktree-recovery.md).

---

## Development & Verification

```bash
npm ci
npm run check   # lint:arch && lint && typecheck && test && build
```

## License

[MIT](./LICENSE)