mcp_tools_probe.py

scripts/mcp_tools_probe.py

WHAT THE SERVER ACTUALLY SERVES, asked over real MCP stdio rather than by import.

main

int mcp_tools_probe.main()

Report the tool list for every way this package can be started.

scripts/mcp_tools_probe.py:124

Source · 23 lines
def main() -> int:
    """@brief Compare the served tool set across entry points.
    @return 0 when they agree, 1 otherwise.
    @version 1
    """
    venv_script = REPO / ".venv" / "bin" / "clew-mcp"
    console = str(venv_script) if venv_script.exists() else "clew-mcp"
    spellings = {
        "console script": [console],
        "-m clew.mcp_server.server": [sys.executable, "-m", "clew.mcp_server.server"],
        "-m clew.mcp_server": [sys.executable, "-m", "clew.mcp_server"],
    }
    results = {label: served_tools(cmd, cwd=REPO) for label, cmd in spellings.items()}
    for label, tools in results.items():
        print(f"{label:<28} tools={len(tools):<3} {tools}")
    distinct = {tuple(t) for t in results.values()}
    if len(distinct) != 1:
        print("\nDISAGREEMENT: these spellings do not serve the same tools (gh#14).")
        return 1
    print("\nevery entry point serves the same tools")
    return 0

Activity · 12 steps
lines 129–129venv_script = REPO / ".venv" / "bin" / "clew-mcp"lines 130–130console = str(venv_script) if venv_script.exists() else "clew-mcp"lines 131–135spellings = { "console script": [console], "-m clew.mcp_server.server": [sys.executable, "-m", "clew.mcp_server.server"], "-m clew.mcp_server": [sys.executable, "-m", "clew.mcp_server"], }lines 136–136results = {label: served_tools(cmd, cwd=REPO) for label, cmd in spellings.items()}lines 137–137◇ for label, tools in results.items()lines 138–138print(f"{label:<28} tools={len(tools):<3} {tools}")lines 139–139distinct = {tuple(t) for t in results.values()}lines 140–140◇ if len(distinct) != 1lines 141–141print("\nDISAGREEMENT: these spellings do not serve the same tools (gh#14).")lines 142–142return 1lines 143–143print("\nevery entry point serves the same tools")lines 144–144return 0

Flows

served_tools

list[str] mcp_tools_probe.served_tools(list[str] cmd, Path|str|None cwd=None)

Ask one server command for its tool list over stdio.

scripts/mcp_tools_probe.py:45

Show on the map →

Called by main, test_every_entry_point_serves_the_same_tools

Calls none

Source · 76 lines
def served_tools(cmd: list[str], cwd: Path | str | None = None) -> list[str]:
    """Returns [] for BOTH "answered with no tools" and "never answered", deliberately:
    from a client's seat those are the same outcome, and gh#14's whole point is that the
    second was indistinguishable from the first. A caller wanting to tell them apart
    should compare against a known-good command, which is what the tests do.

    @brief The tool names a server command serves.
    @return Sorted names, or [].
    @version 1
    """
    proc = subprocess.Popen(
        cmd,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        cwd=str(cwd) if cwd else None,
    )
    handshake = [
        {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "2024-11-05",
                "capabilities": {},
                "clientInfo": {"name": "mcp_tools_probe", "version": "1"},
            },
        },
        {"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}},
        {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}},
    ]
    ## Read on a thread, because `readline` on a pipe blocks and a server that never answers
    ## — gh#14's exact shape — would otherwise hang the caller instead of reporting nothing.
    replies: queue.Queue = queue.Queue()

    def _drain() -> None:
        for line in proc.stdout:
            replies.put(line)

    reader = threading.Thread(target=_drain, daemon=True)
    reader.start()
    try:
        for message in handshake:
            proc.stdin.write(json.dumps(message) + "\n")
            proc.stdin.flush()
    except (BrokenPipeError, OSError):
        ## The server exited before the handshake finished — gh#14's shape exactly.
        pass

    tools: list[str] = []
    deadline = time.monotonic() + _DEADLINE_SECONDS
    while time.monotonic() < deadline:
        try:
            line = replies.get(timeout=0.2)
        except queue.Empty:
            if proc.poll() is not None and replies.empty():
                break
            continue
        try:
            payload = json.loads(line)
        except (ValueError, TypeError):
            continue
        if payload.get("id") == 2 and "result" in payload:
            tools = sorted(t["name"] for t in payload["result"].get("tools", []))
            break

    proc.terminate()
    try:
        proc.communicate(timeout=15)
    except subprocess.TimeoutExpired:
        proc.kill()
        proc.communicate()
    return tools

Activity · 35 steps
lines 55–62proc = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd=str(cwd) if cwd else None, )lines 63–76handshake = [ { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "mcp_tools_probe", "version": "1"}, }, }, {"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}}, {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}, ]lines 79–79replies: queue.Queue = queue.Queue()lines 81–83def _drain() -> None: for line in proc.stdout: replies.put(line)lines 85–85reader = threading.Thread(target=_drain, daemon=True)lines 86–86reader.start()lines 87–87trylines 88–88◇ for message in handshakelines 89–89proc.stdin.write(json.dumps(message) + "\n")lines 90–90proc.stdin.flush()lines 91–91except (BrokenPipeError, OSError)lines 93–93passlines 95–95tools: list[str] = []lines 96–96deadline = time.monotonic() + _DEADLINE_SECONDSlines 97–97◇ while time.monotonic() < deadlinelines 98–98trylines 99–99line = replies.get(timeout=0.2)lines 100–100except queue.Emptylines 101–101◇ if proc.poll() is not None and replies.empty()lines 102–102breaklines 103–103continuelines 104–104trylines 105–105payload = json.loads(line)lines 106–106except (ValueError, TypeError)lines 107–107continuelines 108–108◇ if payload.get("id") == 2 and "result" in payloadlines 109–109tools = sorted(t["name"] for t in payload["result"].get("tools", []))lines 110–110breaklines 112–112proc.terminate()lines 113–113trylines 114–114proc.communicate(timeout=15)lines 115–115except subprocess.TimeoutExpiredlines 116–116proc.kill()lines 117–117proc.communicate()lines 118–118return tools

Flows