import json
import subprocess
import sys
import time

def send(proc, payload):
    proc.stdin.write((json.dumps(payload) + "\n").encode("utf-8"))
    proc.stdin.flush()

def read_line(proc, timeout=10.0):
    start = time.time()
    while time.time() - start < timeout:
        line = proc.stdout.readline()
        if line:
            return line.decode("utf-8", errors="replace").strip()
        time.sleep(0.05)
    return ""

def main():
    proc = subprocess.Popen(
        ["python3", "scripts/run-gitea-mcp.py"],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    try:
        send(proc, {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "2024-11-05",
                "capabilities": {},
                "clientInfo": {"name": "test", "version": "1.0.0"},
            },
        })
        init_resp = read_line(proc)
        send(proc, {
            "jsonrpc": "2.0",
            "id": 2,
            "method": "tools/list",
            "params": {}
        })
        tools_resp = read_line(proc)
        print(tools_resp)
    finally:
        proc.terminate()

if __name__ == "__main__":
    main()
