蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 MCP JSON-RPC 2.0 initialize、notifications/initialized、tools/list/call 与 resources/read 往返

PYTHONWindows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。explore-mcp-protocol.py
explore-mcp-protocol.py270 行
"""Offline network protocol verification lab for Chapter 29 (mcp-protocol)."""
import json

VERSION = "CPython 3.12.14 offline network protocol frame & state-machine verifier"


class OfflineMCPServer:
    """In-memory deterministic JSON-RPC 2.0 MCP server for offline protocol verification."""

    def __init__(self):
        self.state = "UNINITIALIZED"
        self.tools = {
            "calc_sum": {
                "description": "Compute deterministic integer sum",
                "inputSchema": {"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}},
            }
        }
        self.resources = {
            "docs://protocols/mcp": "MCP standardizes LLM host-client-server context integration over JSON-RPC 2.0."
        }
        self.notifications_log = []

    def handle_json(self, raw: str) -> str | None:
        msg = json.loads(raw)
        if msg.get("jsonrpc") != "2.0" or "method" not in msg:
            return json.dumps(
                {"jsonrpc": "2.0", "id": msg.get("id"), "error": {"code": -32600, "message": "Invalid Request"}}
            )

        method = msg["method"]
        params = msg.get("params", {})

        # Notification: no "id" field -> one-way, must NOT emit a response
        if "id" not in msg:
            self.notifications_log.append((method, params))
            if method == "notifications/initialized" and self.state == "INITIALIZING":
                self.state = "READY"
            return None

        req_id = msg["id"]
        if method == "initialize":
            self.state = "INITIALIZING"
            result = {
                "protocolVersion": params.get("protocolVersion", "2025-03-26"),
                "capabilities": {"tools": {}, "resources": {}},
                "serverInfo": {"name": "mbsky-offline-mcp", "version": "1.0.0"},
            }
            return json.dumps({"jsonrpc": "2.0", "id": req_id, "result": result})

        if self.state != "READY":
            return json.dumps(
                {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32002, "message": "Server not initialized"}}
            )

        if method == "tools/list":
            items = [{"name": k, **v} for k, v in self.tools.items()]
            return json.dumps({"jsonrpc": "2.0", "id": req_id, "result": {"tools": items}})

        if method == "tools/call":
            name = params.get("name")
            args = params.get("arguments", {})
            if name == "calc_sum":
                total = args["a"] + args["b"]
                return json.dumps(
                    {
                        "jsonrpc": "2.0",
                        "id": req_id,
                        "result": {"content": [{"type": "text", "text": str(total)}], "isError": False},
                    }
                )
            return json.dumps(
                {
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "error": {"code": -32602, "message": f"Unknown tool: {name}", "data": {"tool": name}},
                }
            )

        if method == "resources/read":
            uri = params.get("uri")
            if uri in self.resources:
                return json.dumps(
                    {
                        "jsonrpc": "2.0",
                        "id": req_id,
                        "result": {"contents": [{"uri": uri, "mimeType": "text/plain", "text": self.resources[uri]}]},
                    }
                )
            return json.dumps(
                {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32002, "message": "Resource not found"}}
            )

        return json.dumps(
            {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}}
        )


def case_mcp_initialize_and_capabilities_request():
    srv = OfflineMCPServer()
    req = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {"protocolVersion": "2025-03-26", "clientInfo": {"name": "mbsky-client", "version": "1.0"}},
    }
    resp = json.loads(srv.handle_json(json.dumps(req)))
    expected = {
        "jsonrpc": "2.0",
        "id_matched": True,
        "has_result_only": True,
        "protocol_version": "2025-03-26",
        "capabilities": ["resources", "tools"],
        "state_before_initialized_notif": "INITIALIZING",
    }
    actual = {
        "jsonrpc": resp["jsonrpc"],
        "id_matched": resp["id"] == req["id"],
        "has_result_only": ("result" in resp) and ("error" not in resp),
        "protocol_version": resp["result"]["protocolVersion"],
        "capabilities": sorted(resp["result"]["capabilities"].keys()),
        "state_before_initialized_notif": srv.state,
    }
    return {
        "name": "mcp_initialize_and_capabilities_request",
        "summary": "校验 MCP JSON-RPC 2.0 initialize 请求消息字段(jsonrpc/id/method/params)与能力协商响应",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_mcp_tools_list_and_call_response():
    srv = OfflineMCPServer()
    srv.handle_json(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}))
    srv.handle_json(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}))

    list_resp = json.loads(srv.handle_json(json.dumps({"jsonrpc": "2.0", "id": "req-list", "method": "tools/list"})))
    call_ok = json.loads(
        srv.handle_json(
            json.dumps(
                {
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "tools/call",
                    "params": {"name": "calc_sum", "arguments": {"a": 17, "b": 25}},
                }
            )
        )
    )
    call_err = json.loads(
        srv.handle_json(
            json.dumps(
                {
                    "jsonrpc": "2.0",
                    "id": 3,
                    "method": "tools/call",
                    "params": {"name": "missing_tool", "arguments": {}},
                }
            )
        )
    )

    expected = {
        "listed_tools": ["calc_sum"],
        "call_result_text": "42",
        "ok_result_error_exclusive": True,
        "err_code": -32602,
        "err_has_message_and_data": True,
        "err_result_error_exclusive": True,
    }
    actual = {
        "listed_tools": [t["name"] for t in list_resp["result"]["tools"]],
        "call_result_text": call_ok["result"]["content"][0]["text"],
        "ok_result_error_exclusive": ("result" in call_ok) and ("error" not in call_ok),
        "err_code": call_err["error"]["code"],
        "err_has_message_and_data": bool(call_err["error"].get("message")) and ("data" in call_err["error"]),
        "err_result_error_exclusive": ("error" in call_err) and ("result" not in call_err),
    }
    return {
        "name": "mcp_tools_list_and_call_response",
        "summary": "验证 MCP tools/list 与 tools/call 正常响应(result)及未知工具错误响应(error.code/message/data)互斥规范",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_mcp_notifications_and_resources_read():
    srv = OfflineMCPServer()
    srv.handle_json(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}))
    # Notification must omit "id" and receive no response
    notif = {"jsonrpc": "2.0", "method": "notifications/initialized", "params": {"client": "ide-host"}}
    notif_reply = srv.handle_json(json.dumps(notif))

    read_resp = json.loads(
        srv.handle_json(
            json.dumps(
                {
                    "jsonrpc": "2.0",
                    "id": 4,
                    "method": "resources/read",
                    "params": {"uri": "docs://protocols/mcp"},
                }
            )
        )
    )
    expected = {
        "notif_has_no_id": True,
        "notif_returns_none": True,
        "server_state_ready": True,
        "resource_uri": "docs://protocols/mcp",
        "resource_mentions_jsonrpc": True,
    }
    actual = {
        "notif_has_no_id": "id" not in notif,
        "notif_returns_none": notif_reply is None,
        "server_state_ready": srv.state == "READY",
        "resource_uri": read_resp["result"]["contents"][0]["uri"],
        "resource_mentions_jsonrpc": "JSON-RPC 2.0" in read_resp["result"]["contents"][0]["text"],
    }
    return {
        "name": "mcp_notifications_and_resources_read",
        "summary": "验证 MCP 单向通知消息(无 id 且无应答)完成初始化后执行 resources/read 资源上下文拉取",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_mcp_architecture_and_transport_lifecycle():
    arch = {
        "components": ["Host", "Client", "Server", "Base Protocol"],
        "transports": ["Stdio", "HTTP/SSE"],
        "lifecycle": ["Initialization", "Operation", "Shutdown"],
        "client_server_cardinality": "1:1",
    }
    expected = {
        "component_count": 4,
        "supports_stdio_and_sse": True,
        "lifecycle_stages": ["Initialization", "Operation", "Shutdown"],
        "client_server_cardinality": "1:1",
    }
    actual = {
        "component_count": len(arch["components"]),
        "supports_stdio_and_sse": set(arch["transports"]) == {"Stdio", "HTTP/SSE"},
        "lifecycle_stages": arch["lifecycle"],
        "client_server_cardinality": arch["client_server_cardinality"],
    }
    return {
        "name": "mcp_architecture_and_transport_lifecycle",
        "summary": "核对 MCP 四大架构组件(Host/Client/Server/Base Protocol)、Stdio/SSE 传输与三阶段生命周期",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_mcp_initialize_and_capabilities_request(),
        case_mcp_tools_list_and_call_response(),
        case_mcp_notifications_and_resources_read(),
        case_mcp_architecture_and_transport_lifecycle(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。

入口文件:projects/np-mcp-protocol-lab/explore-mcp-protocol.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-mcp-protocol.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:网络协议

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a2722.zip

下载课程关联工程包:网络协议

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2733.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习