How to Migrate from Cursor to Claude Code: Chat History, Rules, MCP Servers and Settings
Switching from Cursor to Claude Code is easy for the code. Your repo doesn’t care which agent edits it. What gets lost is the context: months of agent chats, the rules you tuned in .cursor/rules, your MCP servers, and the habits built around Cursor’s shortcuts.
This guide moves all of it. Use the free one-click app for Mac and Windows, or the tested, re-runnable Python script it is built on. Either one turns Cursor agent chats into native Claude Code sessions (they show up in claude --resume), converts Cursor rules into .claude/rules, and copies MCP servers into .mcp.json. Nothing in Cursor is changed, so you can keep using both while you switch.
- Cursor files changed
- None
- Re-runnable
- Yes
- Dependencies
- Python stdlib
- App
- Mac + Windows
Download the one-click app (Mac and Windows)
Don’t want to run a script? The free Cursor to Claude Code app does the same thing with one button. It finds your Cursor agent chats, plans, and any repos with Cursor rules or MCP servers, shows what will move, and migrates when you press Migrate. Advanced settings let you pick the Claude Code folder, limit it to one project, add a repo, preview without writing, and read the log.



Installing.
- Mac: open the download (Safari unzips it to
Cursor to Claude Code.app), drag it to Applications and open it. The app is signed with our Apple Developer ID and notarized by Apple, so it opens like any other app. - Windows: run
Cursor-to-Claude-Code.exe. It isn’t code-signed yet, so Windows SmartScreen may say it protected your PC: click More info › Run anyway. It uses the Microsoft Edge WebView2 runtime, which Windows 11 and current Windows 10 already include.
The app runs the same migration code shown in the script below: it only reads Cursor’s files, makes no network calls and reads no tokens. Not affiliated with Anysphere (Cursor) or Anthropic (Claude).
What moves, and where it lands
| Cursor | Claude Code | How |
|---|---|---|
Agent chats ~/.cursor/projects/<slug>/agent-transcripts/ | Sessions ~/.claude/projects/-<slug>/<id>.jsonl | Script (below) |
Plans ~/.cursor/plans/*.plan.md | ~/.claude/plans/*.md | Script |
Project rules .cursor/rules/*.mdc | .claude/rules/*.md (globs become paths:) | Script, --rules |
Legacy .cursorrules | Imported from CLAUDE.md with @.cursorrules | Script, --rules |
AGENTS.md | Read as-is when there is no CLAUDE.md | Nothing to do |
MCP servers .cursor/mcp.json | .mcp.json (project) or claude mcp add-json | Script, --mcp |
.cursorignore | permissions.deny rules in .claude/settings.json | By hand (example below) |
Composer chats in state.vscdb | Not importable on current Cursor builds | See Composer chats |
Before you start
- Install Claude Code and run it once in each repo you’ll migrate, so its project folder exists.
- Quit Cursor while the script runs. It only reads Cursor’s files, but a quiet disk avoids half-written transcripts.
- Python 3.10 or newer. No packages to install.
- Back up
~/.claude/projectsif you already have Claude Code sessions you care about:cp -R ~/.claude/projects ~/claude-projects-backup. - Raise session retention if you want old chats kept: Claude Code deletes old local sessions after
cleanupPeriodDays(30 by default). Set it in~/.claude/settings.json.
{
"cleanupPeriodDays": 365
}Where Cursor keeps your data
On macOS most of Cursor’s state lives in ~/Library/Application Support/Cursor/; Linux uses ~/.config/Cursor and Windows %APPDATA%\Cursor. The agent work itself is in your home folder:
| Path | What it holds | Migrated? |
|---|---|---|
~/.cursor/projects/<slug>/agent-transcripts/<run>/<run>.jsonl | One file per agent run: your prompts, the agent’s replies and its tool calls | Yes |
~/.cursor/plans/*.plan.md | Plan-mode documents | Yes |
User/workspaceStorage/<hash>/workspace.json | Which folder each workspace was | Read to find each chat’s repo |
User/globalStorage/state.vscdb | SQLite: settings, Composer index and data | No (see below) |
~/.cursor/projects/<slug>/terminals, canvases, mcps | Terminal logs, canvases, MCP tool caches | No |
The <slug> is the repo’s absolute path with slashes, dots, underscores and spaces turned into dashes: /Users/you/dev/my-app becomes Users-you-dev-my-app. Claude Code uses the same encoding with a leading dash, -Users-you-dev-my-app, which is what makes the mapping reliable.
Security note: state.vscdb also holds Cursor’s auth tokens. Never copy that file into a script or tool that sends data anywhere. The script below reads only transcripts, plans and workspace.json, and makes no network calls.
How the two formats differ
A Cursor transcript line holds a role and a list of content blocks. Your prompt is wrapped in <timestamp> and <user_query> tags, and agent tool calls appear as tool_use blocks without results or IDs. Some lines are only status markers.
{"role": "user", "message": {"content": [{"type": "text", "text": "<timestamp>Friday, Nov 6, 2026, 6:32 AM</timestamp>\n<user_query>Add retries to the upload client</user_query>"}]}}
{"role": "assistant", "message": {"content": [{"type": "text", "text": "I'll add exponential backoff..."}, {"type": "tool_use", "name": "Shell", "input": {"command": "pytest -q"}}]}}
{"type": "turn_ended", "status": "success"}A Claude Code session line is richer. Each message has its own uuid and points to the previous one through parentUuid; that chain is how --resume rebuilds the conversation. The file also carries a title and a pointer to the last message.
{"type": "user", "parentUuid": null, "uuid": "…", "sessionId": "…", "timestamp": "2026-11-06T01:02:00.000Z",
"cwd": "/Users/you/dev/my-app", "isSidechain": false, "userType": "external", "entrypoint": "cursor-migrated",
"message": {"role": "user", "content": "Add retries to the upload client"}}
{"type": "assistant", "parentUuid": "<uuid of the line above>", "uuid": "…", "message": {"role": "assistant", "content": [{"type": "text", "text": "I'll add exponential backoff..."}]}, "…": "…"}
{"type": "custom-title", "customTitle": "[Cursor] Add retries to the upload client", "sessionId": "…"}
{"type": "last-prompt", "lastPrompt": "Add retries to the upload client", "leafUuid": "<last message uuid>", "sessionId": "…"}Three conversions matter, and the first version of this guide got two of them wrong:
- Chain the messages. Every message needs a
parentUuidpointing at the one before it. Leaving them allnullgives Claude Code a pile of disconnected messages. - Don’t copy tool calls as tool calls. Cursor logs a
tool_usewith no matching result. If that reaches the API on resume, the request fails. The script turns each one into a short note such as[Cursor tool: Shell `pytest -q`], so you still see what the agent did. - Skip status lines and unwrap prompts.
turn_endedrows are dropped, Cursor’s wrapper tags are removed, and the real prompt time from<timestamp>is kept instead of stamping everything with today’s date.
The migration script
Save this as migrate_cursor_to_claude.py. It uses only the Python standard library. We tested it against real Cursor transcripts and Claude Code 2.1.302: every migrated session starts with a user message, alternates roles, has an unbroken parentUuid chain, contains no orphaned tool calls, and keeps timestamps in order.
#!/usr/bin/env python3
"""Migrate Cursor agent chats, plans, rules and MCP servers into Claude Code.
Reads Cursor's local files (never modifies them) and writes Claude Code
session JSONL files so migrated chats show up in `claude --resume`.
python3 migrate_cursor_to_claude.py --dry-run
python3 migrate_cursor_to_claude.py --yes
python3 migrate_cursor_to_claude.py --project ~/dev/my-app --yes
python3 migrate_cursor_to_claude.py --rules ~/dev/my-app --yes # .cursor/rules -> .claude/rules
python3 migrate_cursor_to_claude.py --mcp ~/dev/my-app --yes # .cursor/mcp.json -> .mcp.json
Python 3.10+, standard library only. No network calls.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import sys
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Optional
from urllib.parse import unquote, urlparse
HOME = Path.home()
if sys.platform == "darwin":
CURSOR_APP = HOME / "Library/Application Support/Cursor"
elif sys.platform == "win32":
CURSOR_APP = Path(os.environ.get("APPDATA", HOME / "AppData/Roaming")) / "Cursor"
else:
CURSOR_APP = HOME / ".config/Cursor"
WORKSPACES = CURSOR_APP / "User/workspaceStorage"
CURSOR_PROJECTS = HOME / ".cursor/projects"
CURSOR_PLANS = HOME / ".cursor/plans"
TS_RE = re.compile(r"<timestamp>(.*?)</timestamp>", re.S)
QUERY_RE = re.compile(r"<user_query>(.*?)</user_query>", re.S)
TAG_BLOCK_RE = re.compile(r"<(timestamp|image_files|attached_files)>.*?</\1>", re.S)
# ---------- paths and slugs ----------
def cursor_slug(abs_path: str) -> str:
"""Cursor and Claude Code both encode a repo path by turning separators into dashes."""
out = abs_path
for ch in ("/", "\\", ":", ".", "_", " "):
out = out.replace(ch, "-")
return out.lstrip("-")
def slug_to_repo_map() -> dict[str, str]:
"""Cursor project slug -> real repo path, read from workspaceStorage/*/workspace.json."""
mapping = {cursor_slug(str(HOME)): str(HOME)}
if not WORKSPACES.exists():
return mapping
for ws in WORKSPACES.iterdir():
wj = ws / "workspace.json"
if not wj.is_file():
continue
try:
folder = json.loads(wj.read_text(encoding="utf-8")).get("folder")
except (OSError, ValueError):
continue
if folder and folder.startswith("file://"):
path = unquote(urlparse(folder).path)
if sys.platform == "win32" and re.match(r"^/[A-Za-z]:", path):
path = path[1:]
if os.path.isdir(path):
mapping[cursor_slug(path)] = path
return mapping
def short(p) -> str:
"""Show paths under your home folder as ~/..."""
s, h = str(p), str(HOME)
return "~" + s[len(h):] if s == h or s.startswith(h + os.sep) else s
def stable_uuid(text: str) -> str:
"""Same input always gives the same UUID-shaped id, so re-runs overwrite instead of duplicating."""
h = hashlib.sha256(text.encode()).hexdigest()
return f"{h[:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}"
# ---------- reading Cursor chats ----------
def list_chats(claude_dir: Path, project: Optional[str]) -> list[dict]:
chats = []
if not CURSOR_PROJECTS.exists():
return chats
repos = slug_to_repo_map()
for proj in sorted(CURSOR_PROJECTS.iterdir()):
transcripts = proj / "agent-transcripts"
if not transcripts.is_dir():
continue
repo = repos.get(proj.name)
if project and (not repo or Path(repo).resolve() != Path(project).resolve()):
continue
for run in transcripts.iterdir():
f = run / f"{run.name}.jsonl"
if f.is_file():
st = f.stat()
chats.append({
"slug": proj.name, "run": run.name, "path": str(f),
"repo": repo or str(HOME), "repo_found": bool(repo), "mtime": st.st_mtime, "size": st.st_size,
"dest": claude_dir / "projects" / f"-{proj.name}" / f"{stable_uuid(str(f))}.jsonl",
})
return sorted(chats, key=lambda c: c["mtime"], reverse=True)
def parse_cursor_time(raw: str) -> Optional[datetime]:
raw = " ".join(raw.split())
for fmt in ("%A, %b %d, %Y, %I:%M %p", "%A, %B %d, %Y, %I:%M %p", "%A, %b %d, %Y, %H:%M"):
try:
return datetime.strptime(raw, fmt).astimezone(timezone.utc)
except ValueError:
continue
return None
def user_text(blocks: list) -> tuple[str, Optional[datetime]]:
"""Strip Cursor's wrapper tags; keep the real prompt and its timestamp."""
raw = "\n".join(b.get("text", "") for b in blocks if b.get("type") == "text")
ts = TS_RE.search(raw)
when = parse_cursor_time(ts.group(1)) if ts else None
queries = QUERY_RE.findall(raw)
text = "\n\n".join(q.strip() for q in queries) if queries else TAG_BLOCK_RE.sub("", raw).strip()
if "<image_files>" in raw:
text = "[Image attached in Cursor; not migrated]\n\n" + text
return text.strip(), when
def assistant_text(blocks: list) -> str:
"""Keep text; turn tool calls into short notes (Cursor logs have no tool results to pair them with)."""
parts = []
for b in blocks:
if b.get("type") == "text" and b.get("text", "").strip():
parts.append(b["text"].strip())
elif b.get("type") == "tool_use":
inp = b.get("input") or {}
detail = inp.get("command") or inp.get("path") or inp.get("target_file") or inp.get("query") or ""
note = f"[Cursor tool: {b.get('name', 'tool')}"
note += f" `{str(detail)[:200]}`]" if detail else "]"
parts.append(note)
return "\n\n".join(parts)
def read_turns(path: str) -> list[dict]:
turns = []
for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines():
if not line.strip():
continue
try:
row = json.loads(line)
except ValueError:
continue
role = row.get("role")
content = (row.get("message") or {}).get("content")
if role not in ("user", "assistant") or content is None:
continue # e.g. {"type": "turn_ended", "status": "success"}
blocks = content if isinstance(content, list) else [{"type": "text", "text": str(content)}]
if role == "user":
text, when = user_text(blocks)
else:
text, when = assistant_text(blocks), None
if not text:
continue
if turns and turns[-1]["role"] == role: # merge consecutive same-role rows
turns[-1]["text"] += "\n\n" + text
continue
turns.append({"role": role, "text": text, "when": when})
while turns and turns[0]["role"] != "user": # a session must start with the user
turns.pop(0)
return turns
# ---------- writing Claude Code sessions ----------
def iso(dt: datetime) -> str:
return dt.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
def build_session(chat: dict) -> list[dict]:
turns = read_turns(chat["path"])
if not turns:
return []
sid = stable_uuid(chat["path"])
base = {"isSidechain": False, "userType": "external", "cwd": chat["repo"], "sessionId": sid,
"version": "migrated-from-cursor", "gitBranch": "", "entrypoint": "cursor-migrated"}
clock = turns[0]["when"] or datetime.fromtimestamp(chat["mtime"], timezone.utc) - timedelta(seconds=len(turns))
rows: list[dict] = [{"type": "queue-operation", "operation": "enqueue", "timestamp": iso(clock), "sessionId": sid}]
parent = None
for i, t in enumerate(turns):
clock = max(clock + timedelta(seconds=1), t["when"] or clock)
mid = stable_uuid(f"{chat['path']}#{i}")
if t["role"] == "user":
message = {"role": "user", "content": t["text"]}
else:
message = {"role": "assistant", "type": "message", "model": "cursor-migrated",
"content": [{"type": "text", "text": t["text"]}], "stop_reason": "end_turn"}
rows.append({**base, "parentUuid": parent, "type": t["role"], "message": message,
"uuid": mid, "timestamp": iso(clock)})
parent = mid
first = next(t["text"] for t in turns if t["role"] == "user")
title = " ".join(first.split())[:70] or f"Cursor chat {chat['run'][:8]}"
rows.append({"type": "custom-title", "customTitle": f"[Cursor] {title}", "sessionId": sid})
rows.append({"type": "last-prompt", "lastPrompt": first[:200], "leafUuid": parent, "sessionId": sid})
return rows
def write_jsonl(dest: Path, rows: list[dict]) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
tmp = dest.with_suffix(".jsonl.tmp")
with tmp.open("w", encoding="utf-8") as fh:
for r in rows:
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
tmp.replace(dest) # atomic: Claude Code never sees a half-written file
# ---------- plans, rules, MCP ----------
def strip_front_matter(text: str) -> tuple[dict, str]:
if not text.startswith("---"):
return {}, text
end = text.find("\n---", 3)
if end == -1:
return {}, text
meta = {}
for line in text[3:end].splitlines():
if ":" in line:
k, v = line.split(":", 1)
meta[k.strip()] = v.strip().strip('"\'')
return meta, text[end + 4:].lstrip("\n")
def migrate_plans(claude_dir: Path, dry: bool, log=print) -> int:
n = 0
for p in sorted(CURSOR_PLANS.glob("*.plan.md")) if CURSOR_PLANS.exists() else []:
name = re.sub(r"_[0-9a-f]{8}$", "", p.name[: -len(".plan.md")]) + ".md"
dest = claude_dir / "plans" / name
log(f" plan {p.name} -> {short(dest)}")
if not dry:
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(strip_front_matter(p.read_text(encoding="utf-8"))[1], encoding="utf-8")
n += 1
return n
def migrate_rules(repo: Path, dry: bool, log=print) -> int:
""".cursor/rules/*.mdc -> .claude/rules/*.md (globs -> paths); .cursorrules -> CLAUDE.md import."""
n = 0
for src in sorted((repo / ".cursor/rules").rglob("*.mdc")) if (repo / ".cursor/rules").exists() else []:
meta, body = strip_front_matter(src.read_text(encoding="utf-8"))
rel = src.relative_to(repo / ".cursor/rules").with_suffix(".md")
dest = repo / ".claude/rules" / rel
globs = [g.strip() for g in meta.get("globs", "").strip("[]").split(",") if g.strip()]
always = meta.get("alwaysApply", "").lower() == "true"
head = ""
if globs and not always:
head = "---\npaths:\n" + "".join(f' - "{g.strip(chr(34))}"\n' for g in globs) + "---\n\n"
if meta.get("description"):
body = f"<!-- Cursor description: {meta['description']} -->\n\n{body}"
kind = "always" if always or not globs else "paths: " + ", ".join(globs)
log(f" rule {src.relative_to(repo)} -> {dest.relative_to(repo)} ({kind})")
if not dry:
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(head + body, encoding="utf-8")
n += 1
legacy = repo / ".cursorrules"
if legacy.is_file():
claude_md = repo / "CLAUDE.md"
line = "@.cursorrules"
has = claude_md.exists() and line in claude_md.read_text(encoding="utf-8")
log(f" rule .cursorrules -> import in CLAUDE.md{' (already there)' if has else ''}")
if not dry and not has:
prev = claude_md.read_text(encoding="utf-8") if claude_md.exists() else "# Project instructions\n"
claude_md.write_text(prev.rstrip() + f"\n\n## Rules carried over from Cursor\n{line}\n", encoding="utf-8")
n += 1
return n
def migrate_mcp(repo: Path, dry: bool, log=print) -> int:
""".cursor/mcp.json -> .mcp.json (same mcpServers shape; remote servers need an explicit type)."""
src = repo / ".cursor/mcp.json"
if not src.is_file():
return 0
servers = json.loads(src.read_text(encoding="utf-8")).get("mcpServers", {})
dest = repo / ".mcp.json"
merged = json.loads(dest.read_text(encoding="utf-8")) if dest.exists() else {"mcpServers": {}}
added = 0
for name, cfg in servers.items():
cfg = dict(cfg)
if "url" in cfg and "type" not in cfg:
cfg["type"] = "http" # Claude Code treats a url without type as a config error
if name in merged["mcpServers"]:
log(f" mcp {name}: already in .mcp.json, skipped")
continue
merged["mcpServers"][name] = cfg
log(f" mcp {name} -> .mcp.json ({cfg.get('type', 'stdio')})")
added += 1
if added and not dry:
dest.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8")
return added
# ---------- main ----------
def pending_chats(claude_dir: Path, project: Optional[str] = None) -> tuple[list[dict], list[dict]]:
"""All Cursor agent chats, and the ones that are new or changed since the last run."""
manifest = load_manifest(claude_dir)
chats = list_chats(claude_dir, project)
todo = [c for c in chats if not (c["dest"].exists() and manifest.get(c["path"], 0) >= c["mtime"])]
return chats, todo
def load_manifest(claude_dir: Path) -> dict:
path = claude_dir / ".cursor-migration-manifest.json"
try:
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
except ValueError:
return {}
def migrate_chats(claude_dir: Path, project: Optional[str] = None, dry: bool = False,
plans: bool = True, log=print) -> dict:
"""Convert new or changed Cursor chats (and plans) into Claude Code sessions."""
chats, todo = pending_chats(claude_dir, project)
log(f"Found {len(chats)} Cursor agent chat(s); {len(todo)} new or changed")
log(f"Target: {short(claude_dir / 'projects')}")
for c in todo:
where = short(c["repo"]) if c["repo_found"] else f"{short(c['repo'])} (repo folder not found, using home)"
log(f" chat {c['run'][:8]} {c['size'] / 1024:.1f} KB {where}")
result = {"found": len(chats), "migrated": 0, "unchanged": len(chats) - len(todo),
"empty": 0, "failed": 0, "plans": 0}
if dry:
if plans:
result["plans"] = migrate_plans(claude_dir, True, log)
log("Preview only: nothing written.")
return result
manifest = load_manifest(claude_dir)
for c in todo:
try:
rows = build_session(c)
if not rows:
result["empty"] += 1
continue
write_jsonl(c["dest"], rows)
manifest[c["path"]] = c["mtime"]
result["migrated"] += 1
except Exception as exc: # one bad file never stops the batch
result["failed"] += 1
log(f" fail {short(c['path'])}: {exc}")
path = claude_dir / ".cursor-migration-manifest.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
if plans:
result["plans"] = migrate_plans(claude_dir, False, log)
log(f"Done: {result['migrated']} migrated, {result['unchanged']} unchanged, "
f"{result['empty']} empty, {result['failed']} failed, {result['plans']} plan(s)")
return result
def default_claude_dir() -> Path:
return Path(os.environ.get("CLAUDE_CONFIG_DIR", HOME / ".claude")).expanduser()
def main() -> None:
ap = argparse.ArgumentParser(description="Migrate Cursor chats, plans, rules and MCP servers to Claude Code")
ap.add_argument("--project", type=Path, help="only migrate chats for this repo")
ap.add_argument("--rules", type=Path, metavar="REPO", help="convert .cursor/rules and .cursorrules in REPO")
ap.add_argument("--mcp", type=Path, metavar="REPO", help="copy .cursor/mcp.json servers into REPO/.mcp.json")
ap.add_argument("--claude-dir", type=Path, default=default_claude_dir(),
help="Claude Code config folder (default ~/.claude or $CLAUDE_CONFIG_DIR)")
ap.add_argument("--dry-run", action="store_true", help="show what would change, write nothing")
ap.add_argument("--yes", action="store_true", help="write without asking")
ap.add_argument("--no-plans", action="store_true")
a = ap.parse_args()
dry = a.dry_run
claude_dir = a.claude_dir.expanduser()
if a.rules or a.mcp:
if not dry and not a.yes and input("Write into the repo? [y/N] ").lower() != "y":
sys.exit("Cancelled.")
if a.rules:
print(f"Rules: {migrate_rules(a.rules.expanduser().resolve(), dry)} file(s)")
if a.mcp:
print(f"MCP: {migrate_mcp(a.mcp.expanduser().resolve(), dry)} server(s)")
return
project = str(a.project.expanduser().resolve()) if a.project else None
if not dry and not a.yes:
_, todo = pending_chats(claude_dir, project)
if input(f"Write {len(todo)} session(s) to {short(claude_dir)}? [y/N] ").lower() != "y":
sys.exit("Cancelled.")
migrate_chats(claude_dir, project, dry=dry, plans=not a.no_plans)
if not dry:
print("Next: cd into the repo, run `claude --resume`, and look for titles starting with [Cursor].")
if __name__ == "__main__":
main()What it does, in short:
- Stable IDs. Session and message IDs come from a hash of the source path, so a re-run overwrites the same file instead of creating duplicates.
- Manifest.
~/.claude/.cursor-migration-manifest.jsonrecords each source file’s modified time. Unchanged chats are skipped, so you can run it after every Cursor session during a transition. - Atomic writes. Each session is written to a temp file and renamed, so Claude Code never sees half a file.
- Correct folder. The repo path comes from Cursor’s
workspace.json. If the repo folder no longer exists, the script says so and uses your home folder as the session’s working directory. - Titles. Each session is titled
[Cursor] <first prompt>so you can spot it in the picker.
Run it, step by step
1. Dry run
python3 migrate_cursor_to_claude.py --dry-run
# just one repo
python3 migrate_cursor_to_claude.py --project ~/dev/my-app --dry-runYou get one line per chat with its size, repo and target folder, plus any plans. Nothing is written.
2. Migrate
python3 migrate_cursor_to_claude.py --yesOutput ends with a summary such as Done: 6 migrated, 0 unchanged, 0 empty, 0 failed, 2 plan(s). Running it again right away reports 0 new or changed.
3. Rules and MCP servers, per repo
python3 migrate_cursor_to_claude.py --rules ~/dev/my-app --mcp ~/dev/my-app --dry-run
python3 migrate_cursor_to_claude.py --rules ~/dev/my-app --mcp ~/dev/my-app --yes4. Try it somewhere safe first
python3 migrate_cursor_to_claude.py --yes --claude-dir /tmp/claude-test
find /tmp/claude-test/projects -name '*.jsonl' | head--claude-dir (or the CLAUDE_CONFIG_DIR environment variable) points the output anywhere, so you can inspect the files before touching your real ~/.claude.
Check the result in Claude Code
cd ~/dev/my-app
claude --resume # pick a session titled "[Cursor] ..."
# count migrated sessions for this repo
grep -l '"entrypoint": "cursor-migrated"' ~/.claude/projects/-Users-you-dev-my-app/*.jsonl | wc -lIn the VS Code or Cursor extension, open Session history at the top of the Claude Code panel and search for [Cursor]. If nothing shows, restart Claude Code and check the folder name has its leading dash.
A migrated session is a transcript, not a replay: Claude sees the prompts, replies and notes of what tools ran, but not file contents the Cursor agent read. Start your first message with what you want next, for example “Continue from here: the retry logic is in, now add tests.”
Move your Cursor rules
Cursor’s .mdc rules have three front-matter fields. Claude Code’s .claude/rules/ folder supports one, paths, which loads a rule only when Claude works on matching files. The script maps them like this:
| Cursor rule type | Front matter | Becomes in Claude Code |
|---|---|---|
| Always | alwaysApply: true | .claude/rules/<name>.md, loaded every session |
| Auto Attached | globs: src/**/*.tsx | .claude/rules/<name>.md with paths: list |
| Agent Requested | description: only | Loaded every session (description kept as a comment). Consider turning long ones into a skill. |
| Manual | none; you @-mention it | Loaded every session. Move rarely-needed ones out of .claude/rules and import them with @path when needed. |
Legacy .cursorrules | plain text at repo root | @.cursorrules import line in CLAUDE.md |
Before and after for an auto-attached rule:
<!-- .cursor/rules/frontend/react.mdc -->
---
description: React conventions
globs: src/**/*.tsx, src/**/*.ts
alwaysApply: false
---
- Function components only.
<!-- .claude/rules/frontend/react.md (generated) -->
---
paths:
- "src/**/*.tsx"
- "src/**/*.ts"
---
<!-- Cursor description: React conventions -->
- Function components only.Three tips once rules are in place:
- Run
/initin Claude Code. It reads the codebase and suggests aCLAUDE.mdwith build and test commands; if one exists it suggests improvements. - Keep each file under about 200 lines. Anthropic’s guidance is that longer instruction files reduce how well they are followed.
- Already use
AGENTS.md? Claude Code reads it when the repo has noCLAUDE.md. If you add aCLAUDE.md, import the other file with@AGENTS.mdso both tools share one source.
Move your MCP servers
Cursor’s .cursor/mcp.json and Claude Code’s .mcp.json use the same mcpServers shape, with one catch: Claude Code needs an explicit "type": "http" on remote servers (a url without a type is a configuration error). The script adds it.
{
"mcpServers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/",
"headers": { "Authorization": "Bearer ${GITHUB_TOKEN}" }
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "${DATABASE_URL}"]
}
}
}Claude Code expands ${VAR} and ${VAR:-default} in commands, args, env, URLs and headers, so keep secrets in environment variables rather than in the file. Pick the scope that matches who should get the server:
| Scope | Stored in | Who gets it |
|---|---|---|
local (default) | ~/.claude.json, under this project | Only you, this project |
project | .mcp.json at the repo root | Everyone who clones the repo (they approve it once) |
user | ~/.claude.json | Only you, every project |
# one server, without editing files
claude mcp add-json github '{"type":"http","url":"https://api.githubcopilot.com/mcp/"}' --scope project
claude mcp listGlobal Cursor servers in ~/.cursor/mcp.json move the same way with --scope user.
Replace .cursorignore with deny rules
Claude Code has no ignore file. Use permissions.deny in .claude/settings.json (shared) or .claude/settings.local.json (just you):
{
"permissions": {
"deny": [
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)"
]
}
}Deny rules apply as soon as the file exists, without waiting for workspace trust. Run /status to confirm the settings file loaded.
Cursor features and their Claude Code equivalents
| In Cursor | In Claude Code | Notes |
|---|---|---|
| Tab autocomplete | No equivalent | Claude Code is an agent, not an autocomplete engine. Keep Cursor or Copilot for Tab, or see our best AI for coding guide. |
| Agent chat | claude in the terminal, or the extension panel | Same idea; Claude runs commands and edits files with your approval |
| Plan mode | Plan mode | Switch permission modes with Shift+Tab; the extension opens plans as a document you can comment on |
| Checkpoints / restore | Checkpoints and /rewind | Rewind code, conversation, or both |
| @-mention files | @path/to/file | Option+K / Alt+K in the extension inserts a reference with line range |
| Rules | CLAUDE.md and .claude/rules/ | Converted by the script |
| Model picker | /model and /effort | Claude Fable 5.2, Opus 5.5, Sonnet 5.5, Haiku 5.5 |
| Background agents | Claude Code on the web (cloud sessions) | Runs on a fresh clone of your repo |
| Chat history | claude --resume / Session history | Your Cursor chats appear here after migration |
Switch fully, or run Claude Code inside Cursor?
You don’t have to choose. Google Trends shows the most common search next to “cursor to claude code” in the US is “claude code in cursor”: many developers keep Cursor as the editor and use Claude Code as the agent.
- Install the extension in Cursor: open Extensions (Cmd+Shift+X / Ctrl+Shift+X), search “Claude Code”, install. Anthropic also publishes it on the Open VSX Registry. Sign in with a paid Claude plan or a Console account.
- You get: side-by-side diffs with per-change accept or reject, @-mentions, plan review, checkpoints and rewind, and searchable session history, which includes your migrated Cursor chats.
- Or skip the extension: run
claudein Cursor’s built-in terminal.
A sensible transition: keep Cursor for Tab completion and quick inline edits, use Claude Code for multi-step agent work, and re-run the script weekly so new Cursor chats stay available in Claude Code.
Going the other way? Cursor 3 can import Claude Code conversations itself, and our guide to importing Claude Code chats into Cursor shows where that setting is, plus a script for Markdown exports.
Everything on the left is read-only; everything on the right is written by the script
What about older Composer chats?
Older Cursor builds stored Composer conversations as plain rows in state.vscdb: composerData:<id> for metadata and bubbleId:<id>:<bubble> for each message, in the cursorDiskKV table. On the Cursor build we tested in November 2026, that is no longer true: there were no bubbleId rows, Composer headers had moved to their own composerHeaders table, and conversation records carried a blobEncryptionKey.
So for current builds, the agent transcripts are the reliable source, and that is what the script migrates. If you have chats from an older build, open the Composer panel in Cursor, export the ones that matter to Markdown, put them in a docs/history/ folder, and reference them from Claude Code with @docs/history/<file>.md when you need them.
Safety, rollback and re-runs
- Cursor is never modified. The script opens Cursor files for reading only.
- No network. Nothing leaves your machine, and no tokens are read.
- Errors don’t stop the batch. A corrupt transcript is reported and skipped.
- Rules files are regenerated on each
--rulesrun, so edit the Cursor source until you switch fully, then edit.claude/rulesinstead.
To undo a migration for one repo, delete only the migrated sessions, not the whole folder (which also holds your native Claude Code sessions):
grep -l '"entrypoint": "cursor-migrated"' ~/.claude/projects/-Users-you-dev-my-app/*.jsonl | xargs rm
rm ~/.claude/.cursor-migration-manifest.json # forces a full re-migration next timeTroubleshooting
| Problem | Fix |
|---|---|
| “Found 0 Cursor agent chat(s)” | Check ~/.cursor/projects/*/agent-transcripts/ exists. Only agent runs are logged there; very old Composer chats are not. |
Sessions don’t appear in --resume | Run claude from the repo root, restart Claude Code, and check the project folder starts with a dash. |
| “repo folder not found, using home as cwd” | The repo moved or was deleted. Restore or re-clone it at the original path and re-run with --project. |
| Old chats vanish after a month | Raise cleanupPeriodDays in ~/.claude/settings.json. |
| Remote MCP server errors | Make sure the entry in .mcp.json has "type": "http" and that its environment variables are set; claude mcp list warns about unset ones. |
| A rule loads everywhere | It had no globs in Cursor. Add a paths: list to its .claude/rules file. |
Once you’re on Claude Code, our free Kompactor plugin trims the tokens it spends on noisy tool output, and our best AI for coding guide covers which Claude model to run for which task.
FAQ
Can I import my Cursor chat history into Claude Code?
Yes, for Cursor agent chats. They are stored as JSONL under ~/.cursor/projects/<slug>/agent-transcripts/. The script in this guide converts each one into a Claude Code session file under ~/.claude/projects/, and they appear in claude --resume with titles starting “[Cursor]”.
Does the migration change or delete anything in Cursor?
No. Cursor files are only read. You can keep using Cursor and re-run the script to pick up new chats; unchanged chats are skipped.
Will my .cursorrules and .cursor/rules work in Claude Code?
Not directly, but they convert cleanly. Rules with globs become .claude/rules files with a paths list, always-apply rules become plain .claude/rules files, and a legacy .cursorrules file is imported from CLAUDE.md with @.cursorrules.
How do I move MCP servers from Cursor to Claude Code?
Copy the mcpServers entries from .cursor/mcp.json into .mcp.json at the repo root (or use claude mcp add-json). Remote servers need "type": "http" in Claude Code.
Can I use Claude Code inside Cursor?
Yes. The Claude Code extension installs in Cursor from the Extensions view or the Open VSX Registry, or you can run claude in Cursor’s terminal. Many developers keep Cursor for Tab completion and use Claude Code for agent work.
Does Claude Code have tab completion like Cursor?
No. Claude Code is an agent that plans, edits files and runs commands; it does not offer inline Tab autocomplete. Keep Cursor, Copilot or another autocomplete tool alongside it.
Why are my migrated chats missing tool output?
Cursor’s transcripts log tool calls without their results, so the script keeps a short note of each call (for example the shell command) instead. Claude sees what the Cursor agent did, not the files it read.
Sources
Claude Code behaviour checked against Anthropic’s documentation and Claude Code 2.1.302 in November 2026. Cursor file layout observed on a current macOS install.
- Claude Code docs: How Claude remembers your project (CLAUDE.md, AGENTS.md, .claude/rules)
- Claude Code docs: Connect Claude Code to tools via MCP
- Claude Code docs: Settings files and precedence
- Claude Code docs: Use Claude Code in VS Code (and Cursor)
- Open VSX Registry: Claude Code extension
- Google Trends: “cursor to claude code”, United States, past 12 months
