|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Send drafts to Codebasic TTS through its signed MCP helper, over pipes. |
| 3 | +
|
| 4 | +A pseudo-terminal must not sit between an agent and the helper: its line |
| 5 | +discipline cuts long lines and swallows bytes, so a long Korean script never |
| 6 | +arrives whole and no reply comes back. This client talks to the helper over |
| 7 | +plain pipes, one complete UTF-8 JSON-RPC frame per request, and reports every |
| 8 | +send as exactly one of: |
| 9 | +
|
| 10 | + confirmed the app answered this request: accepted, or duplicate |
| 11 | + rejected the app, the helper or this client refused it; nothing was opened |
| 12 | + unconfirmed no matching answer arrived; whether it was received is unknown |
| 13 | +
|
| 14 | +An unconfirmed send is never repeated automatically. `retry()` repeats it once |
| 15 | +on the same connection, with the same key and bytes and a new request id. |
| 16 | +Diagnostics hold states and byte counts only, never the draft text. |
| 17 | +
|
| 18 | + tts_mcp_client.py --helper PATH status |
| 19 | + tts_mcp_client.py --helper PATH send --key K --display-file F [--speech-file F] |
| 20 | +""" |
| 21 | +import argparse |
| 22 | +import json |
| 23 | +import os |
| 24 | +import select |
| 25 | +import subprocess |
| 26 | +import sys |
| 27 | +import time |
| 28 | + |
| 29 | +TEXT_LIMIT = 8192 # UTF-8 bytes per text field, agreed with the app |
| 30 | +FRAME_LIMIT = 100 * 1024 # UTF-8 bytes of one whole request frame, newline included |
| 31 | +CONFIRMED = {"accepted", "duplicate"} |
| 32 | + |
| 33 | + |
| 34 | +class Session: |
| 35 | + """One live helper process. Keep it open across turns; closing it is harmless.""" |
| 36 | + |
| 37 | + def __init__(self, helper, client=None, name="tts-mcp-client", launcher=None, **popen): |
| 38 | + command = list(launcher or []) + [helper] + (["--client", client] if client else []) |
| 39 | + # Binary pipes: no terminal, no echo, no line-length limit, no translation. |
| 40 | + self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 41 | + stderr=subprocess.DEVNULL, bufsize=0, **popen) |
| 42 | + self.next_id = 0 |
| 43 | + self.buffer = b"" |
| 44 | + self.limits = {"text_bytes": TEXT_LIMIT, "frame_bytes": FRAME_LIMIT} |
| 45 | + self.last = None |
| 46 | + reply = self._request("initialize", {"protocolVersion": "2025-11-25", "capabilities": {}, |
| 47 | + "clientInfo": {"name": name, "version": "1"}})[1] |
| 48 | + if reply is None or "result" not in reply: |
| 49 | + raise RuntimeError("helper did not initialize") |
| 50 | + self.server = reply["result"]["serverInfo"]["name"] |
| 51 | + self._write(self._frame({"jsonrpc": "2.0", "method": "notifications/initialized"})) |
| 52 | + |
| 53 | + @staticmethod |
| 54 | + def _frame(message): |
| 55 | + # json.dumps escapes every newline inside strings; the only raw LF ends the frame. |
| 56 | + return json.dumps(message, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n" |
| 57 | + |
| 58 | + def _write(self, frame): |
| 59 | + view = memoryview(frame) |
| 60 | + while view: # a short write is continued on this connection only |
| 61 | + view = view[os.write(self.proc.stdin.fileno(), view):] |
| 62 | + |
| 63 | + def _read(self, request_id, timeout): |
| 64 | + deadline = time.monotonic() + timeout |
| 65 | + while True: |
| 66 | + while b"\n" in self.buffer: |
| 67 | + line, self.buffer = self.buffer.split(b"\n", 1) |
| 68 | + try: |
| 69 | + message = json.loads(line) |
| 70 | + except ValueError: |
| 71 | + continue |
| 72 | + if message.get("id") == request_id: |
| 73 | + return message |
| 74 | + remaining = deadline - time.monotonic() |
| 75 | + if remaining <= 0 or not select.select([self.proc.stdout], [], [], remaining)[0]: |
| 76 | + return None |
| 77 | + chunk = os.read(self.proc.stdout.fileno(), 65536) |
| 78 | + if not chunk: |
| 79 | + return None |
| 80 | + self.buffer += chunk |
| 81 | + |
| 82 | + def _request(self, method, params, timeout=8.0, discard_reply=False): |
| 83 | + self.next_id += 1 |
| 84 | + frame = self._frame({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params}) |
| 85 | + if len(frame) > self.limits["frame_bytes"]: |
| 86 | + return len(frame), {"local": "frame_too_large"} |
| 87 | + try: |
| 88 | + self._write(frame) |
| 89 | + except OSError: |
| 90 | + return len(frame), None |
| 91 | + reply = self._read(self.next_id, timeout) |
| 92 | + return len(frame), (None if discard_reply else reply) |
| 93 | + |
| 94 | + def call(self, tool, arguments=None, **options): |
| 95 | + size, reply = self._request("tools/call", {"name": tool, "arguments": arguments or {}}, **options) |
| 96 | + return size, reply |
| 97 | + |
| 98 | + def status(self): |
| 99 | + reply = self.call("tts_agent_status")[1] |
| 100 | + content = (reply or {}).get("result", {}).get("structuredContent", {}) |
| 101 | + self.limits.update(content.get("limits", {})) |
| 102 | + return content.get("status", "unconfirmed") |
| 103 | + |
| 104 | + def read_instruction(self): |
| 105 | + """Returns the selected saved instruction (profile, revision, instructions) or None.""" |
| 106 | + reply = self.call("get_tts_instructions")[1] |
| 107 | + result = (reply or {}).get("result", {}) |
| 108 | + return None if result.get("isError", True) else result.get("structuredContent") |
| 109 | + |
| 110 | + def send(self, key, display, speech=None, profile=None, revision=None, |
| 111 | + local_checks=True, discard_reply=False, timeout=8.0): |
| 112 | + """One draft, one frame. `discard_reply` drops the answer, as a lost reply would.""" |
| 113 | + arguments = {"idempotency_key": key, "display_text": display} |
| 114 | + if speech is not None: |
| 115 | + arguments["speech_text"] = speech |
| 116 | + tool = "submit_tts_draft" |
| 117 | + if profile is not None: |
| 118 | + arguments.update(profile=profile, revision=revision) |
| 119 | + tool = "submit_explanation_draft" |
| 120 | + sizes = {name: len(arguments[name].encode("utf-8")) for name in ("display_text", "speech_text") if name in arguments} |
| 121 | + report = {"key": key, "display_bytes": sizes["display_text"], "speech_bytes": sizes.get("speech_text", 0)} |
| 122 | + self.last = (tool, arguments, report) |
| 123 | + if local_checks: |
| 124 | + for name, size in sizes.items(): |
| 125 | + if size > self.limits["text_bytes"]: |
| 126 | + return {**report, "outcome": "rejected", "status": "too_large", "by": "client", |
| 127 | + "field": name, "limit_bytes": self.limits["text_bytes"]} |
| 128 | + return self._finish(tool, arguments, dict(report), discard_reply, timeout) |
| 129 | + |
| 130 | + def retry(self, timeout=8.0): |
| 131 | + """Repeat the last send once: same connection, same key and bytes, new request id.""" |
| 132 | + tool, arguments, report = self.last |
| 133 | + return self._finish(tool, arguments, dict(report), False, timeout) |
| 134 | + |
| 135 | + def _finish(self, tool, arguments, report, discard_reply, timeout): |
| 136 | + size, reply = self.call(tool, arguments, timeout=timeout, discard_reply=discard_reply) |
| 137 | + report.update(frame_bytes=size, request_id=self.next_id) |
| 138 | + if reply is not None and reply.get("local"): |
| 139 | + return {**report, "outcome": "rejected", "status": "frame_too_large", "by": "client", |
| 140 | + "limit_bytes": self.limits["frame_bytes"]} |
| 141 | + if reply is None or "result" not in reply: |
| 142 | + return {**report, "outcome": "unconfirmed", "status": "unconfirmed"} |
| 143 | + result = reply["result"] |
| 144 | + status = (result.get("structuredContent") or {}).get("status", "invalid" if result.get("isError") else "unconfirmed") |
| 145 | + report["status"] = status |
| 146 | + for extra in ("field", "bytes", "limit_bytes"): |
| 147 | + if extra in (result.get("structuredContent") or {}): |
| 148 | + report[extra] = result["structuredContent"][extra] |
| 149 | + if status in CONFIRMED and not result.get("isError"): |
| 150 | + report["outcome"] = "confirmed" |
| 151 | + elif status == "unconfirmed": |
| 152 | + report["outcome"] = "unconfirmed" |
| 153 | + else: |
| 154 | + report["outcome"] = "rejected" |
| 155 | + return report |
| 156 | + |
| 157 | + def close(self, kill=False): |
| 158 | + if self.proc.poll() is None: |
| 159 | + if kill: |
| 160 | + self.proc.kill() |
| 161 | + else: |
| 162 | + self.proc.stdin.close() |
| 163 | + try: |
| 164 | + self.proc.wait(timeout=3) |
| 165 | + except subprocess.TimeoutExpired: |
| 166 | + self.proc.kill() |
| 167 | + self.proc.wait(timeout=3) |
| 168 | + for stream in (self.proc.stdin, self.proc.stdout): |
| 169 | + if stream and not stream.closed: |
| 170 | + stream.close() |
| 171 | + |
| 172 | + |
| 173 | +def main(): |
| 174 | + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 175 | + parser.add_argument("--helper", required=True, help="path to the app's bundled CodebasicAgentMCP") |
| 176 | + parser.add_argument("--client", help="name of this client's key slot (default: this program's MCP name)") |
| 177 | + commands = parser.add_subparsers(dest="command", required=True) |
| 178 | + commands.add_parser("status") |
| 179 | + send = commands.add_parser("send") |
| 180 | + send.add_argument("--key", required=True) |
| 181 | + send.add_argument("--display-file", required=True) |
| 182 | + send.add_argument("--speech-file") |
| 183 | + options = parser.parse_args() |
| 184 | + session = Session(options.helper, options.client) |
| 185 | + try: |
| 186 | + state = session.status() |
| 187 | + if options.command == "status": |
| 188 | + print(json.dumps({"status": state, "limits": session.limits})) |
| 189 | + return 0 |
| 190 | + with open(options.display_file, "rb") as handle: |
| 191 | + display = handle.read().decode("utf-8") |
| 192 | + speech = None |
| 193 | + if options.speech_file: |
| 194 | + with open(options.speech_file, "rb") as handle: |
| 195 | + speech = handle.read().decode("utf-8") |
| 196 | + instruction = session.read_instruction() if state == "ready" else None |
| 197 | + report = session.send(options.key, display, speech, |
| 198 | + profile=instruction and instruction["profile"], |
| 199 | + revision=instruction and instruction["revision"]) |
| 200 | + print(json.dumps({**report, "connection": state})) |
| 201 | + return 0 if report["outcome"] == "confirmed" else 2 if report["outcome"] == "rejected" else 3 |
| 202 | + finally: |
| 203 | + session.close() |
| 204 | + |
| 205 | + |
| 206 | +if __name__ == "__main__": |
| 207 | + sys.exit(main()) |
0 commit comments