# Cursor MCP Not Loading? Fix It in 12 Steps, 60 Min

> Source: <https://shattered.io/cursor-mcp-not-loading-doctor-script-12-steps-2026/>
> Published: 2026-11-27 23:21:16+00:00

**Recommendation:** When a Cursor MCP server silently fails to load, run its mcp.json command outside the editor, send initialize then tools/list, and gate CI on the results to catch breakage from six-month protocol updates.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

A Cursor MCP server that fails to load rarely says why. The toggle stays grey, the tool list stays empty, and the agent behaves as if the server never existed. The protocol underneath keeps moving too. The Model Context Protocol project lists [2026-07-28 as its newest specification](http://blog.modelcontextprotocol.io/tags/specification/index.xml) and now ships on a six-month cadence, with 2027-03-30 as the next target, so a config that worked in the spring can break after a client or SDK update.

Plenty of developers meet this wall. Stack Overflow’s 2025 Developer Survey reported that 18% of developers used Cursor (see the [survey press release](https://stackoverflow.co/company/press/archive/stack-overflow-2025-developer-survey)). Almost everyone who wires a server into the editor ends up debugging it by hand. A guide on how to [set up Cursor MCP servers](https://shattered.io/set-up-cursor-mcp-servers-2026/) covers installation. What follows starts where that one stops: the server is configured and nothing works.

The tool at the center is `mcp-doctor`, one short Python file. It reads your `mcp.json`, launches each server the way the editor would, speaks JSON-RPC to it over stdio or HTTP, and prints a verdict per check with a fix hint. Twelve steps and about an hour get you a script, ten passing tests and a CI gate. Every output block below comes from a real run.

Don't miss new tech stories on Google

Add Shattered once in the Google app and our stories show up in your news suggestions.

[Add now](https://www.google.com/preferences/source?hl=en&q=https%3A%2F%2Fshattered.io%2F)

## Why a Cursor MCP Server Fails Without a Clear Error

The editor sits between you and the server, and it hides most of what goes wrong. When a stdio server crashes on import, you see a red dot. When it prints a banner to stdout, you see a spinner that never resolves. When an environment variable is missing, the server may start fine and then reject every call. Three different root causes produce nearly the same symptom, and none of them show up in the chat window.

The fastest way out is to reproduce the launch outside the editor. A stdio MCP server is just a child process that reads newline-delimited JSON-RPC from stdin and writes replies to stdout. Anything you can do by hand in a terminal, a script can do on every run and in CI. That is the idea behind the doctor: run the exact command from `mcp.json`, send an `initialize` request, ask for `tools/list`, and report what comes back.

The script checks the server, not the editor. It cannot see Cursor’s approval prompts, team policy or Privacy Mode, so a later section covers those by hand. For servers you write yourself, a walkthrough to [build a Cursor MCP server in Python](https://shattered.io/build-cursor-mcp-server-python-12-steps-2026/) produces one that should pass every check here on the first run.

Cursor’s own documentation says custom servers are configured through `mcp.json`, and that official plugins install in one click from the Marketplace. Plugin-installed servers still end up as processes and URLs, so the same layers apply. Cursor’s release notes reportedly describe a November 17 fix covering `${VAR}` placeholders in plugin server URL paths, clean restarts after a rotated authentication header, and MCP sign-in in remote windows. If your symptom matches one of those, update the editor before you debug anything else.

## Prerequisites and Versions for the Cursor MCP Doctor

Nothing here needs a paid plan or a cloud account. The script uses only the Python standard library, and pytest is the single dev dependency. Use the table to check your machine before you start.

| Component | Version used | Why it matters | 
|---|---|---|
| Python | A current Python release | The script uses modern type hints and `dataclasses` | 
| pytest | Any current release | Runs the ten-test suite in step 11 | 
| Cursor desktop | A current build | Older builds miss MCP fixes and may refuse to run | 
| Node.js | A current LTS, optional | Only needed when a server launches through `npx` | 
| MCP revision in `initialize` | 2025-11-25 by default | Overridable with `--protocol` | 
| Operating system | macOS, Linux or Windows | The `--gui-path` flag targets POSIX systems | 

On the editor side, Cursor reportedly requires version 3.12 or newer from November 22, and older builds stop working, according to its release notes. Update before you blame your config. You also need at least one server entry in `~/.cursor/mcp.json` (all projects) or `.cursor/mcp.json` (one project).

The default protocol string deserves a sentence. The MCP team’s Ruby SDK announcement says its server handles both lifecycle eras side by side, so current clients keep working while clients on 2026-07-28 use the stateless path. The doctor sends the classic `initialize` handshake because SDKs still answer it. If your SDK drops that path, pass `--protocol 2026-07-28` and adjust the probe. The same post marks Roots, Sampling and Logging as deprecated in the newest revision, which is one more reason to send your debug output to stderr instead of protocol logging.

For wider context on editors, agents and the tools around them, the [coding and developer tools section](https://shattered.io/category/software/) collects related how-tos.

## Five Layers Where a Cursor MCP Server Breaks

Every failure falls into one of five layers, and each layer has a different fix. Debugging goes faster when you know which layer you are in before you touch anything. The table maps each layer to the symptom you see in the editor and the doctor check that catches it.

| Layer | What breaks | What you see in Cursor | Doctor check | 
|---|---|---|---|
| 1. Config parse | Trailing comma, comment, missing `mcpServers` key | Server absent from the list or an error toast | `json` ,`schema` | 
| 2. Placeholder expansion | Unset `${env:NAME}` , typo in a variable | Server starts, then rejects calls with auth errors | `interpolation` | 
| 3. Process spawn | Command not found, space inside `command` , crash on import | Red dot, no tools | `command` ,`spawn` ,`handshake` | 
| 4. Protocol handshake | Banner on stdout, silent server, slow cold start | Endless spinner, then red | `handshake` ,`stdout-noise` ,`startup` | 
| 5. Tool surface | Zero tools, invalid schema, duplicate names | Green dot, but the agent never calls the tool | `tools` ,`tool-schema` ,`tool-name` | 

Layers one and two are pure configuration, so a script can check them in milliseconds without starting anything. Layer three needs a real process but no protocol knowledge. Layers four and five need the protocol, which is why the doctor speaks JSON-RPC itself instead of shelling out to a client.

A sixth layer sits above these: permissions. The editor can ask before running a tool, and a team administrator can block a server that works fine on your laptop. Reports in the release notes suggest enterprise connector access depends on the organization’s MCP policy, and a server that passes every check below can still be unavailable under that policy. Teams that need to go past debugging can [audit the MCP servers installed across their workspaces](https://shattered.io/audit-cursor-mcp-servers-allowlist-hooks-12-steps-2026/) and enforce an allowlist.

## Steps 1 and 2: Project Skeleton and a Fake MCP Server

**Step 1: create the project.** Make a folder, a virtual environment and the file layout. The `demo` directory holds a sample `.cursor/mcp.json` that you will break on purpose later.

```
mkdir -p mcp-doctor/fixtures mcp-doctor/tests mcp-doctor/demo/.cursor
cd mcp-doctor
python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install pytest

touch mcp_doctor.py fixtures/fake_server.py tests/test_doctor.py
```

**Step 2: write a fake server with failure modes.** Testing against a real server hides bugs, because a real server only fails in one way at a time and rarely on demand. The fixture below is a stdlib-only MCP server that changes behavior with a `MODE` environment variable: `good`, `noisy` (prints a banner to stdout), `crash` (exits with a stack trace on stderr), `slow` (sleeps before answering), `lint` (returns malformed tools) and `empty` (returns no tools). Save it as `fixtures/fake_server.py`.

``` python
import json
import os
import sys
import time

MODE = os.environ.get("MODE", "good")

if MODE == "noisy":
    print("Server starting on stdio...", flush=True)
if MODE == "crash":
    sys.stderr.write("Traceback (most recent call last):\n")
    sys.stderr.write("ModuleNotFoundError: No module named 'httpx'\n")
    sys.exit(1)
if MODE == "slow":
    time.sleep(float(os.environ.get("DELAY", "3")))

GOOD = [
    {"name": "echo", "description": "Echo text back",
     "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}},
    {"name": "word_count", "description": "Count words in a string",
     "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}}},
]
BAD = [
    {"name": "search the web", "description": "Search", "inputSchema": {"type": "string"}},
    {"name": "ok_tool", "inputSchema": {"type": "object"}},
]
EMPTY = []
TOOLS = {"lint": BAD, "empty": EMPTY}.get(MODE, GOOD)

for line in sys.stdin:
    msg = json.loads(line)
    if "id" not in msg:
        continue
    if msg["method"] == "initialize":
        result = {"protocolVersion": msg["params"]["protocolVersion"], "capabilities": {"tools": {}},
                  "serverInfo": {"name": "fake-server", "version": "0.0.1"}}
    elif msg["method"] == "tools/list":
        result = {"tools": TOOLS}
    else:
        result = {}
    print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": result}), flush=True)
```

The server reads one JSON object per line, ignores notifications (messages with no `id`), and answers `initialize` and `tools/list`. That is the whole surface the doctor touches. It echoes back whatever `protocolVersion` the client sent, which keeps the fixture valid when you test other protocol strings.

## Steps 3 and 4: Parse mcp.json Without Surprises

**Step 3: define a finding and expand placeholders.** Every check produces a `Finding` with a server name, a check name, a level (`ok`, `warn` or `fail`), a message and an optional hint. Plain data classes keep the report easy to print as text or JSON. The code blocks in steps 3 to 9 are consecutive pieces of one file, so append each to `mcp_doctor.py` in the order shown. The `expand` function resolves `${env:NAME}`, `${workspaceFolder}`, `${userHome}` and similar tokens, and returns the names it could not resolve. Cursor expands placeholders of this kind inside `mcp.json` fields, but confirm the exact token list against the docs for your build.

``` bash
#!/usr/bin/env python3
"""mcp-doctor: find out why a Cursor MCP server does not load."""
from __future__ import annotations

import argparse
import json
import os
import queue
import re
import shutil
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
from dataclasses import asdict, dataclass
from pathlib import Path

VERSION = "0.1.0"
DEFAULT_PROTOCOL = "2025-11-25"
GUI_PATH = "/usr/bin:/bin:/usr/sbin:/sbin"
TOOL_NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
INTERP_RE = re.compile(r"\$\{([^}]+)\}")

@dataclass
class Finding:
    server: str
    check: str
    level: str  # ok | warn | fail
    message: str
    hint: str = ""

def expand(value: str, ctx: dict) -> tuple[str, list[str]]:
    missing: list[str] = []

    def sub(match: re.Match) -> str:
        key = match.group(1)
        if key.startswith("env:"):
            name = key[4:]
            if name in os.environ:
                return os.environ[name]
            missing.append(name)
            return match.group(0)
        if key in ctx:
            return ctx[key]
        missing.append(key)
        return match.group(0)

    return INTERP_RE.sub(sub, value), missing
```

**Step 4: load the file and fail loudly.** The loader reads with `utf-8-sig` so a byte-order mark from a Windows editor does not look like a syntax error. It reports the line and column of a JSON error, which usually points straight at a trailing comma or a pasted comment. It also insists on a top-level `mcpServers` object, because a file with `servers` or `mcp_servers` at the top parses fine and loads nothing.

``` php
def load_servers(path: Path, out: list[Finding]) -> dict | None:
    label = str(path)
    try:
        text = path.read_text(encoding="utf-8-sig")
    except OSError as exc:
        out.append(Finding(label, "config", "fail", f"cannot read file: {exc}"))
        return None
    try:
        data = json.loads(text)
    except json.JSONDecodeError as exc:
        hint = "mcp.json is strict JSON: no trailing commas, no comments, double quotes only."
        out.append(Finding(label, "json", "fail",
                           f"invalid JSON at line {exc.lineno}, column {exc.colno}: {exc.msg}", hint))
        return None
    servers = data.get("mcpServers") if isinstance(data, dict) else None
    if not isinstance(servers, dict):
        out.append(Finding(label, "schema", "fail", "no top-level \"mcpServers\" object",
                           "Wrap your servers in {\"mcpServers\": {...}}."))
        return None
    out.append(Finding(label, "json", "ok", f"valid JSON, {len(servers)} server(s)"))
    return servers
```

A missing key is the quietest failure in this layer. JSON that parses correctly but uses the wrong top-level name gives the editor nothing to complain about. The doctor treats it as a hard failure and says exactly what to wrap.

## Steps 5 to 7: Probe a Stdio Server Like Cursor Does

### Step 5: A subprocess wrapper that never hangs

The riskiest part of any probe is waiting on a child process. A naive `readline()` blocks forever on a silent server, and a full stderr pipe can deadlock the child. The wrapper below starts two daemon threads, one per pipe. The stdout thread tries to parse each line as JSON and puts valid messages on a queue, and anything that fails to parse goes into a `noise` list. The stderr thread stores lines for later. `wait_for` pulls from the queue with a deadline, ignores server-initiated requests and notifications, and returns only the reply with the matching `id`.

``` python
class StdioProbe:
    def __init__(self, argv: list[str], env: dict, cwd: str):
        self.proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE, env=env, cwd=cwd, text=True, bufsize=1)
        self.messages: queue.Queue = queue.Queue()
        self.noise: list[str] = []
        self.stderr_lines: list[str] = []
        threading.Thread(target=self._read_stdout, daemon=True).start()
        threading.Thread(target=self._read_stderr, daemon=True).start()

    def _read_stdout(self) -> None:
        for line in self.proc.stdout:
            line = line.strip()
            if not line:
                continue
            try:
                self.messages.put(json.loads(line))
            except json.JSONDecodeError:
                self.noise.append(line)
        self.messages.put(None)

    def _read_stderr(self) -> None:
        for line in self.proc.stderr:
            self.stderr_lines.append(line.rstrip())

    def send(self, payload: dict) -> None:
        self.proc.stdin.write(json.dumps(payload) + "\n")
        self.proc.stdin.flush()

    def wait_for(self, request_id: int, timeout: float) -> dict | None:
        deadline = time.monotonic() + timeout
        while True:
            left = deadline - time.monotonic()
            if left <= 0:
                return None
            try:
                msg = self.messages.get(timeout=left)
            except queue.Empty:
                return None
            if msg is None:
                return None
            if isinstance(msg, dict) and msg.get("id") == request_id and "method" not in msg:
                return msg

    def close(self) -> None:
        try:
            self.proc.stdin.close()
        except OSError:
            pass
        try:
            self.proc.wait(timeout=2)
        except subprocess.TimeoutExpired:
            self.proc.kill()
```

The `noise` list is the heart of the stdout check. Cursor reads the same stream, and a single stray line before the first JSON message can stall or break the connection. Some clients tolerate a banner and others drop the session, so a server that works in one client can fail in another.

### Step 6: Lint the tool list

A green dot proves the handshake worked, not that the server is useful. The linter catches the problems that make an agent ignore a tool: names with spaces, duplicate names, a missing `inputSchema` or one that is not an object, and a blank description. The agent chooses tools by name and description, so an empty description is a real defect and not a style nit. The name pattern is a house rule, stricter than the protocol needs, which keeps names portable between clients. If you maintain servers across SDK generations, the same lint helps when [migrating an MCP server to SDK v2](https://shattered.io/migrate-mcp-server-sdk-v2-python-typescript-2026/), because tool metadata is where small breaking changes hide.

``` php
def lint_tools(name: str, tools: list) -> list[Finding]:
    out: list[Finding] = []
    seen: set[str] = set()
    for tool in tools:
        tname = tool.get("name", "") if isinstance(tool, dict) else ""
        if not TOOL_NAME_RE.match(tname):
            out.append(Finding(name, "tool-name", "warn", f"tool name {tname!r} breaks the house rule",
                               "Use 1-64 characters from A-Z a-z 0-9 _ . -"))
        if tname in seen:
            out.append(Finding(name, "tool-name", "fail", f"duplicate tool name {tname!r}"))
        seen.add(tname)
        schema = tool.get("inputSchema") if isinstance(tool, dict) else None
        if not isinstance(schema, dict) or schema.get("type") != "object":
            out.append(Finding(name, "tool-schema", "fail", f"tool {tname!r} has no object inputSchema",
                               "inputSchema must be a JSON Schema with \"type\": \"object\"."))
        if not (isinstance(tool, dict) and tool.get("description")):
            out.append(Finding(name, "tool-desc", "warn", f"tool {tname!r} has no description",
                               "The agent picks tools by description. Write one."))
    return out
```

### Step 7: Run the handshake

This function is the center of the doctor. It expands placeholders, resolves the command with `shutil.which` against either your real `PATH` or the minimal GUI path, starts the process, and sends `initialize`. If no reply arrives, it distinguishes two cases: the process exited (and reports the exit code plus the last three stderr lines) or it stayed alive and silent (and reports the timeout). After a good reply it sends the `notifications/initialized` message, requests `tools/list`, runs the linter, and reports any stdout noise.

``` php
def probe_stdio(name: str, entry: dict, ctx: dict, args: argparse.Namespace) -> list[Finding]:
    out: list[Finding] = []
    command, missing = expand(str(entry["command"]), ctx)
    argv_tail = []
    for item in entry.get("args", []):
        value, miss = expand(str(item), ctx)
        argv_tail.append(value)
        missing += miss
    env = os.environ.copy()
    if args.gui_path:
        env["PATH"] = GUI_PATH
    for key, raw in (entry.get("env") or {}).items():
        value, miss = expand(str(raw), ctx)
        env[key] = value
        missing += miss
    if missing:
        out.append(Finding(name, "interpolation", "fail", "unresolved placeholders: " + ", ".join(sorted(set(missing))),
                           "Export the variable before launching Cursor, or use ${env:NAME} with a value that exists."))
        return out

    resolved = shutil.which(command, path=env.get("PATH"))
    if not resolved:
        where = "the GUI-style PATH" if args.gui_path else "PATH"
        out.append(Finding(name, "command", "fail", f"{command!r} not found on {where}",
                           "Use an absolute path in \"command\", or fix the PATH Cursor inherits."))
        return out
    out.append(Finding(name, "command", "ok", f"{command} -> {resolved}"))

    started = time.monotonic()
    try:
        probe = StdioProbe([resolved, *argv_tail], env, ctx["workspaceFolder"])
    except OSError as exc:
        out.append(Finding(name, "spawn", "fail", f"cannot start process: {exc}"))
        return out

    try:
        probe.send({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
            "protocolVersion": args.protocol, "capabilities": {},
            "clientInfo": {"name": "mcp-doctor", "version": VERSION}}})
        reply = probe.wait_for(1, args.timeout)
        elapsed = time.monotonic() - started

        if reply is None:
            code = probe.proc.poll()
            tail = " | ".join(probe.stderr_lines[-3:]) or "no stderr output"
            if code is not None:
                out.append(Finding(name, "handshake", "fail", f"process exited with code {code} before answering",
                                   f"stderr: {tail}"))
            else:
                out.append(Finding(name, "handshake", "fail", f"no initialize reply within {args.timeout:.0f}s",
                                   f"stderr: {tail}"))
            if probe.noise:
                out.append(Finding(name, "stdout-noise", "fail",
                                   f"{len(probe.noise)} non-JSON line(s) on stdout, first: {probe.noise[0][:70]!r}",
                                   "Send logs to stderr. Anything on stdout that is not JSON-RPC corrupts the stream."))
            return out

        if "error" in reply:
            out.append(Finding(name, "handshake", "fail", f"initialize rejected: {reply['error']}"))
            return out
        result = reply.get("result", {})
        info = result.get("serverInfo", {})
        out.append(Finding(name, "handshake", "ok",
                           f"initialized in {elapsed * 1000:.0f} ms, protocol {result.get('protocolVersion')}, "
                           f"server {info.get('name', '?')} {info.get('version', '')}".strip()))
        if elapsed > args.slow:
            out.append(Finding(name, "startup", "warn", f"slow start ({elapsed:.1f}s, limit {args.slow:.0f}s)",
                               "Pre-install the package instead of fetching it on every launch."))

        probe.send({"jsonrpc": "2.0", "method": "notifications/initialized"})
        probe.send({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
        listing = probe.wait_for(2, args.timeout)
        if listing is None or "result" not in listing:
            out.append(Finding(name, "tools", "fail", "tools/list returned nothing usable"))
        else:
            tools = listing["result"].get("tools", [])
            level = "ok" if tools else "warn"
            names = ", ".join(t.get("name", "?") for t in tools[:6])
            out.append(Finding(name, "tools", level, f"{len(tools)} tool(s): {names}" if tools else "0 tools exposed",
                               "" if tools else "A server with no tools shows green in the UI but gives the agent nothing."))
            out += lint_tools(name, tools)

        if probe.noise:
            out.append(Finding(name, "stdout-noise", "fail",
                               f"{len(probe.noise)} non-JSON line(s) on stdout, first: {probe.noise[0][:70]!r}",
                               "Send logs to stderr. Some clients tolerate this, others drop the connection."))
        else:
            out.append(Finding(name, "stdout-noise", "ok", "stdout carried only JSON-RPC"))
    finally:
        probe.close()
    return out
```

The `finally` block closes stdin and kills the process if it ignores the hint, so a failing probe never leaves orphans behind. That matters in CI, where leaked children can hold a job open until the runner times out.

## Step 8: Probe Remote Servers and Auth Errors

Remote servers use a URL instead of a command, and their failures look different. There is no process to crash. Instead you meet DNS errors, certificate problems, redirects, and a wall of 401 and 404 responses. The probe sends the same `initialize` request as an HTTP POST with the `Accept` header that streamable endpoints expect, accepts either a plain JSON body or the first `data:` line of an event stream, and maps status codes to hints.

``` php
def probe_http(name: str, entry: dict, ctx: dict, args: argparse.Namespace) -> list[Finding]:
    out: list[Finding] = []
    url, missing = expand(str(entry["url"]), ctx)
    headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
    for key, raw in (entry.get("headers") or {}).items():
        value, miss = expand(str(raw), ctx)
        headers[key] = value
        missing += miss
    if missing:
        out.append(Finding(name, "interpolation", "fail", "unresolved placeholders: " + ", ".join(sorted(set(missing))),
                           "Export the variable before launching Cursor."))
        return out
    body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
        "protocolVersion": args.protocol, "capabilities": {},
        "clientInfo": {"name": "mcp-doctor", "version": VERSION}}}).encode()
    request = urllib.request.Request(url, data=body, headers=headers, method="POST")
    started = time.monotonic()
    try:
        with urllib.request.urlopen(request, timeout=args.timeout) as resp:
            raw = resp.read(65536).decode("utf-8", "replace")
            ctype = resp.headers.get("Content-Type", "")
            ms = (time.monotonic() - started) * 1000
            if "text/event-stream" in ctype:
                raw = next((ln[5:].strip() for ln in raw.splitlines() if ln.startswith("data:")), "")
            payload = json.loads(raw) if raw else {}
            if "result" in payload:
                out.append(Finding(name, "handshake", "ok", f"HTTP {resp.status} in {ms:.0f} ms, initialize answered"))
            else:
                out.append(Finding(name, "handshake", "fail", f"HTTP {resp.status} but no JSON-RPC result",
                                   "The URL answers, but it is not an MCP endpoint."))
    except urllib.error.HTTPError as exc:
        hints = {401: "The server wants credentials. Add an Authorization header or complete OAuth in Cursor.",
                 403: "Credentials were sent but refused. Check scopes and the token's owner.",
                 404: "Wrong path. Many servers expose /mcp, not the site root.",
                 405: "The path exists but rejects POST. This may be a legacy SSE-only endpoint."}
        out.append(Finding(name, "handshake", "fail", f"HTTP {exc.code} from {url}", hints.get(exc.code, "")))
    except urllib.error.URLError as exc:
        out.append(Finding(name, "handshake", "fail", f"cannot reach {url}: {exc.reason}",
                           "Check DNS, TLS certificates, VPN and proxy settings."))
    except (json.JSONDecodeError, TimeoutError, OSError) as exc:
        out.append(Finding(name, "handshake", "fail", f"bad response: {exc}"))
    return out
```

The status codes carry most of the diagnosis. A 401 means the server wants credentials, so add an `Authorization` header or finish the OAuth flow in the editor. A 403 means credentials arrived and were refused, which points at scopes or the token’s owner. A 404 almost always means the path is wrong, because many servers expose `/mcp` and not the site root. A 405 can mean you hit a legacy endpoint that only speaks server-sent events. Header values go through the same placeholder expansion as stdio fields, so `${env:API_TOKEN}` works in `headers` and a missing variable is reported before any request leaves your machine.

When you build the server side, follow the hardening advice in a guide to a [secure MCP server](https://shattered.io/build-secure-mcp-server-claude-2026/). Authentication mistakes that the doctor reports as a 401 are cheap to fix, while the ones it cannot see, like an over-broad token, are expensive.

## Step 9: Wire the Command Line

The last block of the file ties everything together. `check_entry` validates the entry shape (exactly one of `command` or `url`, an array for `args`, no spaces inside `command`) and routes to the right probe. `render` prints one line per finding with an indented hint for anything that is not green. `main` discovers both config files, runs every server and returns exit code 1 if any check failed, which is what lets CI block a bad config.

``` php
def check_entry(name: str, entry, ctx: dict, args: argparse.Namespace) -> list[Finding]:
    if not isinstance(entry, dict):
        return [Finding(name, "schema", "fail", "server entry is not an object")]
    has_cmd, has_url = "command" in entry, "url" in entry
    if has_cmd and has_url:
        return [Finding(name, "schema", "fail", "entry has both \"command\" and \"url\"",
                        "Pick one transport: stdio (command) or remote (url).")]
    if not has_cmd and not has_url:
        return [Finding(name, "schema", "fail", "entry has neither \"command\" nor \"url\"")]
    if has_cmd:
        if not isinstance(entry.get("args", []), list):
            return [Finding(name, "schema", "fail", "\"args\" must be an array of strings",
                            "Split \"npx -y pkg\" into command \"npx\" and args [\"-y\", \"pkg\"].")]
        if " " in str(entry["command"]).strip():
            return [Finding(name, "schema", "fail", f"command {entry['command']!r} contains a space",
                            "Put only the executable in \"command\"; move the rest into \"args\".")]
        return probe_stdio(name, entry, ctx, args)
    return probe_http(name, entry, ctx, args)

def render(findings: list[Finding]) -> str:
    tags = {"ok": "[ ok ]", "warn": "[warn]", "fail": "[FAIL]"}
    lines = []
    for f in findings:
        lines.append(f"{tags[f.level]} {f.server:<14} {f.check:<14} {f.message}")
        if f.hint and f.level != "ok":
            lines.append(f"       {'':<14} {'':<14} -> {f.hint}")
    return "\n".join(lines)

def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(prog="mcp-doctor", description=__doc__)
    ap.add_argument("--project", default=".", help="project root (default: current directory)")
    ap.add_argument("--config", action="append", help="explicit mcp.json path (repeatable)")
    ap.add_argument("--only", help="check a single server by name")
    ap.add_argument("--timeout", type=float, default=10.0, help="seconds to wait for each reply")
    ap.add_argument("--slow", type=float, default=5.0, help="warn when startup exceeds this many seconds")
    ap.add_argument("--protocol", default=DEFAULT_PROTOCOL, help="protocolVersion sent in initialize")
    ap.add_argument("--gui-path", action="store_true", help="resolve commands with a minimal GUI-style PATH")
    ap.add_argument("--json", action="store_true", help="print findings as JSON")
    args = ap.parse_args(argv)

    project = Path(args.project).resolve()
    ctx = {"userHome": str(Path.home()), "workspaceFolder": str(project),
           "workspaceFolderBasename": project.name, "pathSeparator": os.sep}
    paths = [Path(p) for p in args.config] if args.config else [
        Path.home() / ".cursor" / "mcp.json", project / ".cursor" / "mcp.json"]

    findings: list[Finding] = []
    found_any = False
    for path in paths:
        if not path.exists():
            continue
        found_any = True
        servers = load_servers(path, findings)
        for name, entry in (servers or {}).items():
            if args.only and name != args.only:
                continue
            findings += check_entry(name, entry, ctx, args)
    if not found_any:
        findings.append(Finding("-", "config", "fail", "no mcp.json found in: " + ", ".join(map(str, paths)),
                                "Create .cursor/mcp.json in the project or ~/.cursor/mcp.json for all projects."))

    if args.json:
        print(json.dumps([asdict(f) for f in findings], indent=2))
    else:
        print(f"mcp-doctor {VERSION}  project={project}")
        print(render(findings))
        fails = sum(f.level == "fail" for f in findings)
        warns = sum(f.level == "warn" for f in findings)
        print(f"\nsummary: {len(findings)} checks, {fails} fail, {warns} warn")
    return 1 if any(f.level == "fail" for f in findings) else 0

if __name__ == "__main__":
    sys.exit(main())
```

The flags are small but each one answers a real question. Use the table as a reference.

| Flag | Default | Use it to | 
|---|---|---|
| `--project` | Current directory | Point at another repo and resolve `${workspaceFolder}` against it | 
| `--config` | Both Cursor files | Check a single file, repeatable, handy in CI | 
| `--only NAME` | All servers | Probe one server while you iterate on a fix | 
| `--timeout` | 10 seconds | Wait longer for slow cold starts or shorter in tests | 
| `--slow` | 5 seconds | Warn when startup passes this limit | 
| `--protocol` | 2025-11-25 | Send another `protocolVersion` in`initialize` | 
| `--gui-path` | Off | Resolve commands with a minimal PATH, the way a Dock-launched app sees it | 
| `--json` | Off | Print findings as JSON for CI and diffing | 

## Step 10: Run the Doctor on Seven Broken Servers

Time to see it work. The demo config holds seven servers, each broken in a different way except the first. Save it as `demo/.cursor/mcp.json`.

```
{
  "mcpServers": {
    "healthy": {
      "command": "python3",
      "args": ["${workspaceFolder}/../fixtures/fake_server.py"]
    },
    "chatty": {
      "command": "python3",
      "args": ["${workspaceFolder}/../fixtures/fake_server.py"],
      "env": {"MODE": "noisy"}
    },
    "crashy": {
      "command": "python3",
      "args": ["${workspaceFolder}/../fixtures/fake_server.py"],
      "env": {"MODE": "crash"}
    },
    "spacey": {
      "command": "npx -y @example/server"
    },
    "missing-bin": {
      "command": "definitely-not-installed",
      "args": ["--stdio"]
    },
    "needs-token": {
      "command": "python3",
      "args": ["${workspaceFolder}/../fixtures/fake_server.py"],
      "env": {"API_TOKEN": "${env:DOCTOR_DEMO_TOKEN}"}
    },
    "lint-me": {
      "command": "python3",
      "args": ["${workspaceFolder}/../fixtures/fake_server.py"],
      "env": {"MODE": "lint"}
    }
  }
}
```

Run the doctor against it. The `${workspaceFolder}` token resolves to the `demo` directory, which is why the fixture path starts with `..`.

```
python3 mcp_doctor.py --project demo --config demo/.cursor/mcp.json; echo "exit=$?"
```

Expect the following output. Timings on your machine will differ by a few milliseconds.

```
mcp-doctor 0.1.0  project=/tmp/sh-mirror-work-AwDMzJ/mcp-doctor/demo
[ ok ] demo/.cursor/mcp.json json           valid JSON, 7 server(s)
[ ok ] healthy        command        python3 -> /usr/bin/python3
[ ok ] healthy        handshake      initialized in 24 ms, protocol 2025-11-25, server fake-server 0.0.1
[ ok ] healthy        tools          2 tool(s): echo, word_count
[ ok ] healthy        stdout-noise   stdout carried only JSON-RPC
[ ok ] chatty         command        python3 -> /usr/bin/python3
[ ok ] chatty         handshake      initialized in 23 ms, protocol 2025-11-25, server fake-server 0.0.1
[ ok ] chatty         tools          2 tool(s): echo, word_count
[FAIL] chatty         stdout-noise   1 non-JSON line(s) on stdout, first: 'Server starting on stdio...'
                                     -> Send logs to stderr. Some clients tolerate this, others drop the connection.
[ ok ] crashy         command        python3 -> /usr/bin/python3
[FAIL] crashy         handshake      process exited with code 1 before answering
                                     -> stderr: Traceback (most recent call last): | ModuleNotFoundError: No module named 'httpx'
[FAIL] spacey         schema         command 'npx -y @example/server' contains a space
                                     -> Put only the executable in "command"; move the rest into "args".
[FAIL] missing-bin    command        'definitely-not-installed' not found on PATH
                                     -> Use an absolute path in "command", or fix the PATH Cursor inherits.
[FAIL] needs-token    interpolation  unresolved placeholders: DOCTOR_DEMO_TOKEN
                                     -> Export the variable before launching Cursor, or use ${env:NAME} with a value that exists.
[ ok ] lint-me        command        python3 -> /usr/bin/python3
[ ok ] lint-me        handshake      initialized in 24 ms, protocol 2025-11-25, server fake-server 0.0.1
[ ok ] lint-me        tools          2 tool(s): search the web, ok_tool
[warn] lint-me        tool-name      tool name 'search the web' breaks the house rule
                                     -> Use 1-64 characters from A-Z a-z 0-9 _ . -
[FAIL] lint-me        tool-schema    tool 'search the web' has no object inputSchema
                                     -> inputSchema must be a JSON Schema with "type": "object".
[warn] lint-me        tool-desc      tool 'ok_tool' has no description
                                     -> The agent picks tools by description. Write one.
[ ok ] lint-me        stdout-noise   stdout carried only JSON-RPC

summary: 21 checks, 6 fail, 2 warn
exit=1
```

Read the report from the bottom of each server’s block up. The `healthy` server is green on every check. The `chatty` server completes the handshake and exposes two tools, yet it fails the noise check, which is the classic server that works in one client and stalls in another. The `crashy` server never answers, and the hint carries the last stderr lines, which here name the missing `httpx` module. That one line replaces ten minutes of staring at a red dot.

The remaining three show the configuration layer. A command with a space inside it is the most common copy-paste error, because documentation often shows a shell one-liner and the config needs it split. A missing binary is reported against `PATH`. An unset variable stops the run before anything starts, so no half-configured process touches your real services.

Now test the PATH problem for real. Create a stub executable in a folder that is on your shell path, then compare the two modes.

```
mkdir -p demo/bin && printf '#!/bin/sh\necho stub\n' > demo/bin/mytool && chmod +x demo/bin/mytool
cat > demo/gui.json <<'EOF'
{"mcpServers": {"tooling": {"command": "mytool", "args": ["--stdio"]}}}
EOF

# shell PATH: the command resolves
PATH="$PWD/demo/bin:$PATH" python3 mcp_doctor.py --project demo --config demo/gui.json --only tooling --timeout 2

# GUI PATH: the same command disappears
PATH="$PWD/demo/bin:$PATH" python3 mcp_doctor.py --project demo --config demo/gui.json --only tooling --gui-path
php
--- shell PATH
[ ok ] tooling        command        mytool -> /tmp/sh-mirror-work-AwDMzJ/mcp-doctor/demo/bin/mytool
[FAIL] tooling        handshake      process exited with code 0 before answering
[FAIL] tooling        stdout-noise   1 non-JSON line(s) on stdout, first: 'stub'

--- GUI PATH
[FAIL] tooling        command        'mytool' not found on the GUI-style PATH
                                     -> Use an absolute path in "command", or fix the PATH Cursor inherits.
```

The shell run resolves the command and then fails the handshake, because the stub is not an MCP server. The GUI run never gets that far. Apps launched from a dock or launcher commonly inherit a short system PATH instead of the one your shell profile builds, so a tool installed through a version manager can be invisible to the editor even though it works in your terminal. When `--gui-path` fails and the normal run passes, the fix is an absolute path in `command`.

## Steps 11 and 12: Test the Doctor and Gate It in CI

**Step 11: write the tests.** The suite runs each fixture mode through the real `check_entry` and asserts on the check levels. It also starts a throwaway HTTP server on a random local port to exercise the 200, 401 and 404 paths without touching the network. Save this as `tests/test_doctor.py`.

``` python
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import mcp_doctor as md  # noqa: E402

FAKE = str(Path(__file__).resolve().parent.parent / "fixtures" / "fake_server.py")

def run(tmp_path, servers, *extra):
    cfg = tmp_path / "mcp.json"
    cfg.write_text(json.dumps({"mcpServers": servers}))
    findings = []
    args = md.argparse.Namespace(timeout=3.0, slow=5.0, protocol=md.DEFAULT_PROTOCOL, gui_path=False)
    ctx = {"userHome": "/home/x", "workspaceFolder": str(tmp_path), "workspaceFolderBasename": "p", "pathSeparator": "/"}
    for name, entry in servers.items():
        findings += md.check_entry(name, entry, ctx, args)
    return findings

def levels(findings, check):
    return [f.level for f in findings if f.check == check]

def entry(mode="good", **env):
    return {"command": sys.executable, "args": [FAKE], "env": {"MODE": mode, **env}}

def test_healthy_server_passes(tmp_path):
    f = run(tmp_path, {"ok": entry()})
    assert levels(f, "handshake") == ["ok"]
    assert levels(f, "tools") == ["ok"]
    assert levels(f, "stdout-noise") == ["ok"]

def test_stdout_noise_detected(tmp_path):
    f = run(tmp_path, {"ok": entry("noisy")})
    assert levels(f, "stdout-noise") == ["fail"]

def test_crash_reports_stderr(tmp_path):
    f = run(tmp_path, {"ok": entry("crash")})
    assert levels(f, "handshake") == ["fail"]
    assert "httpx" in [x for x in f if x.check == "handshake"][0].hint

def test_slow_server_times_out(tmp_path):
    args = md.argparse.Namespace(timeout=1.0, slow=5.0, protocol=md.DEFAULT_PROTOCOL, gui_path=False)
    ctx = {"userHome": "/", "workspaceFolder": str(tmp_path), "workspaceFolderBasename": "p", "pathSeparator": "/"}
    f = md.check_entry("slow", entry("slow", DELAY="4"), ctx, args)
    assert levels(f, "handshake") == ["fail"]

def test_command_with_space_rejected(tmp_path):
    f = run(tmp_path, {"bad": {"command": "npx -y pkg"}})
    assert levels(f, "schema") == ["fail"]

def test_missing_env_placeholder(tmp_path):
    f = run(tmp_path, {"bad": {"command": sys.executable, "env": {"K": "${env:NOPE_NOT_SET_123}"}}})
    assert levels(f, "interpolation") == ["fail"]

def test_tool_lint(tmp_path):
    f = run(tmp_path, {"x": entry("lint")})
    assert "fail" in levels(f, "tool-schema")
    assert "warn" in levels(f, "tool-name")

def test_empty_tools_warn(tmp_path):
    f = run(tmp_path, {"x": entry("empty")})
    assert levels(f, "tools") == ["warn"]

def test_trailing_comma_in_config(tmp_path):
    cfg = tmp_path / "mcp.json"
    cfg.write_text('{"mcpServers": {"a": {"command": "x",}}}')
    out = []
    assert md.load_servers(cfg, out) is None
    assert out[0].level == "fail" and "line 1" in out[0].message

class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path == "/mcp":
            if self.headers.get("Authorization") != "Bearer good":
                self.send_response(401)
                self.end_headers()
                return
            body = json.dumps({"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": md.DEFAULT_PROTOCOL}}).encode()
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.end_headers()

    def log_message(self, *a):
        pass

def test_http_auth_paths(tmp_path):
    srv = HTTPServer(("127.0.0.1", 0), Handler)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    base = f"http://127.0.0.1:{srv.server_port}"
    try:
        ok = run(tmp_path, {"r": {"url": base + "/mcp", "headers": {"Authorization": "Bearer good"}}})
        no_auth = run(tmp_path, {"r": {"url": base + "/mcp"}})
        wrong_path = run(tmp_path, {"r": {"url": base + "/", "headers": {"Authorization": "Bearer good"}}})
    finally:
        srv.shutdown()
    assert levels(ok, "handshake") == ["ok"]
    assert "401" in no_auth[0].message
    assert "404" in wrong_path[0].message
bash
$ python3 -m pytest -q tests
..........                                                               [100%]
10 passed in 3.74s
```

Ten tests in under four seconds is fast enough to run on every commit. The slow-server test is the longest, since it waits out a one-second timeout against a four-second sleep.

**Step 12: run it in CI and on edit.** Commit the project’s `.cursor/mcp.json` and let the pipeline check it. Servers that need secrets will fail the interpolation check in CI, which is the right result, so either inject dummy values or probe only the servers that run without credentials with `--only`. The JSON mode makes the output easy to archive. If you also run the [Cursor CLI](https://shattered.io/cursor-cli-local-setup-permissions-sandbox-12-steps-2026/) in pipelines, run the doctor first so a broken server config fails fast instead of surfacing as a confusing agent error.

```
name: mcp-doctor
on:
  pull_request:
    paths: [".cursor/mcp.json", "mcp-doctor/**"]
jobs:
  doctor:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install pytest
      - run: python3 -m pytest -q mcp-doctor/tests
      - run: python3 mcp-doctor/mcp_doctor.py --project . --config .cursor/mcp.json --json > doctor.json
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: doctor-report
          path: doctor.json
```

Pin the action versions to whatever your organization approves. The workflow triggers only when the MCP config or the doctor itself changes, so it adds no cost to unrelated pull requests. For local use, a short script run by [Cursor hooks](https://shattered.io/cursor-hooks-tutorial-guard-agent-12-steps-2026/) after the agent edits `.cursor/mcp.json` catches a broken config seconds after the agent writes it.

## Cross-Checking With the Editor: Logs, Toggles and Approvals

The doctor proves the server works from a clean process. If the editor still shows a problem, the cause lives in the editor’s state. Work through these checks in order, because each one rules out a different layer.

1. **Open the MCP settings.** In Cursor Settings, find the Tools & MCP page (older builds label it MCP). Confirm the server is listed, enabled and not showing an error badge.
2. **Toggle it off and on.** A restart forces the editor to re-read`mcp.json` and respawn the process. Cursor’s release notes reportedly describe a fix so that changed servers restart cleanly after configuration changes, but a manual toggle is still the cheapest test.
3. **Read the MCP log.** Open the Output panel and choose the MCP entry in the channel dropdown. Compare its first error with the doctor’s report. If the log shows a spawn error that the doctor did not, your PATH differs between the two environments.
4. **Check approvals.** The agent can ask permission before it runs a tool. A tool that never fires may be waiting for a click you scrolled past, or auto-run settings may block it.
5. **Check team policy.** On Teams and Enterprise plans an administrator can restrict which servers run, and the release notes reportedly allow up to 1,000 configured servers per team or member. A server rejected by policy fails the same way as a broken one.
6. **Check model access.** Team model controls decide which models run, and Cursor’s release notes say Auto now follows team model settings. A blocked model can look like a broken tool-calling setup, so pick a model your team allows before you blame the server.

Cloud agents add one more wrinkle. They run in a remote environment, so a server that depends on your laptop’s PATH, a localhost port or a local file cannot work there no matter how green the doctor is. If a server works in the desktop editor and fails in a cloud run, read the guide to [building Cursor cloud agents](https://shattered.io/build-cursor-cloud-agents-2026/) and move the server to a URL the remote environment can reach.

## Common Pitfalls That Waste an Afternoon

- **Logging to stdout.** A`print()` call or a framework banner corrupts the JSON-RPC stream. Send every log line to stderr, and set the logger up before the first request, not after.
- **Putting the whole command line in `command`.** The field takes an executable only. Split` npx -y package` into`npx` and`["-y", "package"]` .
- **Trusting your shell PATH.** The editor may not inherit it. Use absolute paths for anything installed through nvm, pyenv, asdf or Homebrew, and verify with`--gui-path` .
- **Hard-coding secrets in `mcp.json`.** The file often gets committed. Reference`${env:NAME}` and export the variable in the profile that launches the editor.
- **Forgetting the editor reads config at launch or on toggle.** Edit, save, then toggle the server. Otherwise you test the old config for twenty minutes.
- **Slow cold starts through `npx`.** Fetching a package on every launch can exceed the editor’s patience on a bad network. Install the package once and point`command` at the local binary.
- **Exposing too many tools.** Every tool definition costs input tokens on every request, and a crowded tool list makes the model pick worse. Ship fewer, sharper tools with clear descriptions.

## Troubleshooting: 10 Symptoms and Fixes

Match your symptom to a line below, then run the doctor with `--only` to confirm the fix.

1. **The server is missing from the list.** The file is not valid JSON, or the top-level key is not`mcpServers` . Run the doctor and read the line and column it prints.
2. **Red dot, no message.** The process exited. The doctor’s`handshake` line shows the exit code and the last stderr lines. Fix the import or the missing runtime it names.
3. **Spinner that never stops.** The server is alive but silent or noisy. Look for the`stdout-noise` failure and move logging to stderr. Also check for a server that waits on a prompt or login.
4. **Green dot, zero tools.** The server registered no tools or they failed validation. The doctor prints`0 tools exposed` or a schema failure. Check that tool registration runs before the server starts listening.
5. **Works in the terminal, fails in the editor.** PATH or working directory differs. Run with`--gui-path` and switch`command` to an absolute path.
6. **401 from a remote server.** Credentials are missing or expired. Add the`Authorization` header through`${env:NAME}` or redo the OAuth sign-in in the editor.
7. **404 from a remote server.** The path is wrong. Try the`/mcp` path, and check for a trailing slash that triggers a redirect which drops the POST body.
8. **Certificate or DNS error.** A VPN, proxy or corporate TLS interception is in the way. The doctor prints the underlying reason from the network stack, which tells you which one.
9. **Tools appear but the agent never calls them.** Descriptions are blank or vague, the tool list is too long, or approvals are pending. Fix the descriptions first. Rules can also tell the agent when to reach for a tool.
10. **Works on your machine, fails for a teammate.** A variable, binary or path differs. Run the doctor on their machine and compare the`command` and`interpolation` lines.

## Advanced Tips for Keeping Cursor MCP Servers Healthy

**Fingerprint the tool list.** Save the JSON output from a known-good run and diff it on later runs. A changed tool name or schema after an SDK bump shows up as a one-line diff, which beats finding out when the agent starts misbehaving.

**Budget tokens for tool definitions.** Tool names, descriptions and schemas ride along with requests, so a bloated server taxes every turn. Cursor publishes [per-token rates for each model](https://cursor.com/docs/account/pricing/request-based-legacy.md) in its pricing documentation, and its Composer page lists Composer 2.5 at $0.50 per million input tokens and $2.50 per million output tokens. Multiply your tool-definition size by your daily request count and the cost of a sprawling server becomes concrete.

**Test against protocol revisions.** The MCP project publishes two specification releases a year, normally on the last Tuesday of March and September, and has targeted 2027-03-30 for the next one. Run the doctor with `--protocol` set to each revision your SDK claims to support, and treat a failure as a migration task you can schedule instead of a surprise.

**Pin and package your servers.** A team that distributes servers through a [Cursor plugin](https://shattered.io/cursor-plugins-team-guardrails-rules-hooks-mcp-12-steps-2026/) gets one reviewed bundle instead of fifty hand-edited configs. Put the doctor in the bundle’s preflight step so every install proves itself.

**Teach the agent when to use a tool.** A healthy server still goes unused if nothing says when it applies. Short project guidance in [Cursor rules](https://shattered.io/cursor-rules-tutorial-mdc-globs-test-harness-12-steps-2026/) that names the tool and the situation raises the call rate more than any rewrite of the schema.

**Run on a macOS runner with `--gui-path`.** If your team ships to macOS users, CI on a Linux runner can miss PATH problems. A second job with the minimal path flag catches them before users do.

**Extend the checks.** Natural next additions include a call to one safe, read-only tool per server, a latency budget per call, and a check that flags tokens passed as plain strings instead of environment references. Each fits the same `Finding` shape, so the report format never changes.

## FAQ: Fixing MCP Servers in Cursor

**Where does Cursor look for the MCP config file?** It reads a global file at `~/.cursor/mcp.json` and a project file at `.cursor/mcp.json`. The doctor checks both by default. Project entries are the right place for servers that only make sense inside one repository.

**Why does my MCP server work in a terminal but not in Cursor?** The editor starts the process with its own environment, working directory and PATH. A command that resolves in your shell can be invisible to a GUI app. Run the doctor with `--gui-path` and switch to an absolute command path.

**Can I use environment variables in mcp.json?** Yes. Use the `${env:NAME}` form for secrets and keep the real values in your shell profile or a secrets manager. The doctor reports any placeholder it cannot resolve before it starts a process.

**What does a stdout-noise failure mean?** The server wrote something that is not JSON-RPC to stdout, usually a startup banner or a debug print. The editor parses that stream, so the extra line can stall or break the connection. Move all logging to stderr.

**Does the doctor work for remote HTTP servers?** It checks reachability, status codes and whether the endpoint answers an `initialize` request. It maps 401, 403, 404 and 405 to specific hints. It does not complete an OAuth flow, so authenticate in the editor for servers that need one.

**Which protocol version should I send?** The script defaults to 2025-11-25 because SDKs still answer the classic handshake. Pass `--protocol` to test another revision. The newest published specification is 2026-07-28, and your SDK’s release notes say which revisions it supports.

**How many MCP servers should I enable at once?** Enable only the servers a task needs. Each one adds tool definitions to every request, which costs tokens and can dilute tool selection. Disable what you are not using and keep descriptions short and specific.
