MCP Inspector 使用指南:用命令行测试并排查 MCP 服务器

MCP 服务器出问题时,第一件事是定位断在哪一步:进程没起来、连接被拒、协议版本对不上、工具列表是空的,还是某次调用失败。MCP Inspector 回答的正是这个问题,它的命令行客户端还能让脚本来判定结果,同一个测试既能在本机跑,也能放进 CI。

下面用 Inspector 2.12.0 的 CLI 客户端完成六项检查:连接服务器、确认协议版本、列出工具、检查可移植性、调用工具,以及按退出码定位故障。示例运行在一个基于官方 Python SDK 的参考服务器上,常见症状会直接对应到原因和处理办法。Web 与终端客户端、各个参数和配置文件见来源里的官方文档。

1. 该用哪个 Inspector 客户端

这个包在一个可执行文件后面提供三个客户端,它们共用同一套连接逻辑:

客户端启动方式适合做什么
Webnpx @modelcontextprotocol/[email protected]手动探索服务器:工具有表单,JSON-RPC 流量可实时查看
终端界面npx @modelcontextprotocol/[email protected] --tui没有浏览器时做同样的探索
CLInpx @modelcontextprotocol/[email protected] --cli每次运行只发一个请求,stdout 输出 JSON,退出码稳定:脚本、CI,以及改服务器时的快速检查

CLI 每次运行都会连接、发出你用 --method 指定的那一个请求、打印结果然后退出。失败因此容易归类,这也是后面都用 CLI 的原因。凡是要自动化的地方都要固定版本(@modelcontextprotocol/[email protected]):下面的脚本依赖的正是 CLI 的参数和退出码。

2. 连接:目标、分隔符与超时

CLI 把服务器当作“目标”:stdio 服务器给命令,Streamable HTTP 服务器给 URL。

# stdio:先写命令及其自己的参数,再写“--”,最后是 Inspector 的选项
npx -y @modelcontextprotocol/[email protected] --cli python3 sdk_server.py stdio -- --method tools/list

# Streamable HTTP
npx -y @modelcontextprotocol/[email protected] --cli --server-url http://127.0.0.1:8300/mcp --transport http --method tools/list

多数“第一次就失败”来自三个细节:

  • -- 分隔符。 在 CLI 里,-- 之前的全部是目标,之后的全部是 Inspector 自己的选项;没有 -- 时,目标只是开头那一串不以连字符开头的参数,所以带参数的服务器必须加分隔符。Web 与终端客户端的划分方向相反。场景 stdio-server-flag 在 -- 之前给参考服务器传了它自己的 --name flagged,服务器把这个名字报了回来。
  • 超时。 --connect-timeout 的单位是毫秒。服务器一直不应答会得到退出码 4 和 Connection timed out after N ms(场景 stdio-silent,--connect-timeout 4000)。
  • 状态目录。 用 MCP_STORAGE_DIR 定向 OAuth 状态,MCP_CATALOG_PATH 指向练习 catalog;无凭据实验显式使用 MCP_INSPECTOR_SECRET_STORE=memory。不修改 HOME,也不访问已有 catalog、OAuth 或钥匙串。memory 不适用于跨进程 OAuth 登录。

在独立的练习 shell 中先设置以下目录;结束时退出该 shell 回收目录。npm 等下载缓存继续使用系统现有配置。此配置针对本页无凭据 CLI,不代表 OAuth 持久化配方。

PLAN034_INSPECTOR_WORK=$(mktemp -d)
printf '%s\n' "$PLAN034_INSPECTOR_WORK"
trap 'rm -rf "$PLAN034_INSPECTOR_WORK"' EXIT HUP INT TERM
export MCP_STORAGE_DIR="$PLAN034_INSPECTOR_WORK/storage"
export MCP_CATALOG_PATH="$PLAN034_INSPECTOR_WORK/catalog.json"
export MCP_INSPECTOR_SECRET_STORE=memory

3. 协议世代:一次通过说明了什么

2026-07-28 修订版对协议改动很大,所以 Inspector 把协议世代(protocol era)当作每次运行的独立设置,与传输方式无关。--protocol-era 取 legacy、auto 或 modern:

世代Inspector 连接时做什么线路上看到的
legacy(Inspector 的默认值)直接发 initialize,完全不探测initialize、notifications/initialized,然后是请求本身
auto先探测 server/discover,服务器不是 modern 就回退到 initializeserver/discover,桩服务器回答 -32601 后再发 initialize
modern严格固定为 2026-07-28,不回退,所以不是 modern 的服务器会明确失败在任何工具请求之前就报错(场景 stub-modern)

由此带来一个容易漏掉的后果:默认世代下的一次通过,对 2026-07-28 什么也没说明。 同一个官方 SDK 服务器,legacy 下协商到 2025-11-25,modern 与 auto 下协商到 2026-07-28(场景 sdk-http-legacy、sdk-http-modern、sdk-http-auto)。因此冒烟脚本默认 --era modern,协商到的版本不是 2026-07-28 时给 WARN,对确知较旧的服务器可以主动选 legacy 或 auto。

4. 一个能放进 CI 的冒烟测试

inspector_smoke.py 对一个服务器运行 Inspector CLI,每项检查输出一行。它只需要 Python 3 和 Inspector,不导入 MCP SDK。

检查做什么PASS、WARN、FAIL
inspector--cli -V打印版本。Inspector 根本跑不起来时,脚本以退出码 2 结束,不输出结果行
connect--method initializePASS 并给出服务器名和协议版本;FAIL 给出退出码、Inspector 的错误码、消息和提示
era把协商到的版本与 2026-07-28 比较相同为 PASS,否则 WARN
tools-list--method tools/list --strict --format jsonPASS 并列出工具名;可移植性警告或空列表为 WARN;出现错误级别的 schema 问题(退出码 6)为 FAIL
tools-call带 --call NAME --arg KEY=VALUE 时:--method tools/call结果不是错误为 PASS;带 --expect-error 时,只有工具返回 isError: true 才 PASS
stdout-clean带 --check-stdout(仅 stdio):手动用原始 JSON-RPC 会话驱动服务器stdout 的每一行都是 JSON-RPC 消息为 PASS;否则 FAIL 并给出第一条违规行

退出码:没有 FAIL 为 0(允许有警告),至少一项失败为 1,用法错误或 Inspector 启动不了为 2。

# stdio 服务器:可以用 --check-stdout
python3 inspector_smoke.py --call add --arg a=2 --arg b=3 --check-stdout -- python3 sdk_server.py stdio ok
# Streamable HTTP 服务器
python3 inspector_smoke.py --call add --arg a=2 --arg b=3 http://127.0.0.1:8300/mcp
# 确知比 2026-07-28 旧的服务器
python3 inspector_smoke.py --era legacy http://127.0.0.1:9000/mcp

脚本默认用 npx -y @modelcontextprotocol/[email protected] 启动 Inspector;用 --inspector CMD 可以换成其他已固定版本或本地安装。

inspector_smoke.py
#!/usr/bin/env python3
"""Smoke-test an MCP server through the MCP Inspector CLI (stdlib only).

  inspector_smoke.py [options] URL
  inspector_smoke.py [options] -- COMMAND [ARG...]

Checks, in order: inspector (version), connect (initialize), era (which protocol version was
negotiated), tools-list (tools/list --strict), tools-call (with --call), stdout-clean (with
--check-stdout, stdio only).

Options:
  --inspector CMD    how to start the Inspector (default: npx -y @modelcontextprotocol/[email protected])
  --era ERA          legacy | auto | modern (default: modern)
  --transport T      http | sse, for a URL target (default: http)
  --timeout-ms N     the Inspector's --connect-timeout, in milliseconds (default: 15000)
  --call NAME        also call this tool once, with the --arg values
  --arg KEY=VALUE    argument for --call (repeatable); a value is sent as JSON when it parses
  --expect-error     the --call is expected to return isError: true
  --check-stdout     stdio only: drive the server by hand and require stdout to carry only JSON-RPC

Exit status: 0 no FAIL (WARN allowed), 1 at least one FAIL, 2 usage error or Inspector cannot run.
"""
import argparse
import json
import queue
import shlex
import subprocess
import sys
import textwrap
import threading

PROCESS_TIMEOUT_S = 90
RAW_TIMEOUT_S = 10
MODERN_VERSION = "2026-07-28"
results = []


def report(level, name, detail):
    """Record and print one check result."""
    results.append(level)
    print(f"{level} {name}: {detail}")


def parse_json(text):
    """Parse text as JSON; return None when it is not JSON."""
    try:
        return json.loads(text)
    except ValueError:
        return None


def run_cli(base, args):
    """Run the Inspector CLI once; return (exit code, stdout, stderr), exit code None on timeout."""
    try:
        done = subprocess.run(base + ["--cli"] + args, capture_output=True, text=True,
                              stdin=subprocess.DEVNULL, timeout=PROCESS_TIMEOUT_S)
    except subprocess.TimeoutExpired:
        return None, "", ""
    return done.returncode, done.stdout, done.stderr


def error_envelope(stderr):
    """The Inspector writes a one-line JSON error envelope last on stderr; return its dict or {}."""
    for line in reversed(stderr.strip().splitlines()):
        value = parse_json(line)
        if isinstance(value, dict):
            return value.get("error") or {}
    return {}


def server_stderr(stderr):
    """The last stderr line that is not the error envelope: what a stdio server wrote before it died."""
    lines = [line for line in stderr.strip().splitlines() if line.strip() and not line.startswith('{"error"')]
    return textwrap.shorten(lines[-1], 80, placeholder="...") if lines else ""


def explain(code, stderr):
    """One-line description of a failed run: exit code, error code, message and what to check."""
    if code is None:
        return f"no result within {PROCESS_TIMEOUT_S}s (the Inspector or the server hangs)"
    err = error_envelope(stderr)
    message = textwrap.shorten(str(err.get("message", "")), 150, placeholder="...")
    hint = ""
    if "timed out" in message:
        hint = "the server did not answer in time: raise --timeout-ms, or check that it speaks MCP on this transport"
    elif code == 4:
        hint = "is the server running and the URL or command right?"
    elif code == 3:
        hint = "the server wants credentials (HTTP 401 or 403)"
    elif err.get("status") == 404:
        hint = "the endpoint answered 404: wrong path?"
    elif "Unexpected content type" in message:
        hint = "the URL answers with something that is not MCP (login page, proxy?)"
    elif "Connection closed" in message:
        hint = "the server process exited during startup: run it by hand and read its stderr"
    elif "ENOENT" in message:
        hint = "the command was not found"
    elif "Error POSTing" in message:
        hint = "the server answered with an HTTP error status"
    elif "Version negotiation failed" in message:
        hint = "the server does not speak 2026-07-28; try --era legacy"
    text = f"exit {code} {err.get('code', '-')}: {message}"
    if server_stderr(stderr):
        text += f"; stderr: {server_stderr(stderr)!r}"
    return f"{text} -> {hint}" if hint else text


def coerce(value):
    """Mirror the Inspector's --tool-arg rule for the raw session: JSON when it parses, else a string."""
    try:
        return json.loads(value)
    except ValueError:
        return value


def first_text(stdout):
    """The first text block of a tools/call result, shortened, or an empty string."""
    content = (parse_json(stdout) or {}).get("content") or [{}]
    return textwrap.shorten(str(content[0].get("text", "")), 150, placeholder="...")


def check_connect(run):
    """initialize; return the result dict, or None when the connection failed."""
    code, out, err = run(["--method", "initialize"])
    info = parse_json(out) if code == 0 else None
    if not isinstance(info, dict):
        report("FAIL", "connect", explain(code, err))
        return None
    version = info.get("protocolVersion")
    name = (info.get("serverInfo") or {}).get("name")
    if not (isinstance(version, str) and name and isinstance(info.get("capabilities"), dict)):
        report("FAIL", "connect", "initialize result lacks serverInfo.name, protocolVersion or capabilities")
        return None
    report("PASS", "connect", f"server={name} protocolVersion={version}")
    return info


def check_era(version):
    """WARN when the 2026-07-28 behavior was not exercised."""
    if version == MODERN_VERSION:
        report("PASS", "era", f"negotiated {MODERN_VERSION}")
    else:
        report("WARN", "era", f"negotiated {version}; 2026-07-28 behavior not exercised (--era modern pins it)")


def describe(tool, finding):
    """A short label for one schema finding: tool, location and rule."""
    location = ".".join(part for part in (finding["schema"], finding["path"]) if part)
    return f"{tool} {location} ({finding['rule']})"


def listed_tools(body):
    """The tools array of a --format json tools/list output, or an empty list."""
    if not isinstance(body, dict):
        return []
    return (body.get("result") or {}).get("tools") or []


def check_tools_list(run, advertised):
    """tools/list with --strict; exit 6 means an error-severity schema portability finding.

    The Inspector does not send tools/list when the server did not advertise capabilities.tools: it prints an
    empty list and exits 0. An empty list from a server that did advertise it is repeated once before it is reported.
    """
    options = ["--method", "tools/list", "--strict", "--format", "json"]
    code, out, err = run(options)
    body, again = parse_json(out), False
    if code == 0 and advertised and not listed_tools(body):
        code, out, err = run(options)
        body, again = parse_json(out), True
    if code not in (0, 6) or not isinstance(body, dict):
        report("FAIL", "tools-list", explain(code, err))
        return
    tools = listed_tools(body)
    where = [(tool["toolName"], f) for tool in body.get("schemaFindings", []) for f in tool["findings"]]
    errors = [describe(n, f) for n, f in where if f["severity"] == "error"]
    warnings = [describe(n, f) for n, f in where if f["severity"] != "error"]
    if code == 6 or errors:
        report("FAIL", "tools-list", f"exit {code}, {len(errors)} portability error(s): " + "; ".join(errors))
    elif not advertised:
        report("WARN", "tools-list", "capabilities.tools is not advertised, so the Inspector lists no tools without asking")
    elif not tools:
        report("WARN", "tools-list", "the server lists no tools (asked twice)")
    elif warnings:
        report("WARN", "tools-list", f"{len(tools)} tools, {len(warnings)} portability warning(s): " + "; ".join(warnings))
    else:
        names = ", ".join(sorted(t.get("name", "?") for t in tools))
        report("PASS", "tools-list", f"{len(tools)} tools: {names}" + (" (second attempt)" if again else ""))


def check_tools_call(run, name, pairs, expect_error):
    """tools/call once; exit 5 is isError (tool_is_error) or an unknown tool (tool_not_found)."""
    options = ["--method", "tools/call", "--tool-name", name]
    for pair in pairs:
        options += ["--tool-arg", pair]
    code, out, err = run(options)
    kind = error_envelope(err).get("code")
    if code == 0 and not expect_error:
        report("PASS", "tools-call", f"{name} returned isError false")
    elif code == 0:
        report("FAIL", "tools-call", f"{name} succeeded but isError true was expected")
    elif code == 5 and kind == "tool_is_error" and expect_error:
        report("PASS", "tools-call", f"{name} returned isError true (exit 5 tool_is_error), as expected")
    elif code == 5 and kind == "tool_is_error":
        report("FAIL", "tools-call", f"{name} returned isError true (exit 5 tool_is_error): {first_text(out)}")
    else:
        report("FAIL", "tools-call", explain(code, err))


def is_jsonrpc(line):
    """True when the line is a JSON object with jsonrpc 2.0."""
    parsed = parse_json(line)
    return isinstance(parsed, dict) and parsed.get("jsonrpc") == "2.0"


def pump(stream, out):
    """Copy a stream into a queue, line by line, and end with None."""
    for line in stream:
        out.put(line.rstrip("\n"))
    out.put(None)


def check_stdout_clean(command, call, pairs):
    """Drive a stdio server by hand; every stdout line must be a JSON-RPC message."""
    messages = [
        {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
            "protocolVersion": "2025-11-25", "capabilities": {},
            "clientInfo": {"name": "inspector-smoke", "version": "1"}}},
        {"jsonrpc": "2.0", "method": "notifications/initialized"},
        {"jsonrpc": "2.0", "id": 2, "method": "tools/list"},
    ]
    if call:
        arguments = {k: coerce(v) for k, v in (pair.split("=", 1) for pair in pairs)}
        messages.append({"jsonrpc": "2.0", "id": 3, "method": "tools/call",
                         "params": {"name": call, "arguments": arguments}})
    try:
        proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                stderr=subprocess.DEVNULL, text=True)
    except OSError as exc:
        report("FAIL", "stdout-clean", f"cannot start the command: {exc}")
        return
    lines, seen, answered = queue.Queue(), [], set()
    threading.Thread(target=pump, args=(proc.stdout, lines), daemon=True).start()
    why = ""
    try:
        for message in messages:
            proc.stdin.write(json.dumps(message) + "\n")
            proc.stdin.flush()
            while message.get("id") is not None and message["id"] not in answered:
                line = lines.get(timeout=RAW_TIMEOUT_S)
                if line is None:
                    raise EOFError
                if line.strip():
                    seen.append(line)
                    parsed = parse_json(line)
                    if isinstance(parsed, dict) and "id" in parsed and "method" not in parsed:
                        answered.add(parsed["id"])
    except queue.Empty:
        why = f"no response within {RAW_TIMEOUT_S}s"
    except (EOFError, BrokenPipeError):
        why = "the server closed stdout or its stdin before answering"
    finally:
        proc.kill()
        proc.wait()
    last_id = messages[-1]["id"]
    bad = [(i, line) for i, line in enumerate(seen, 1) if not is_jsonrpc(line)]
    if last_id not in answered:
        report("FAIL", "stdout-clean", f"request {last_id} not answered: {why}")
    elif bad:
        i, line = bad[0]
        report("FAIL", "stdout-clean", f"{len(bad)} of {len(seen)} stdout lines are not JSON-RPC; first is line {i}: {line[:60]!r}")
    else:
        report("PASS", "stdout-clean", f"{len(seen)} stdout lines, all JSON-RPC")


def main(argv):
    parser = argparse.ArgumentParser(usage=__doc__, add_help=False)
    parser.add_argument("--inspector", default="npx -y @modelcontextprotocol/[email protected]")
    parser.add_argument("--era", choices=["legacy", "auto", "modern"], default="modern")
    parser.add_argument("--transport", choices=["http", "sse"], default="http")
    parser.add_argument("--timeout-ms", type=int, default=15000)
    parser.add_argument("--call")
    parser.add_argument("--arg", action="append", default=[])
    parser.add_argument("--expect-error", action="store_true")
    parser.add_argument("--check-stdout", action="store_true")
    parser.add_argument("target", nargs="+")
    try:
        opts = parser.parse_args(argv)
    except SystemExit:
        return 2
    is_url = len(opts.target) == 1 and opts.target[0].startswith(("http://", "https://"))
    if (opts.check_stdout and is_url) or (opts.expect_error and not opts.call) \
            or any("=" not in pair for pair in opts.arg) or opts.timeout_ms < 0:
        sys.stderr.write(__doc__)
        return 2
    base = shlex.split(opts.inspector)
    try:
        version = subprocess.run(base + ["--cli", "-V"], capture_output=True, text=True,
                                 stdin=subprocess.DEVNULL, timeout=PROCESS_TIMEOUT_S)
    except (OSError, subprocess.TimeoutExpired) as exc:
        sys.stderr.write(f"cannot run the Inspector ({opts.inspector!r}): {exc}\n")
        return 2
    if version.returncode != 0:
        sys.stderr.write(f"the Inspector exited {version.returncode} on -V: {version.stderr.strip()[:200]}\n")
        return 2
    report("PASS", "inspector", version.stdout.strip())

    options = ["--protocol-era", opts.era, "--connect-timeout", str(opts.timeout_ms)]

    def run(method_options):
        """One CLI run against the target; the documented form puts the target before "--" and options after."""
        if is_url:
            return run_cli(base, ["--server-url", opts.target[0], "--transport", opts.transport] + method_options + options)
        return run_cli(base, opts.target + ["--"] + method_options + options)

    info = check_connect(run)
    if info is not None:
        check_era(info["protocolVersion"])
        check_tools_list(run, "tools" in info["capabilities"])
        if opts.call:
            check_tools_call(run, opts.call, opts.arg, opts.expect_error)
    if opts.check_stdout:
        check_stdout_clean(opts.target, opts.call, opts.arg)
    print(f"{results.count('PASS')} pass, {results.count('WARN')} warn, {results.count('FAIL')} fail")
    return 1 if "FAIL" in results else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

改写它之前,先了解四个设计选择:

  • 读的是 Inspector 的契约,不是它的文字。 PASS 与 FAIL 来自退出码、CLI 在每次非零退出时写到 stderr 的那行 JSON 错误信封里的 code 字段,以及 --format json 的输出;消息文字只用来生成提示。
  • tools/list 一直带 --strict。 Inspector 会完整报告工具 schema 的可移植性问题,错误级别的问题退出码为 6。在 2.12.0 里,我们的运行中唯一出现过的错误级别规则是裸布尔 schema(在应当是 schema 对象的位置写了 true);type 数组和空 schema 是警告。
  • 空列表会问两次。 如果服务器声明了 tools 能力,而第一次 tools/list 以退出码 0 返回了空列表,脚本会再问一次才给警告(见第 8 节的边界)。
  • stdout-clean 是另一个原始会话。 Inspector 能容忍 stdio 服务器 stdout 上的杂散文本,所以 Inspector 一次通过并不能证明数据流是干净的。原始会话使用 2025-11-25 的握手,不协商世代。

5. 一个用来测试的参考服务器

sdk_server.py 是基于官方 Python SDK(pip install mcp==2.3.0)的小服务器,有三个工具(add、get_weather、explode),支持 stdio 和 Streamable HTTP。stdio 模式还带有几种故意设置的故障(banner、noisy-tool、crash 和 silent),供下一节的场景展示。

pip install mcp==2.3.0
python3 sdk_server.py http 8300      # Streamable HTTP,地址 http://127.0.0.1:8300/mcp
python3 sdk_server.py stdio ok       # stdio;冒烟脚本和 Inspector 会替你启动它
sdk_server.py
"""Reference server on the official Python SDK (mcp==2.3.0) for the Inspector checks.

  sdk_server.py http PORT           Streamable HTTP at http://127.0.0.1:PORT/mcp, no auth
  sdk_server.py stdio [MODE] [--name NAME]
                                    stdio; MODE is one of the values below; NAME is the serverInfo name
                                    (default inspector-ref), a flag that must reach the server itself

MODE (stdio only):
  ok          well-behaved server
  banner      fault: prints a line to stdout (flushed) before the protocol starts
  noisy-tool  the add tool prints to stdout (flushed) while it runs; SDK 2.3.0 reroutes that to stderr
  crash       fault: writes to stderr and exits with status 3 before serving
  silent      fault: never answers (sleeps)
"""
import sys
import time
from typing import Annotated

USAGE = __doc__
MODES = ("ok", "banner", "noisy-tool", "crash", "silent")


def parse_args(argv):
    """Return (transport, port, mode, name) or exit with status 2 and the usage text."""
    name = "inspector-ref"
    if len(argv) >= 2 and argv[-2] == "--name":
        argv, name = argv[:-2], argv[-1]
    if len(argv) == 2 and argv[0] == "http" and argv[1].isdigit():
        return "http", int(argv[1]), "ok", name
    if argv and argv[0] == "stdio" and len(argv) <= 2:
        mode = argv[1] if len(argv) == 2 else "ok"
        if mode in MODES:
            return "stdio", 0, mode, name
    sys.stderr.write(USAGE)
    sys.exit(2)


transport, port, mode, server_name = parse_args(sys.argv[1:])

if mode == "crash":
    sys.stderr.write("fatal: cannot open database\n")
    sys.exit(3)
if mode == "silent":
    time.sleep(600)
if mode == "banner":
    print("Server starting...", flush=True)

from mcp.server.mcpserver import MCPServer  # noqa: E402  (after the fault modes on purpose)
from pydantic import Field  # noqa: E402

server = MCPServer(server_name)


@server.tool()
def add(a: int, b: int) -> int:
    """Add two integers."""
    if mode == "noisy-tool":
        print("debug: adding", a, b, flush=True)
    return a + b


@server.tool()
def get_weather(location: Annotated[str, Field(min_length=2)]) -> str:
    """Return fixed weather for a location."""
    return f"Partly cloudy in {location}"


@server.tool()
def explode() -> str:
    """Always raise."""
    raise RuntimeError("boom")


if __name__ == "__main__":
    if transport == "http":
        server.run("streamable-http", port=port)
    else:
        server.run("stdio")

对它运行冒烟脚本,在 modern 世代下(第 6 节的第一个场景,走 stdio)输出如下:

PASS inspector: 2.12.0
PASS connect: server=inspector-ref protocolVersion=2026-07-28
PASS era: negotiated 2026-07-28
PASS tools-list: 3 tools: add, explode, get_weather
PASS tools-call: add returned isError false
PASS stdout-clean: 3 stdout lines, all JSON-RPC
6 pass, 0 warn, 0 fail

6. 场景

每个场景是冒烟脚本的一次运行。全部 26 个场景的完整输出(含退出状态)已录制,每次重跑都会比对。下表保留设置与汇总行,第 7 节解释各种失败。

场景设置结果
sdk-http-modern官方 SDK 服务器,HTTP,默认世代 modern,--call add5 pass, 0 warn, 0 fail, exit 0
sdk-http-auto同一个服务器,--era auto4 pass, 0 warn, 0 fail, exit 0
sdk-http-legacy同一个服务器,--era legacy3 pass, 1 warn, 0 fail, exit 0
stub-modern只会 2025-11-25 的桩服务器,默认世代 modern1 pass, 0 warn, 1 fail, exit 1
stub-auto同一个桩服务器,--era auto3 pass, 1 warn, 0 fail, exit 0
stub-legacy-call同一个桩服务器,--era legacy,--call echo4 pass, 1 warn, 0 fail, exit 0
stub-bad-schema一个工具含裸布尔值、type 数组和空 schema2 pass, 1 warn, 1 fail, exit 1
stub-warn-schema一个工具只含 type 数组2 pass, 2 warn, 0 fail, exit 0
stub-no-capabilityinitialize 里没有 capabilities.tools2 pass, 2 warn, 0 fail, exit 0
http-auth401,带 WWW-Authenticate 头1 pass, 0 warn, 1 fail, exit 1
http-forbidden4031 pass, 0 warn, 1 fail, exit 1
http-not-found4041 pass, 0 warn, 1 fail, exit 1
http-error-5005001 pass, 0 warn, 1 fail, exit 1
http-non-json200,响应体是 HTML1 pass, 0 warn, 1 fail, exit 1
http-unreachable该端口没有进程监听1 pass, 0 warn, 1 fail, exit 1
stdio-ok-modernSDK 的 stdio 服务器,modern,--call add,--check-stdout6 pass, 0 warn, 0 fail, exit 0
stdio-server-flag服务器自己的 --name flagged 写在 -- 之前3 pass, 1 warn, 0 fail, exit 0
stdio-banner开始服务前向 stdout 打印横幅4 pass, 1 warn, 1 fail, exit 1
stdio-noisy-tooladd 工具向 stdout 打印5 pass, 1 warn, 0 fail, exit 0
stdio-crash启动时写 stderr 并以状态 3 退出1 pass, 0 warn, 2 fail, exit 1
stdio-silent从不应答,--timeout-ms 40001 pass, 0 warn, 1 fail, exit 1
stdio-unknown-tool--call nope3 pass, 1 warn, 1 fail, exit 1
stdio-bad-arg--call add --arg a=two --arg b=33 pass, 1 warn, 1 fail, exit 1
stdio-tool-error-expected--call explode --expect-error4 pass, 1 warn, 0 fail, exit 0
stdio-tool-error-unexpected--call explode3 pass, 1 warn, 1 fail, exit 1
stdio-bad-command命令不存在1 pass, 0 warn, 1 fail, exit 1

另有三次运行读的是流量而不是输出,用的是会记录每个请求方法的桩服务器:legacy 从不发 server/discover,auto 先发它;不声明 tools 能力的桩服务器没有收到任何 tools/list;调用一个不存在的工具只产生了 tools/list,没有 tools/call。

7. 故障模式与处理

按行从左往右读:症状是脚本打印的内容,下一列是产生它的场景,其余说明它的含义和处理办法。引用的片段摘自录制的输出。

症状场景与脚本的输出原因处理
连不上服务器http-unreachable:FAIL connect: exit 4 unreachable: fetch failed该主机和端口上没有进程监听,或被防火墙、代理挡住先用 curl 打开这个 URL。确认主机、端口和路径,以及进程在运行
连接挂起后超时stdio-silent:exit 4 unreachable: Connection timed out after 4000 ms进程起来了但从不应答 initialize:它不是这个传输上的 MCP 服务器、在等别的东西,或者启动非常慢手动运行该命令且什么也不输入:stdio 服务器应当安静地等输入。只有启动确实慢时才加大 --connect-timeout
服务器启动时就退出stdio-crash:exit 1 error: Connection closed; stderr: 'fatal: cannot open database'进程在开始服务前就退出了;Inspector 会透传它的 stderr,脚本显示最后一行手动运行该命令,读完整的 stderr,修掉启动错误。常见原因是缺环境变量和工作目录不对
“spawn … ENOENT”stdio-bad-command:spawn /nonexistent/mcp-server ENOENT在 Inspector 的环境里找不到这个命令用绝对路径,或确认解释器在 Inspector 看到的 PATH 里
服务器要求凭据http-auth:exit 3 auth_required;http-forbidden:exit 3 auth_required: Error POSTing to endpointHTTP 401 或 403。文字不同:没有终端时 401 的消息说交互式 OAuth 需要 TTY,403 的响应体原样显示在终端里 Inspector 会启动浏览器 OAuth 流程。在 CI 里官方给的办法是 --stored-auth-only:用已存的令牌,没有就立即失败,而不是等一个没人操作的浏览器
端点写错了http-not-found:exit 1 error: Error POSTing to endpoint: not found该路径返回 404,常见的是把 /mcp 写成了 /核对服务器文档里的路径。404 不是认证问题,退出码是 1,不是 3
服务器返回错误状态码http-error-500:exit 1 error: Error POSTing to endpoint: boom服务器处理请求时失败看服务器自己的日志;Inspector 只能显示响应体
URL 返回的是网页http-non-json:Unexpected content type: text/html登录页、代理的错误页,或者这个站点根本不是 MCP 端点用 curl -i 打开这个 URL,看响应体开头几行
“Version negotiation failed”stub-modern:Version negotiation failed: the server did not offer pinned protocol version 2026-07-28modern 固定为 2026-07-28,而服务器说的是更旧的修订版升级服务器,或者对旧服务器有意选择 --era legacy(或 auto)
tools/list 以退出码 6 失败stub-bad-schema:exit 6, 1 portability error(s): flag inputSchema.properties.x (boolean-schema)某个工具的 schema 在应当是 schema 对象的位置写了裸布尔值,一些客户端和模型提供方无法使用把 true 换成对象 schema,例如自由对象写 {"type": "object", "additionalProperties": true}。这是改契约,不是等价改写
可移植性警告stub-warn-schema:portability warning(s): maybe inputSchema.properties.note (type-union)["string", "null"] 这样的 type 数组是合法的 JSON Schema,但把 schema 映射到单 type 方言的客户端可能拒绝这个工具或丢掉约束如果要服务这样的客户端,改用 anyOf,每个分支一个 type。警告不会让运行失败
工具列表为空,退出码却是 0stub-no-capability:capabilities.tools is not advertised, so the Inspector lists no tools without asking服务器没有声明 tools 能力。Inspector 对这样的服务器不调用 tools/list,线路日志里确实没有这个请求支持工具的服务器必须声明 tools 能力。在 initialize 里声明后再列一次
stdout-clean 失败,Inspector 运行却是绿的stdio-banner:1 of 4 stdout lines are not JSON-RPC; first is line 1: 'Server starting...'服务器在协议开始前向 stdout 打印了横幅。Inspector 会跳过它,更严格的客户端未必stdout 只放 MCP 消息;日志和横幅写到 stderr
工具里的 print 没有破坏数据流stdio-noisy-tool:PASS stdout-clean: 3 stdout lines, all JSON-RPC这是 SDK 2.3.0 的特性,不是 MCP 的:它的 stdio 传输在服务期间把协议流移出了进程的 stdout,调试行出现在 stderr。在 server.run 之前的 print 仍会破坏数据流(上一行)不要把它当成其他 SDK 或手写服务器的行为;这里没有验证它们
调用失败,退出码 5 且 tool_not_foundstdio-unknown-tool:exit 5 tool_not_found: Tool 'nope' not found on server.工具名不在服务器的列表里;Inspector 在列表中查找后自己报错,没有发出调用对照 tools-list 那一行,它会打印工具名,注意大小写
调用失败,退出码 5 且 tool_is_errorstdio-tool-error-unexpected:returned isError true (exit 5 tool_is_error): Error executing tool explode工具运行了并返回 isError: true:这是执行错误,不是协议错误读错误文本;测试本来就想要这个错误时,用 --expect-error 把同样的结果变成 PASS(stdio-tool-error-expected)
数字参数到了服务器变成 Nonestdio-bad-arg:Input should be a valid integer [type=int_type, input_value=None--tool-arg a=two 不是合法 JSON,所以按字符串发送,Inspector 再把它转成 schema 声明的类型;two 转换的结果是 null改正参数,或需要控制类型时用 --tool-args-json 传整个对象

退出码

CLI 把每种失败映射为稳定的退出码,并在 stderr 写一行 JSON 信封({"error": {"code": ..., "message": ...}})。脚本依据它们判断,而不是依据文字:

码含义(取自 Inspector 文档)出现在
0成功sdk-http-modern
1用法错误或意外错误,兜底stdio-crash、http-not-found、http-error-500、http-non-json、stub-modern、stdio-bad-command
2工具上没有 MCP App(--app-info 探测)未运行
3服务器要求认证(HTTP 401 或 403)http-auth、http-forbidden
4服务器不可达(DNS、连接被拒、超时、fetch failed)http-unreachable、stdio-silent
5tools/call 返回了 isError: true,或找不到工具stdio-unknown-tool、stdio-bad-arg、stdio-tool-error-unexpected
6--strict 发现错误级别的工具 schema 可移植性问题stub-bad-schema
7、8、9对技能(skills/list、skills/get)的 --verify 检查未运行

8. 没有验证的部分

  • 界面。 没有运行 Web 客户端、终端界面和 mcpdo。这里的一切都是 CLI 客户端。
  • 传输与认证。 运行了 Streamable HTTP 和 stdio;旧的 SSE 传输(--transport sse)没有运行。OAuth 流程、--stored-auth-only 和自定义请求头没有运行;凭据那一行描述的是失败的样子,处理办法来自 Inspector 的文档。
  • 其他 SDK。 唯一独立的实现是官方 Python SDK 2.3.0。桩服务器和冒烟脚本出自同一份对规范的理解,可能共享同一个错误。第 7 节里 stdout 的行为只属于这个 SDK。
  • 偶发的空列表。 在对一个正常桩服务器的大约三百次运行中,有一次 tools/list 以退出码 0 返回了空列表。我们没能复现,也没找到原因。脚本因此会问两次,第二次请求拿到工具时输出 (second attempt)。
  • 平台。 只有 macOS。

9. 发布服务器之前

  • 用 --era modern 能连上,或者你有意选了更旧的世代并清楚是哪一个。
  • tools/list 在 --strict 下是干净的,或者每个警告你都清楚来由。
  • 提供工具就声明了 tools 能力。
  • stdout 只放协议消息;日志和横幅写到 stderr。
  • 认证失败返回 401 或 403,而不是一个网页。
  • 冒烟脚本在 CI 里运行且固定了 Inspector 的版本,更换 SDK、网关或你所服务的修订版时重新运行。

版本与验证说明

行为来自实际运行:Inspector 2.12.0(@modelcontextprotocol/inspector,需要 Node 22.19.0 或更高,实测用 Node 24.18.0)对官方 Python SDK 2.3.0(mcp==2.3.0,Python 3.14)和一个每次只弄坏一处的标准库桩服务器,系统为 macOS。完整运行覆盖 26 个录制的场景。规范与 Inspector 官方文档的措辞取自官方仓库的一个固定提交(dae694f6)。Inspector 或 SDK 发布新版本后需要重新运行。没有验证的部分见第 8 节。

2026-10-30 使用 Node 24.18.0、Inspector 2.12.0、Python 3.11.12 与 mcp==2.3.0,重跑连接指南用到的子集:正常 stdio 的 add 返回 5、显式 flush 的启动前横幅、进程退出、旧式 HTTP 与 modern 差异,以及 HTTP 401 / 403 / 404 / HTML。上表保留先前的完整录制;此次未重跑全部 26 个场景,也未运行 Web / TUI / OAuth。

来源