From 925583efdd07d3a0b8946625a31ce76bc3dcf280 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Mon, 7 Sep 2026 11:49:59 +0200 Subject: [PATCH] feat(mcp): stdio transport for hosts that only launch a subprocess MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Some MCP hosts never speak HTTP to a server: they run it as a command and talk over stdin/stdout. Glama's Dockerfile deployments wrap exactly that (and a local self-host user can now skip the web server entirely), so the directory could not introspect our tools at all — mcp.openshorts.app 401s without a key, by design. mcp_stdio.py is transport only: mcp_server keeps the protocol, and tool calls go through the same call_tool -> ASGITransport path, so stdio and HTTP cannot answer differently. Two things it has to get right, both covered by the test: stdout is swapped for stderr before app is imported, because the pipeline prints everywhere and one stray line corrupts the JSON-RPC stream; and the app's lifespan is entered explicitly, which ASGITransport does not do on its own. glama.json declares the maintainer, one of the listing gaps the directory reports. Claude-Session: https://claude.ai/code/session_01PkWCDoMsdmSxGXXh4jqF1m --- CLAUDE.md | 7 +++ README.md | 3 + glama.json | 6 ++ mcp_stdio.py | 125 ++++++++++++++++++++++++++++++++++++++++ tests/test_mcp_stdio.py | 54 +++++++++++++++++ 5 files changed, 195 insertions(+) create mode 100644 glama.json create mode 100644 mcp_stdio.py create mode 100644 tests/test_mcp_stdio.py diff --git a/CLAUDE.md b/CLAUDE.md index 1ebd8a0..e3e77f5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -273,6 +273,13 @@ portrait clip cannot reproduce the shrink either. back into this same app in-process (`httpx.ASGITransport`) forwarding the caller's auth headers, so it can never drift from the REST behavior. Cloud mode 401s without a resolvable user; self-host stays BYOK-open. +- **stdio transport** (`mcp_stdio.py`): the same `handle_message` / `call_tool` + as a subprocess, for hosts that only launch MCP servers as a command (Glama's + Dockerfile deployments wrap one; a local client can skip the web server). + Two invariants: `sys.stdout` is swapped for stderr **before `app` is + imported**, because the pipeline prints everywhere and one stray line + corrupts the JSON-RPC stream; and the app's lifespan is entered + (`router.lifespan_context`), which `ASGITransport` does not do on its own. - **OAuth for MCP clients** (`cloud/mcp_oauth.py`, cloud mode only): claude.ai and ChatGPT connect by URL, so the server publishes RFC 9728/8414 metadata under `/.well-known/`, accepts dynamic client registration (`POST diff --git a/README.md b/README.md index 0d09568..af89264 100644 --- a/README.md +++ b/README.md @@ -344,6 +344,9 @@ claude mcp add --transport http openshorts https://mcp.openshorts.app/mcp \ # Self-hosted (no key needed, BYOK rules apply): claude mcp add --transport http openshorts http://localhost:8000/mcp + +# Self-hosted without running the web server: same tools over stdio +claude mcp add openshorts -- python mcp_stdio.py ``` Tools: `process_video` (URL or `upload_id`; `captions: false` when the source already has subtitles, `auto_hook: false` to skip the hook line, burned by default like the dashboard), `create_upload` (hand the agent a local file: PUT the bytes, then process), `get_job_status`, `list_clips`, `get_quota`, `add_subtitles`, `recut_clip`, `publish_clip`. A prompt like *"clip this podcast and schedule the best 3 to TikTok"* is now a one-liner in your agent of choice. diff --git a/glama.json b/glama.json new file mode 100644 index 0000000..77eb059 --- /dev/null +++ b/glama.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://glama.ai/mcp/schemas/server.json", + "maintainers": [ + "mutonby" + ] +} diff --git a/mcp_stdio.py b/mcp_stdio.py new file mode 100644 index 0000000..f33bd63 --- /dev/null +++ b/mcp_stdio.py @@ -0,0 +1,125 @@ +"""Stdio transport for the same MCP server that ``/mcp`` serves over HTTP. + +``mcp_server.py`` owns the protocol; this file is only a transport: it reads +newline-delimited JSON-RPC from stdin, hands each message to +``mcp_server.handle_message`` and writes the response to stdout. Tool calls go +through the identical in-process path (``call_tool`` -> httpx ASGITransport -> +this app), so stdio and HTTP can never answer differently. + +Why it exists: some hosts only launch MCP servers as a subprocess (Glama's +Dockerfile deployments wrap a stdio command, and a local client that would +rather not run a web server can do +``claude mcp add openshorts -- python mcp_stdio.py``). The hosted endpoint at +mcp.openshorts.app stays the HTTP one. + +Two things this transport has to get right: + +- **stdout belongs to the protocol.** The pipeline prints progress everywhere + (main.py, app.py, yt-dlp), and one stray line corrupts the JSON-RPC stream, + so ``sys.stdout`` is swapped for stderr before the app is imported and the + real handle is kept private to the writer below. +- **The app's lifespan must run.** Job queues, output dirs and the resume scan + are set up there; ASGITransport does not run it on its own. +""" +import asyncio +import json +import os +import sys + +# Must happen before importing app: import-time prints would land on stdout. +_PROTOCOL_OUT = sys.stdout +sys.stdout = sys.stderr + +from starlette.requests import Request # noqa: E402 + +import app as app_module # noqa: E402 +import mcp_server # noqa: E402 + +# BYOK credentials reach the tools the same way an HTTP client would send them: +# as forwarded headers (mcp_server._FORWARD_HEADERS), not as a second code path. +_ENV_HEADERS = { + "authorization": lambda: ( + f"Bearer {os.environ['OPENSHORTS_API_KEY']}" + if os.environ.get("OPENSHORTS_API_KEY") else None + ), + "x-gemini-key": lambda: os.environ.get("GEMINI_API_KEY"), + "x-upload-post-key": lambda: os.environ.get("UPLOAD_POST_API_KEY"), +} + + +def _request() -> Request: + """A synthetic ASGI request carrying the app and the auth headers. + + ``mcp_server.call_tool`` only reads ``.app`` and ``.headers`` off it.""" + headers = [] + for name, read in _ENV_HEADERS.items(): + value = read() + if value: + headers.append((name.encode(), value.encode())) + return Request({ + "type": "http", + "asgi": {"version": "3.0"}, + "http_version": "1.1", + "method": "POST", + "scheme": "http", + "path": "/mcp", + "raw_path": b"/mcp", + "query_string": b"", + "root_path": "", + "headers": headers, + "client": ("127.0.0.1", 0), + "server": ("openshorts.internal", 80), + "app": app_module.app, + }) + + +def _write(response: dict) -> None: + _PROTOCOL_OUT.write(json.dumps(response, ensure_ascii=False) + "\n") + _PROTOCOL_OUT.flush() + + +async def _stdin_lines(): + """Yield stdin lines without blocking the loop (tool calls run for minutes).""" + loop = asyncio.get_running_loop() + reader = asyncio.StreamReader() + await loop.connect_read_pipe(lambda: asyncio.StreamReaderProtocol(reader), sys.stdin) + while True: + line = await reader.readline() + if not line: # EOF: the host closed the pipe + return + yield line + + +async def _serve() -> None: + async with app_module.app.router.lifespan_context(app_module.app): + request = _request() + + async def tool_caller(name, args): + return await mcp_server.call_tool(request, name, args) + + async for line in _stdin_lines(): + line = line.strip() + if not line: + continue + try: + msg = json.loads(line) + except Exception: + _write(mcp_server._rpc_error(None, -32700, "Parse error")) + continue + if isinstance(msg, list): + _write(mcp_server._rpc_error(None, -32600, "Batching is not supported")) + continue + response = await mcp_server.handle_message(msg, tool_caller) + if response is not None: + _write(response) + + +def main() -> None: + try: + asyncio.run(_serve()) + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/tests/test_mcp_stdio.py b/tests/test_mcp_stdio.py new file mode 100644 index 0000000..bdf638b --- /dev/null +++ b/tests/test_mcp_stdio.py @@ -0,0 +1,54 @@ +"""Stdio transport (mcp_stdio.py), exercised as the subprocess a host launches. + +It has to be a real subprocess: the thing most likely to break this transport +is the pipeline's own chatter (the app prints on import and on startup), and +that only shows up when stdout is a pipe. Every line the host reads must be +JSON-RPC and nothing else. +""" +import json +import os +import subprocess +import sys + +import pytest + +from mcp_server import TOOLS + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +MESSAGES = [ + {"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "pytest", "version": "1"}}}, + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, +] + + +@pytest.fixture(scope="module") +def responses(): + env = dict(os.environ, BILLING_ENABLED="0", PYTHONPATH=REPO) + env.pop("PROXY_URL", None) + proc = subprocess.run( + [sys.executable, "-u", os.path.join(REPO, "mcp_stdio.py")], + input="".join(json.dumps(m) + "\n" for m in MESSAGES), + capture_output=True, text=True, cwd=REPO, env=env, timeout=300, + ) + assert proc.returncode == 0, proc.stderr[-2000:] + return [json.loads(line) for line in proc.stdout.splitlines() if line.strip()] + + +class TestStdioTransport: + def test_stdout_carries_only_protocol_lines(self, responses): + # The notification gets no reply, and no print() leaked into the stream. + assert [r["id"] for r in responses] == [1, 2] + assert all(r["jsonrpc"] == "2.0" for r in responses) + + def test_initialize_reports_the_same_server(self, responses): + result = responses[0]["result"] + assert result["serverInfo"]["name"] == "openshorts" + assert result["protocolVersion"] == "2025-06-18" + + def test_tools_match_the_http_transport(self, responses): + names = [t["name"] for t in responses[1]["result"]["tools"]] + assert names == [t["name"] for t in TOOLS]