How to Migrate from Cursor to Claude Code: Chat History, Rules, MCP Servers and Settings

By stackcone · Updated November 2026

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.

Cursor to Claude Code app showing 6 chats, 2 plans and 1 repo ready to migrate
1. It finds what to move
Cursor to Claude Code app after migrating, with the claude --resume next step
2. One click, done
Advanced settings: Claude Code folder, one project, extra repo, preview and log
3. Advanced settings and log

Installing.

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

CursorClaude CodeHow
Agent chats ~/.cursor/projects/<slug>/agent-transcripts/Sessions ~/.claude/projects/-<slug>/<id>.jsonlScript (below)
Plans ~/.cursor/plans/*.plan.md~/.claude/plans/*.mdScript
Project rules .cursor/rules/*.mdc.claude/rules/*.md (globs become paths:)Script, --rules
Legacy .cursorrulesImported from CLAUDE.md with @.cursorrulesScript, --rules
AGENTS.mdRead as-is when there is no CLAUDE.mdNothing to do
MCP servers .cursor/mcp.json.mcp.json (project) or claude mcp add-jsonScript, --mcp
.cursorignorepermissions.deny rules in .claude/settings.jsonBy hand (example below)
Composer chats in state.vscdbNot importable on current Cursor buildsSee Composer chats

Before you start

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

PathWhat it holdsMigrated?
~/.cursor/projects/<slug>/agent-transcripts/<run>/<run>.jsonlOne file per agent run: your prompts, the agent’s replies and its tool callsYes
~/.cursor/plans/*.plan.mdPlan-mode documentsYes
User/workspaceStorage/<hash>/workspace.jsonWhich folder each workspace wasRead to find each chat’s repo
User/globalStorage/state.vscdbSQLite: settings, Composer index and dataNo (see below)
~/.cursor/projects/<slug>/terminals, canvases, mcpsTerminal logs, canvases, MCP tool cachesNo

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:

  1. Chain the messages. Every message needs a parentUuid pointing at the one before it. Leaving them all null gives Claude Code a pile of disconnected messages.
  2. Don’t copy tool calls as tool calls. Cursor logs a tool_use with 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.
  3. Skip status lines and unwrap prompts. turn_ended rows 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:

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-run

You 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 --yes

Output 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 --yes

4. 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 -l

In 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 typeFront matterBecomes in Claude Code
AlwaysalwaysApply: true.claude/rules/<name>.md, loaded every session
Auto Attachedglobs: src/**/*.tsx.claude/rules/<name>.md with paths: list
Agent Requesteddescription: onlyLoaded every session (description kept as a comment). Consider turning long ones into a skill.
Manualnone; you @-mention itLoaded every session. Move rarely-needed ones out of .claude/rules and import them with @path when needed.
Legacy .cursorrulesplain 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:

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:

ScopeStored inWho gets it
local (default)~/.claude.json, under this projectOnly you, this project
project.mcp.json at the repo rootEveryone who clones the repo (they approve it once)
user~/.claude.jsonOnly 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 list

Global 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 CursorIn Claude CodeNotes
Tab autocompleteNo equivalentClaude Code is an agent, not an autocomplete engine. Keep Cursor or Copilot for Tab, or see our best AI for coding guide.
Agent chatclaude in the terminal, or the extension panelSame idea; Claude runs commands and edits files with your approval
Plan modePlan modeSwitch permission modes with Shift+Tab; the extension opens plans as a document you can comment on
Checkpoints / restoreCheckpoints and /rewindRewind code, conversation, or both
@-mention files@path/to/fileOption+K / Alt+K in the extension inserts a reference with line range
RulesCLAUDE.md and .claude/rules/Converted by the script
Model picker/model and /effortClaude Fable 5.2, Opus 5.5, Sonnet 5.5, Haiku 5.5
Background agentsClaude Code on the web (cloud sessions)Runs on a fresh clone of your repo
Chat historyclaude --resume / Session historyYour 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.

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.

flowchart LR classDef c fill:#e5e7eb,stroke:#374151,color:#111827 classDef a fill:#ffedd5,stroke:#ea580c,color:#7c2d12 classDef s fill:#ccfbf1,stroke:#0d9488,color:#115e59 T["agent-transcripts/*.jsonl"]:::c --> S["migrate_cursor_to_claude.py"]:::s P["~/.cursor/plans"]:::c --> S R[".cursor/rules + .cursorrules"]:::c --> S M[".cursor/mcp.json"]:::c --> S S --> CS["~/.claude/projects sessions\n(claude --resume)"]:::a S --> CP["~/.claude/plans"]:::a S --> CR[".claude/rules + CLAUDE.md"]:::a S --> CM[".mcp.json"]:::a

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

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 time

Troubleshooting

ProblemFix
“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 --resumeRun 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 monthRaise cleanupPeriodDays in ~/.claude/settings.json.
Remote MCP server errorsMake 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 everywhereIt 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.

Moving a whole team to Claude Code?

stackcone migrates engineering teams between AI coding tools: chat history, rules, MCP servers, permissions and CI, with a written handover so nobody loses context.