From c0041cee1469246fe0b784e1e842f971431a32aa Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 15 Nov 2026 18:51:39 -0600 Subject: [PATCH 01/10] deps(build) Pin the owned-program core candidate why: Owned execution and recovery require the core API under review in libtmux PR833; the published dependency has no equivalent owner contract. what: - Pin the exact core source revision in package metadata and the lockfile - Permit that declared source reference in the draft package metadata - Keep publication held until the core API has a released dependency --- pyproject.toml | 5 ++++- uv.lock | 40 ++++++++++++++++++---------------------- 2 files changed, 22 insertions(+), 23 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index ad325266..02bc2eec 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,7 +39,7 @@ include = [ ] dependencies = [ - "libtmux>=0.62.0,<1.0", + "libtmux @ git+https://github.com/tmux-python/libtmux.git@1d8fb61dc2eef798b16730ec50f0a88de7f94e3c", "fastmcp>=4.0.2,<5.0.0", "regex>=2024.11.6", ] @@ -111,6 +111,9 @@ lint = [ requires = ["hatchling"] build-backend = "hatchling.build" +[tool.hatch.metadata] +allow-direct-references = true + [tool.uv.exclude-newer-package] # git-pull packages release in lockstep with their workspaces, so a # fresh release blocking on the 3-day cooldown blocks every diff --git a/uv.lock b/uv.lock index 96e369c2..9b9f463b 100644 --- a/uv.lock +++ b/uv.lock @@ -1,12 +1,12 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.11, <4.0" resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*' and sys_platform == 'emscripten'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", - "(python_full_version >= '3.11.5' and python_full_version < '3.12') or (python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten')", + "(python_full_version >= '3.11.5' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten')", "python_full_version < '3.11.5'", ] @@ -15,26 +15,26 @@ exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for exclude-newer-span = "P3D" [options.exclude-newer-package] -fastmcp = false -fastmcp-slim = false -gp-furo-theme = false -gp-libs = false -gp-sphinx = false libtmux = false +gp-sphinx = false +sphinx-autodoc-sphinx = false sphinx-autodoc-api-style = false -sphinx-autodoc-argparse = false -sphinx-autodoc-docutils = false sphinx-autodoc-fastmcp = false sphinx-autodoc-pytest-fixtures = false -sphinx-autodoc-sphinx = false -sphinx-autodoc-typehints-gp = false -sphinx-fonts = false sphinx-gp-llms = false -sphinx-gp-opengraph = false -sphinx-gp-sitemap = false -sphinx-gp-theme = false +sphinx-autodoc-argparse = false sphinx-ux-autodoc-layout = false sphinx-ux-badges = false +fastmcp = false +gp-libs = false +fastmcp-slim = false +sphinx-autodoc-docutils = false +gp-furo-theme = false +sphinx-gp-sitemap = false +sphinx-fonts = false +sphinx-autodoc-typehints-gp = false +sphinx-gp-opengraph = false +sphinx-gp-theme = false [[package]] name = "accessible-pygments" @@ -1220,11 +1220,7 @@ wheels = [ [[package]] name = "libtmux" version = "0.62.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0c/b8/0410c8487f7673926d141a5aaaf60133984a564b3c90eb4f3f99e92e7740/libtmux-0.62.0.tar.gz", hash = "sha256:41e9e80602b2656fd119b13253b27bad46af5cfef32099be53cdd391e2936b61", size = 571757, upload-time = "2026-07-12T21:48:02.781Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/87/96/471ac01844ee157fe794446e17568e9bf219d323575c2acc7957a9a2d8c9/libtmux-0.62.0-py3-none-any.whl", hash = "sha256:626aa6fae45e3a423e1acc81604efafa63b7262b1d67b2c7a8778b1ad691456b", size = 127700, upload-time = "2026-07-12T21:48:01.52Z" }, -] +source = { git = "https://github.com/tmux-python/libtmux.git?rev=1d8fb61dc2eef798b16730ec50f0a88de7f94e3c#1d8fb61dc2eef798b16730ec50f0a88de7f94e3c" } [[package]] name = "libtmux-mcp" @@ -1285,7 +1281,7 @@ testing = [ [package.metadata] requires-dist = [ { name = "fastmcp", specifier = ">=4.0.2,<5.0.0" }, - { name = "libtmux", specifier = ">=0.62.0,<1.0" }, + { name = "libtmux", git = "https://github.com/tmux-python/libtmux.git?rev=1d8fb61dc2eef798b16730ec50f0a88de7f94e3c" }, { name = "regex", specifier = ">=2024.11.6" }, ] @@ -2494,7 +2490,7 @@ resolution-markers = [ "python_full_version == '3.14.*' and sys_platform == 'emscripten'", "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", "python_full_version == '3.14.*' and sys_platform != 'emscripten'", - "(python_full_version >= '3.11.5' and python_full_version < '3.12') or (python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten')", + "(python_full_version >= '3.11.5' and python_full_version < '3.14' and sys_platform != 'emscripten') or (python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform == 'emscripten')", ] sdist = { url = "https://files.pythonhosted.org/packages/95/48/21a393ff731b8f928fa4f8176f9a7ceba2252ee60a5149f25b45c292aa5c/soupsieve-4.1.tar.gz", hash = "sha256:ca9abf7126667010d8f6e9b39bfc1bc3b23c8aed9bcb0f54a754dde969bb8aab", size = 161955, upload-time = "2026-11-10T01:59:50.399Z" } wheels = [ From a733a5747fd5307abda2b59c8b2693b38cde7e29 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 15 Nov 2026 19:16:06 -0600 Subject: [PATCH 02/10] deps(build) Pin reviewed core recovery and native waits why: Owned MCP calls need public cleanup disposition and bounded native-client recovery from the same tested core revision. what: - Advance the explicit draft source dependency to the reviewed ff7a6552 core head. - Keep release publication held until the core API has a published dependency. --- pyproject.toml | 2 +- uv.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 02bc2eec..bf5c6b80 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,7 +39,7 @@ include = [ ] dependencies = [ - "libtmux @ git+https://github.com/tmux-python/libtmux.git@1d8fb61dc2eef798b16730ec50f0a88de7f94e3c", + "libtmux @ git+https://github.com/tmux-python/libtmux.git@ff7a6552de1ae2f87a11584df4aa48b0547af95b", "fastmcp>=4.0.2,<5.0.0", "regex>=2024.11.6", ] diff --git a/uv.lock b/uv.lock index 9b9f463b..55d67488 100644 --- a/uv.lock +++ b/uv.lock @@ -1220,7 +1220,7 @@ wheels = [ [[package]] name = "libtmux" version = "0.62.0" -source = { git = "https://github.com/tmux-python/libtmux.git?rev=1d8fb61dc2eef798b16730ec50f0a88de7f94e3c#1d8fb61dc2eef798b16730ec50f0a88de7f94e3c" } +source = { git = "https://github.com/tmux-python/libtmux.git?rev=ff7a6552de1ae2f87a11584df4aa48b0547af95b#ff7a6552de1ae2f87a11584df4aa48b0547af95b" } [[package]] name = "libtmux-mcp" @@ -1281,7 +1281,7 @@ testing = [ [package.metadata] requires-dist = [ { name = "fastmcp", specifier = ">=4.0.2,<5.0.0" }, - { name = "libtmux", git = "https://github.com/tmux-python/libtmux.git?rev=1d8fb61dc2eef798b16730ec50f0a88de7f94e3c" }, + { name = "libtmux", git = "https://github.com/tmux-python/libtmux.git?rev=ff7a6552de1ae2f87a11584df4aa48b0547af95b" }, { name = "regex", specifier = ">=2024.11.6" }, ] From 524cfd93e903cfcdea111580f7b1bcc34fd7b75b Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 15 Nov 2026 20:01:04 -0600 Subject: [PATCH 03/10] mcp(feat): retain bounded program owners why: Cancelled MCP calls must settle native work and retain cleanup obligations without adopting arbitrary panes. what: - Reserve owner capacity before worker admission - Join cooperative AnyIO workers across request cancellation - Keep bounded recovery records and stable pagination - Carry public core recovery evidence through tool errors --- pyproject.toml | 1 + src/libtmux_mcp/_programs.py | 302 ++++++++++++++++++++++++++++++++++ src/libtmux_mcp/_utils.py | 18 ++ src/libtmux_mcp/middleware.py | 9 + src/libtmux_mcp/models.py | 92 +++++++++++ uv.lock | 2 + 6 files changed, 424 insertions(+) create mode 100644 src/libtmux_mcp/_programs.py diff --git a/pyproject.toml b/pyproject.toml index bf5c6b80..edea433e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,7 @@ include = [ ] dependencies = [ + "anyio>=4.16.0,<5.0", "libtmux @ git+https://github.com/tmux-python/libtmux.git@ff7a6552de1ae2f87a11584df4aa48b0547af95b", "fastmcp>=4.0.2,<5.0.0", "regex>=2024.11.6", diff --git a/src/libtmux_mcp/_programs.py b/src/libtmux_mcp/_programs.py new file mode 100644 index 00000000..1418edbc --- /dev/null +++ b/src/libtmux_mcp/_programs.py @@ -0,0 +1,302 @@ +"""Keep program owners reachable across MCP request cancellation.""" + +from __future__ import annotations + +import asyncio +import contextlib +import dataclasses +import threading +import typing as t +import uuid + +import anyio +from libtmux import Program, ProgramExit, ProgramScreen + +from libtmux_mcp._utils import ExpectedToolError +from libtmux_mcp.models import ProgramObservation + +if t.TYPE_CHECKING: + from libtmux import ProgramRecovery, Server + +_T = t.TypeVar("_T") +_MAX_RUNS = 32 + + +def _error_text(error: object, limit: int = 2048) -> str: + """Bound error evidence in UTF-8 bytes without splitting a code point.""" + return str(error).encode("utf-8")[:limit].decode("utf-8", "ignore") + + +async def _run_in_worker(call: t.Callable[[threading.Event], _T]) -> _T: + """Cancel native work cooperatively, then join it before leaving the handler.""" + cancel = threading.Event() + # Reservations bound concurrency; this limiter avoids unrelated worker queues. + task = asyncio.create_task( + anyio.to_thread.run_sync(call, cancel, limiter=anyio.CapacityLimiter(1)) + ) + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + cancel.set() + with anyio.CancelScope(shield=True): + while not task.done(): + try: + await asyncio.shield(task) + except asyncio.CancelledError: + continue + except Exception: # noqa: BLE001 - the worker records its retained owner. + break + with contextlib.suppress(BaseException): + task.result() + raise + + +@dataclasses.dataclass +class _Run: + run_id: str + sequence: int + operation: t.Literal["run", "capabilities"] + session_id: str | None + socket_name: str | None + socket_path: str | None + status: t.Literal["running", "cleanup_required", "cleanup_in_progress"] = "running" + owner: Program | None = None + recovery: ProgramRecovery | None = None + error: str | None = None + cleanup_errors: tuple[str, ...] = () + last_observation: ProgramObservation | None = None + + +class _ProgramRunError(ExpectedToolError): + """Carry a cleanup record through the existing tool-error middleware.""" + + def __init__( + self, + message: str, + recovery_id: str | None = None, + cleanup_errors: tuple[str, ...] = (), + observation: ProgramObservation | None = None, + ) -> None: + self.program_recovery_id = recovery_id + self.program_cleanup_errors = cleanup_errors + self.program_observation = observation + super().__init__( + _error_text(message), + suggestion=( + "Inspect list_program_runs and retry " + f"cleanup_program(run_id={recovery_id!r})." + if recovery_id is not None + else None + ), + ) + + +class _ProgramRuns: + """Reserve capacity before launch; remove records only after verified cleanup.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._runs: dict[str, _Run] = {} + self._sequence = 0 + + def reserve( + self, + operation: t.Literal["run", "capabilities"], + session_id: str | None, + server: Server, + ) -> _Run: + with self._lock: + if len(self._runs) >= _MAX_RUNS: + msg = ( + "Program capacity is full; inspect list_program_runs " + "and clean up retained runs" + ) + raise ExpectedToolError(msg) + self._sequence += 1 + run = _Run( + uuid.uuid4().hex, + self._sequence, + operation, + session_id, + server.socket_name, + str(server.socket_path) if server.socket_path is not None else None, + ) + self._runs[run.run_id] = run + return run + + def retire(self, run: _Run) -> None: + with self._lock: + del self._runs[run.run_id] + + def failed(self, run: _Run, error: BaseException) -> _ProgramRunError: + owner = getattr(error, "owner", None) + observed = getattr(error, "last_observation", None) + capture = getattr(error, "last_capture", None) + raw = ( + capture.text.encode("utf-8") if isinstance(capture, ProgramScreen) else None + ) + observation = ( + ProgramObservation( + exit_status=observed.exit_status + if isinstance(observed, ProgramExit) + else None, + exit_signal=observed.exit_signal + if isinstance(observed, ProgramExit) + else None, + screen_text=raw[-2048:].decode("utf-8", "ignore") + if raw is not None + else None, + screen_truncated=raw is not None and len(raw) > 2048, + ) + if isinstance(observed, ProgramExit) or raw is not None + else None + ) + failures = tuple( + _error_text(item) for item in getattr(error, "cleanup_errors", ()) + )[-8:] + if isinstance(owner, Program) and owner.recovery.cleanup_pending: + try: + owner.cleanup(timeout=0.5) + except BaseException as cleanup_error: # noqa: BLE001 - retain partial-start owners too. + failures = (*failures, _error_text(cleanup_error))[-8:] + if isinstance(owner, Program) and owner.recovery.cleanup_pending: + with self._lock: + run.owner = owner + run.recovery = owner.recovery + run.error = _error_text(error) + run.cleanup_errors = failures + run.last_observation = observation + run.status = "cleanup_required" + return _ProgramRunError(str(error), run.run_id, failures, observation) + self.retire(run) + return _ProgramRunError( + str(error), cleanup_errors=failures, observation=observation + ) + + async def execute( + self, + call: t.Callable[[threading.Event], _T], + operation: t.Literal["run", "capabilities"], + server: Server, + session_id: str | None = None, + ) -> _T: + """Bound queued workers as well as running and unresolved owners.""" + run = self.reserve(operation, session_id, server) + entered = threading.Event() + + def work(cancel: threading.Event) -> _T: + entered.set() + try: + result = call(cancel) + except BaseException as error: + raise self.failed(run, error) from error + self.retire(run) + return result + + try: + return await _run_in_worker(work) + finally: + if not entered.is_set(): + self.retire(run) + + @staticmethod + def _snapshot(run: _Run, *, details: bool = False) -> dict[str, t.Any]: + data: dict[str, t.Any] = { + "run_id": run.run_id, + "operation": run.operation, + "session_id": run.session_id, + "socket_name": run.socket_name, + "socket_path": run.socket_path, + "status": run.status, + "pane_id": run.recovery.pane_id if run.recovery is not None else None, + "pane_state": run.recovery.pane_state if run.recovery is not None else None, + "cleanup_pending": run.recovery.cleanup_pending + if run.recovery is not None + else None, + } + if details: + data.update( + error=run.error, + cleanup_errors=list(run.cleanup_errors), + last_observation=run.last_observation, + ) + else: + data["error_preview"] = ( + _error_text(run.error, 256) if run.error is not None else None + ) + return data + + def page(self, cursor: str | None, limit: int) -> dict[str, t.Any]: + after = int(cursor) if cursor is not None else 0 + with self._lock: + following = [run for run in self._runs.values() if run.sequence > after] + selected = following[:limit] + return { + "items": [self._snapshot(run) for run in selected], + "next_cursor": str(selected[-1].sequence) + if len(following) > limit + else None, + } + + def inspect(self, run_id: str) -> dict[str, t.Any]: + with self._lock: + run = self._runs.get(run_id) + if run is None: + msg = "No retained program has that run_id" + raise ExpectedToolError(msg) + return self._snapshot(run, details=True) + + async def cleanup(self, run_id: str) -> str | None: + """Claim the retained owner before scheduling its one cleanup worker.""" + with self._lock: + run = self._runs.get(run_id) + if run is None: + msg = "No retained program has that run_id" + raise ExpectedToolError(msg) + if run.status != "cleanup_required" or run.owner is None: + msg = "The worker is still settling; inspect list_program_runs again" + raise ExpectedToolError(msg) + run.status = "cleanup_in_progress" + owner = run.owner + entered = threading.Event() + + def work(cancel: threading.Event) -> str | None: + entered.set() + try: + if cancel.is_set(): + msg = "Program cleanup was cancelled before admission" + raise _ProgramRunError(msg, run_id) # noqa: TRY301 - retain retry state. + if owner.recovery.pane_state == "receipt-recorded": + owner.terminate(timeout=0.5) + owner.cleanup(timeout=0.5) + if owner.recovery.cleanup_pending: + msg = "Program cleanup remains unverified" + raise _ProgramRunError(msg, run_id) # noqa: TRY301 - retain retry state. + except BaseException as error: + with self._lock: + run.error = _error_text(error) + run.cleanup_errors = ( + *run.cleanup_errors, + *( + _error_text(item) + for item in getattr(error, "cleanup_errors", ()) + ), + _error_text(error), + )[-8:] + run.recovery = owner.recovery + run.status = "cleanup_required" + raise _ProgramRunError( + str(error), run_id, run.cleanup_errors, run.last_observation + ) from error + self.retire(run) + return owner.recovery.pane_id + + try: + return await _run_in_worker(work) + finally: + if not entered.is_set(): + with self._lock: + run.status = "cleanup_required" + + +_program_runs = _ProgramRuns() diff --git a/src/libtmux_mcp/_utils.py b/src/libtmux_mcp/_utils.py index 94ebac0e..b89829d9 100644 --- a/src/libtmux_mcp/_utils.py +++ b/src/libtmux_mcp/_utils.py @@ -572,6 +572,24 @@ def _tmux_argv(server: Server, *tmux_args: str) -> list[str]: _server_cache_lock = threading.Lock() +def _new_server( + socket_name: str | None = None, + socket_path: str | None = None, +) -> Server: + """Construct the configured route without issuing an unbounded liveness query.""" + return Server( + socket_name=( + socket_name if socket_name is not None else os.environ.get("LIBTMUX_SOCKET") + ), + socket_path=( + socket_path + if socket_path is not None + else os.environ.get("LIBTMUX_SOCKET_PATH") + ), + tmux_bin=os.environ.get("LIBTMUX_TMUX_BIN"), + ) + + def _get_server( socket_name: str | None = None, socket_path: str | None = None, diff --git a/src/libtmux_mcp/middleware.py b/src/libtmux_mcp/middleware.py index 47127e0c..6ed4d4ef 100644 --- a/src/libtmux_mcp/middleware.py +++ b/src/libtmux_mcp/middleware.py @@ -389,6 +389,15 @@ def _error_tool_result( if suggestion: meta["suggestion"] = suggestion text = f"{text}\n{suggestion}" + recovery_id = getattr(error, "program_recovery_id", None) + if recovery_id is not None: + meta["program_recovery_id"] = recovery_id + cleanup_errors = getattr(error, "program_cleanup_errors", ()) + if cleanup_errors: + meta["program_cleanup_errors"] = list(cleanup_errors) + observation = getattr(error, "program_observation", None) + if observation is not None: + meta["program_observation"] = observation.model_dump(mode="json") return ToolResult( content=[TextContent(type="text", text=text)], meta=meta, diff --git a/src/libtmux_mcp/models.py b/src/libtmux_mcp/models.py index 90733671..b725c7e3 100644 --- a/src/libtmux_mcp/models.py +++ b/src/libtmux_mcp/models.py @@ -7,6 +7,98 @@ from pydantic import BaseModel, ConfigDict, Field +class ProgramRunResult(BaseModel): + """Exit evidence and bounded rendered output after owned pane cleanup.""" + + pane_id: str + exit_status: int | None + exit_signal: str | None + screen_text: str = Field( + description="Rendered terminal tail; stdout and stderr share the PTY" + ) + screen_truncated: bool = Field( + description="The MCP byte limit removed older captured text" + ) + history_complete: None = Field( + default=None, description="Complete program output is not established" + ) + pane_removed: t.Literal[True] = True + effective_timeout: float + + +class ProgramObservation(BaseModel): + """Evidence retained before a failed program operation, when available.""" + + exit_status: int | None + exit_signal: str | None + screen_text: str | None + screen_truncated: bool + history_complete: None = None + + +class _ProgramRunState(BaseModel): + """Target and cleanup disposition shared by summaries and details.""" + + run_id: str + operation: t.Literal["run", "capabilities"] + session_id: str | None + socket_name: str | None + socket_path: str | None + status: t.Literal["running", "cleanup_required", "cleanup_in_progress"] + pane_id: str | None + pane_state: ( + t.Literal["not-submitted", "unverified", "receipt-recorded", "removed"] | None + ) + cleanup_pending: bool | None + + +class ProgramRunSummary(_ProgramRunState): + """One recovery record with a 256-byte error preview.""" + + error_preview: str | None + + +class ProgramRunPage(BaseModel): + """Current recovery summaries in creation order, with optional continuation.""" + + items: list[ProgramRunSummary] + next_cursor: str | None + + +class ProgramRunInfo(_ProgramRunState): + """One owner with bounded errors and any previously captured result.""" + + error: str | None + cleanup_errors: list[str] + last_observation: ProgramObservation | None + + +class ProgramCleanupResult(BaseModel): + """Verified cleanup of the retained owner identified by run_id.""" + + run_id: str + pane_id: str | None + cleanup_pending: t.Literal[False] = False + + +class LibraryFeatureInfo(BaseModel): + """One feature decision from the connected daemon's core registry.""" + + name: str + since: str + status: t.Literal["supported", "unsupported", "unknown"] + reason: str + + +class ServerCapabilityInfo(BaseModel): + """Fresh daemon identity and advisory library feature decisions.""" + + pid: int + start_time: int + version: str + features: list[LibraryFeatureInfo] + + class SessionInfo(BaseModel): """Serialized tmux session.""" diff --git a/uv.lock b/uv.lock index 55d67488..ec50321b 100644 --- a/uv.lock +++ b/uv.lock @@ -1227,6 +1227,7 @@ name = "libtmux-mcp" version = "0.1.0a22" source = { editable = "." } dependencies = [ + { name = "anyio" }, { name = "fastmcp" }, { name = "libtmux" }, { name = "regex" }, @@ -1280,6 +1281,7 @@ testing = [ [package.metadata] requires-dist = [ + { name = "anyio", specifier = ">=4.16.0,<5.0" }, { name = "fastmcp", specifier = ">=4.0.2,<5.0.0" }, { name = "libtmux", git = "https://github.com/tmux-python/libtmux.git?rev=ff7a6552de1ae2f87a11584df4aa48b0547af95b" }, { name = "regex", specifier = ">=2024.11.6" }, From 3b887f97aa2c7fa3197b171e44b96f1d22ccca53 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 15 Nov 2026 20:01:04 -0600 Subject: [PATCH 04/10] mcp(feat): expose owned program tools why: Agents need exact process results and a cleanup path independent of shell prompt heuristics. what: - Run literal argv through the core owner with bounded output - Expose daemon capabilities, recovery pages and cleanup retries - Apply existing toolset policy and operation duration ceilings - Exercise native cancellation, admission and recovery failures --- src/libtmux_mcp/_wait_policy.py | 4 +- src/libtmux_mcp/server.py | 11 +- src/libtmux_mcp/tools/__init__.py | 2 + src/libtmux_mcp/tools/program_tools.py | 228 ++++++ src/libtmux_mcp/tools/server_tools.py | 69 +- .../test_tool_surface_matches_snapshot.json | 20 + tests/test_program_tools.py | 680 ++++++++++++++++++ tests/test_server.py | 1 + tests/test_tool_annotations.py | 5 + 9 files changed, 1010 insertions(+), 10 deletions(-) create mode 100644 src/libtmux_mcp/tools/program_tools.py create mode 100644 tests/test_program_tools.py diff --git a/src/libtmux_mcp/_wait_policy.py b/src/libtmux_mcp/_wait_policy.py index a3998f44..9eb6827a 100644 --- a/src/libtmux_mcp/_wait_policy.py +++ b/src/libtmux_mcp/_wait_policy.py @@ -1,7 +1,7 @@ """Duration policy for the pane wait tools. -A wait tool is the only MCP tool in this server that blocks for a -caller-chosen duration. The ceiling bounds the AGENT'S TURN, not the +Wait tools and owned program runs share a ceiling on caller-chosen +duration. The ceiling bounds the AGENT'S TURN, not the transport: the wait tools await throughout, so a long wait does not stall the connection. Measured on fastmcp 3.4.4 over stdio, a tool awaiting for 6 s served 58 interleaved calls at a 3.4 ms median, while diff --git a/src/libtmux_mcp/server.py b/src/libtmux_mcp/server.py index 44b28505..5b8823ae 100644 --- a/src/libtmux_mcp/server.py +++ b/src/libtmux_mcp/server.py @@ -64,9 +64,10 @@ _INSTR_HIERARCHY = ( "libtmux MCP server for tmux. " "tmux hierarchy: Server > Session > Window > Pane. " - "Prefer pane_id (e.g. '%1') for targeting. " + "Prefer pane_id ('%1'). " "Targeted tmux tools accept socket_name (defaults to LIBTMUX_SOCKET); " - "list_servers discovers sockets via TMUX_TMPDIR plus extra_socket_paths." + "list_servers scans TMUX_TMPDIR and extra_socket_paths. " + "Program records keep their original socket." ) #: Activation rule. Names positive triggers and explicit anti-triggers @@ -95,9 +96,9 @@ ) _INSTR_WAIT_NOT_POLL = ( - "WAIT, DON'T POLL: run_command for authored commands needing " - "status; wait_for_channel for custom tmux wait-for; capture_since " - "for tailing; wait_for_text for output you don't author " + "WAIT, DON'T POLL: run_program for owned argv; run_command for shell status; " + "wait_for_channel for signals; capture_since for tailing; " + "wait_for_text for other output " "(patterns=null=any output; stop=[] bails); " "send_keys_batch for raw input." ) diff --git a/src/libtmux_mcp/tools/__init__.py b/src/libtmux_mcp/tools/__init__.py index 7a72f9ab..a0b30c75 100644 --- a/src/libtmux_mcp/tools/__init__.py +++ b/src/libtmux_mcp/tools/__init__.py @@ -17,6 +17,7 @@ def register_tools(mcp: FastMCP) -> None: hook_tools, option_tools, pane_tools, + program_tools, server_tools, session_tools, wait_for_tools, @@ -28,6 +29,7 @@ def register_tools(mcp: FastMCP) -> None: session_tools.register(mcp) window_tools.register(mcp) pane_tools.register(mcp) + program_tools.register(mcp) option_tools.register(mcp) env_tools.register(mcp) wait_for_tools.register(mcp) diff --git a/src/libtmux_mcp/tools/program_tools.py b/src/libtmux_mcp/tools/program_tools.py new file mode 100644 index 00000000..356b135a --- /dev/null +++ b/src/libtmux_mcp/tools/program_tools.py @@ -0,0 +1,228 @@ +"""Owned terminal programs and their cleanup records.""" + +from __future__ import annotations + +import math +import re +import threading +import typing as t + +from libtmux import Session +from pydantic import Field + +from libtmux_mcp._programs import _program_runs +from libtmux_mcp._utils import ( + ANNOTATIONS_AMBIENT_UNKNOWN, + TAG_SELF_BOUNDED, + TOOLSET_EXECUTE, + TOOLSET_INSPECT, + ExpectedToolError, + _coerce_dict_arg, + _new_server, + _prepare_start_directory, + handle_tool_errors_async, +) +from libtmux_mcp._wait_policy import _wait_ceiling_seconds +from libtmux_mcp.models import ( + ProgramCleanupResult, + ProgramRunInfo, + ProgramRunPage, + ProgramRunResult, +) + +if t.TYPE_CHECKING: + from fastmcp import FastMCP + + +@handle_tool_errors_async +async def run_program( + session_id: t.Annotated[str, Field(pattern=r"^\$[0-9]+$")], + argv: t.Annotated[list[str], Field(min_length=2, max_length=256)], + socket_name: str | None = None, + socket_path: str | None = None, + start_directory: str | None = None, + environment: dict[str, str] | str | None = None, + width: int | None = None, + height: int | None = None, + timeout: float = 30, + output_bytes: t.Annotated[int, Field(ge=1, le=65536)] = 8192, +) -> ProgramRunResult: + """Run literal argv in a fresh PTY, return its exit and remove its pane. + + Discover a stable session_id with list_sessions first. Requires connected + tmux 3.8+; get_server_capabilities explains availability. Arguments bypass + a command shell. The returned tail is rendered terminal text with merged + stdout/stderr, not a lossless byte stream. Request cancellation and timeout + clean up the owned pane; pane removal does not prove descendant exit. + Use list_program_runs and cleanup_program if cleanup remains unresolved. + Terminal ownership does not confine filesystem, network or privileges. + + Parameters + ---------- + session_id : str + Stable borrowed session ID such as ``$0``; its existing panes survive. + argv : list[str] + Executable followed by at least one argument, without shell expansion. + socket_name : str, optional + Socket name; defaults to LIBTMUX_SOCKET. + socket_path : str, optional + Socket path; defaults to LIBTMUX_SOCKET_PATH and takes precedence. + start_directory : str, optional + Existing directory for the program; relative paths resolve locally. + environment : dict or str, optional + Program environment overrides, also accepted as a JSON object string. + Values are visible in native argv and tmux state; use credential references. + width : int, optional + Initial terminal width, independent of the borrowed window. + height : int, optional + Initial terminal height, independent of the borrowed window. + timeout : float + Positive operation budget, clamped to LIBTMUX_MCP_WAIT_MAX_SECONDS. + Bounded cleanup can continue after that budget expires. + output_bytes : int + UTF-8 byte limit for the returned tail, from 1 to 65536. + + Returns + ------- + ProgramRunResult + Exact status or signal and a bounded screen after verified pane cleanup. + """ + if re.fullmatch(r"\$[0-9]+", session_id) is None: + msg = "session_id must be a stable ID from list_sessions" + raise ExpectedToolError(msg) + if not math.isfinite(timeout) or timeout <= 0: + msg = "timeout must be finite and positive" + raise ExpectedToolError(msg) + if type(output_bytes) is not int or not 1 <= output_bytes <= 65536: + msg = "output_bytes must be an integer from 1 to 65536" + raise ExpectedToolError(msg) + effective_timeout = min(timeout, _wait_ceiling_seconds()) + server = _new_server(socket_name, socket_path) + + def work(cancel: threading.Event) -> ProgramRunResult: + session = Session(server=server, session_id=session_id) + result = session.run_program( + argv, + timeout=effective_timeout, + cancel_event=cancel, + start_directory=_prepare_start_directory(start_directory), + environment=_coerce_dict_arg("environment", environment), + width=width, + height=height, + ) + raw = result.screen.text.encode("utf-8") + return ProgramRunResult( + pane_id=result.exit.pane_id, + exit_status=result.exit.exit_status, + exit_signal=result.exit.exit_signal, + screen_text=raw[-output_bytes:].decode("utf-8", "ignore"), + screen_truncated=len(raw) > output_bytes, + effective_timeout=effective_timeout, + ) + + return await _program_runs.execute(work, "run", server, session_id) + + +@handle_tool_errors_async +async def list_program_runs( + cursor: t.Annotated[str | None, Field(pattern=r"^[0-9]{1,20}$")] = None, + limit: t.Annotated[int, Field(ge=1, le=16)] = 4, +) -> ProgramRunPage: + """Page through running workers and unresolved cleanup in this MCP process. + + Summaries include a 256-byte error preview. Use get_program_run for one + owner's cleanup errors and prior output. Records remain until cleanup + succeeds; they do not survive a process restart. At most 32 queued, + running and unresolved owners share capacity; full capacity refuses new runs. + A missing pane ID can mean an unverified receipt, not absence of effects. + Pages follow creation order. Cleanup between pages cannot invalidate the + cursor; new records can appear later. No page grants cleanup authority. + + Parameters + ---------- + cursor : str, optional + Copy next_cursor from the previous page; omit to start again. + limit : int + Maximum summaries per page, from 1 to 16; defaults to 4. + + Returns + ------- + ProgramRunPage + Local summaries and next_cursor, which is null at the current end. + """ + if type(limit) is not int or not 1 <= limit <= 16: + msg = "limit must be an integer from 1 to 16" + raise ExpectedToolError(msg) + if cursor is not None and re.fullmatch(r"[0-9]{1,20}", cursor) is None: + msg = "cursor must be copied from list_program_runs" + raise ExpectedToolError(msg) + return ProgramRunPage(**_program_runs.page(cursor, limit)) + + +@handle_tool_errors_async +async def get_program_run(run_id: str) -> ProgramRunInfo: + """Inspect one retained program's cleanup evidence without querying tmux. + + Start with list_program_runs or program_recovery_id from error metadata. + This returns up to eight cleanup error summaries of 2048 UTF-8 bytes each, + the bounded primary error, and any prior exit or 2048-byte capture tail. + A running or cleanup_in_progress record is still settling. Retry + cleanup_program only for cleanup_required. Missing or removed records + return an error; no new owner is adopted. + + Parameters + ---------- + run_id : str + Opaque owner ID from this MCP process, not a pane ID or page cursor. + + Returns + ------- + ProgramRunInfo + Current local disposition and bounded prior evidence for one owner. + """ + return ProgramRunInfo(**_program_runs.inspect(run_id)) + + +@handle_tool_errors_async +async def cleanup_program(run_id: str) -> ProgramCleanupResult: + """Retry cleanup of the original owner retained by a failed program call. + + Use a cleanup_required run_id from list_program_runs or error metadata. + This can terminate that owner's program. It cannot adopt arbitrary panes + or bypass a missing creation receipt or changed lifetime. Failed cleanup + keeps the record available for another retry. The borrowed session survives. + + Parameters + ---------- + run_id : str + Opaque record ID from this MCP process, not a pane ID. + + Returns + ------- + ProgramCleanupResult + Verified cleanup; native client-only failures may have no pane ID. + """ + pane_id = await _program_runs.cleanup(run_id) + return ProgramCleanupResult(run_id=run_id, pane_id=pane_id) + + +def register(mcp: FastMCP) -> None: + """Register owned execution, recovery and daemon discovery.""" + for tool, title, toolset in ( + (run_program, "Run Program", TOOLSET_EXECUTE), + (cleanup_program, "Clean Up Program", TOOLSET_EXECUTE), + ): + mcp.tool( + title=title, + annotations=ANNOTATIONS_AMBIENT_UNKNOWN, + tags={toolset, TAG_SELF_BOUNDED}, + )(tool) + for inspect_tool, title in ( + (list_program_runs, "List Program Runs"), + (get_program_run, "Get Program Run"), + ): + mcp.tool( + title=title, + annotations=ANNOTATIONS_AMBIENT_UNKNOWN, + tags={TOOLSET_INSPECT}, + )(inspect_tool) diff --git a/src/libtmux_mcp/tools/server_tools.py b/src/libtmux_mcp/tools/server_tools.py index 3b7fdab8..1be43f74 100644 --- a/src/libtmux_mcp/tools/server_tools.py +++ b/src/libtmux_mcp/tools/server_tools.py @@ -3,10 +3,12 @@ from __future__ import annotations import contextlib +import dataclasses import logging import os import pathlib import socket +import threading import typing as t from fastmcp import Context @@ -14,8 +16,10 @@ from mcp.types import InputRequiredResult from libtmux_mcp._history import _prepare_spawn_environment +from libtmux_mcp._programs import _program_runs from libtmux_mcp._utils import ( ANNOTATIONS_AMBIENT_UNKNOWN, + TAG_SELF_BOUNDED, TOOLSET_EXECUTE, TOOLSET_INSPECT, TOOLSET_TEARDOWN, @@ -27,13 +31,19 @@ _get_caller_identity, _get_server, _invalidate_server, + _new_server, _prepare_start_directory, _serialize_session, _tmux_identity, handle_tool_errors, handle_tool_errors_async, ) -from libtmux_mcp.models import ServerInfo, SessionInfo +from libtmux_mcp.models import ( + LibraryFeatureInfo, + ServerCapabilityInfo, + ServerInfo, + SessionInfo, +) logger = logging.getLogger(__name__) @@ -234,6 +244,47 @@ def get_server_info(socket_name: str | None = None) -> ServerInfo: ) +@handle_tool_errors_async +async def get_server_capabilities( + socket_name: str | None = None, socket_path: str | None = None +) -> ServerCapabilityInfo: + """Read fresh daemon identity and library feature decisions before choosing a tool. + + This does not start a daemon. Unknown versions remain unknown; client binary + versions do not substitute for the connected daemon. Decisions are advisory: + each operation checks its own requirements. Toolset policy still determines + which tools are enabled. A failed native-client cleanup remains discoverable + through list_program_runs and cleanup_program. + + Parameters + ---------- + socket_name : str, optional + Socket name; defaults to LIBTMUX_SOCKET. + socket_path : str, optional + Socket path; defaults to LIBTMUX_SOCKET_PATH and takes precedence. + + Returns + ------- + ServerCapabilityInfo + Observed daemon identity, version, feature states and reasons. + """ + server = _new_server(socket_name, socket_path) + + def work(cancel: threading.Event) -> ServerCapabilityInfo: + report = server.capabilities(timeout=5, cancel_event=cancel) + return ServerCapabilityInfo( + pid=report.pid, + start_time=report.start_time, + version=report.version, + features=[ + LibraryFeatureInfo(**dataclasses.asdict(item)) + for item in report.features + ], + ) + + return await _program_runs.execute(work, "capabilities", server) + + def _is_tmux_socket_live(path: pathlib.Path) -> bool: """Return True if a tmux socket has a listener accepting connections. @@ -301,14 +352,21 @@ def _probe_server_by_path(socket_path: pathlib.Path) -> ServerInfo | None: #: Tools that intentionally do NOT accept ``socket_name`` because they #: either discover sockets themselves or coordinate nested tools whose -#: arguments carry their own targeting. Read by +#: arguments carry their own targeting, or operate on process-local program +#: records bound to their original socket. Read by #: ``test_registered_tools_accept_socket_name`` to enforce the #: agent-facing contract advertised in #: :data:`libtmux_mcp.server._BASE_INSTRUCTIONS`. When you add a new #: discovery-style tool, append it here AND update the prose in #: ``_BASE_INSTRUCTIONS`` so the two stay in lockstep. SOCKET_NAME_EXEMPT: frozenset[str] = frozenset( - {"call_read_tools_batch", "list_servers"} + { + "call_read_tools_batch", + "list_servers", + "list_program_runs", + "get_program_run", + "cleanup_program", + } ) @@ -377,6 +435,11 @@ def list_servers( def register(mcp: FastMCP) -> None: """Register server-level tools with the MCP instance.""" + mcp.tool( + title="Get Server Capabilities", + annotations=ANNOTATIONS_AMBIENT_UNKNOWN, + tags={TOOLSET_INSPECT, TAG_SELF_BOUNDED}, + )(get_server_capabilities) mcp.tool( title="List tmux Sessions", annotations=ANNOTATIONS_AMBIENT_UNKNOWN, diff --git a/tests/__snapshots__/test_server/test_tool_surface_matches_snapshot.json b/tests/__snapshots__/test_server/test_tool_surface_matches_snapshot.json index b8c74d3e..400a2951 100644 --- a/tests/__snapshots__/test_server/test_tool_surface_matches_snapshot.json +++ b/tests/__snapshots__/test_server/test_tool_surface_matches_snapshot.json @@ -11,6 +11,10 @@ "bytes": 3624, "sha256": "1ef50ddb5d67b1ef" }, + "cleanup_program": { + "bytes": 1134, + "sha256": "3c75cc23e2450ebf" + }, "clear_pane": { "bytes": 1200, "sha256": "1f8bd6ce014ff564" @@ -47,6 +51,14 @@ "bytes": 4196, "sha256": "c6120a0d78ce6bef" }, + "get_program_run": { + "bytes": 2520, + "sha256": "9259f144f3b5578c" + }, + "get_server_capabilities": { + "bytes": 1768, + "sha256": "fabff18f71a68b41" + }, "get_server_info": { "bytes": 1217, "sha256": "257a0887a6a895ea" @@ -79,6 +91,10 @@ "bytes": 4999, "sha256": "aece89d3b1e85f40" }, + "list_program_runs": { + "bytes": 2461, + "sha256": "f4107d591b62d583" + }, "list_servers": { "bytes": 2266, "sha256": "e344d9e06b50686d" @@ -135,6 +151,10 @@ "bytes": 3788, "sha256": "c6d6a536635729bd" }, + "run_program": { + "bytes": 3429, + "sha256": "4ed86d8b2d825c74" + }, "search_panes": { "bytes": 6449, "sha256": "b30a2e2651af1449" diff --git a/tests/test_program_tools.py b/tests/test_program_tools.py new file mode 100644 index 00000000..ec29cabf --- /dev/null +++ b/tests/test_program_tools.py @@ -0,0 +1,680 @@ +"""Owned program tools through the public MCP client.""" + +from __future__ import annotations + +import asyncio +import concurrent.futures +import contextlib +import json +import os +import pathlib +import sys +import threading +import typing as t + +import anyio +import pytest +from fastmcp import Client, FastMCP +from fastmcp.server.dependencies import get_context +from libtmux import Session, program +from libtmux.common import has_gte_version +from mcp.types import CancelledNotification, CancelledNotificationParams + +from libtmux_mcp import _programs +from libtmux_mcp.middleware import ToolErrorResultMiddleware +from libtmux_mcp.tools import program_tools, register_tools + + +def _application() -> FastMCP: + app = FastMCP("owned-program-test") + app.add_middleware(ToolErrorResultMiddleware()) + register_tools(app) + return app + + +@pytest.mark.skipif( + not has_gte_version("3.8"), reason="owned programs require tmux 3.8" +) +def test_program_run_returns_exit_output_and_preserves_parent( + mcp_session: Session, tmp_path: pathlib.Path +) -> None: + """One public call owns argv, environment, geometry and terminal cleanup.""" + before = mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout + arguments = ["space value", "$HOME", "semi;", ""] + source = ( + "import json,os,sys; " + "print(json.dumps([sys.argv[1:], os.getcwd(), os.environ['PROGRAM_VALUE'], " + "list(os.get_terminal_size())])); print('last line'); raise SystemExit(7)" + ) + + async def exercise() -> None: + async with Client(_application()) as client: + listed = {tool.name for tool in await client.list_tools()} + assert {"run_program", "list_program_runs", "cleanup_program"} <= listed + result = await client.call_tool( + "run_program", + { + "session_id": mcp_session.session_id, + "socket_name": mcp_session.server.socket_name, + "argv": [sys.executable, "-c", source, *arguments], + "start_directory": str(tmp_path), + "environment": {"PROGRAM_VALUE": "literal ; $HOME"}, + "width": 90, + "height": 21, + }, + ) + data = result.structured_content + assert data is not None + assert data["exit_status"] == 7 and data["exit_signal"] is None + expected = json.dumps( + [arguments, str(tmp_path), "literal ; $HOME", [90, 21]] + ) + assert expected in data["screen_text"] + assert data["screen_text"].endswith("last line") + assert data["pane_removed"] and not data["screen_truncated"] + assert data["history_complete"] is None + records = await client.call_tool("list_program_runs", {}) + assert records.data.items == [] + + asyncio.run(exercise()) + assert mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout == before + + +def test_program_capabilities_report_the_connected_daemon(mcp_session: Session) -> None: + """Discovery serializes core decisions without a second version table.""" + expected = mcp_session.server.capabilities() + + async def exercise() -> None: + async with Client(_application()) as client: + result = await client.call_tool( + "get_server_capabilities", + {"socket_name": mcp_session.server.socket_name}, + ) + data = result.structured_content + assert data is not None + assert data["pid"] == expected.pid + assert data["start_time"] == expected.start_time + assert data["version"] == expected.version + assert ( + data["features"][0]["status"] + == expected.feature("program-owned").status + ) + assert ( + data["features"][0]["reason"] + == expected.feature("program-owned").reason + ) + + asyncio.run(exercise()) + + +@pytest.mark.skipif( + not has_gte_version("3.8"), reason="owned programs require tmux 3.8" +) +def test_program_tail_reports_byte_truncation(mcp_session: Session) -> None: + """The public result keeps a valid UTF-8 tail and explicitly reports loss.""" + + async def exercise() -> None: + async with Client(_application()) as client: + result = await client.call_tool( + "run_program", + { + "session_id": mcp_session.session_id, + "socket_name": mcp_session.server.socket_name, + "argv": [ + sys.executable, + "-c", + "print('prefix' + 'é' * 20 + 'END')", + ], + "output_bytes": 10, + }, + ) + data = result.structured_content + assert data is not None + assert data["screen_truncated"] + assert data["screen_text"] == "éééEND" + assert len(data["screen_text"].encode()) <= 10 + + asyncio.run(exercise()) + + +@pytest.mark.skipif( + not has_gte_version("3.8"), reason="owned programs require tmux 3.8" +) +def test_program_cleanup_retry_keeps_exit_and_capture( + mcp_session: Session, monkeypatch: pytest.MonkeyPatch +) -> None: + """Inject a real buffer cleanup failure and recover through the MCP owner ID.""" + discard = program.Program._discard_capture + + def fail_discard(owner: program.Program) -> None: + if owner._capture_buffer is not None: + msg = "Capture buffer cleanup is temporarily unavailable" + raise OSError(msg) + discard(owner) + + async def exercise() -> None: + async with Client(_application()) as client: + run_id = None + cleanup_task = None + admitted, release = asyncio.Event(), asyncio.Event() + worker = _programs._run_in_worker + + async def queued(call: t.Callable[[threading.Event], t.Any]) -> t.Any: + admitted.set() + await release.wait() + return await worker(call) + + try: + with monkeypatch.context() as patch: + patch.setattr(program.Program, "_discard_capture", fail_discard) + result = await client.call_tool( + "run_program", + { + "session_id": mcp_session.session_id, + "socket_name": mcp_session.server.socket_name, + "argv": [ + sys.executable, + "-c", + "print('kept'); raise SystemExit(7)", + ], + }, + raise_on_error=False, + ) + assert result.is_error + meta = result.meta or {} + run_id = meta["program_recovery_id"] + assert meta["program_cleanup_errors"] + assert meta["program_observation"]["exit_status"] == 7 + assert meta["program_observation"]["screen_text"] == "kept" + records = await client.call_tool("list_program_runs", {}) + assert len(records.data.items) == 1 + record = records.data.items[0] + assert record.run_id == run_id + assert record.pane_state == "removed" + assert record.cleanup_pending + detail = await client.call_tool("get_program_run", {"run_id": run_id}) + assert detail.structured_content is not None + assert detail.structured_content["last_observation"]["exit_status"] == 7 + # Hold worker admission to expose duplicate queued cleanup requests. + with monkeypatch.context() as patch: + patch.setattr(_programs, "_run_in_worker", queued) + cleanup_task = asyncio.create_task( + client.call_tool("cleanup_program", {"run_id": run_id}) + ) + await asyncio.wait_for(admitted.wait(), 1) + records = await client.call_tool("list_program_runs", {}) + assert records.data.items[0].status == "cleanup_in_progress" + duplicate = await asyncio.wait_for( + client.call_tool( + "cleanup_program", {"run_id": run_id}, raise_on_error=False + ), + 1, + ) + assert duplicate.is_error + finally: + release.set() + if cleanup_task is not None: + result = await cleanup_task + assert result.structured_content is not None + assert result.structured_content["cleanup_pending"] is False + elif run_id is not None: + result = await client.call_tool( + "cleanup_program", {"run_id": run_id} + ) + assert result.structured_content is not None + assert result.structured_content["cleanup_pending"] is False + assert (await client.call_tool("list_program_runs", {})).data.items == [] + + asyncio.run(exercise()) + + +def test_program_rejected_parent_does_not_consume_capacity( + mcp_session: Session, +) -> None: + """An effect-free refusal leaves the bounded recovery table empty.""" + + async def exercise() -> None: + async with Client(_application()) as client: + result = await client.call_tool( + "run_program", + { + "session_id": "$999999999", + "socket_name": mcp_session.server.socket_name, + "argv": [sys.executable, "-c", "raise SystemExit(7)"], + }, + raise_on_error=False, + ) + assert result.is_error + assert "program_recovery_id" not in (result.meta or {}) + assert (await client.call_tool("list_program_runs", {})).data.items == [] + + asyncio.run(exercise()) + + +@pytest.mark.skipif( + not has_gte_version("3.8"), reason="owned programs require tmux 3.8" +) +def test_program_recovery_pages_survive_deleted_cursor( + mcp_session: Session, monkeypatch: pytest.MonkeyPatch +) -> None: + """Retain real failed buffers; deletion between pages cannot repeat an owner.""" + discard = program.Program._discard_capture + + def fail_discard(owner: program.Program) -> None: + if owner._capture_buffer is not None: + raise OSError("Capture cleanup unavailable: " + "é" * 4096) + discard(owner) + + async def exercise() -> None: + async with Client(_application()) as client: + retained: list[str] = [] + try: + with monkeypatch.context() as patch: + patch.setattr(program.Program, "_discard_capture", fail_discard) + for _ in range(3): + result = await client.call_tool( + "run_program", + { + "session_id": mcp_session.session_id, + "socket_name": mcp_session.server.socket_name, + "argv": [sys.executable, "-c", "print('retained')"], + }, + raise_on_error=False, + ) + retained.append((result.meta or {})["program_recovery_id"]) + first = ( + await client.call_tool("list_program_runs", {"limit": 2}) + ).structured_content + assert first is not None + assert [item["run_id"] for item in first["items"]] == retained[:2] + assert first["next_cursor"] is not None + for item in first["items"]: + assert len(item["error_preview"].encode()) <= 256 + assert "cleanup_errors" not in item + assert "last_observation" not in item + for limit in (0, 17): + refused = await client.call_tool( + "list_program_runs", {"limit": limit}, raise_on_error=False + ) + assert refused.is_error + detail = await client.call_tool( + "get_program_run", {"run_id": retained[0]} + ) + assert detail.structured_content is not None + assert ( + detail.structured_content["last_observation"]["screen_text"] + == "retained" + ) + assert all( + len(error.encode()) <= 2048 + for error in detail.structured_content["cleanup_errors"] + ) + await client.call_tool("cleanup_program", {"run_id": retained[1]}) + retained.pop(1) + second = ( + await client.call_tool( + "list_program_runs", + {"limit": 2, "cursor": first["next_cursor"]}, + ) + ).structured_content + assert second is not None + assert [item["run_id"] for item in second["items"]] == retained[1:] + assert second["next_cursor"] is None + current = ( + await client.call_tool("list_program_runs", {}) + ).structured_content + assert current is not None + assert [item["run_id"] for item in current["items"]] == retained + finally: + for run_id in retained: + await client.call_tool("cleanup_program", {"run_id": run_id}) + empty = (await client.call_tool("list_program_runs", {})).structured_content + assert empty == {"items": [], "next_cursor": None} + + asyncio.run(exercise()) + + +@pytest.mark.skipif( + not has_gte_version("3.8"), reason="owned programs require tmux 3.8" +) +@pytest.mark.parametrize("backend", ["asyncio", "anyio"]) +def test_program_cancellation_does_not_wait_for_unrelated_executor( + mcp_session: Session, monkeypatch: pytest.MonkeyPatch, backend: str +) -> None: + """Occupy the shared executor with a real worker and cancel a program request.""" + before = mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout + reserve = _programs._ProgramRuns.reserve + execute = _programs._ProgramRuns.execute + + async def exercise() -> None: + loop = asyncio.get_running_loop() + occupied, reserved, joined = (asyncio.Event() for _ in range(3)) + release = threading.Event() + + def unrelated_work() -> None: + loop.call_soon_threadsafe(occupied.set) + release.wait() + + def observed_reserve(owner: _programs._ProgramRuns, *args: t.Any) -> t.Any: + result = reserve(owner, *args) + reserved.set() + return result + + async def observed_execute( + owner: _programs._ProgramRuns, *args: t.Any, **kwargs: t.Any + ) -> t.Any: + try: + return await execute(owner, *args, **kwargs) + finally: + joined.set() + + monkeypatch.setattr(_programs._ProgramRuns, "reserve", observed_reserve) + monkeypatch.setattr(_programs._ProgramRuns, "execute", observed_execute) + async with Client(_application()) as client: + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: + loop.set_default_executor(executor) + limiter = anyio.to_thread.current_default_thread_limiter() + old_tokens = limiter.total_tokens + limiter.total_tokens = 1 + blocker = ( + loop.run_in_executor(None, unrelated_work) + if backend == "asyncio" + else asyncio.create_task(anyio.to_thread.run_sync(unrelated_work)) + ) + task = None + try: + await asyncio.wait_for(occupied.wait(), 1) + task = asyncio.create_task( + client.call_tool( + "run_program", + { + "session_id": mcp_session.session_id, + "socket_name": mcp_session.server.socket_name, + "argv": [ + sys.executable, + "-c", + "import signal; signal.pause()", + ], + }, + ) + ) + await asyncio.wait_for(reserved.wait(), 1) + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + await asyncio.wait_for(joined.wait(), 1) + assert not blocker.done() + assert ( + await client.call_tool("list_program_runs", {}) + ).data.items == [] + finally: + release.set() + await blocker + limiter.total_tokens = old_tokens + if task is not None: + task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await task + if reserved.is_set(): + await asyncio.wait_for(joined.wait(), 1) + + asyncio.run(exercise()) + assert mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout == before + + +@pytest.mark.skipif( + not has_gte_version("3.8"), reason="owned programs require tmux 3.8" +) +def test_program_thread_start_failure_cannot_execute_later( + mcp_session: Session, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path +) -> None: + """Refuse a real thread start, then prove later work cannot drain a lost launch.""" + marker = tmp_path / "unexpected-launch" + + def unavailable(thread: threading.Thread) -> t.NoReturn: + msg = "Native worker thread creation is unavailable" + raise RuntimeError(msg) + + async def exercise() -> None: + async with Client(_application()) as client: + with monkeypatch.context() as patch: + patch.setattr(threading.Thread, "start", unavailable) + refused = await client.call_tool( + "run_program", + { + "session_id": mcp_session.session_id, + "socket_name": mcp_session.server.socket_name, + "argv": [ + sys.executable, + "-c", + "import pathlib,sys; pathlib.Path(sys.argv[1]).touch()", + str(marker), + ], + }, + raise_on_error=False, + ) + assert refused.is_error + assert (await client.call_tool("list_program_runs", {})).data.items == [] + await client.call_tool( + "get_server_capabilities", + {"socket_name": mcp_session.server.socket_name}, + ) + assert not marker.exists() + assert (await client.call_tool("list_program_runs", {})).data.items == [] + + asyncio.run(exercise()) + + +@pytest.mark.skipif( + not has_gte_version("3.8"), reason="owned programs require tmux 3.8" +) +@pytest.mark.parametrize("boundary", ["running", "admission", "cleanup", "disconnect"]) +def test_program_request_cancellation_settles_worker( + mcp_session: Session, + tmp_path: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + boundary: str, +) -> None: + """Native FIFO readiness and explicit admission/cleanup barriers expose races.""" + fifo = tmp_path / "ready" + os.mkfifo(fifo, 0o600) + descriptor = os.open(fifo, os.O_RDWR | os.O_NONBLOCK) + before = mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout + run = Session.run_program + execute = _programs._ProgramRuns.execute + + async def exercise() -> None: + loop = asyncio.get_running_loop() + ready, entered, cleaned, joined = (asyncio.Event() for _ in range(4)) + admission, release_cleanup = threading.Event(), threading.Event() + cancellation: list[threading.Event] = [] + request_ids: list[str | int] = [] + if boundary != "admission": + admission.set() + if boundary != "cleanup": + release_cleanup.set() + + def readable() -> None: + if os.read(descriptor, 64): + ready.set() + loop.remove_reader(descriptor) + + def controlled(owner: Session, *args: t.Any, **kwargs: t.Any) -> t.Any: + if request_ids: + return run(owner, *args, **kwargs) + context = get_context().request_context + assert context is not None + assert context.request_id is not None + request_ids.append(context.request_id) + cancellation.append(kwargs["cancel_event"]) + loop.call_soon_threadsafe(entered.set) + try: + assert admission.wait(1), "Admission barrier was not released" + return run(owner, *args, **kwargs) + finally: + loop.call_soon_threadsafe(cleaned.set) + assert release_cleanup.wait(1), "Cleanup barrier was not released" + + async def observed( + owner: _programs._ProgramRuns, *args: t.Any, **kwargs: t.Any + ) -> t.Any: + context = get_context().request_context + assert context is not None + try: + return await execute(owner, *args, **kwargs) + finally: + if request_ids and context.request_id == request_ids[0]: + joined.set() + + monkeypatch.setattr(Session, "run_program", controlled) + monkeypatch.setattr(_programs._ProgramRuns, "execute", observed) + if boundary == "admission": + monkeypatch.setattr(_programs, "_MAX_RUNS", 1) + loop.add_reader(descriptor, readable) + app = ( + "import os,signal; f=os.open(os.environ['READY_FIFO'],os.O_WRONLY); " + "os.write(f,b'R'); os.close(f); signal.pause()" + ) + async with contextlib.AsyncExitStack() as stack: + client = await stack.enter_async_context(Client(_application())) + task = asyncio.create_task( + client.call_tool( + "run_program", + { + "session_id": mcp_session.session_id, + "socket_name": mcp_session.server.socket_name, + "argv": [sys.executable, "-c", app], + "environment": {"READY_FIFO": str(fifo)}, + }, + ) + ) + try: + async with asyncio.timeout(1): + await (entered if boundary == "admission" else ready).wait() + records = await client.call_tool("list_program_runs", {}) + assert len(records.data.items) == 1 + if boundary == "admission": + marker = tmp_path / "capacity-bypass" + refused = await client.call_tool( + "run_program", + { + "session_id": mcp_session.session_id, + "socket_name": mcp_session.server.socket_name, + "argv": [ + sys.executable, + "-c", + "import pathlib,sys; pathlib.Path(sys.argv[1]).touch()", + str(marker), + ], + }, + raise_on_error=False, + ) + assert refused.is_error + assert "capacity is full" in refused.content[0].text + assert not marker.exists() + if boundary == "disconnect": + async with asyncio.timeout(1): + await stack.aclose() + with contextlib.suppress(asyncio.CancelledError, Exception): + await task + client = await stack.enter_async_context(Client(_application())) + else: + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + async with asyncio.timeout(1): + await client.call_tool("list_program_runs", {}) + assert cancellation[0].is_set() + if boundary == "admission": + assert not ready.is_set() + admission.set() + if boundary == "cleanup": + async with asyncio.timeout(1): + await cleaned.wait() + await client.session.send_notification( + CancelledNotification( + params=CancelledNotificationParams( + request_id=request_ids[0], + reason="Repeated cleanup cancellation", + ) + ) + ) + async with asyncio.timeout(1): + await client.call_tool("list_program_runs", {}) + assert not joined.is_set() + release_cleanup.set() + async with asyncio.timeout(1): + await joined.wait() + assert ( + await client.call_tool("list_program_runs", {}) + ).data.items == [] + finally: + admission.set() + release_cleanup.set() + for event in cancellation: + event.set() + task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await task + if entered.is_set(): + async with asyncio.timeout(1): + await joined.wait() + loop.remove_reader(descriptor) + + try: + asyncio.run(exercise()) + finally: + os.close(descriptor) + assert mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout == before + + +@pytest.mark.skipif( + not has_gte_version("3.8"), reason="owned programs require tmux 3.8" +) +def test_program_missing_receipt_keeps_unknown_owner( + mcp_session: Session, monkeypatch: pytest.MonkeyPatch +) -> None: + """Lose a real creation receipt; the private server fixture owns final disposal.""" + store = _programs._ProgramRuns() + monkeypatch.setattr(program_tools, "_program_runs", store) + native = program.Program._run + before = mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout + + def lose_receipt( + owner: program.Program, args: tuple[str, ...], *rest: t.Any, **kwargs: t.Any + ) -> bytes: + result = native(owner, args, *rest, **kwargs) + if args[0] == "if-shell" and any("new-window" in arg for arg in args): + return b"" + return result + + async def exercise() -> None: + async with Client(_application()) as client: + with monkeypatch.context() as patch: + patch.setattr(program.Program, "_run", lose_receipt) + result = await client.call_tool( + "run_program", + { + "session_id": mcp_session.session_id, + "socket_name": mcp_session.server.socket_name, + "argv": [sys.executable, "-c", "raise SystemExit(7)"], + }, + raise_on_error=False, + ) + assert result.is_error + run_id = (result.meta or {})["program_recovery_id"] + (record,) = (await client.call_tool("list_program_runs", {})).data.items + assert record.pane_state == "unverified" + assert record.pane_id is None and record.cleanup_pending + cleanup = await client.call_tool( + "cleanup_program", {"run_id": run_id}, raise_on_error=False + ) + assert cleanup.is_error + assert (cleanup.meta or {})["program_recovery_id"] == run_id + assert ( + len((await client.call_tool("list_program_runs", {})).data.items) == 1 + ) + + asyncio.run(exercise()) + panes = mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout + assert set(before) < set(panes) and len(panes) == len(before) + 1 diff --git a/tests/test_server.py b/tests/test_server.py index 29be7d4f..7d062c7e 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -414,6 +414,7 @@ def test_base_instructions_surface_flagship_read_tools() -> None: def test_base_instructions_prefer_typed_completion_over_polling() -> None: """_BASE_INSTRUCTIONS names typed completion and observation primitives.""" + assert "run_program" in _BASE_INSTRUCTIONS assert "run_command" in _BASE_INSTRUCTIONS assert "wait_for_channel" in _BASE_INSTRUCTIONS assert "capture_since" in _BASE_INSTRUCTIONS diff --git a/tests/test_tool_annotations.py b/tests/test_tool_annotations.py index 0159ae5e..c4e19117 100644 --- a/tests/test_tool_annotations.py +++ b/tests/test_tool_annotations.py @@ -34,9 +34,12 @@ "find_pane_by_position", "get_pane_info", "get_server_info", + "get_server_capabilities", "get_session_info", "get_window_info", "list_panes", + "list_program_runs", + "get_program_run", "list_servers", "list_sessions", "list_windows", @@ -78,6 +81,8 @@ "pipe_pane", "respawn_pane", "run_command", + "run_program", + "cleanup_program", "send_keys", "send_keys_batch", "set_environment", From 5d66cd6b122383fb3c2e732818ef55788479ff5c Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 15 Nov 2026 20:01:04 -0600 Subject: [PATCH 05/10] docs(program): show execution and recovery why: Agents and operators need runnable examples and explicit limits before adopting the owned-program workflow. what: - Document the five tools, pagination and cleanup obligations - Explain terminal ownership and the explicit core source pin - Check documented dependency source URLs against the manifest --- README.md | 13 ++++ docs/conf.py | 10 +++ docs/reference/compatibility.md | 10 ++- docs/tools/index.md | 37 +++++++++- docs/tools/program/cleanup-program.md | 14 ++++ docs/tools/program/get-program-run.md | 12 +++ docs/tools/program/index.md | 78 ++++++++++++++++++++ docs/tools/program/list-program-runs.md | 18 +++++ docs/tools/program/run-program.md | 27 +++++++ docs/tools/server/get-server-capabilities.md | 15 ++++ docs/tools/server/index.md | 5 ++ tests/docs/test_compatibility.py | 26 +++---- 12 files changed, 249 insertions(+), 16 deletions(-) create mode 100644 docs/tools/program/cleanup-program.md create mode 100644 docs/tools/program/get-program-run.md create mode 100644 docs/tools/program/index.md create mode 100644 docs/tools/program/list-program-runs.md create mode 100644 docs/tools/program/run-program.md create mode 100644 docs/tools/server/get-server-capabilities.md diff --git a/README.md b/README.md index 725eefa4..30f9b97f 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ commands, read output, orchestrate panes. | **Session** | `list_windows`, `get_session_info`, `create_window`, `rename_session`, `select_window`, `kill_session` | | **Window** | `list_panes`, `get_window_info`, `split_window`, `rename_window`, `select_layout`, `resize_window`, `move_window`, `kill_window` | | **Pane** | `run_command`, `send_keys`, `send_keys_batch`, `paste_text`, `capture_pane`, `capture_since`, `snapshot_pane`, `search_panes`, `find_pane_by_position`, `get_pane_info`, `wait_for_text`, `wait_for_channel`, `signal_channel`, `display_message`, `select_pane`, `swap_pane`, `resize_pane`, `set_pane_title`, `clear_pane`, `pipe_pane`, `enter_copy_mode`, `exit_copy_mode`, `respawn_pane`, `kill_pane` | +| **Owned program** | `run_program`, `list_program_runs`, `get_program_run`, `cleanup_program`, `get_server_capabilities` | | **Options** | `show_option`, `set_option` | | **Environment** | `show_environment`, `set_environment` | | **Buffers** | `load_buffer`, `paste_buffer`, `show_buffer`, `delete_buffer` | @@ -45,6 +46,11 @@ commands, read output, orchestrate panes. **Requirements:** Python 3.11+, tmux >= 3.2a on `$PATH`. +Owned program tools require a connected tmux 3.8+ daemon. This development +branch pins [libtmux core PR #833](https://github.com/tmux-python/libtmux/pull/833) +as a source dependency. From this checkout, run `uv sync --all-extras --dev` +and `uv run libtmux-mcp`. Publication is held until the core API is released. + The distribution is `libtmux-mcp`, the import is `libtmux_mcp`, and the installed executable is `libtmux-mcp`. @@ -111,6 +117,13 @@ to tmux, but a better place to put the control loop. The server-side moves are: +**Owned programs.** `run_program` launches literal argv in a fresh PTY, returns +exit evidence and a bounded rendered tail, and cleans up its pane. The borrowed +session survives. `get_server_capabilities` reports live feature decisions; +`list_program_runs`, `get_program_run` and `cleanup_program` expose unresolved cleanup after +failure or cancellation. See the [owned-program guide](docs/tools/program/index.md) +for the output, descendant and process-restart limits. + **Running.** [`run_command`](https://libtmux-mcp.git-pull.com/tools/pane/run-command/) sends an authored shell command, waits for deterministic completion, and returns exit status plus tail-preserved output as one typed value. diff --git a/docs/conf.py b/docs/conf.py index a3cac7ba..e86b896a 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -137,6 +137,7 @@ def _patched_tool_collector_tool(self: ToolCollector, **kwargs: t.Any) -> t.Any: "libtmux_mcp.tools.session_tools", "libtmux_mcp.tools.window_tools", "libtmux_mcp.tools.pane_tools", + "libtmux_mcp.tools.program_tools", "libtmux_mcp.tools.option_tools", "libtmux_mcp.tools.env_tools", "libtmux_mcp.tools.buffer_tools", @@ -149,6 +150,7 @@ def _patched_tool_collector_tool(self: ToolCollector, **kwargs: t.Any) -> t.Any: "session_tools": "session/index", "window_tools": "window/index", "pane_tools": "pane/index", + "program_tools": "program/index", "option_tools": "server/index", "env_tools": "server/index", "buffer_tools": "buffer/index", @@ -171,6 +173,14 @@ def _patched_tool_collector_tool(self: ToolCollector, **kwargs: t.Any) -> t.Any: "EnvironmentSetResult", "WaitForTextResult", "RunCommandResult", + "ProgramRunResult", + "ProgramObservation", + "ProgramRunInfo", + "ProgramRunSummary", + "ProgramRunPage", + "ProgramCleanupResult", + "ServerCapabilityInfo", + "LibraryFeatureInfo", "SendKeysOperation", "SendKeysOperationResult", "SendKeysBatchResult", diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.md index 1cd4039c..47a0c6ac 100644 --- a/docs/reference/compatibility.md +++ b/docs/reference/compatibility.md @@ -19,11 +19,19 @@ | >= 3.2a | Supported | | < 3.2a | Not supported (libtmux requirement) | +Owned program tools require tmux 3.8+. Use `get_server_capabilities` to inspect +the connected daemon before choosing them. + ## Dependencies +This draft pins the unreleased core implementation in +[libtmux PR #833](https://github.com/tmux-python/libtmux/pull/833). Install from +this checkout; publication remains held until that core API is released. + | Package | Required version | |---------|-----------------| -| [libtmux](https://libtmux.git-pull.com/) | >= 0.62.0, < 1.0 | +| [libtmux](https://libtmux.git-pull.com/) | @ git+https://github.com/tmux-python/libtmux.git@ff7a6552de1ae2f87a11584df4aa48b0547af95b | +| [AnyIO](https://anyio.readthedocs.io/) | >= 4.16.0, < 5.0 | | [FastMCP](https://github.com/jlowin/fastmcp) | >= 4.0.2, < 5.0.0 | | [regex](https://github.com/mrabarnett/mrab-regex) | >= 2024.11.6 | diff --git a/docs/tools/index.md b/docs/tools/index.md index 287d85a7..d7f76130 100644 --- a/docs/tools/index.md +++ b/docs/tools/index.md @@ -5,7 +5,8 @@ Targeted tmux tools accept an optional `socket_name` parameter for multi-server support. It defaults to the {envvar}`LIBTMUX_SOCKET` env var. {toolref}`list-servers` discovers sockets itself, and batch tools -leave socket selection inside each nested tool's arguments. See +leave socket selection inside each nested tool's arguments. Program recovery +records keep their original socket; listing and cleanup use their local IDs. See {ref}`configuration`. ## Which tool do I want? @@ -25,6 +26,9 @@ leave socket selection inside each nested tool's arguments. See - Already know the `pane_id` → use it directly **Running a command?** +- {tool}`run-program` — literal argv in a fresh owned PTY, exact exit evidence and cleanup on tmux 3.8+ +- {tool}`get-server-capabilities` — connected daemon requirements and feature decisions +- {tool}`list-program-runs` / {tool}`get-program-run` / {tool}`cleanup-program` — page through, inspect and retry unresolved cleanup - {tool}`run-command` — one call to run a shell command, wait for completion, capture output, and return exit status - {tool}`send-keys` / {tool}`send-keys-batch` — raw interactive input for TUIs, control keys, and persistent shell state - {tool}`wait-for-channel` — low-level custom completion when `run-command` does not fit the shell composition @@ -155,6 +159,24 @@ Search text across panes. Wait for text to appear in a pane. ::: +:::{grid-item-card} get_server_capabilities +:link: get-server-capabilities +:link-type: ref +Read the connected daemon's library feature decisions. +::: + +:::{grid-item-card} get_program_run +:link: get-program-run +:link-type: ref +Read one owner's bounded error and prior-output evidence. +::: + +:::{grid-item-card} list_program_runs +:link: list-program-runs +:link-type: ref +Inspect active programs and unresolved cleanup records. +::: + :::{grid-item-card} get_server_info :link: get-server-info :link-type: ref @@ -357,6 +379,18 @@ Send raw keystrokes to a pane. Send several ordered raw-input operations. ::: +:::{grid-item-card} run_program +:link: run-program +:link-type: ref +Run literal argv in a fresh PTY and remove its owned pane. +::: + +:::{grid-item-card} cleanup_program +:link: cleanup-program +:link-type: ref +Retry cleanup using the original retained program owner. +::: + :::{grid-item-card} run_command :link: run-command :link-type: ref @@ -455,6 +489,7 @@ batch/index session/index window/index pane/index +program/index buffer/index hook/index ``` diff --git a/docs/tools/program/cleanup-program.md b/docs/tools/program/cleanup-program.md new file mode 100644 index 00000000..938c43ad --- /dev/null +++ b/docs/tools/program/cleanup-program.md @@ -0,0 +1,14 @@ +# Clean up program + +```{fastmcp-tool} program_tools.cleanup_program +``` + +Pass the `run_id` from {tool}`list-program-runs` or the `program_recovery_id` +from error metadata. Cleanup uses the retained owner; it does not reconstruct +ownership from a pane ID. Failed cleanup keeps the record for retry. + +The tool belongs to `execute` so an operator who permits owned execution can +also recover its resources. It can terminate that owner's remaining program. + +```{fastmcp-tool-input} program_tools.cleanup_program +``` diff --git a/docs/tools/program/get-program-run.md b/docs/tools/program/get-program-run.md new file mode 100644 index 00000000..fe9d31a7 --- /dev/null +++ b/docs/tools/program/get-program-run.md @@ -0,0 +1,12 @@ +# Get program run + +```{fastmcp-tool} program_tools.get_program_run +``` + +Read one owner's bounded error summaries and any exit or capture obtained before +a failure. The record contains the original route and public cleanup disposition. +The capture's truncation flag and unknown history completeness remain explicit. +Use {tool}`cleanup-program` when its status is `cleanup_required`. + +```{fastmcp-tool-input} program_tools.get_program_run +``` diff --git a/docs/tools/program/index.md b/docs/tools/program/index.md new file mode 100644 index 00000000..e35dbd84 --- /dev/null +++ b/docs/tools/program/index.md @@ -0,0 +1,78 @@ +# Owned programs + +Run an executable with literal arguments in a fresh PTY, read its exit and +rendered output, then remove its pane. The borrowed session and its existing +panes survive. Use {tool}`run-program` for a bounded command on tmux 3.8+. +Use {tool}`run-command` when the command needs an existing interactive shell. + +This development branch depends on the source revision of +[libtmux core PR #833](https://github.com/tmux-python/libtmux/pull/833) pinned in +`pyproject.toml` and `uv.lock`. It uses no experimental engine package. Release +is held until that core API is published and the dependency uses its release. + +Discover a stable session ID with {tool}`list-sessions`, then check +{tool}`get-server-capabilities`. Direct Python callers use the same async tool: + +```python +>>> import asyncio +>>> import sys +>>> from libtmux_mcp.tools.program_tools import run_program +>>> from libtmux_mcp.tools.server_tools import get_server_capabilities +>>> report = asyncio.run(get_server_capabilities(socket_name=server.socket_name)) +>>> if any(item.name == "program-owned" and item.status == "supported" for item in report.features): +... result = asyncio.run(run_program( +... session_id=session.session_id, +... socket_name=server.socket_name, +... argv=[sys.executable, "-c", "print('finished'); raise SystemExit(7)"], +... )) +... assert result.exit_status == 7 +... assert result.screen_text == "finished" +... assert result.pane_removed +``` + +## Cancellation and recovery + +Request cancellation signals the native worker, which attempts cleanup before +the server handler settles. An MCP client can acknowledge cancellation before +remote cleanup finishes. {tool}`list-program-runs` reports running workers and +retained cleanup summaries in pages of four (at most sixteen). +Use {tool}`get-program-run` to inspect one owner's bounded error and prior-output +details. Records survive request cancellation, including +repeated cancellation during cleanup. + +Failed calls include `program_cleanup_errors` and any `program_observation` in +MCP error metadata. If cleanup remains pending, `program_recovery_id` identifies +the original owner. Call {tool}`cleanup-program` with that ID after correcting +the cause. Retry is serialized and rechecks the original ownership. Missing +receipts or replaced lifetimes refuse cleanup; a pane ID alone cannot establish +ownership. Do not infer that a missing receipt means creation failed. + +At most 32 running, queued or unresolved owners share capacity. New work is +refused before effects when capacity is full. Records are never evicted to make +room. They exist in this MCP process and do not survive a process restart. +An unverified receipt can require operator intervention; this API cannot adopt +or force-delete an arbitrary pane to settle the record. + +## Output and lifetime limits + +The result is a tail of rendered terminal history and screen. Stdout and stderr +share the PTY. `screen_truncated` reports clipping by the MCP byte bound; +`history_complete` remains `null` because tmux may have discarded earlier +history. A core capture exceeding its own bound fails rather than returning +unmarked loss. This initial tool does not expose raw streaming or a persistent +interactive handle. + +`timeout` is clamped to `LIBTMUX_MCP_WAIT_MAX_SECONDS`; successful results report +`effective_timeout`. Cleanup has separate finite budgets and can continue after +the operation deadline. Pane removal closes the PTY but does not prove that +every descendant exited. Terminal ownership does not restrict filesystem, +network or privilege access, and it provides no controller-crash lease. + +```{toctree} +:maxdepth: 1 + +run-program +list-program-runs +get-program-run +cleanup-program +``` diff --git a/docs/tools/program/list-program-runs.md b/docs/tools/program/list-program-runs.md new file mode 100644 index 00000000..f1cbd590 --- /dev/null +++ b/docs/tools/program/list-program-runs.md @@ -0,0 +1,18 @@ +# List program runs + +```{fastmcp-tool} program_tools.list_program_runs +``` + +Read compact local summaries without querying tmux. Follow `next_cursor` until +it is `null`; each page defaults to four items and accepts at most sixteen. +Deleting a previous page's record does not invalidate its cursor. Pages reflect +current state, so newly created records may appear later and completed records +can disappear. Start again without a cursor to refresh the whole view. + +Use {tool}`get-program-run` for one owner's cleanup errors and prior exit or +capture evidence. A record marked `running` or `cleanup_in_progress` is still +settling. Retry {tool}`cleanup-program` only for `cleanup_required` records. +Successful runs leave no record. Pagination never evicts an unresolved owner. + +```{fastmcp-tool-input} program_tools.list_program_runs +``` diff --git a/docs/tools/program/run-program.md b/docs/tools/program/run-program.md new file mode 100644 index 00000000..2060899b --- /dev/null +++ b/docs/tools/program/run-program.md @@ -0,0 +1,27 @@ +# Run program + +```{fastmcp-tool} program_tools.run_program +``` + +Pass an executable and at least one argument. No command shell expands the +arguments; explicitly invoke a shell when the application needs one. + +```json +{ + "tool": "run_program", + "arguments": { + "session_id": "$0", + "argv": ["python3", "-c", "print('finished'); raise SystemExit(7)"], + "timeout": 10, + "output_bytes": 8192 + } +} +``` + +A nonzero application exit is a successful tool result with that exit status. +An operation or cleanup failure is a tool error; its metadata preserves +available exit and capture evidence and identifies any retained cleanup owner. +See {doc}`index` for cancellation, output bounds and recovery. + +```{fastmcp-tool-input} program_tools.run_program +``` diff --git a/docs/tools/server/get-server-capabilities.md b/docs/tools/server/get-server-capabilities.md new file mode 100644 index 00000000..5024a937 --- /dev/null +++ b/docs/tools/server/get-server-capabilities.md @@ -0,0 +1,15 @@ +# Get server capabilities + +```{fastmcp-tool} server_tools.get_server_capabilities +``` + +The report includes the observed daemon PID, start time, version and each +library feature's minimum release, status and reason. It reads the selected +daemon afresh and does not start one. Unknown version strings remain unknown. +Operations recheck their own requirements; a saved report cannot authorize a +later operation after the daemon restarts. + +MCP toolsets still determine the tools advertised by `tools/list`. + +```{fastmcp-tool-input} server_tools.get_server_capabilities +``` diff --git a/docs/tools/server/index.md b/docs/tools/server/index.md index 299d5bbb..c6df5de1 100644 --- a/docs/tools/server/index.md +++ b/docs/tools/server/index.md @@ -17,6 +17,10 @@ Discover tmux daemons on the system. Query server process identity and version. ::: +:::{grid-item-card} {tooliconl}`get-server-capabilities` +Read connected daemon feature requirements and availability. +::: + :::{grid-item-card} {tooliconl}`create-session` Create a new tmux session. ::: @@ -50,6 +54,7 @@ Set an environment variable on the server. list-sessions list-servers get-server-info +get-server-capabilities create-session kill-server show-option diff --git a/tests/docs/test_compatibility.py b/tests/docs/test_compatibility.py index c89fd0f6..3e7ae58d 100644 --- a/tests/docs/test_compatibility.py +++ b/tests/docs/test_compatibility.py @@ -5,9 +5,8 @@ drifts silently every time one moves — and a reader planning an upgrade gets a number the resolver will never agree with. -Ranges are compared as :class:`~packaging.specifiers.SpecifierSet` -values, so the doc stays free to write ``>= 0.62.0, < 1.0`` where the -manifest writes ``>=0.62.0,<1.0``. +Requirements compare both normalized version ranges and direct source URLs. +A documented source pin must match the dependency the resolver installs. """ from __future__ import annotations @@ -18,7 +17,6 @@ import pytest import tomlkit from packaging.requirements import Requirement -from packaging.specifiers import SpecifierSet from packaging.utils import NormalizedName, canonicalize_name if t.TYPE_CHECKING: @@ -29,7 +27,7 @@ _LINK = re.compile(r"\[([^\]]+)\]\([^)]*\)") -def _documented(text: str) -> dict[NormalizedName, SpecifierSet]: +def _documented(text: str) -> dict[NormalizedName, Requirement]: """Return the ``## Dependencies`` table keyed by canonical name.""" for chunk in re.split(r"^## ", text, flags=re.MULTILINE)[1:]: title, _, body = chunk.partition("\n") @@ -40,29 +38,29 @@ def _documented(text: str) -> dict[NormalizedName, SpecifierSet]: for line in body.splitlines() if line.strip().startswith("|") ] - return { - canonicalize_name( - m.group(1) if (m := _LINK.search(name)) else name - ): SpecifierSet(version) - for name, version, *_ in rows[2:] - } + requirements = {} + for name, version, *_ in rows[2:]: + match = _LINK.search(name) + requirement = Requirement((match.group(1) if match else name) + version) + requirements[canonicalize_name(requirement.name)] = requirement + return requirements pytest.fail("compatibility.md has no '## Dependencies' section") -def _declared(repo_root: pathlib.Path) -> dict[NormalizedName, SpecifierSet]: +def _declared(repo_root: pathlib.Path) -> dict[NormalizedName, Requirement]: """Return ``[project].dependencies`` keyed by canonical name.""" manifest = tomlkit.loads( (repo_root / "pyproject.toml").read_text(encoding="utf-8") ).unwrap() reqs = [Requirement(spec) for spec in manifest["project"]["dependencies"]] - return {canonicalize_name(r.name): r.specifier for r in reqs} + return {canonicalize_name(r.name): r for r in reqs} def test_documented_dependency_ranges_match_the_manifest( docs_dir: pathlib.Path, repo_root: pathlib.Path, ) -> None: - """Every runtime dependency is listed, with the range the resolver enforces.""" + """Document every dependency with its enforced range or source URL.""" text = (docs_dir / "reference" / "compatibility.md").read_text(encoding="utf-8") assert _documented(text) == _declared(repo_root) From ca667782c917a5f1d70cc400882a97841e0df3af Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 15 Nov 2026 20:16:06 -0600 Subject: [PATCH 06/10] mcp(fix): redact program argv in audit records why: Argument lists can contain credentials, and auditing occurs before the tool schema rejects malformed values. what: - Digest the whole argv payload regardless of its input shape - Check accepted and rejected calls through the public MCP server --- src/libtmux_mcp/middleware.py | 5 +++- tests/test_program_tools.py | 49 +++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/libtmux_mcp/middleware.py b/src/libtmux_mcp/middleware.py index 6ed4d4ef..72bff030 100644 --- a/src/libtmux_mcp/middleware.py +++ b/src/libtmux_mcp/middleware.py @@ -622,6 +622,7 @@ def _summarize_args(args: dict[str, t.Any]) -> dict[str, t.Any]: ``respawn_pane``) have each *value* digested while keys remain visible — env-var-name-like keys are operator-debug-useful and rarely sensitive, while their values usually are. + The whole argv value is digested, including malformed payload shapes. Known nested operation lists are summarized recursively so batched tool calls keep target metadata while redacting inner payloads. @@ -647,7 +648,9 @@ def _summarize_args(args: dict[str, t.Any]) -> dict[str, t.Any]: """ summary: dict[str, t.Any] = {} for key, value in args.items(): - if key in _SENSITIVE_ARG_NAMES and isinstance(value, str): + if key == "argv": + summary[key] = _redact_digest(str(value)) + elif key in _SENSITIVE_ARG_NAMES and isinstance(value, str): summary[key] = _redact_digest(value) elif key in _SENSITIVE_ARG_NAMES and isinstance(value, dict): summary[key] = {k: _redact_digest(str(v)) for k, v in value.items()} diff --git a/tests/test_program_tools.py b/tests/test_program_tools.py index ec29cabf..5a02e4cf 100644 --- a/tests/test_program_tools.py +++ b/tests/test_program_tools.py @@ -6,6 +6,7 @@ import concurrent.futures import contextlib import json +import logging import os import pathlib import sys @@ -22,6 +23,7 @@ from libtmux_mcp import _programs from libtmux_mcp.middleware import ToolErrorResultMiddleware +from libtmux_mcp.server import build_mcp_server from libtmux_mcp.tools import program_tools, register_tools @@ -80,6 +82,53 @@ async def exercise() -> None: assert mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout == before +@pytest.mark.skipif( + not has_gte_version("3.8"), reason="owned programs require tmux 3.8" +) +@pytest.mark.parametrize("malformed", [False, True]) +def test_program_audit_redacts_argv_before_validation( + mcp_session: Session, caplog: pytest.LogCaptureFixture, malformed: bool +) -> None: + """Public calls redact both accepted argv and rejected payload shapes.""" + secret = "PROGRAM_ARG_PAYLOAD_72be" + environment_secret = "PROGRAM_ENV_PAYLOAD_d628" + argv: t.Any = ( + {secret: "invalid list"} + if malformed + else [sys.executable, "-c", "raise SystemExit(7)", secret] + ) + + async def exercise() -> None: + async with Client(build_mcp_server()) as client: + result = await client.call_tool( + "run_program", + { + "session_id": mcp_session.session_id, + "socket_name": mcp_session.server.socket_name, + "argv": argv, + "environment": {"PROGRAM_VALUE": environment_secret}, + }, + raise_on_error=False, + ) + assert result.is_error is malformed + if not malformed: + assert result.structured_content is not None + assert result.structured_content["exit_status"] == 7 + + with caplog.at_level(logging.INFO, logger="libtmux_mcp.audit"): + asyncio.run(exercise()) + messages = [record.getMessage() for record in caplog.records] + audit = [ + record.getMessage() + for record in caplog.records + if record.name == "libtmux_mcp.audit" + ] + assert any("tool=run_program" in message for message in audit) + assert any("sha256_prefix" in message for message in audit) + assert all(secret not in message for message in messages) + assert all(environment_secret not in message for message in messages) + + def test_program_capabilities_report_the_connected_daemon(mcp_session: Session) -> None: """Discovery serializes core decisions without a second version table.""" expected = mcp_session.server.capabilities() From fd9734f2f303ee121f2250a9ee2869abd0da98d3 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 15 Nov 2026 20:16:06 -0600 Subject: [PATCH 07/10] docs(changelog): record owned program tools why: The execution and recovery workflow changes the public tool set. what: - Describe program results, capability discovery and cleanup retries - State the core source dependency and ownership limits --- CHANGES | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/CHANGES b/CHANGES index e530660e..fca97a0f 100644 --- a/CHANGES +++ b/CHANGES @@ -13,8 +13,33 @@ _Notes on upcoming releases will be added here_ `libtmux-mcp` requires Python 3.11 or newer. Python 3.10 reached end of life in October 2026. +### Dependencies + +**Program tools require the core development source** + +The dependency is pinned to the reviewed source of +[libtmux core PR #833](https://github.com/tmux-python/libtmux/pull/833). +Release remains held until that API is published and the pin is replaced +with its release. AnyIO is an explicit runtime dependency for cooperative +worker execution. + ### What's new +**Run a program and recover its cleanup** + +{tooliconl}`run-program` starts literal argv in an owned terminal, waits for its +exit and returns status or signal plus a bounded screen. The borrowed session +survives. It requires a connected tmux 3.8+ daemon; use +{tooliconl}`get-server-capabilities` to inspect the library's feature decisions. +Cancellation joins the worker before the request settles. + +{tooliconl}`list-program-runs` pages through running and unresolved owners. +{tooliconl}`get-program-run` reads one owner's bounded error and prior output; +{tooliconl}`cleanup-program` retries cleanup using that retained owner. Records +remain in the MCP process until cleanup succeeds. Terminal ownership does not +confine filesystem, network or privileges, and removing a pane does not prove +that every descendant exited. See {doc}`tools/program/index`. + **Kill tools ask the user first** When the client supports MCP elicitation, {tooliconl}`kill-session`, From 81e2d5d90272035536e7455746e1b201728d2c1f Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 15 Nov 2026 20:50:18 -0600 Subject: [PATCH 08/10] deps(fix): use core command payload redaction why: Native transport failures must not expose argv or environment values through MCP errors and logs. what: - Pin the core revision that protects command representations - Keep the lock and documented source dependency aligned --- docs/reference/compatibility.md | 2 +- pyproject.toml | 2 +- uv.lock | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.md index 47a0c6ac..1f87d2af 100644 --- a/docs/reference/compatibility.md +++ b/docs/reference/compatibility.md @@ -30,7 +30,7 @@ this checkout; publication remains held until that core API is released. | Package | Required version | |---------|-----------------| -| [libtmux](https://libtmux.git-pull.com/) | @ git+https://github.com/tmux-python/libtmux.git@ff7a6552de1ae2f87a11584df4aa48b0547af95b | +| [libtmux](https://libtmux.git-pull.com/) | @ git+https://github.com/tmux-python/libtmux.git@4cdc8da33dbb93bc5b4c45292e2d44501b08c6a6 | | [AnyIO](https://anyio.readthedocs.io/) | >= 4.16.0, < 5.0 | | [FastMCP](https://github.com/jlowin/fastmcp) | >= 4.0.2, < 5.0.0 | | [regex](https://github.com/mrabarnett/mrab-regex) | >= 2024.11.6 | diff --git a/pyproject.toml b/pyproject.toml index edea433e..13650554 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,7 +40,7 @@ include = [ dependencies = [ "anyio>=4.16.0,<5.0", - "libtmux @ git+https://github.com/tmux-python/libtmux.git@ff7a6552de1ae2f87a11584df4aa48b0547af95b", + "libtmux @ git+https://github.com/tmux-python/libtmux.git@4cdc8da33dbb93bc5b4c45292e2d44501b08c6a6", "fastmcp>=4.0.2,<5.0.0", "regex>=2024.11.6", ] diff --git a/uv.lock b/uv.lock index ec50321b..24f60f49 100644 --- a/uv.lock +++ b/uv.lock @@ -1220,7 +1220,7 @@ wheels = [ [[package]] name = "libtmux" version = "0.62.0" -source = { git = "https://github.com/tmux-python/libtmux.git?rev=ff7a6552de1ae2f87a11584df4aa48b0547af95b#ff7a6552de1ae2f87a11584df4aa48b0547af95b" } +source = { git = "https://github.com/tmux-python/libtmux.git?rev=4cdc8da33dbb93bc5b4c45292e2d44501b08c6a6#4cdc8da33dbb93bc5b4c45292e2d44501b08c6a6" } [[package]] name = "libtmux-mcp" @@ -1283,7 +1283,7 @@ testing = [ requires-dist = [ { name = "anyio", specifier = ">=4.16.0,<5.0" }, { name = "fastmcp", specifier = ">=4.0.2,<5.0.0" }, - { name = "libtmux", git = "https://github.com/tmux-python/libtmux.git?rev=ff7a6552de1ae2f87a11584df4aa48b0547af95b" }, + { name = "libtmux", git = "https://github.com/tmux-python/libtmux.git?rev=4cdc8da33dbb93bc5b4c45292e2d44501b08c6a6" }, { name = "regex", specifier = ">=2024.11.6" }, ] From 7704cad7dadd6fe50ccc23ceb01df5a581952e80 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 15 Nov 2026 20:50:18 -0600 Subject: [PATCH 09/10] program(fix): retry cleanup after termination observation fails why: A retained owner can verify pane removal even after its process observer is lost. what: - Attempt cleanup after termination errors and retain both failure details - Retire records only after cleanup verifies all owned resources - Exercise native launch refusal, payload redaction and cleanup retry through MCP --- docs/tools/program/cleanup-program.md | 3 + src/libtmux_mcp/_programs.py | 28 +++++-- tests/test_program_tools.py | 107 ++++++++++++++++++++++++++ 3 files changed, 130 insertions(+), 8 deletions(-) diff --git a/docs/tools/program/cleanup-program.md b/docs/tools/program/cleanup-program.md index 938c43ad..dbe66dba 100644 --- a/docs/tools/program/cleanup-program.md +++ b/docs/tools/program/cleanup-program.md @@ -6,6 +6,9 @@ Pass the `run_id` from {tool}`list-program-runs` or the `program_recovery_id` from error metadata. Cleanup uses the retained owner; it does not reconstruct ownership from a pane ID. Failed cleanup keeps the record for retry. +If termination fails, cleanup still checks whether the owned pane is absent. +A verified absence retires the record; otherwise both failures remain available +in its cleanup details. The tool belongs to `execute` so an operator who permits owned execution can also recover its resources. It can terminate that owner's remaining program. diff --git a/src/libtmux_mcp/_programs.py b/src/libtmux_mcp/_programs.py index 1418edbc..969d1cd1 100644 --- a/src/libtmux_mcp/_programs.py +++ b/src/libtmux_mcp/_programs.py @@ -262,31 +262,43 @@ async def cleanup(self, run_id: str) -> str | None: def work(cancel: threading.Event) -> str | None: entered.set() + termination_error: BaseException | None = None try: if cancel.is_set(): msg = "Program cleanup was cancelled before admission" raise _ProgramRunError(msg, run_id) # noqa: TRY301 - retain retry state. if owner.recovery.pane_state == "receipt-recorded": - owner.terminate(timeout=0.5) + try: + owner.terminate(timeout=0.5) + except BaseException as error: # noqa: BLE001 - cleanup may verify an absent pane without its observer. + termination_error = error owner.cleanup(timeout=0.5) if owner.recovery.cleanup_pending: msg = "Program cleanup remains unverified" raise _ProgramRunError(msg, run_id) # noqa: TRY301 - retain retry state. except BaseException as error: + errors = ( + (error,) + if termination_error is None + else (termination_error, error) + ) + failures: list[str] = [] + for cause in errors: + failures.extend( + _error_text(item) + for item in getattr(cause, "cleanup_errors", ()) + ) + failures.append(_error_text(cause)) with self._lock: - run.error = _error_text(error) + run.error = _error_text(errors[0]) run.cleanup_errors = ( *run.cleanup_errors, - *( - _error_text(item) - for item in getattr(error, "cleanup_errors", ()) - ), - _error_text(error), + *failures, )[-8:] run.recovery = owner.recovery run.status = "cleanup_required" raise _ProgramRunError( - str(error), run_id, run.cleanup_errors, run.last_observation + str(errors[0]), run_id, run.cleanup_errors, run.last_observation ) from error self.retire(run) return owner.recovery.pane_id diff --git a/tests/test_program_tools.py b/tests/test_program_tools.py index 5a02e4cf..cbe47e9e 100644 --- a/tests/test_program_tools.py +++ b/tests/test_program_tools.py @@ -129,6 +129,113 @@ async def exercise() -> None: assert all(environment_secret not in message for message in messages) +@pytest.mark.skipif( + not has_gte_version("3.8"), reason="owned programs require tmux 3.8" +) +def test_program_rejected_launch_recovers_after_verified_removal( + mcp_session: Session, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """Native errors hide payloads and absent-pane cleanup survives lost observation.""" + store = _programs._ProgramRuns() + monkeypatch.setattr(program_tools, "_program_runs", store) + native = program._Client.__init__ + argument = "PROGRAM_RECOVERY_ARG_ba71" + environment = "PROGRAM_RECOVERY_ENV_c329" + before = mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout + + def reject_launch( + client: program._Client, command: tuple[str, ...], *args: t.Any + ) -> None: + changed = tuple( + value.replace("respawn-pane ", "program-test-invalid-command ", 1) + for value in command + ) + native(client, changed, *args) + + def retain_owner(*args: t.Any, **kwargs: t.Any) -> None: + msg = "Controlled initial removal failure" + raise OSError(msg) + + async def exercise() -> None: + async with Client(build_mcp_server()) as client: + run_id = None + try: + with monkeypatch.context() as patch: + patch.setattr(program._Client, "__init__", reject_launch) + patch.setattr(program.Program, "_remove", retain_owner) + result = await client.call_tool( + "run_program", + { + "session_id": mcp_session.session_id, + "socket_name": mcp_session.server.socket_name, + "argv": [ + sys.executable, + "-c", + "raise SystemExit(7)", + argument, + ], + "environment": {"PROGRAM_VALUE": environment}, + }, + raise_on_error=False, + ) + assert result.is_error + run_id = (result.meta or {})["program_recovery_id"] + detail = await client.call_tool("get_program_run", {"run_id": run_id}) + page = await client.call_tool("list_program_runs", {}) + evidence = repr((result, detail, page)) + assert argument not in evidence and environment not in evidence + records = repr([record.__dict__ for record in caplog.records]) + assert argument not in records and environment not in records + refused = await client.call_tool( + "cleanup_program", {"run_id": run_id}, raise_on_error=False + ) + assert refused.is_error + assert (refused.meta or {})["program_recovery_id"] == run_id + cleanup_errors = (refused.meta or {})["program_cleanup_errors"] + assert "submitted program lifetime is unknown" in cleanup_errors[-2] + assert ( + "program lifetime observation is unavailable" in cleanup_errors[-1] + ) + owner = store._runs[run_id].owner + assert owner is not None and owner.recovery.cleanup_pending + pane_id = owner.recovery.pane_id + assert pane_id is not None + assert ( + pane_id + in mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout + ) + mcp_session.cmd("kill-pane", "-t", pane_id) + cleaned = await client.call_tool( + "cleanup_program", {"run_id": run_id}, raise_on_error=False + ) + assert not cleaned.is_error + assert cleaned.structured_content is not None + assert not cleaned.structured_content["cleanup_pending"] + assert ( + await client.call_tool("list_program_runs", {}) + ).data.items == [] + finally: + if run_id is not None and run_id in store._runs: + retained = store._runs[run_id] + assert retained.owner is not None + owner = retained.owner + panes = mcp_session.cmd( + "list-panes", "-s", "-F", "#{pane_id}" + ).stdout + pane_id = owner.recovery.pane_id + if pane_id is not None and pane_id in panes: + mcp_session.cmd("kill-pane", "-t", pane_id) + owner.cleanup(timeout=0.5) + assert not owner.recovery.cleanup_pending + store.retire(retained) + + with caplog.at_level(logging.DEBUG, logger="libtmux.program"): + asyncio.run(exercise()) + assert mcp_session.cmd("list-panes", "-s", "-F", "#{pane_id}").stdout == before + + def test_program_capabilities_report_the_connected_daemon(mcp_session: Session) -> None: """Discovery serializes core decisions without a second version table.""" expected = mcp_session.server.capabilities() From 2e79d92eaacdd9d0c582ac3c9ace05fc71c0eefe Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 15 Nov 2026 20:50:18 -0600 Subject: [PATCH 10/10] docs(changes): describe program recovery corrections why: Callers need the cleanup retry and diagnostic payload guarantees. what: - Document verified-absence recovery and retained failure details - Describe command and audit payload redaction --- CHANGES | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGES b/CHANGES index fca97a0f..36fe4833 100644 --- a/CHANGES +++ b/CHANGES @@ -17,7 +17,7 @@ in October 2026. **Program tools require the core development source** -The dependency is pinned to the reviewed source of +The dependency is pinned to the source of [libtmux core PR #833](https://github.com/tmux-python/libtmux/pull/833). Release remains held until that API is published and the pin is replaced with its release. AnyIO is an explicit runtime dependency for cooperative @@ -40,6 +40,10 @@ remain in the MCP process until cleanup succeeds. Terminal ownership does not confine filesystem, network or privileges, and removing a pane does not prove that every descendant exited. See {doc}`tools/program/index`. +Cleanup retries check for an absent owned pane even when termination observation +fails. If cleanup also fails, the record keeps both errors. Native command +representations and audit summaries hide submitted argv and environment values. + **Kill tools ask the user first** When the client supports MCP elicitation, {tooliconl}`kill-session`,