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

在本机调用天气样本和待办工具

PYTHONPython 3.10+ 与 Node.js 20+,实际子进程和标准输入输出。mcp_lab.py
mcp_lab.py65 行
"""Exercise two local MCP subprocesses using newline-delimited JSON-RPC."""
import json
from pathlib import Path
import shutil
import subprocess
import sys


BASE = Path(__file__).resolve().parent
VERSION = "2025-11-25"
HELLO = {"protocolVersion": VERSION, "capabilities": {}, "clientInfo": {"name": "mbsky-lab", "version": "1.0"}}


def rpc(method, **params):
    return {"method": method, "params": params}


def request_tool(name, **arguments):
    return rpc("tools/call", name=name, arguments=arguments)


def session(command, actions):
    wire = [{"jsonrpc": "2.0", **rpc("initialize", **HELLO), "id": 1},
            {"jsonrpc": "2.0", **rpc("notifications/initialized")}]
    wire.extend({"jsonrpc": "2.0", "id": index, **action}
                for index, action in enumerate(actions, 2))
    completed = subprocess.run(command, cwd=BASE, input="".join(json.dumps(row) + "\n" for row in wire),
                               capture_output=True, encoding="utf-8", timeout=10, check=True)
    if completed.stderr:
        raise ValueError(completed.stderr)
    received = [json.loads(line) for line in completed.stdout.splitlines()]
    assert [reply["id"] for reply in received] == [1, *range(2, len(wire))]
    assert all(reply["jsonrpc"] == "2.0" for reply in received)
    assert received[0]["result"]["protocolVersion"] == VERSION
    return {"initialize": received[0]["result"],
            "events": [{"request": action, "response": reply} for action, reply in zip(actions, received[1:], strict=True)]}


def main():
    node = shutil.which("node")
    if not node:
        raise SystemExit("This exercise needs Node.js on PATH")
    python_server = [sys.executable, "-I", str(BASE / "weather_server.py")]
    todo_server = [node, str(BASE / "todo_server.mjs")]
    weather = session(python_server, [
        rpc("tools/list"), rpc("resources/list"), rpc("resources/read", uri="weather://samples/cities"),
        request_tool("sample_weather", city=" Beijing "), request_tool("sample_weather", city="Oslo"),
        request_tool("sample_weather", city=4), rpc("unknown"),
    ])
    todo = session(todo_server, [
        rpc("tools/list"), request_tool("list_tasks"), request_tool("add_task", item="准备习题"),
        request_tool("add_task", item="核对结果"), request_tool("list_tasks"),
        request_tool("add_task", item=" "), request_tool("list_tasks"),
    ])
    fresh = session(todo_server, [request_tool("list_tasks")])
    versions = {
        "python": sys.version,
        "node": subprocess.run([node, "--version"], text=True, capture_output=True, check=True, timeout=5).stdout.strip(),
    }
    print(json.dumps({"versions": versions, "weather": weather, "todo": todo, "fresh": fresh}, indent=2))


if __name__ == "__main__":
    main()
本例需在 Python 3.10+ 与 Node.js 20+,实际子进程和标准输入输出。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Python 3.10+ 与 Node.js 20+,实际子进程和标准输入输出。

入口文件:projects/vibe-coding-mcp/mcp_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 mcp_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Python 3.10+ 与 Node.js 20+,实际子进程和标准输入输出。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Vibe Coding

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

下载课程关联工程包:Vibe Coding

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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