MCP Inspector 使用指南:用命令行测试并排查 MCP 服务器
MCP 服务器出问题时,第一件事是定位断在哪一步:进程没起来、连接被拒、协议版本对不上、工具列表是空的,还是某次调用失败。MCP Inspector 回答的正是这个问题,它的命令行客户端还能让脚本来判定结果,同一个测试既能在本机跑,也能放进 CI。
下面用 Inspector 2.12.0 的 CLI 客户端完成六项检查:连接服务器、确认协议版本、列出工具、检查可移植性、调用工具,以及按退出码定位故障。示例运行在一个基于官方 Python SDK 的参考服务器上,常见症状会直接对应到原因和处理办法。Web 与终端客户端、各个参数和配置文件见来源里的官方文档。
1. 该用哪个 Inspector 客户端
这个包在一个可执行文件后面提供三个客户端,它们共用同一套连接逻辑:
| 客户端 | 启动方式 | 适合做什么 |
|---|---|---|
| Web | npx @modelcontextprotocol/[email protected] | 手动探索服务器:工具有表单,JSON-RPC 流量可实时查看 |
| 终端界面 | npx @modelcontextprotocol/[email protected] --tui | 没有浏览器时做同样的探索 |
| CLI | npx @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=memory3. 协议世代:一次通过说明了什么
2026-07-28 修订版对协议改动很大,所以 Inspector 把协议世代(protocol era)当作每次运行的独立设置,与传输方式无关。--protocol-era 取 legacy、auto 或 modern:
| 世代 | Inspector 连接时做什么 | 线路上看到的 |
|---|---|---|
legacy(Inspector 的默认值) | 直接发 initialize,完全不探测 | initialize、notifications/initialized,然后是请求本身 |
auto | 先探测 server/discover,服务器不是 modern 就回退到 initialize | server/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 initialize | PASS 并给出服务器名和协议版本;FAIL 给出退出码、Inspector 的错误码、消息和提示 |
era | 把协商到的版本与 2026-07-28 比较 | 相同为 PASS,否则 WARN |
tools-list | --method tools/list --strict --format json | PASS 并列出工具名;可移植性警告或空列表为 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 fail6. 场景
每个场景是冒烟脚本的一次运行。全部 26 个场景的完整输出(含退出状态)已录制,每次重跑都会比对。下表保留设置与汇总行,第 7 节解释各种失败。
| 场景 | 设置 | 结果 |
|---|---|---|
sdk-http-modern | 官方 SDK 服务器,HTTP,默认世代 modern,--call add | 5 pass, 0 warn, 0 fail, exit 0 |
sdk-http-auto | 同一个服务器,--era auto | 4 pass, 0 warn, 0 fail, exit 0 |
sdk-http-legacy | 同一个服务器,--era legacy | 3 pass, 1 warn, 0 fail, exit 0 |
stub-modern | 只会 2025-11-25 的桩服务器,默认世代 modern | 1 pass, 0 warn, 1 fail, exit 1 |
stub-auto | 同一个桩服务器,--era auto | 3 pass, 1 warn, 0 fail, exit 0 |
stub-legacy-call | 同一个桩服务器,--era legacy,--call echo | 4 pass, 1 warn, 0 fail, exit 0 |
stub-bad-schema | 一个工具含裸布尔值、type 数组和空 schema | 2 pass, 1 warn, 1 fail, exit 1 |
stub-warn-schema | 一个工具只含 type 数组 | 2 pass, 2 warn, 0 fail, exit 0 |
stub-no-capability | initialize 里没有 capabilities.tools | 2 pass, 2 warn, 0 fail, exit 0 |
http-auth | 401,带 WWW-Authenticate 头 | 1 pass, 0 warn, 1 fail, exit 1 |
http-forbidden | 403 | 1 pass, 0 warn, 1 fail, exit 1 |
http-not-found | 404 | 1 pass, 0 warn, 1 fail, exit 1 |
http-error-500 | 500 | 1 pass, 0 warn, 1 fail, exit 1 |
http-non-json | 200,响应体是 HTML | 1 pass, 0 warn, 1 fail, exit 1 |
http-unreachable | 该端口没有进程监听 | 1 pass, 0 warn, 1 fail, exit 1 |
stdio-ok-modern | SDK 的 stdio 服务器,modern,--call add,--check-stdout | 6 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-tool | add 工具向 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 4000 | 1 pass, 0 warn, 1 fail, exit 1 |
stdio-unknown-tool | --call nope | 3 pass, 1 warn, 1 fail, exit 1 |
stdio-bad-arg | --call add --arg a=two --arg b=3 | 3 pass, 1 warn, 1 fail, exit 1 |
stdio-tool-error-expected | --call explode --expect-error | 4 pass, 1 warn, 0 fail, exit 0 |
stdio-tool-error-unexpected | --call explode | 3 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 endpoint | HTTP 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-28 | modern 固定为 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。警告不会让运行失败 |
| 工具列表为空,退出码却是 0 | stub-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_found | stdio-unknown-tool:exit 5 tool_not_found: Tool 'nope' not found on server. | 工具名不在服务器的列表里;Inspector 在列表中查找后自己报错,没有发出调用 | 对照 tools-list 那一行,它会打印工具名,注意大小写 |
调用失败,退出码 5 且 tool_is_error | stdio-tool-error-unexpected:returned isError true (exit 5 tool_is_error): Error executing tool explode | 工具运行了并返回 isError: true:这是执行错误,不是协议错误 | 读错误文本;测试本来就想要这个错误时,用 --expect-error 把同样的结果变成 PASS(stdio-tool-error-expected) |
数字参数到了服务器变成 None | stdio-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 |
5 | tools/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。