MCP Bridge 报 401 就是启动失败吗?Windows 端口占用与 Doctor 排障实战
启动 MCP Bridge 后,浏览器或脚本突然返回 401 Unauthorized,第一反应可能是“服务没起来”。但换个角度想:既然收到了 HTTP 401,至少说明有服务响应了这次请求。 真正需要查的是:谁在响应、服务是否健康,以及当前请求为什么没有通过认证。
端口被占用、健康检查超时也常常和 401 一起出现。它们看上去都是“连不上”,实际却属于不同问题。本文从这三个现象出发,用 Windows PowerShell 和 Python 搭一个只在本机运行的小实验,逐个复现,再用 doctor 给出可解释的诊断结果。
先看三个结论:
401不等于启动失败。对于需要身份验证的接口,未携带凭据时返回 401 可能正是正常行为。- 端口正在监听,不代表监听的是目标服务。 也可能是上一次残留的进程,或者完全不同的程序。
- Doctor 不该只看能否连接。 服务身份、健康状态、鉴权响应都要检查;失败时保留真实错误类型,不要为了“通过测试”随意改成某一种结果。
本文提供的所有实验文件和执行命令都已写在正文中,照着创建文件即可练习,不需要下载任何配套资源。实验仅覆盖本地 HTTP 故障,不等于真实 MCP 协议或生产 Bridge 的集成验收。
标签: MCP、Codex、Python、PowerShell、故障排查
一、先用一张流程图判断从哪里查起
这是一条排障思路,不是对所有 MCP 服务的统一接口规范。真实项目可能有不同的健康接口或认证机制,不能照搬本文的 /health 规则。
为了让结果不受个人账号、网络代理和第三方服务器影响,我们使用一个本机 HTTP 模拟服务。它提供两个演示接口:/health 负责报告服务状态,/mcp 负责模拟鉴权响应。它不是完整的 MCP Server,也没有实现 JSON-RPC、OAuth 或真实工具调用。
在这个实验里,doctor 只有同时确认服务身份正确、/health 正常、未经授权访问 /mcp 返回 401 并包含认证挑战头,才会给出 HEALTHY。这样可以直观看到:单个 401 只是线索,不是最终结论。
二、实验准备:只要 Python,不需要额外安装包
建议使用 Windows 10/11、PowerShell 5.1 或 PowerShell 7,以及 Python 3.11 或更高版本。下面使用 Windows 的 py -3 启动器;如果机器只有 python 命令,可以将示例里的 py -3 替换成对应的 Python 3.11+ 解释器命令。
先在 PowerShell 中检查版本:
py -0p
py -3 --version
然后选择一个用于存放练习的目录,执行以下命令。它会创建新的 B01-mcp-demo 文件夹;如果同名目录已经存在,会停止,防止覆盖你原有的文件。
$ErrorActionPreference = 'Stop'
$root = Join-Path (Get-Location).Path 'B01-mcp-demo'
if (Test-Path -LiteralPath $root) {
throw "目录已存在,请换一个名称:$root"
}
New-Item -ItemType Directory -Path $root | Out-Null
foreach ($name in @('b01diag', 'tests', 'scripts', 'reports')) {
New-Item -ItemType Directory -Path (Join-Path $root $name) | Out-Null
}
Set-Location $root
后面会给出 5 个 Python 文件的完整内容。用 VS Code、记事本或其他编辑器建立对应文件,并保存为 UTF-8 编码:
B01-mcp-demo/
├── lab.py
├── b01diag/
│ ├── __init__.py
│ └── core.py
├── tests/
│ └── test_b01.py
├── scripts/
│ └── collect_evidence.py
└── reports/
其中 b01diag/core.py 负责模拟服务和故障分类,lab.py 提供命令行,tests/test_b01.py 负责单元测试,scripts/collect_evidence.py 自动整理故障结果。不需要 pip install,程序只使用 Python 标准库。
三、先读懂实验要验证什么
我们人为准备了几种常见场景:
| 表面现象 | 实际要确认什么 | 实验会如何判断 |
|---|---|---|
| 访问接口返回 401 | 是否只因为没有授权 | 检查健康、服务身份和认证挑战头 |
| 第二次启动时端口冲突 | 是否已有服务在监听 | 返回端口绑定失败,不结束现有进程 |
/health 返回 503 | 服务虽然存在,是否处于降级状态 | DEGRADED |
| 返回 200,但不是预期服务 | 是否连接到了其他程序 | FOREIGN_SERVICE |
| 健康检查长时间无响应 | 是连接失败还是请求超时 | UNREACHABLE 或 TIMEOUT |
| 未授权请求居然返回 200 | 模拟鉴权有没有失效 | AUTH_NOT_ENFORCED |
一个容易忽略的细节: probe 的退出码为 0,只代表“成功拿到了 HTTP 响应”;即使 HTTP 状态是 401,也可以是一次成功的探测。doctor 的退出码则代表健康诊断结论。不要把这两个命令的返回值混为一谈。
四、复制核心代码:本地服务与诊断命令
先建立下面三个文件。代码中的 demo 授权值只是写死的非秘密教学标记,不需要输入真实 API Key、Token 或账号信息。服务固定监听 127.0.0.1,诊断请求也只访问回环地址。
文件:b01diag/__init__.py
"""B-01 diagnostic teaching module; never use as a production MCP bridge."""
__version__ = "0.1.1"
文件:b01diag/core.py
"""B-01 offline HTTP diagnostic fixture. NOT an MCP server or OAuth provider."""
from __future__ import annotations
import json
import os
import socket
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib import error, request
FIXTURE_NAME = "b01-local-fixture"
FIXTURE_SCHEMA = 1
# This is a fixed, non-secret classroom marker, never a real credential.
_DEMO_MARKER = "B01_ONLY_FAKE_MARKER_NOT_A_CREDENTIAL"
MODES = ("healthy", "degraded", "foreign", "bad-json", "auth-bypass", "slow-health", "redirect-health")
EXIT_CODES = {
"HEALTHY": 0,
"DEGRADED": 21,
"FOREIGN_SERVICE": 22,
"UNREACHABLE": 23,
"TIMEOUT": 24,
"BAD_HEALTH_RESPONSE": 25,
"WRONG_INSTANCE": 26,
"AUTH_NOT_ENFORCED": 27,
"MCP_UNEXPECTED_STATUS": 28,
}
class LoopbackServer(ThreadingHTTPServer):
# On Windows SO_REUSEADDR can permit a second server to bind an occupied port.
# Disable it there to make the port-conflict experiment safe and deterministic.
allow_reuse_address = os.name != "nt"
daemon_threads = True
def create_server(*, port: int, mode: str, instance: str) -> LoopbackServer:
if mode not in MODES:
raise ValueError("unsupported fixture mode")
if port < 0 or port > 65535:
raise ValueError("port must be 0..65535")
if not instance or len(instance) > 64 or not instance.isascii() or not all(c.isalnum() or c in "_-" for c in instance):
raise ValueError("instance must be 1..64 ASCII-like letters, digits, _ or -")
class FixtureHandler(BaseHTTPRequestHandler):
server_version = "B01TeachingFixture/0.1"
sys_version = ""
def log_message(self, format, *args):
# Never log Authorization headers or any body contents.
return
def send_json(self, status: int, body: dict, extra_headers: dict | None = None):
payload = json.dumps(body, separators=(",", ":"), sort_keys=True).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
self.send_header("Cache-Control", "no-store")
if extra_headers:
for key, value in extra_headers.items():
self.send_header(key, value)
self.end_headers()
try:
self.wfile.write(payload)
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
# Expected if the client intentionally timed out / aborted on Windows.
pass
def do_GET(self):
if self.path == "/health":
if mode == "slow-health":
import time
time.sleep(1.0)
if mode == "redirect-health":
self.send_response(302)
self.send_header("Location", "https://example.invalid/never-follow")
self.end_headers()
return
if mode == "bad-json":
payload = b"not-json"
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
try:
self.wfile.write(payload)
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
pass
return
if mode == "foreign":
self.send_json(200, {"service": "unrelated-listener", "status": "ok"})
return
status = 503 if mode == "degraded" else 200
self.send_json(status, {
"service": FIXTURE_NAME,
"schema": FIXTURE_SCHEMA,
"instance": instance,
"status": "degraded" if mode == "degraded" else "ok",
})
return
if self.path == "/mcp":
if mode == "foreign":
self.send_json(404, {"error": "NOT_FOUND"})
return
if mode == "auth-bypass":
self.send_json(200, {"fixture": True, "note": "deliberately bypassed auth"})
return
value = self.headers.get("Authorization", "")
if value != "Bearer " + _DEMO_MARKER:
self.send_json(401, {"error": "UNAUTHORIZED"}, {
"WWW-Authenticate": 'Bearer realm="b01-local-teaching-only"'
})
return
self.send_json(200, {"fixture": True, "note": "demo marker accepted; not MCP"})
return
self.send_json(404, {"error": "NOT_FOUND"})
return LoopbackServer(("127.0.0.1", port), FixtureHandler)
# Ignore ambient HTTP_PROXY/HTTPS_PROXY; never query anything except loopback.
class RejectRedirect(request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
# A foreign local listener must not force our doctor to contact an external host.
return None
_OPENER = request.build_opener(request.ProxyHandler({}), RejectRedirect())
def local_get(port: int, path: str, *, timeout: float, auth: str = "none") -> dict:
if port < 1 or port > 65535:
raise ValueError("target port must be 1..65535")
if path not in ("/health", "/mcp"):
raise ValueError("only the two teaching paths are supported")
if auth not in ("none", "wrong", "demo"):
raise ValueError("auth must be none/wrong/demo")
headers = {"User-Agent": "B01LocalDiagnostic/0.1"}
if auth == "wrong":
headers["Authorization"] = "Bearer B01_INTENTIONALLY_INVALID"
elif auth == "demo":
headers["Authorization"] = "Bearer " + _DEMO_MARKER
req = request.Request(f"http://127.0.0.1:{port}{path}", headers=headers)
try:
with _OPENER.open(req, timeout=timeout) as resp:
return _response(resp)
except error.HTTPError as exc:
with exc:
return _response(exc)
def _response(resp) -> dict:
raw = resp.read(8193)
if len(raw) > 8192:
return {"status": resp.status, "body": None, "too_large": True,
"challenge": bool(resp.headers.get("WWW-Authenticate"))}
try:
body = json.loads(raw.decode("utf-8"))
except (UnicodeError, json.JSONDecodeError):
body = None
return {"status": resp.status, "body": body,
"challenge": bool(resp.headers.get("WWW-Authenticate"))}
def _is_timeout(exc: Exception) -> bool:
reason = getattr(exc, "reason", exc)
return isinstance(reason, (TimeoutError, socket.timeout)) or "timed out" in str(reason).lower()
def _transport_metadata(exc: Exception, phase: str) -> dict:
"""Record bounded safe OS facts, not raw exception strings/URLs/credentials."""
cause = getattr(exc, "reason", exc)
info = {"phase": phase, "exception_type": type(cause).__name__}
# In particular WinError 10060 vs 10061 can help explain a Windows result.
for field in ("errno", "winerror"):
value = getattr(cause, field, None)
if isinstance(value, int):
info[field] = value
return info
def diagnose(*, port: int, instance: str, timeout: float = 0.35) -> dict:
"""Classify observations without killing, restarting or writing anything."""
result = {"tool": "B01_LOCAL_DOCTOR", "port": port, "expected_instance": instance,
"ok": False, "result": "UNREACHABLE", "checks": {},
"scope": "local simulation only; no real MCP/OAuth/Tunnel"}
def decide(name: str) -> dict:
result["result"] = name
result["ok"] = name == "HEALTHY"
result["exit_code"] = EXIT_CODES[name]
return result
try:
health = local_get(port, "/health", timeout=timeout)
except (error.URLError, TimeoutError, socket.timeout, ConnectionError, OSError) as exc:
result["checks"]["transport"] = _transport_metadata(exc, "health")
return decide("TIMEOUT" if _is_timeout(exc) else "UNREACHABLE")
result["checks"]["health_http"] = health["status"]
body = health.get("body")
if isinstance(body, dict) and body.get("service") == FIXTURE_NAME:
if body.get("schema") != FIXTURE_SCHEMA:
return decide("BAD_HEALTH_RESPONSE")
if body.get("instance") != instance:
return decide("WRONG_INSTANCE")
if health["status"] == 503 or body.get("status") == "degraded":
return decide("DEGRADED")
if health["status"] != 200 or body.get("status") != "ok":
return decide("BAD_HEALTH_RESPONSE")
elif health["status"] == 200 and isinstance(body, dict):
return decide("FOREIGN_SERVICE")
else:
return decide("BAD_HEALTH_RESPONSE")
try:
mcp = local_get(port, "/mcp", timeout=timeout, auth="none")
except (error.URLError, TimeoutError, socket.timeout, ConnectionError, OSError) as exc:
result["checks"]["transport"] = _transport_metadata(exc, "mcp")
return decide("TIMEOUT" if _is_timeout(exc) else "UNREACHABLE")
result["checks"]["unauthenticated_mcp_http"] = mcp["status"]
result["checks"]["has_www_authenticate"] = mcp["challenge"]
if mcp["status"] == 200:
return decide("AUTH_NOT_ENFORCED")
if mcp["status"] != 401 or not mcp["challenge"]:
return decide("MCP_UNEXPECTED_STATUS")
return decide("HEALTHY")
def probe(*, port: int, path: str, auth: str, timeout: float) -> dict:
"""Demonstrate HTTP status, never print fake or real Authorization values."""
resp = local_get(port, path, timeout=timeout, auth=auth)
return {"tool": "B01_LOCAL_PROBE", "path": path, "auth_case": auth,
"http_status": resp["status"], "has_www_authenticate": resp["challenge"],
"note": "synthetic marker only; not an MCP protocol request"}
文件:lab.py
"""B-01 command-line entry point; dependency-free Python 3.11+."""
from __future__ import annotations
import argparse
import json
import os
import sys
from urllib import error
from b01diag import __version__
from b01diag.core import MODES, create_server, diagnose, probe
def emit(obj: dict) -> None:
print(json.dumps(obj, ensure_ascii=False, sort_keys=True), flush=True)
def port_number(value: str, *, allow_zero: bool) -> int:
try:
port = int(value)
except ValueError as exc:
raise argparse.ArgumentTypeError("port must be integer") from exc
if not (0 if allow_zero else 1) <= port <= 65535:
raise argparse.ArgumentTypeError("port outside permitted range")
return port
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Local B-01 HTTP-only diagnostic lab (NOT actual MCP)")
parser.add_argument("--version", action="version", version=__version__)
sub = parser.add_subparsers(dest="command", required=True)
serve = sub.add_parser("serve", help="start a loopback-only teaching fixture")
serve.add_argument("--port", type=lambda x: port_number(x, allow_zero=True), default=0)
serve.add_argument("--mode", choices=MODES, default="healthy")
serve.add_argument("--instance", default="demo-workspace")
doctor = sub.add_parser("doctor", help="read-only local fixture diagnostic")
doctor.add_argument("--port", required=True, type=lambda x: port_number(x, allow_zero=False))
doctor.add_argument("--instance", default="demo-workspace")
doctor.add_argument("--timeout-ms", type=int, default=350)
chk = sub.add_parser("probe", help="observe a synthetic auth/health request")
chk.add_argument("--port", required=True, type=lambda x: port_number(x, allow_zero=False))
chk.add_argument("--path", choices=("/mcp", "/health"), default="/mcp")
chk.add_argument("--auth", choices=("none", "wrong", "demo"), default="none")
chk.add_argument("--timeout-ms", type=int, default=350)
args = parser.parse_args(argv)
if args.command in ("doctor", "probe") and not 1 <= args.timeout_ms <= 5000:
parser.error("--timeout-ms must be 1..5000")
if args.command == "serve":
try:
srv = create_server(port=args.port, mode=args.mode, instance=args.instance)
except OSError as exc:
emit({"event": "bind_error", "result": "PORT_BUSY_OR_UNAVAILABLE",
"port": args.port, "os_errno": exc.errno, "exit_code": 30})
return 30
except ValueError as exc:
parser.error(str(exc))
try:
emit({"event": "listening", "host": "127.0.0.1",
"port": srv.server_address[1], "mode": args.mode,
"instance": args.instance, "pid": os.getpid(),
"fixture": True})
srv.serve_forever(poll_interval=0.05)
except KeyboardInterrupt:
pass
finally:
srv.server_close()
return 0
try:
if args.command == "doctor":
report = diagnose(port=args.port, instance=args.instance, timeout=args.timeout_ms / 1000)
emit(report)
return report["exit_code"]
report = probe(port=args.port, path=args.path, auth=args.auth, timeout=args.timeout_ms / 1000)
emit(report)
return 0 # probe only reports HTTP observations; 401 is not a CLI execution failure
except (error.URLError, TimeoutError, ConnectionError, OSError) as exc:
emit({"event": "request_failed", "result": "TIMEOUT_OR_UNREACHABLE", "exit_code": 31,
"note": "no credential included"})
return 31
if __name__ == "__main__":
sys.exit(main())
核心代码虽然稍长,实际只做了三件事:
serve:启动一个受控的本机 HTTP 服务。通过--mode可以让它故意返回 503、错误 JSON、错误服务身份或延迟响应。probe:分别用无授权、错误授权和演示授权访问接口,看看 HTTP 返回了什么。doctor:先看/health,再看/mcp,最后给出HEALTHY、DEGRADED、TIMEOUT等分类;它只诊断,不自动重启服务。
4.1 用两个 PowerShell 窗口亲手观察 401
窗口 A: 先切换到刚创建的 B01-mcp-demo 目录,然后执行:
py -3 .\lab.py serve --port 0 --mode healthy
--port 0 表示由系统选择一个可用端口。程序会打印 "event": "listening" 和实际的 "port"。窗口 A 保持运行,不要关闭。
窗口 B: 也进入同一个目录,将 $port 替换成窗口 A 显示的端口:
$port = 50000 # 示例值;一定要替换成窗口 A 打印的端口
py -3 .\lab.py doctor --port $port
Write-Host "DOCTOR_EXIT=$LASTEXITCODE"
py -3 .\lab.py probe --port $port --auth none
py -3 .\lab.py probe --port $port --auth wrong
py -3 .\lab.py probe --port $port --auth demo
如果服务按预期运行,doctor 会得到 HEALTHY,三次探测分别对应:
| 请求方式 | 预期 HTTP 状态 | 原因 |
|---|---|---|
none | 401 | 没有提供授权 |
wrong | 401 | 提供了错误的教学授权 |
demo | 200 | 使用程序内置的演示标记 |
这里的 401 正好说明:未授权访问被拒绝,并不意味着服务没有启动。 但也不能反过来说“有 401 就一定健康”;健康是由多项检查共同确定的。
4.2 再试一次端口占用
保持窗口 A 的服务运行,在窗口 B 输入:
py -3 .\lab.py serve --port $port --mode healthy
Write-Host "BIND_EXIT=$LASTEXITCODE"
py -3 .\lab.py doctor --port $port
第二个服务应报告 PORT_BUSY_OR_UNAVAILABLE,退出码为 30;之前已启动的服务应仍能被诊断为 HEALTHY。这才是安全的端口冲突实验:让新进程明确失败,而不是去停止一个来历不明的 PID。
如果要查看 Windows 上具体由哪个进程监听了某个端口,可以只读检查:
Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue |
Select-Object LocalAddress, LocalPort, OwningProcess
4.3 让健康检查故意失败
在窗口 A 按 Ctrl+C 停止你刚刚启动的服务。再运行:
py -3 .\lab.py serve --port 0 --mode degraded
记下新的 port,回到窗口 B:
$port = 50000 # 替换成新端口
py -3 .\lab.py doctor --port $port
Write-Host "DOCTOR_EXIT=$LASTEXITCODE"
这时应得到 DEGRADED、退出码 21。可见服务正在监听,却不等于服务处于健康状态。类似地,把 --mode 换成 foreign、bad-json、auth-bypass 或 slow-health,可以观察不同的故障分类。每次换模式前,先停止你自己启动的上一个演示服务。
五、复制自动化测试代码
手工操作有助于看懂原理,但还不够:如果每次改完代码都要手动启动十几次服务,很容易漏掉边界情况。因此我们再放入一套 unittest 用例,它会自行创建并关闭回环服务,检查鉴权、端口冲突、超时和恢复等行为。
把下面内容保存到 tests/test_b01.py:
文件:tests/test_b01.py
"""Real isolated loopback and subprocess tests; no cloud, tokens, or host files."""
import contextlib
import io
import json
import socket
import subprocess
import sys
import threading
import unittest
from types import SimpleNamespace
from unittest import mock
from urllib import error
from pathlib import Path
from b01diag.core import EXIT_CODES, create_server, diagnose, local_get, probe
LAB = Path(__file__).resolve().parents[1]
class B01Tests(unittest.TestCase):
def start(self, mode="healthy", instance="demo-workspace", port=0):
server = create_server(port=port, mode=mode, instance=instance)
thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True)
thread.start()
self.addCleanup(thread.join, 2)
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
return server
def diag(self, mode="healthy", instance="demo-workspace", timeout=0.35):
server = self.start(mode=mode, instance=instance)
return diagnose(port=server.server_address[1], instance="demo-workspace", timeout=timeout)
def test_loopback_only(self):
server = self.start()
self.assertEqual(server.server_address[0], "127.0.0.1")
def test_healthy_requires_401(self):
report = self.diag()
self.assertEqual(report["result"], "HEALTHY")
self.assertEqual(report["exit_code"], 0)
self.assertEqual(report["checks"]["unauthenticated_mcp_http"], 401)
self.assertTrue(report["checks"]["has_www_authenticate"])
def test_wrong_auth_rejected_with_401(self):
server = self.start()
result = probe(port=server.server_address[1], path="/mcp", auth="wrong", timeout=1)
self.assertEqual(result["http_status"], 401)
self.assertTrue(result["has_www_authenticate"])
self.assertNotIn("B01_INTENTIONALLY_INVALID", json.dumps(result))
def test_missing_auth_rejected_with_401(self):
server = self.start()
self.assertEqual(local_get(server.server_address[1], "/mcp", timeout=1)["status"], 401)
def test_synthetic_auth_allowed_only_as_fixture(self):
server = self.start()
result = probe(port=server.server_address[1], path="/mcp", auth="demo", timeout=1)
self.assertEqual(result["http_status"], 200)
self.assertNotIn("B01_ONLY_FAKE_MARKER", json.dumps(result))
def test_degraded_is_not_healthy(self):
self.assertEqual(self.diag("degraded")["result"], "DEGRADED")
def test_foreign_service_is_not_bridge(self):
self.assertEqual(self.diag("foreign")["result"], "FOREIGN_SERVICE")
def test_bad_health_body_is_not_healthy(self):
self.assertEqual(self.diag("bad-json")["result"], "BAD_HEALTH_RESPONSE")
def test_redirect_is_not_followed(self):
self.assertEqual(self.diag("redirect-health")["result"], "BAD_HEALTH_RESPONSE")
def test_auth_bypass_must_fail_closed(self):
self.assertEqual(self.diag("auth-bypass")["result"], "AUTH_NOT_ENFORCED")
def test_wrong_workspace_instance_is_not_healthy(self):
self.assertEqual(self.diag("healthy", instance="other-workspace")["result"], "WRONG_INSTANCE")
def test_health_timeout_is_not_healthy(self):
self.assertEqual(self.diag("slow-health", timeout=0.05)["result"], "TIMEOUT")
def test_no_listener_is_not_healthy(self):
with socket.socket() as held:
held.bind(("127.0.0.1", 0))
unused_port = held.getsockname()[1]
observation = diagnose(port=unused_port, instance="demo-workspace", timeout=0.2)
# Windows/Winsock may report an actual connect timeout instead of refusal.
# Assert observed transport failure without inventing the OS error type.
self.assertIn(observation["result"], ("UNREACHABLE", "TIMEOUT"))
self.assertFalse(observation["ok"])
self.assertEqual(observation["exit_code"], EXIT_CODES[observation["result"]])
self.assertEqual(observation["checks"]["transport"]["phase"], "health")
def test_port_conflict_does_not_kill_existing_listener(self):
original = self.start()
port = original.server_address[1]
attempt = subprocess.run([sys.executable, str(LAB / "lab.py"), "serve", "--port", str(port)],
cwd=LAB, capture_output=True, text=True, timeout=5)
self.assertEqual(attempt.returncode, 30, attempt.stderr)
self.assertEqual(json.loads(attempt.stdout)["result"], "PORT_BUSY_OR_UNAVAILABLE")
self.assertEqual(diagnose(port=port, instance="demo-workspace")["result"], "HEALTHY")
def test_cli_doctor_reports_real_exit_code(self):
server = self.start(mode="degraded")
attempt = subprocess.run([sys.executable, str(LAB / "lab.py"), "doctor", "--port",
str(server.server_address[1])], cwd=LAB, capture_output=True,
text=True, timeout=5)
self.assertEqual(attempt.returncode, 21, attempt.stderr)
self.assertEqual(json.loads(attempt.stdout)["result"], "DEGRADED")
def test_cli_probe_wrong_auth_exposes_no_auth_value(self):
server = self.start()
attempt = subprocess.run([sys.executable, str(LAB / "lab.py"), "probe", "--port",
str(server.server_address[1]), "--auth", "wrong"],
cwd=LAB, capture_output=True, text=True, timeout=5)
self.assertEqual(attempt.returncode, 0, attempt.stderr)
self.assertEqual(json.loads(attempt.stdout)["http_status"], 401)
self.assertNotIn("Authorization", attempt.stdout)
self.assertNotIn("B01_INTENTIONALLY_INVALID", attempt.stdout)
def test_bad_port_rejected_before_network_use(self):
attempt = subprocess.run([sys.executable, str(LAB / "lab.py"), "doctor", "--port", "70000"],
cwd=LAB, capture_output=True, text=True, timeout=5)
self.assertNotEqual(attempt.returncode, 0)
self.assertIn("port outside permitted range", attempt.stderr)
def test_close_and_recover_with_fresh_port(self):
old = create_server(port=0, mode="healthy", instance="demo-workspace")
port = old.server_address[1]
thread = threading.Thread(target=old.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True)
thread.start()
try:
self.assertEqual(diagnose(port=port, instance="demo-workspace")["result"], "HEALTHY")
finally:
old.shutdown()
old.server_close()
thread.join(2)
offline = diagnose(port=port, instance="demo-workspace")
self.assertIn(offline["result"], ("UNREACHABLE", "TIMEOUT"))
self.assertFalse(offline["ok"])
self.assertEqual(offline["exit_code"], EXIT_CODES[offline["result"]])
self.assertEqual(offline["checks"]["transport"]["phase"], "health")
replacement = self.start(port=0)
self.assertEqual(diagnose(port=replacement.server_address[1], instance="demo-workspace")["result"],
"HEALTHY")
def test_refused_transport_is_unreachable(self):
# Deterministic error-injection: verifies classification independently of OS.
with mock.patch("b01diag.core.local_get", side_effect=error.URLError(ConnectionRefusedError(111, "fake refusal"))):
observation = diagnose(port=10001, instance="demo-workspace")
self.assertEqual(observation["result"], "UNREACHABLE")
self.assertEqual(observation["checks"]["transport"],
{"phase": "health", "exception_type": "ConnectionRefusedError", "errno": 111})
def test_timeout_transport_is_timeout(self):
with mock.patch("b01diag.core.local_get", side_effect=error.URLError(TimeoutError("synthetic secret? timed out"))):
observation = diagnose(port=10001, instance="demo-workspace")
self.assertEqual(observation["result"], "TIMEOUT")
self.assertEqual(observation["exit_code"], EXIT_CODES["TIMEOUT"])
self.assertEqual(observation["checks"]["transport"]["phase"], "health")
self.assertNotIn("synthetic secret", json.dumps(observation))
def test_second_phase_timeout_is_reported(self):
with mock.patch("b01diag.core.local_get", side_effect=[
{"status": 200, "body": {"service": "b01-local-fixture", "schema": 1,
"instance": "demo-workspace", "status": "ok"}},
error.URLError(TimeoutError("timed out")),
]):
observation = diagnose(port=10001, instance="demo-workspace")
self.assertEqual(observation["result"], "TIMEOUT")
self.assertEqual(observation["checks"]["transport"]["phase"], "mcp")
self.assertEqual(observation["checks"]["health_http"], 200)
def test_client_abort_during_send_json_is_expected(self):
server = create_server(port=0, mode="healthy", instance="demo-workspace")
self.addCleanup(server.server_close)
class AbortedWriter:
def write(self, unused):
raise ConnectionAbortedError(10053, "synthetic Windows client abort")
dummy = SimpleNamespace(send_response=lambda *_: None, send_header=lambda *_: None,
end_headers=lambda: None, wfile=AbortedWriter())
server.RequestHandlerClass.send_json(dummy, 200, {"ok": True})
def test_client_abort_during_bad_json_is_expected(self):
server = create_server(port=0, mode="bad-json", instance="demo-workspace")
self.addCleanup(server.server_close)
class AbortedWriter:
def write(self, unused):
raise ConnectionAbortedError(10053, "synthetic Windows client abort")
dummy = SimpleNamespace(path="/health", send_response=lambda *_: None,
send_header=lambda *_: None, end_headers=lambda: None,
wfile=AbortedWriter())
server.RequestHandlerClass.do_GET(dummy)
if __name__ == "__main__":
unittest.main()
在实验目录的根目录运行:
$ErrorActionPreference = 'Stop'
py -3 -m unittest discover -s tests -v
if ($LASTEXITCODE -ne 0) { throw '自动化测试失败' }
正常情况下,控制台最后会出现 Ran 23 tests ... 和 OK。这 23 项测试是真实执行本机回环 HTTP 与子进程的测试,并包含少量用于精确验证异常分类的模拟注入;并非真实 MCP Bridge 的生产集成测试。只有你自己的测试运行成功,才应将本次测试记为通过。
六、自动记录 12 个故障场景
单测能告诉我们“断言有没有通过”,但如果想看每种故障实际返回了什么,还需要一份结果记录。下面的收集器会生成 JSON,逐项写入场景名称、命令退出码、观察结果和是否符合预期。
把下面内容保存到 scripts/collect_evidence.py:
文件:scripts/collect_evidence.py
"""Run actual B-01 loopback checks and optionally save a NON-OVERWRITING JSON report."""
from __future__ import annotations
import argparse
import contextlib
from datetime import datetime, timezone
import hashlib
import json
import platform
from pathlib import Path
import subprocess
import sys
import threading
LAB = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(LAB))
from b01diag import __version__ # noqa: E402
from b01diag.core import create_server, EXIT_CODES # noqa: E402
@contextlib.contextmanager
def fixture(mode="healthy", port=0, instance="demo-workspace"):
srv = create_server(mode=mode, port=port, instance=instance)
thread = threading.Thread(target=srv.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True)
thread.start()
try:
yield srv.server_address[1]
finally:
srv.shutdown()
srv.server_close()
thread.join(timeout=2)
def invoke(*args):
command = [sys.executable, str(LAB / "lab.py"), *map(str, args)]
response = subprocess.run(command, capture_output=True, text=True, timeout=8, cwd=str(LAB))
try:
parsed = json.loads(response.stdout)
except json.JSONDecodeError:
parsed = {"parse_error": True}
return {"command": "python lab.py " + " ".join(map(str, args)),
"exit_code": response.returncode, "json": parsed,
"stderr_present": bool(response.stderr)}
def main():
p = argparse.ArgumentParser()
p.add_argument("--output", type=Path, help="optional JSON path; parent must exist; no overwrite")
args = p.parse_args()
if args.output is not None and (args.output.exists() or not args.output.parent.is_dir()):
p.error("output already exists or parent directory is missing")
entries = []
for mode, expected in (
("healthy", "HEALTHY"), ("degraded", "DEGRADED"),
("foreign", "FOREIGN_SERVICE"), ("bad-json", "BAD_HEALTH_RESPONSE"),
("auth-bypass", "AUTH_NOT_ENFORCED"), ("redirect-health", "BAD_HEALTH_RESPONSE"),
("slow-health", "TIMEOUT"),
):
with fixture(mode) as port:
observation = invoke("doctor", "--port", port,
"--timeout-ms", 50 if mode == "slow-health" else 350)
actual = observation["json"].get("result")
observation.update({"scenario": mode, "expected": expected,
"verdict": "PASS" if (actual == expected and
observation["exit_code"] == EXIT_CODES[expected]) else "FAIL"})
entries.append(observation)
with fixture() as port:
for auth, expected_http in (("none", 401), ("wrong", 401), ("demo", 200)):
observation = invoke("probe", "--port", port, "--auth", auth)
observation.update({"scenario": "auth-" + auth, "expected_http": expected_http,
"verdict": "PASS" if observation["exit_code"] == 0 and
observation["json"].get("http_status") == expected_http else "FAIL"})
entries.append(observation)
conflict = invoke("serve", "--port", port)
alive = invoke("doctor", "--port", port)
conflict.update({"scenario": "same-port-second-listener", "expected": "PORT_BUSY_OR_UNAVAILABLE",
"original_still_healthy": alive["json"].get("result") == "HEALTHY",
"verdict": "PASS" if conflict["exit_code"] == 30 and
conflict["json"].get("result") == "PORT_BUSY_OR_UNAVAILABLE" and
alive["json"].get("result") == "HEALTHY" else "FAIL"})
entries.append(conflict)
# Only the fixture created in this program is stopped; no external PID is touched.
server = create_server(mode="healthy", port=0, instance="demo-workspace")
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True)
thread.start()
before = invoke("doctor", "--port", port)
server.shutdown()
server.server_close()
thread.join(timeout=2)
offline = invoke("doctor", "--port", port)
with fixture(port=0) as recovered_port:
after = invoke("doctor", "--port", recovered_port)
# The OS can report connection refused OR an actual TCP timeout after close.
# Both are nonhealthy; do not erase the original network observation.
offline_result = offline["json"].get("result")
offline_transport = offline["json"].get("checks", {}).get("transport", {})
offline_valid = (offline_result in ("UNREACHABLE", "TIMEOUT")
and offline["json"].get("ok") is False
and offline["exit_code"] == EXIT_CODES.get(offline_result)
and offline_transport.get("phase") == "health")
before_valid = (before["json"].get("result") == "HEALTHY" and before["exit_code"] == 0)
after_valid = (after["json"].get("result") == "HEALTHY" and after["exit_code"] == 0)
entries.append({"scenario": "stop-and-restart-owned-fixture",
"expected": {"before": "HEALTHY", "while_stopped": ["UNREACHABLE", "TIMEOUT"],
"after": "HEALTHY", "offline_ok": False},
"observed": [before["json"].get("result"), offline_result, after["json"].get("result")],
"observed_exit_codes": [before["exit_code"], offline["exit_code"], after["exit_code"]],
"offline_transport": offline_transport,
"verdict": "PASS" if before_valid and offline_valid and after_valid else "FAIL"})
source_sha256 = hashlib.sha256((LAB / "lab.py").read_bytes()).hexdigest()
report = {"lab": "B01", "fixture_version": __version__,
"scope": "LOCAL_SIMULATION_ONLY", "real_mcp": False,
"real_authentication": False, "tunnel": False,
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
"platform": platform.platform(), "python": sys.version.splitlines()[0],
"python_executable": sys.executable,
"lab_entry_sha256": source_sha256,
"scenarios": entries,
"summary": {"total": len(entries), "passed": sum(x["verdict"] == "PASS" for x in entries),
"failed": sum(x["verdict"] != "PASS" for x in entries)},
"status": "PASS" if all(x["verdict"] == "PASS" for x in entries) else "FAIL"}
payload = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
if args.output is not None:
try:
with args.output.open("x", encoding="utf-8") as output:
output.write(payload)
except FileExistsError:
print("Output already exists; refusing overwrite", file=sys.stderr)
return 2
print(payload)
return 0 if report["status"] == "PASS" else 1
if __name__ == "__main__":
raise SystemExit(main())
然后执行:
$ErrorActionPreference = 'Stop'
$out = Join-Path (Get-Location).Path ('reports\B01-' + (Get-Date -Format 'yyyyMMdd-HHmmss-fff') + '.json')
py -3 .\scripts\collect_evidence.py --output $out
if ($LASTEXITCODE -ne 0) { throw '故障场景验证失败' }
$report = Get-Content -LiteralPath $out -Raw -Encoding UTF8 | ConvertFrom-Json
$report.summary | Format-List
Write-Host "STATUS=$($report.status)"
Write-Host "REPORT=$out"
收集器共覆盖 12 个场景:正常、降级、其他服务、错误 JSON、鉴权绕过、重定向、慢响应,无授权/错误授权/教学授权,端口冲突,以及服务停止后的恢复。都符合预期时,结果应包含:
{
"summary": {
"total": 12,
"passed": 12,
"failed": 0
},
"status": "PASS"
}
这是便于阅读的关键字段示例,不是原始 JSON 的全部字段。场景本身有意制造“失败的服务”,因此这里的 PASS 指程序正确发现了故障,不代表所有服务都处于健康状态。
七、Windows 上的一个实用经验:超时不等于连接拒绝
在 Windows 上,服务关闭后继续请求原端口,可能出现 TIMEOUT,也可能得到 UNREACHABLE。两者都说明这次健康检查没有成功,但底层的传输结果并不相同。
如果把测试写成“关闭服务后必须等于 UNREACHABLE”,就容易在不同操作系统或网络栈行为下误判。更合理的检查是:只接受明确的非健康结果、核对非零退出码,并保留异常发生在 health 还是 mcp 阶段。
如果客户端在超时后主动断开,服务端写回响应时还可能遇到 ConnectionAbortedError。所以示例只对响应写入时的预期断连做了有限处理,而不是忽略所有异常。
八、真实排障时再记住三件事
第一,先确认接口规范。 本文的 /health 和 /mcp 是用于练习的路径;实际项目可能采用不同的监听方式、认证流程和诊断工具,不能直接用这套判断器去验证真实服务。
第二,别看到端口被占用就结束进程。 先确认监听地址、PID、进程用途,再决定该调整端口还是停止自己负责的服务。
第三,区分只读检查和自动修复。 本文的 lab.py doctor 只读取状态;某些项目提供的 Doctor 命令可能执行重启或修复,使用前需要确认对应版本的行为。
如果想进一步了解源码层面的 Bridge 与 Doctor,可以结合阅读:
- MCP Bridge 源码与工具边界(Codex With ChatGPT源码学习 第 4 章)
- CLI、Daemon 与 Doctor 工作机制(Codex With ChatGPT源码学习 第 8 章)
结语
当 MCP Bridge 报 401,先别急着重启。按监听端口 → 服务身份 → 健康状态 → 认证响应的顺序查,通常能更快明确问题属于哪一层。对于无法确定归属的进程,先确认身份再操作;对于实际超时或网络拒绝,保留原始观测,不要把错误类型硬凑成自己想看的结果。
321




被折叠的 条评论
为什么被折叠?



