"""Author an editable whole-slide threshold graph via actual stdio MCP.

Run with an SDK environment containing the MCP extra and explicitly approved
OpenCV pack metadata. No installation, WSI access or execution is requested.
"""
import argparse
import asyncio
import json
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main(args):
    server = StdioServerParameters(command="microscope", args=["mcp", "--root", args.root, "--runtime-root", args.runtime_root])
    async with stdio_client(server) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            async def call(name, values):
                result = await session.call_tool(name, values)
                if result.isError: raise RuntimeError(result.content[0].text)
                return result.structuredContent or json.loads(result.content[0].text)
            cat = await call("discover_workflow_nodes", {})
            available = {n["id"] for n in cat["nodes"]}
            if not {"microscope_opencv.grayscale", "microscope_opencv.threshold"} <= available:
                raise RuntimeError("Explicitly install/register the OpenCV pack first; this example never installs code")
            graph = await call("create_workflow", {"name": "Agent-authored whole-slide threshold"})
            operations = [
                {"action": "add_node", "id": "wsi", "type": "microscope.source", "parameters": {"scope": "whole_slide", "mpp": 0.5}},
                {"action": "add_node", "id": "gray", "type": "microscope_opencv.grayscale"},
                {"action": "add_node", "id": "mask", "type": "microscope_opencv.threshold", "parameters": {"threshold": 160, "otsu": False}},
                {"action": "connect", "source": "wsi", "source_port": "image", "target": "gray", "target_port": "image"},
                {"action": "connect", "source": "gray", "source_port": "gray", "target": "mask", "target_port": "gray"},
            ]
            graph = await call("edit_workflow", {"workflow": graph, "operations": operations})
            validation = await call("validate_workflow", {"workflow": graph, "tiled": True})
            if not validation["valid"]: raise RuntimeError(validation)
            saved = await call("save_workflow", {"path": args.output, "workflow": graph})
            print(json.dumps(saved, indent=2))
            print("Import this JSON in the viewer, pair Python, review settings, then click Run. No pixels were accessed here.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", required=True)
    parser.add_argument("--runtime-root", required=True)
    parser.add_argument("--output", default="agent-threshold.workflow.json")
    asyncio.run(main(parser.parse_args()))
