diff --git a/docs/features/mcp-service.md b/docs/features/mcp-service.md index ff4a77a09..f0ab52d1c 100644 --- a/docs/features/mcp-service.md +++ b/docs/features/mcp-service.md @@ -518,7 +518,9 @@ sequenceDiagram ### Node Console Execution -The `node_console_exec` tool runs commands on a node's text console server-side. One tool call is one complete console session: the server spawns `timeout N websocat -t --no-close ''`, feeds the command lines through stdin (one line per turn, ~0.3 s pacing, `\r\n` line endings), keeps reading stdout until the timeout kills websocat, and returns the collected output as plain text (`output: …`, or bare error text — no JSON envelope, no status field: the server cannot judge whether the command itself succeeded). Works for **telnet** and **ssh** console types on all computes (the controller proxies the WebSocket); **vnc** consoles have no text channel and fail with a plain message. The client never sees a URL or token — the whole websocat chain is an implementation detail. +The `node_console_exec` tool runs commands on a node's text console server-side. One tool call is one complete console session: the server spawns `timeout N websocat -b --no-close ''`, feeds the command lines through stdin (one line per turn, ~0.3 s pacing, `\r\n` line endings), keeps reading stdout until the timeout kills websocat, and returns the collected output as plain text (`output: …`, or bare error text — no JSON envelope, no status field: the server cannot judge whether the command itself succeeded). Works for **telnet** and **ssh** console types on all computes (the controller proxies the WebSocket); **vnc** consoles have no text channel and fail with a plain message. The client never sees a URL or token — the whole websocat chain is an implementation detail. + +Binary mode (`-b`) is required, not cosmetic: in text mode (`-t`, and also the default) websocat appends a newline after every received WebSocket message and turns CR/LF inside a message into spaces. The compute ships console output as one BINARY frame per `read(1024)` burst, so text mode injects a newline at every arbitrary frame boundary — output comes back diced into short lines mid-word, and carriage-return redraws are lost. `-b` is byte-exact in both directions; binary command frames are still handled as data by the compute console handler. Prerequisites: the node must be started, and the host running gns3server must have the `websocat` binary on its PATH (a missing binary returns a plain install hint). diff --git a/gns3server/agent/mcp/console_exec.py b/gns3server/agent/mcp/console_exec.py index f8a84eaaa..48f734059 100644 --- a/gns3server/agent/mcp/console_exec.py +++ b/gns3server/agent/mcp/console_exec.py @@ -22,10 +22,10 @@ node_console_exec: one-shot node console executor. Server-side equivalent of the client-side chain this workflow used to need: node_console (mint URL+ticket) -> bash: { sleep ..; printf 'cmd\r\n'; .. } - | timeout N websocat -t --no-close '' + | timeout N websocat -b --no-close '' One tool call is one complete console session: the server spawns -``timeout N websocat -t --no-close ``, feeds the command lines through +``timeout N websocat -b --no-close ``, feeds the command lines through stdin, keeps reading stdout until the timeout kills websocat, and returns the collected output as plain text. No session state survives the call; node-side state (config mode, running pings) persists across calls by nature of the @@ -161,7 +161,17 @@ async def _resolve_console_node( async def _spawn(url: str, seconds: int) -> asyncio.subprocess.Process: - """Start ``timeout websocat -t --no-close ``. + """Start ``timeout websocat -b --no-close ``. + + Binary mode is mandatory, not a preference: in text mode (-t, and also + the default) websocat appends a ``\\n`` after every received WebSocket + message and turns CR/LF inside a message into spaces. The compute ships + console output as one BINARY frame per ``read(1024)`` burst, so text mode + injects a newline at every arbitrary frame boundary — output arrives + diced into short lines mid-word (field symptom: prompts split into + pieces, "narrow columns"). ``-b`` is byte-exact in both directions; + binary command frames are still handled as data by the compute console + handler. The subprocess gets its own process group: websocat is a child of ``timeout``, and a cancelled call must take down the whole tree (an @@ -172,7 +182,7 @@ async def _spawn(url: str, seconds: int) -> asyncio.subprocess.Process: "timeout", str(seconds), "websocat", - "-t", + "-b", "--no-close", url, stdin=asyncio.subprocess.PIPE, diff --git a/tests/agent/mcp/test_console_exec.py b/tests/agent/mcp/test_console_exec.py index 749b066e2..ac9b591ad 100644 --- a/tests/agent/mcp/test_console_exec.py +++ b/tests/agent/mcp/test_console_exec.py @@ -504,7 +504,13 @@ async def test_grep_hit_on_long_output_returns_only_matches(): @contextlib.asynccontextmanager async def _serve_console(received, replies): """aiohttp WS server behaving like a console: banner on connect (BINARY, - the way the compute side ships it), reply per received line.""" + the way the compute side ships it), reply per received line. + + ``replies`` is a str (sent whole) or a list of byte frames — the compute + side ships output as one BINARY frame per arbitrary read(1024) burst. + Commands arrive as BINARY frames (websocat runs in -b mode) and are + recorded as bytes. + """ from aiohttp import WSMsgType, web @@ -513,9 +519,13 @@ async def _serve_console(received, replies): await ws.prepare(request) await ws.send_bytes(b"Welcome to the console\r\n") async for msg in ws: - if msg.type == WSMsgType.TEXT: + if msg.type in (WSMsgType.TEXT, WSMsgType.BINARY): received.append(msg.data) - await ws.send_bytes(replies.encode()) + if isinstance(replies, (list, tuple)): + for frame in replies: + await ws.send_bytes(frame) + else: + await ws.send_bytes(replies.encode()) return ws app = web.Application() @@ -546,7 +556,7 @@ async def test_real_websocat_session_end_to_end(): ) assert "uptime 5m" in result - assert received == ["show version\r\n"] + assert received == [b"show version\r\n"] @pytest.mark.asyncio @@ -567,3 +577,30 @@ async def test_real_websocat_stays_open_the_full_window(): elapsed = time.monotonic() - started assert elapsed >= 1.8 # it did not bail out after the echo ack + + +@pytest.mark.asyncio +@pytest.mark.skipif(shutil.which("websocat") is None, reason="websocat is not installed") +async def test_real_websocat_binary_mode_keeps_frame_splits_byte_exact(): + """The compute ships output as one BINARY frame per arbitrary read(1024) + burst. websocat text mode (-t, also the default) appends a newline after + every received message and turns CR/LF into spaces — the field symptom + was output diced into short lines mid-word ("Password: " split in + three) and lost carriage-return redraws. Binary mode must preserve the + stream exactly across frame boundaries.""" + + frames = [b"R1# show ", b"ver", b"sion\r\n", b"lineA\rlineB\r\n"] + received = [] + async with _serve_console(received, replies=frames) as base: + with patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload())): + result = await console_exec( + "11111111-1111-1111-1111-111111111111", + "22222222-2222-2222-2222-222222222222", + "show version", + 2, + gns3_ctx=_ctx(base), + ) + + # frame boundaries must not become line breaks, and CR must survive + assert "R1# show version\r\n" in result + assert "lineA\rlineB\r\n" in result