From fda53be310d2d52354f3db5868fade5c2f9deb7e Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:39:26 -0500 Subject: [PATCH 1/2] Support read-only MCP discovery through an opt-in cmd2 extra Let Cmd own listener startup, shutdown, and snapshot refresh at its command and prompt boundaries. Keep the SDK optional and make the fleet console a consumer of the supported API. Exercise default installations and real MCP clients separately in CI. --- .github/workflows/rerun-unacquired.yml | 2 +- .github/workflows/tests.yml | 34 +- CHANGELOG.md | 11 +- README.md | 6 +- cmd2/_mcp_server.py | 616 ++++++ cmd2/_mcp_snapshot.py | 970 ++++++++++ cmd2/cmd2.py | 101 +- docs/examples/index.md | 2 +- docs/examples/mcp_server.md | 380 +--- docs/features/index.md | 1 + docs/features/mcp_server.md | 96 + docs/overview/installation.md | 3 + examples/README.md | 7 +- examples/mcp_server.py | 1649 +---------------- mkdocs.yml | 1 + pyproject.toml | 5 +- ...ample_mcp_server.py => test_mcp_server.py} | 961 +++++----- 17 files changed, 2364 insertions(+), 2481 deletions(-) create mode 100644 cmd2/_mcp_server.py create mode 100644 cmd2/_mcp_snapshot.py create mode 100644 docs/features/mcp_server.md rename tests/{test_example_mcp_server.py => test_mcp_server.py} (82%) diff --git a/.github/workflows/rerun-unacquired.yml b/.github/workflows/rerun-unacquired.yml index b24a34263..da222dc7f 100644 --- a/.github/workflows/rerun-unacquired.yml +++ b/.github/workflows/rerun-unacquired.yml @@ -45,7 +45,7 @@ jobs: run: | # Count the test jobs no runner took, and the ones which did not pass for another reason. counts=$(gh api "repos/$GH_REPO/actions/runs/$RUN_ID/attempts/$RUN_ATTEMPT/jobs?per_page=100" --jq ' - [.jobs[] | select(.name | startswith("tests (") or startswith("example-tests (")) + [.jobs[] | select(.name | startswith("tests (") or startswith("mcp-tests (")) | select(.conclusion != "success")] as $bad | [$bad[] | select(.conclusion == "cancelled" and .runner_id == 0 and (.steps | length) == 0)] as $unacquired | "\($unacquired | length) \(($bad | length) - ($unacquired | length))"') diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 83424ecf0..2768cc439 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -68,6 +68,10 @@ jobs: allow-prereleases: true - name: Install the project run: uv sync --no-default-groups --group test + - name: Verify the base installation has no MCP SDK + run: + uv run --no-sync python -c "from importlib.util import find_spec; assert find_spec('mcp') + is None" # faulthandler_timeout in pyproject.toml makes pytest print the stack of every thread once a # test has run for a minute. A test which hangs keeps the job going until its timeout, above. @@ -92,10 +96,10 @@ jobs: use_oidc: true verbose: true - # The MCP server example is the one example with tests, and its tests of the server itself need - # the MCP SDK, which the test group does not install. This job installs it, so that they run - # somewhere on every pull request. - example-tests: + mcp-tests: + permissions: + contents: read + id-token: write strategy: matrix: os: [ubuntu-latest, windows-latest] @@ -105,7 +109,7 @@ jobs: timeout-minutes: 10 env: # With this set, a test which needs the SDK fails where the SDK is missing. It is not skipped. - CMD2_EXAMPLE_TESTS_NEED_SDK: "1" + CMD2_MCP_TESTS_NEED_SDK: "1" defaults: run: shell: bash @@ -122,22 +126,28 @@ jobs: with: python-version: ${{ matrix.python-version }} allow-prereleases: true - - name: Install the project with the examples group - run: uv sync --no-default-groups --group test --group examples + - name: Install the project with the MCP extra + run: uv sync --no-default-groups --group test --extra mcp - - name: Run the example's tests + - name: Run MCP server and example tests run: >- - uv run --no-default-groups --group test --group examples python -Xutf8 -m pytest - tests/test_example_mcp_server.py --no-cov -rs + uv run --no-sync python -Xutf8 -m pytest tests/test_mcp_server.py -rs + - name: Upload MCP coverage to Codecov + if: ${{ !cancelled() }} + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + files: coverage.xml + flags: unittests + use_oidc: true # Single stable status check for the whole test matrix, so branch protection # doesn't need updating every time the OS/Python matrix changes. all-tests-passed: name: All Tests Passed if: always() - needs: [tests, example-tests] + needs: [tests, mcp-tests] runs-on: ubuntu-latest steps: - name: Fail if any matrix job did not succeed - if: needs.tests.result != 'success' || needs.example-tests.result != 'success' + if: needs.tests.result != 'success' || needs.mcp-tests.result != 'success' run: exit 1 diff --git a/CHANGELOG.md b/CHANGELOG.md index ccdbbb2e0..1c77bac9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,13 +21,10 @@ cannot be reassigned. A parser given to `@with_argparser` is the spec's `parser_source` itself, shared by every application which has not built the command's parser yet: to change one application's parser, change the one which `self.command_parsers.get(func)` returns. - - Added the - [mcp_server.py](https://github.com/python-cmd2/cmd2/blob/main/examples/mcp_server.py) example, - a `cmd2` application which, while its prompt is live, serves a read-only description of its - own commands to an AI assistant over MCP, so that the assistant can work out the command line - for what the person asks. It needs the MCP SDK, which is not a `cmd2` dependency. See - [MCP Server](docs/examples/mcp_server.md) for how to run it, connect an assistant, and use it - in your own application. + - Added an optional [MCP server](docs/features/mcp_server.md) to `Cmd`. Install `cmd2[mcp]` and + set `mcp_port` to let local clients discover the running application's commands, arguments, + shortcuts, aliases, and macros. The server is read-only and disabled by default. The + [Fleet console example](docs/examples/mcp_server.md) shows how to connect a client. ## 4.4.5 (2026-12-02) diff --git a/README.md b/README.md index fd32549d7..edfdeb7fc 100644 --- a/README.md +++ b/README.md @@ -33,9 +33,9 @@ dashboards and panels that show realtime status and other information. See example. An AI assistant can use the Model Context Protocol (MCP) to discover the commands, arguments, and -aliases available in a running `cmd2` application. The read-only -[MCP server example](examples/mcp_server.py) shows how. Follow the -[setup guide](docs/examples/mcp_server.md) to connect a client or add the server to your own app. +aliases available in a running `cmd2` application. Install `cmd2[mcp]` and pass `mcp_port=8765` to +`cmd2.Cmd` to enable the read-only server. See the [MCP server guide](docs/features/mcp_server.md) +and [Fleet console example](examples/mcp_server.py). ## Quick start diff --git a/cmd2/_mcp_server.py b/cmd2/_mcp_server.py new file mode 100644 index 000000000..09c6172a9 --- /dev/null +++ b/cmd2/_mcp_server.py @@ -0,0 +1,616 @@ +"""Serve read-only command descriptions over MCP on IPv4 loopback.""" + +from __future__ import annotations + +import contextlib +import importlib +import itertools +import logging +import signal +import socket +import threading +import time +from collections import deque +from dataclasses import replace +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import cmd2 + +from ._mcp_snapshot import ( + _NOT_BUILT, + CommandDescription, + CommandList, + DescriptionUnavailableError, + Snapshot, + Tables, + UnknownCommandError, + answer_describe_command, + answer_list_commands, + answer_tables, + build_snapshot, + failed_snapshot, + plain_text, +) + +if TYPE_CHECKING: + from collections.abc import Collection, Generator + from types import FrameType + + from .cmd2 import Cmd + + +HOST = "127.0.0.1" +LIBRARY_LOGGERS = ("uvicorn", "mcp") # the top-level logger of each library the server uses +RECORDS_KEPT = 50 +RECORDS_SHOWN = 5 # by mcp_status() + +# What a client gives its model about this server. +INSTRUCTIONS = ( + "This server describes the commands of an interactive command-line application which a person is using. It cannot " + "run them. To help the person, answer with a command line for them to type. Call list_commands first, and " + "describe_command before giving a command's arguments. The description reflects the last successful rebuild. " + "If stale_reason is set, tell the person that the available commands may have changed." +) + + +class _KeepRecords(logging.Handler): + """Keeps the last RECORDS_KEPT records it is given, and writes them nowhere.""" + + def __init__(self) -> None: + super().__init__() + self.kept: deque[logging.LogRecord] = deque(maxlen=RECORDS_KEPT) + + def emit(self, record: logging.LogRecord) -> None: + self.kept.append(record) + + +class _SharedLogging: + """The changes to the libraries' loggers, owned by every run in the process together.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._holds = 0 + self._saved: dict[str, bool] = {} # each library logger's propagate, as it was found + self._handler = _KeepRecords() # one for the process, so the records outlive any run + + def take(self) -> None: + """Take a hold. The first one saves what it finds and makes the changes.""" + with self._lock: + if self._holds == 0: + for name in LIBRARY_LOGGERS: + logger = logging.getLogger(name) + self._saved[name] = logger.propagate + logger.addHandler(self._handler) + logger.propagate = False + self._holds += 1 + + def release(self) -> None: + """Let go of a hold. The last one removes the handler it added and puts each propagate back.""" + with self._lock: + if self._holds == 0: + return + self._holds -= 1 + if self._holds == 0: + for name, propagate in self._saved.items(): + logger = logging.getLogger(name) + logger.removeHandler(self._handler) + logger.propagate = propagate + self._saved = {} + + @property + def holds(self) -> int: + """The number of runs holding the changes.""" + with self._lock: + return self._holds + + def records(self) -> list[logging.LogRecord]: + """Return the most recent library log records, oldest first.""" + self._handler.acquire() # emit() appends under the same lock on the worker thread + try: + return list(self._handler.kept) + finally: + self._handler.release() + + +_shared_logging = _SharedLogging() # one for the module + + +@contextlib.contextmanager +def _root_logger_left_alone() -> Generator[None, None, None]: + """Hold a temporary handler on the root logger, so that logging.basicConfig(), which MCPServer() calls, does nothing. + + The root logger's level is not touched. + """ + root = logging.getLogger() + placeholder = logging.NullHandler() + root.addHandler(placeholder) + try: + yield + finally: + root.removeHandler(placeholder) + + +@contextlib.contextmanager +def _sigint_deferred() -> Generator[None, None, None]: + """Hold off Ctrl-C until the block has ended, then deliver it to the handler which was there before. + + A start takes something (the hold on the logging, the socket, the worker) and records it in its run inside one of + these, so that an interrupt never falls between the two: whatever the start has taken, its run knows of. cmd2's + sigint_protection cannot do this for the first start, because cmdloop() installs cmd2's handler after it. + + Off the main thread it does nothing: signal.signal() cannot be called there, and Python runs signal handlers on the + main thread alone. A handler which is not a function (SIG_IGN or SIG_DFL) is left as it is installed. + """ + saved = signal.getsignal(signal.SIGINT) if threading.current_thread() is threading.main_thread() else None + if not callable(saved): + yield + return + arrived: list[tuple[int, FrameType | None]] = [] # the first interrupt which arrived, if one did + + def defer(signum: int, frame: FrameType | None) -> None: + if not arrived: + arrived.append((signum, frame)) + + signal.signal(signal.SIGINT, defer) + try: + yield + finally: + signal.signal(signal.SIGINT, saved) + if arrived: + saved(*arrived[0]) # Python's own handler raises KeyboardInterrupt here: after the block, whatever it did + + +_run_numbers = itertools.count(1) # each run of a server in the process takes the next + + +class _Run: + """One run of the server, and everything it owns. A worker touches its own run and nothing else. + + The main thread and the worker both write to a run, and its lock decides which came first. The worker records its + detail and outcome together under it. mcp_stop() asks for the stop under it, and after its wait for the worker, gives + up on the worker if, under it, the worker has not recorded its outcome yet. mcp_status() + reads the fields together under it. Neither thread holds it while it waits for the other. It also makes the run's + hold on the logging taken and let go of once. It is reentrant, so that serving() can be asked while it is held. + """ + + def __init__(self, port: int) -> None: + self.number = next(_run_numbers) + self.port = port # the port asked for until the socket is bound; then the one read back from the socket + self.url = f"http://{HOST}:{port}/mcp" + self.sock: socket.socket | None = None + self.server: Any = None # the uvicorn.Server + self.worker: threading.Thread | None = None # a daemon, named f"mcp-server-{number}"; set once it has started + self.stop_requested = False # mcp_stop() was called for it + self.stop_finished = False # a call of mcp_stop() did all it does; Ctrl-C can cut one short before then + self.abandoned = False # mcp_stop()'s wait ended before the worker had recorded its outcome + self.outcome: str | None = None # "stopped", "failed" or "cancelled", set by the worker when it ends + self.detail: str | None = None # the error it ended with, as text + self.problem: str | None = None # why this run is not serving, for the person + self.lock = threading.RLock() + self._holds_logging = False + + def close_socket(self) -> None: + """Release the listener on either worker exit or stop, whichever comes first.""" + with self.lock, contextlib.suppress(OSError): + if self.sock is not None: + self.sock.close() # idempotent, including when uvicorn has already closed it + + def serving(self) -> bool: + """Whether it serves: no stop was asked for, the worker is alive and has recorded no outcome, and the server started. + + uvicorn's started stays set while it shuts down, after it has closed the listener, so it alone is not enough. + """ + with self.lock: + return ( + not self.stop_requested + and self.outcome is None + and self.worker is not None + and self.worker.is_alive() + and self.server is not None + and bool(self.server.started) + ) + + def take_logging(self) -> None: + """Take this run's hold on the changes to the libraries' logging.""" + with self.lock: + _shared_logging.take() + self._holds_logging = True + + def release_logging(self) -> None: + """Let go of this run's hold once, whoever calls it and however often. Nothing for a run which took none. + + Ctrl-C is held off until it is done, as a start holds it off while it takes the hold. An interrupt between the run + forgetting its hold and the hold being let go of would leave the libraries' logging changed for good. + """ + with _sigint_deferred(), self.lock: + if self._holds_logging: + self._holds_logging = False + _shared_logging.release() + + +class _NotServingError(Exception): + """A start which did not end with the server serving. str() is the reason, for the person.""" + + +def _record_line(record: logging.LogRecord) -> str: + """Format the time, thread name, level, and message of a log record.""" + when = time.strftime("%H:%M:%S", time.localtime(record.created)) + try: + message = record.getMessage() + except Exception: # noqa: BLE001 - a status never raises: logging's own handlers also catch whatever formatting raises + message = str(record.msg) # arguments which do not fit the format: the format, as it was logged + return plain_text(f"{when} {record.threadName} {record.levelname}: {message}") + + +class McpServer: + """Own an application's current command snapshot and the worker that serves it.""" + + MCP_START_TIMEOUT = 5.0 # seconds to wait for the server to begin serving + MCP_STOP_TIMEOUT = 3.0 # seconds to wait for the worker to end + MCP_SHUTDOWN_TIMEOUT = 2 # uvicorn's timeout_graceful_shutdown + + mcp_snapshot: Snapshot # the latest; replaced whole, never changed + mcp_port: int | None + mcp_name: str + mcp_leave_out: frozenset[str] # commands which are never described + mcp_build_error: str | None # why the latest build failed as a whole; None once one has succeeded + _mcp_depth: int # calls of onecmd_plus_hooks() in progress + _mcp_loops: int # calls of cmdloop() in progress + _mcp_starting: bool # from the start of the outermost cmdloop() until preloop() has returned: nothing is built + _mcp_run: _Run | None # the latest run of the server; it stays after it is stopped, to say what became of it + + def __init__(self, app: Cmd, *, port: int | None, name: str, leave_out: Collection[str]) -> None: + """Configure the server and its initial, unpublished command description.""" + self._app = app + # A failed or repeated start can stop its own run. The worker never takes this lock. + self._lifecycle_lock = threading.RLock() + self.active = False + self.mcp_port = port + self.mcp_name = name + self.mcp_leave_out = frozenset((leave_out,)) if isinstance(leave_out, str) else frozenset(leave_out) + self.mcp_snapshot = failed_snapshot(0, _NOT_BUILT) + self.mcp_build_error = None + self._mcp_depth = 0 + self._mcp_loops = 0 + self._mcp_starting = False + self._mcp_run = None + + @contextlib.contextmanager + def command_loop(self) -> Generator[None]: + """Manage the listener for an outermost command loop, respecting manual ownership.""" + outermost = self._mcp_loops == 0 and self._mcp_depth == 0 + owns_server = outermost and not self.active + self._mcp_loops += 1 + try: + if outermost: + self._mcp_starting = True + if owns_server: + if self.mcp_snapshot.error != _NOT_BUILT: + self.mcp_snapshot = failed_snapshot(self.mcp_snapshot.generation + 1, _NOT_BUILT) + self.mcp_build_error = None + self._app.mcp_start() + yield + finally: + self._mcp_loops -= 1 + if outermost: + self._mcp_starting = False + if owns_server: + self._app.mcp_stop() + + def preloop_finished(self) -> None: + """Publish the initial snapshot after the owning loop's preloop hooks and intro.""" + if self._mcp_starting and self._mcp_loops == 1: + self._mcp_starting = False + self._mcp_rebuild() + + def mcp_start(self) -> None: + """Start this server once any concurrent start or stop has finished.""" + with self._lifecycle_lock: + self._mcp_start() + + def _mcp_start(self) -> None: + """Build the first description, then serve it from a worker thread. + + When cmdloop() calls it, it does not build: cmdloop() builds the first description once preloop() has returned. + + Does no more than build when mcp_port is None or this application is serving already. A start which fails is one + warning, and the application carries on without a server: it never raises an Exception. + + Ctrl-C during a start is another matter. Before cmdloop() has installed cmd2's handler, nothing holds it off for + long, so a KeyboardInterrupt can arise anywhere in a start. The start then undoes what it got done, through + mcp_stop(), and raises the KeyboardInterrupt again, whether cmdloop() or the application called it; cmdloop()'s + own mcp_stop() afterwards finds nothing left to do. While the start takes the logging, binds its socket and + starts its worker, Ctrl-C is held off until the run has recorded what was taken, so that the undoing knows of it. + """ + was_active = self.active + self.active = True + try: + self._mcp_rebuild() + except KeyboardInterrupt: + self.active = was_active + raise + if self.mcp_port is None or (self._mcp_run is not None and self._mcp_run.serving()): + return + if self._mcp_run is not None: + # A run which is neither serving nor stopped (its worker ended by itself, perhaps with an error) may still hold + # its socket. Undo it before it is replaced. A run which was stopped is replaced at once, while its worker, if + # it has one still alive, finishes with that run alone. + self.mcp_stop() + self.active = True + # The attempt is recorded before anything can fail: from here on, whatever goes wrong, mcp_status() has a run to + # report and mcp_stop() has a run to undo. + run = self._mcp_run = _Run(self.mcp_port) + try: + self._mcp_start_serving(run) + except KeyboardInterrupt: + self.mcp_stop() + raise + except Exception as error: # noqa: BLE001 - a start which fails is a warning, and the application carries on + why = str(error) if isinstance(error, _NotServingError) else f"{type(error).__name__}: {error}" + run.problem = plain_text(f"MCP server not started on port {run.port}: {why.rstrip('.')}. Continuing without it.") + self.mcp_stop() + # A warning which cannot be written has nowhere else to go, and a start which fails never raises. + with contextlib.suppress(Exception): + self._app.pwarning(run.problem) + + def _mcp_start_serving(self, run: _Run) -> None: + """Take each step of a start in turn, recording in the run what it has done. Raise if the server is not serving.""" + try: + # Check for the SDK v2 server API before acquiring the listener or modifying the library loggers. + importlib.import_module("mcp.server.mcpserver") + uvicorn = importlib.import_module("uvicorn") + except ImportError as error: + raise _NotServingError( + f"the MCP SDK cannot be imported ({error}). Install it with pip install 'cmd2[mcp]'" + ) from error + # Each of the three steps which take something is held together with its recording in the run. + with _sigint_deferred(): + run.take_logging() # before anything of the server can log + with _sigint_deferred(): + run.sock = socket.create_server((HOST, run.port)) + run.port = run.sock.getsockname()[1] # the one the system chose, when 0 was asked for + run.url = f"http://{HOST}:{run.port}/mcp" + # Neither log_level nor access_log=False: each changes loggers which are not the server's to change. + config = uvicorn.Config(self._mcp_asgi_app(), log_config=None, timeout_graceful_shutdown=self.MCP_SHUTDOWN_TIMEOUT) + run.server = uvicorn.Server(config) + worker = threading.Thread(target=self._mcp_serve, args=(run,), name=f"mcp-server-{run.number}", daemon=True) + with _sigint_deferred(): + worker.start() + # Only once it has started, so that a thread which could not be started is never joined; and before Ctrl-C, + # so that a worker which runs is always one its run knows of, which mcp_stop() can wait for or give up on. + run.worker = worker + deadline = time.monotonic() + self.MCP_START_TIMEOUT + while not run.server.started and worker.is_alive() and time.monotonic() < deadline: + time.sleep(0.02) + if not run.serving(): + with run.lock: + ended = run.detail or run.outcome + if ended is not None or not worker.is_alive(): + raise _NotServingError(f"the server ended before it began serving: {ended}") + raise _NotServingError(f"the server did not begin serving within {self.MCP_START_TIMEOUT} seconds") + + @staticmethod + def _mcp_serve(run: _Run) -> None: + """Serve until the worker exits, then record how it ended. + + It is given its run and touches nothing else, so a worker which outlives its command loop does no harm. + """ + try: + detail: str | None = None + try: + run.server.run(sockets=[run.sock]) + except BaseException as error: # noqa: BLE001 - SystemExit too: nothing may reach threading.excepthook + detail = plain_text(f"{type(error).__name__}: {error}") + else: + if not run.server.started: + detail = "the server returned before it had started" + # The detail and the outcome are recorded together, under the lock under which mcp_stop() decides whether it + # has given up on this worker. If it has, this worker was cancelled, whatever happened. If this comes first, + # mcp_stop() keeps what is recorded here, and does not give up on the worker. + with run.lock: + run.detail = detail + if run.abandoned: + run.outcome = "cancelled" # the detail, if any, is kept: it is the expected result of being cancelled + elif detail is None: + run.outcome = "stopped" + else: + run.outcome = "failed" + finally: + try: + run.close_socket() + finally: + run.release_logging() + + def mcp_stop(self) -> None: + """Stop this server once any concurrent start or stop has finished.""" + with self._lifecycle_lock: + self._mcp_stop() + + def _mcp_stop(self) -> None: + """Stop serving: undo what the start got done, in whatever state it finds the run. + + Does nothing when there is no run, or when a stop of it has finished already. A stop which Ctrl-C cut short before + it had finished is finished by the next one, so stopping again is always enough. Otherwise it asks the server to + stop, and waits a while for the worker. Whether the worker has ended or not, it then closes the socket, and lets go + of the logging where no worker started; a worker always lets go of it itself, as its last act. Ctrl-C during the + wait does not prevent that; it is raised once it is done. The run stays, so that mcp_status() can say what became + of it; the next start replaces it. + """ + self.active = False + run = self._mcp_run + if run is None: + return + with run.lock: + if run.stop_finished: + return + run.stop_requested = True # from now on run.serving() is false and mcp_url is None + if run.server is not None: + run.server.should_exit = True + try: + if run.worker is not None: + run.worker.join(self.MCP_STOP_TIMEOUT) # never with the lock held: the worker takes it to record its outcome + finally: + # This happens even when Ctrl-C ends the wait: whatever the worker is doing, the port is let go of. + # Whether the worker has ended is never asked of the thread: on Python 3.11 and 3.12, a join() which Ctrl-C + # interrupted leaves is_alive() false while the worker runs on. What the worker recorded, under the lock, says. + worker = run.worker + with run.lock: + if worker is not None and run.outcome is None: + # The one place a run is given up on. The worker records that it was cancelled when it ends, and lets go + # of the logging then. A worker which recorded its outcome first keeps it, however long it lives on. + run.abandoned = True + run.close_socket() + if worker is None: + run.release_logging() # a start which failed before its worker started: nobody else will + with run.lock: + run.stop_finished = True # only now: a stop which an interrupt ended before this line is done again + + @property + def mcp_url(self) -> str | None: + """The URL a client connects to while this application is serving; else None.""" + run = self._mcp_run + return run.url if run is not None and run.serving() else None + + def mcp_status(self) -> list[str]: + """Return lines which tell the person whether there is a server, and what it serves. + + They are made from the current run and this application's own state. A log record never decides what they say: + the records are every run's in the process, so they are shown apart, under a heading which says so. + + Why there is no server is, of the reasons which hold, the first of: the problem the start met; the worker's + failure; a stop which was asked for; how the worker ended by itself; and, with no run, no configured port or no start. + """ + run = self._mcp_run + lines = [f"No MCP server: {'no port was configured' if self.mcp_port is None else 'it has not been started'}"] + if run is not None: + with run.lock: # read together, as the worker records them together + serving = run.serving() + problem, outcome, detail, stop_requested = run.problem, run.outcome, run.detail, run.stop_requested + cancelled = run.abandoned and run.worker is not None + worker_alive = run.worker is not None and outcome is None # it records one as it ends; see mcp_stop() + if serving: + lines[0] = f"Serving {run.url}" + elif problem is not None: + lines[0] = f"No MCP server: {problem}" + elif outcome == "failed": + lines[0] = f"No MCP server: it failed ({detail})" + elif stop_requested: + lines[0] = "No MCP server: it was stopped" + elif outcome is not None: + lines[0] = f"No MCP server: it ended by itself ({outcome})" + if cancelled and worker_alive: + lines.append(f"The worker of run {run.number} was cancelled, and has not ended yet") + elif cancelled: + ended = f"{outcome}: {detail}" if detail else outcome + lines.append(f"The worker of run {run.number} was cancelled, and has ended ({ended})") + snapshot = self.mcp_snapshot + built = datetime.fromisoformat(snapshot.built_at).strftime("%H:%M:%S") + count = f"{len(snapshot.commands)} commands in {len(snapshot.categories)} categories" + lines.append(f"Description {snapshot.generation}, built {built}: {count}") + failed = [command.name for command in snapshot.commands if command.error is not None] + if failed: + lines.append(f"{len(failed)} of them could not be described: {', '.join(failed)}") + if self.mcp_build_error is not None: + lines.append(f"The description is out of date: the last rebuild failed: {self.mcp_build_error}") + records = _shared_logging.records()[-RECORDS_SHOWN:] + if records: + lines.append("Recent log records from every MCP server this process has run:") + lines.extend(f" {_record_line(record)}" for record in records) + return lines + + def _mcp_asgi_app(self) -> Any: + """Return the SDK's application, which serves the three tools. A seam for tests. + + Each tool reads the latest snapshot once, into a local, and answers from that alone: the main thread may publish a + new one at any moment, and a snapshot never changes once it has been published. + """ + sdk = importlib.import_module("mcp.server") + exceptions = importlib.import_module("mcp.server.mcpserver.exceptions") + types = importlib.import_module("mcp.types") + + with _root_logger_left_alone(): # MCPServer() calls logging.basicConfig() + server = sdk.MCPServer(self.mcp_name, instructions=INSTRUCTIONS, version=getattr(cmd2, "__version__", "")) + read_only = types.ToolAnnotations(read_only_hint=True, open_world_hint=False) + + def list_commands() -> CommandList: + """List the application's commands by category, in the order its help shows them. + + Each command includes its summary, whether a parser checks its arguments, and its subcommands as typed. + Also listed: the help topics which are not commands, and the rules for typing a command line (which + characters end a command, which commands go on over several lines, and whether output can be redirected). + """ + snapshot = self.mcp_snapshot + return answer_list_commands(snapshot) + + def describe_command(command: str) -> CommandDescription: + """Describe one command: its usage, its help, its arguments, and its subcommands by name. + + command is a command's name, or a path with spaces, such as "server add", which names a subcommand. Each + subcommand's typed field is the spelling to append to this path for the next lookup. See usage for arguments + or an end-of-options marker needed to run the command at the prompt. + Each argument's parser_default is declared by argparse. The application can supply a different value + when the argument is omitted. + """ + snapshot = self.mcp_snapshot + try: + return answer_describe_command(snapshot, command) + except (UnknownCommandError, DescriptionUnavailableError) as error: + if snapshot.stale_reason is not None: + raise exceptions.ToolError(f"{error} The description is out of date: {snapshot.stale_reason}") from error + raise exceptions.ToolError(str(error)) from error + + def list_shortcuts_aliases_macros() -> Tables: + """List the shortcuts, aliases and macros: other words the person can type, which stand for commands.""" + snapshot = self.mcp_snapshot + return answer_tables(snapshot) + + for tool in (list_commands, describe_command, list_shortcuts_aliases_macros): + server.add_tool(tool, annotations=read_only) + return server.streamable_http_app(host=HOST, json_response=True, stateless_http=True) + + def _mcp_rebuild(self) -> None: + """Publish a new description, unless a command is in progress or preloop() has not returned. Never raises an Exception. + + A build which fails as a whole keeps the description there is, or, when there is none yet, publishes an empty one + which carries the error. Each failure is reported once, and again only if it comes back after a success. + + It holds cmd2's sigint_protection while it builds, which holds off Ctrl-C once cmdloop() has installed cmd2's + handler: before the first line is read, before each prompt, and at the end of each command. A build in an + mcp_start() which the application calls itself, before cmdloop() or without it, comes before that, so Ctrl-C there + raises KeyboardInterrupt, which leaves the start before it has taken anything. + """ + if not self.active or self._mcp_depth != 0 or self._mcp_starting: + return + with self._app.sigint_protection: + warnings: list[str] = [] + try: + snapshot = self._mcp_build() + except Exception as error: # noqa: BLE001 - a rebuild never raises + message = plain_text(f"{type(error).__name__}: {error}") + previous = self.mcp_snapshot + if previous.error is None: + if previous.stale_reason != message: + self.mcp_snapshot = replace(previous, stale_reason=message) + elif previous.error != message: + self.mcp_snapshot = failed_snapshot(previous.generation + 1, message) + if message != self.mcp_build_error: + warnings.append(f"MCP: the description could not be built: {message}") + self.mcp_build_error = message + else: + reported = {(command.name, command.error) for command in self.mcp_snapshot.commands} + self.mcp_snapshot = snapshot + self.mcp_build_error = None + warnings.extend( + f'MCP: "{command.name}": {command.error}' + for command in snapshot.commands + if command.error is not None and (command.name, command.error) not in reported + ) + for warning in warnings: + # A warning which cannot be written has nowhere else to go, and a rebuild never raises. + with contextlib.suppress(Exception): + self._app.pwarning(warning) + + def _mcp_build(self) -> Snapshot: + """Describe the application as the next generation. A seam for tests.""" + return build_snapshot(self._app, self.mcp_snapshot.generation + 1, self.mcp_leave_out) diff --git a/cmd2/_mcp_snapshot.py b/cmd2/_mcp_snapshot.py new file mode 100644 index 000000000..57fcd99bc --- /dev/null +++ b/cmd2/_mcp_snapshot.py @@ -0,0 +1,970 @@ +"""Build and query plain-data descriptions of a cmd2 application's commands.""" + +import argparse +import copy +import inspect +import itertools +import json +import re +from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence +from dataclasses import dataclass +from datetime import datetime +from functools import cache, partial +from typing import TYPE_CHECKING, Any, NoReturn, TypeAlias, TypeVar, cast + +from rich.console import Console + +from . import utils +from .argparse_utils import Cmd2ArgumentParser +from .constants import INFINITY, MULTILINE_TERMINATOR +from .exceptions import Cmd2ShlexError +from .parsing import StatementParser, shlex_split +from .rich_utils import Cmd2HelpFormatter, HelpFormatterRenderable + +if TYPE_CHECKING: + from .cmd2 import Cmd + + +# Help text is wrapped at this many columns, whatever the size of the terminal. +HELP_WIDTH = 100 + +# Each sequence has a 7-bit form (ESC followed by a character) and an 8-bit form (one C1 character: CSI is \x9b, OSC is \x9d). +# An OSC sequence (a hyperlink is one) ends with BEL, with ST (ESC followed by a backslash, or \x9c). +_OSC_SEQUENCE = re.compile(r"(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x9c|\x1b\\)") +_CSI_SEQUENCE = re.compile(r"(?:\x1b\[|\x9b)[0-?]*[ -/]*[@-~]") +# Every control character (Unicode category Cc, which includes C1) except a tab (\x09) and a newline (\x0a). +_CONTROL_CHARACTERS = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]") + + +def plain_text(value: object) -> str: + """Return a string, a Rich renderable or None as text with no escape sequence. + + The result holds no control character other than a newline or a tab. None is "". + """ + if value is None: + return "" + if isinstance(value, str): + text = value + else: + console = Console(force_terminal=False, color_system=None, width=HELP_WIDTH) + with console.capture() as capture: + console.print(value) + text = capture.get() + # cmd2.string_utils.strip_style() is not enough here: it leaves hyperlinks. + text = _OSC_SEQUENCE.sub("", text) + text = _CSI_SEQUENCE.sub("", text) + # A filesystem string may contain surrogate-escaped bytes. Preserve them visibly in UTF-8 JSON. + return _CONTROL_CHARACTERS.sub("", text).encode("utf-8", "backslashreplace").decode("utf-8") + + +@dataclass(frozen=True) +class Argument: + """One argument of a command, as plain data.""" + + name: str # the destination + metavar: str | None # where one is set; a tuple metavar joined with spaces + flags: tuple[str, ...] # ("-n", "--lines"); () for a positional + help: str + required: bool + min_values: int + max_values: int | None # None when unbounded + takes_rest_of_line: bool # nargs=argparse.REMAINDER, or argparse.PARSER, which takes one value first + parser_default: Any # declared on the action; a namespace provider can supply a different value + choices: tuple[str, ...] | None # None unless choices= was given; no more than MAX_CHOICES of them + more_choices: bool # choices which are not listed: past the first MAX_CHOICES, or all of them, which are an iterator + dynamic_choices: bool # a choices_provider or a completer; never called + type: str | None + repeatable: bool # append, append_const, count, extend + + +# The same four action classes which cmd2's tab completion treats as repeatable. +_REPEATABLE_ACTIONS = ( + argparse._AppendAction, + argparse._AppendConstAction, + argparse._CountAction, + argparse._ExtendAction, +) + + +def _value_range(action: argparse.Action) -> tuple[int, int | None]: + """Return the fewest and the most values an argument takes, with None for no most.""" + # cmd2 installs the range and completion accessors on argparse.Action at runtime. + nargs_range: tuple[int, int | float] | None + nargs_range = action.get_nargs_range() # type: ignore[attr-defined] # ty: ignore[missing-attribute] + if nargs_range is not None: + low, high = nargs_range + return int(low), None if high == INFINITY else int(high) + nargs = action.nargs + if nargs is None: + # Flags such as store_true have nargs=0 and take none, which is not the same as one. + return 1, 1 + if nargs == argparse.OPTIONAL: + return 0, 1 + if nargs in (argparse.ZERO_OR_MORE, argparse.REMAINDER): + return 0, None + if nargs in (argparse.ONE_OR_MORE, argparse.PARSER): # PARSER: one value, then the rest of the line + return 1, None + return int(nargs), int(nargs) + + +_JsonValue: TypeAlias = str | int | float | bool | list["_JsonValue"] | dict[str, "_JsonValue"] | None + + +def _plain_data(value: _JsonValue) -> _JsonValue: + """Return plain data like the value, with every string (a dict's keys too) through plain_text().""" + if isinstance(value, str): + return plain_text(value) + if isinstance(value, list): + return [_plain_data(item) for item in value] + if isinstance(value, dict): + return {plain_text(key): _plain_data(item) for key, item in value.items()} + return value + + +def _describe_default(action: argparse.Action) -> _JsonValue: + """Return the default as data which JSON can hold: a copy, never the parser's own object.""" + default = action.default + if default is None or default is argparse.SUPPRESS: + return None + try: + # A round trip makes a copy of plain data, so a later change to the application's list does not reach it. NaN and + # an infinity, anywhere in the default, are refused: the SDK would send each as JSON null, which says there is no + # default. Such a default is described by its repr(), as a whole. + return _plain_data(json.loads(json.dumps(default, allow_nan=False))) + except (TypeError, ValueError): + return plain_text(repr(default)) + + +def _describe_type(action: argparse.Action) -> str | None: + """Return the name of the argument's type callable, or its repr when it has no name.""" + if action.type is None: + return None + return plain_text(getattr(action.type, "__name__", None) or repr(action.type)) + + +def describe_argument(action: argparse.Action) -> Argument: + """Describe one argument of a parser, without calling a choices provider or a completer.""" + low, high = _value_range(action) + choices, more_choices = _listed_choices(action.choices) + is_option = bool(action.option_strings) + metavar = action.metavar + if isinstance(metavar, tuple): + metavar = " ".join(metavar) + help_text = action.help if isinstance(action.help, str) and action.help != argparse.SUPPRESS else "" + return Argument( + name=plain_text(action.dest), + metavar=None if metavar is None else plain_text(metavar), + flags=tuple(plain_text(flag) for flag in action.option_strings), + help=plain_text(help_text), + required=bool(action.required) if is_option else low >= 1, + min_values=low, + max_values=high, + takes_rest_of_line=action.nargs in (argparse.REMAINDER, argparse.PARSER), + parser_default=_describe_default(action), + choices=choices, + more_choices=more_choices, + dynamic_choices=( + action.get_choices_provider() is not None # type: ignore[attr-defined] # ty: ignore[missing-attribute] + or action.get_completer() is not None # type: ignore[attr-defined] # ty: ignore[missing-attribute] + ), + type=_describe_type(action), + repeatable=isinstance(action, _REPEATABLE_ACTIONS), + ) + + +# The most of an argument's choices which are listed. argparse checks a value against range(2**32) at once, but listing +# all of it would take minutes and gigabytes, on the main thread, before the first prompt. +MAX_CHOICES = 1000 + + +def _listed_choices(choices: Iterable[object] | None) -> tuple[tuple[str, ...] | None, bool]: + """Return the first MAX_CHOICES of an argument's choices as plain text, or None for none, and whether there are more. + + No more of them are read than that. Choices which are an iterator are not listed at all: listing them would use up + what argparse checks each value against. + """ + if choices is None: + return None, False + if isinstance(choices, Iterator): + return None, True + first = list(itertools.islice(choices, MAX_CHOICES + 1)) + return tuple(plain_text(str(choice)) for choice in first[:MAX_CHOICES]), len(first) > MAX_CHOICES + + +@dataclass(frozen=True) +class ExclusiveGroup: + """Arguments of which at most one may be given. A required group may have one: the others are hidden.""" + + # The arguments which exclude each other: an option by its first flag ("--follow"), a positional by its name. Two + # options may share a destination, and so a name, but never a flag. + arguments: tuple[str, ...] + required: bool # one of them must be given + + +@dataclass(frozen=True) +class Subcommand: + """One subcommand, as its parent lists it.""" + + name: str + typed: str # append this spelling to the parent path for describe_command + aliases: tuple[str, ...] + summary: str + + +@dataclass(frozen=True) +class Description: + """One command or subcommand, as plain data.""" + + path: str # as typed: "server tag add" + summary: str + usage: str + help: str + has_parser: bool # False: the arguments are free-form text + arguments: tuple[Argument, ...] + exclusive_groups: tuple[ExclusiveGroup, ...] + subcommands: tuple[Subcommand, ...] + subcommand_required: bool + error: str | None # why it could not be described; else None + + +@dataclass(frozen=True) +class _ShownSubcommand: + """A subcommand as its parent's description shows it: by those of its names which can be typed.""" + + names: tuple[str, ...] # all of them, as argparse has them, the primary first + shown: tuple[str, ...] # those which can be typed, in the same order: the first stands for the subcommand + needs_separator: bool # the parent must consume -- before this name + parser: Cmd2ArgumentParser + subcommand: Subcommand + + +def _shown_subcommands(parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcommand]) -> dict[int, argparse.Action]: + """Return a copy of the parser's subcommands action which knows only the subcommands shown, by the names shown. + + It is returned under the id of the action, or nothing is where argparse would show the subcommands so already. + """ + try: + action = parser.get_subparsers_action() + except ValueError: + return {} + if [name for each in shown for name in each.shown] == list(action.choices): + return {} + # As in _describe_subcommands(), each subcommand added with help= has a pseudo action, named for it, here. + pseudo = {choice.dest: choice for choice in action._choices_actions} + shown_action = copy.copy(action) + shown_action.choices = {name: each.parser for each in shown for name in each.shown} + shown_action._choices_actions = [] + for each in shown: + choice = pseudo.get(each.names[0]) + if choice is None: + continue # one added without help= has no line in help + if each.shown != each.names: + # One as add_parser() makes it: named for the subcommand, with its aliases after the name in help. + choice = argparse._SubParsersAction._ChoicesPseudoAction(each.shown[0], each.shown[1:], choice.help) + shown_action._choices_actions.append(choice) + return {id(action): shown_action} + + +def _to_render( + parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcommand], omitted: Sequence[argparse.Action] +) -> Cmd2ArgumentParser: + """Return a display copy whose usage and help name only the subcommands shown, by the names shown. + + argparse would list every subcommand by every name: usage among the choices, and help with ==SUPPRESS== for the help + of a hidden one. It would also read all of an argument's choices, to list them or to expand %(choices)s in a help, + which uses up choices which are an iterator, though argparse reads them again to check each value given, and could + take minutes for range(2**32). Render those arguments with a marker for the omitted choices. + + The parser itself is never changed. The copy is shallow: its lists of actions and of groups are its own, and name a + copy of each action which is rendered differently. + """ + replaced = _shown_subcommands(parser, shown) + for action in omitted: + unlisted = replaced[id(action)] = copy.copy(action) + unlisted.choices = ("(choices omitted)",) + if unlisted.metavar is None: + # Keep the usual metavar in usage. The marker belongs in help that asks for %(choices)s. + formatter = parser._get_formatter() + if action.option_strings: + unlisted.metavar = formatter._get_default_metavar_for_optional(action) + else: + unlisted.metavar = formatter._get_default_metavar_for_positional(action) + rendered = copy.copy(parser) + # argparse accepts any formatter factory, including one bound to this parser. + rendered.formatter_class = partial(_snapshot_formatter, parser) # type: ignore[assignment] + if not replaced: + return rendered + rendered._actions = [replaced.get(id(each), each) for each in parser._actions] + rendered._action_groups = _with_replaced(parser._action_groups, replaced) + rendered._mutually_exclusive_groups = _with_replaced(parser._mutually_exclusive_groups, replaced) + return rendered + + +_Group = TypeVar("_Group", bound=argparse._ArgumentGroup) + + +def _with_replaced(groups: list[_Group], replaced: Mapping[int, argparse.Action]) -> list[_Group]: + """Return the groups, with a copy in place of each which holds an action replaced, holding its replacement.""" + result = [] + for group in groups: + if any(id(each) in replaced for each in group._group_actions): + own = copy.copy(group) + own._group_actions = [replaced.get(id(each), each) for each in group._group_actions] + result.append(own) + else: + result.append(group) + return result + + +def _snapshot_formatter(parser: Cmd2ArgumentParser, prog: str, **kwargs: Any) -> Cmd2HelpFormatter: + """Build the configured formatter and render at a fixed width without changing the prompt or process environment.""" + factory = cast(type[Cmd2HelpFormatter], parser.formatter_class) # type: ignore[redundant-cast] + if "width" in inspect.signature(factory).parameters: + kwargs["width"] = HELP_WIDTH + formatter = factory(prog=prog, **kwargs) + formatter._width = HELP_WIDTH # also supports custom formatters which take only prog and file + formatter.console = copy.copy(formatter.console) + formatter.console.width = HELP_WIDTH + return formatter + + +def _first_line(value: object) -> str: + """Return the first non-blank line of a string or a Rich renderable as plain text.""" + for line in plain_text(value).splitlines(): + if line.strip(): + return line.strip() + return "" + + +def _parser_summary(parser: Cmd2ArgumentParser) -> str: + """Return the first line of the description as text, using the parser's formatter when required.""" + if isinstance(parser.description, HelpFormatterRenderable): + formatter = _snapshot_formatter(parser, parser.prog) + formatter.add_text(parser.description) + return _first_line(formatter.format_help()) + return _first_line(parser.description) + + +def _is_described(action: argparse.Action) -> bool: + """Return whether the action is an argument of the command, not the help, the subcommands or a hidden one.""" + if isinstance(action, (argparse._HelpAction, argparse._SubParsersAction)): + return False + return action.help != argparse.SUPPRESS + + +def _exclusive_name(argument: Argument) -> str: + """Name an argument as an exclusive group does: an option by its first flag, a positional by its name.""" + return argument.flags[0] if argument.flags else argument.name + + +@dataclass(frozen=True) +class _Reading: + """How the prompt reads the words typed after a command's name, and gives them to its parser.""" + + statements: StatementParser # with the application's terminators, which is all that such a word depends on + keeps_quotes: bool # the command's preserve_quotes: argparse is given each word with its quotation marks + + def argument_for(self, word: str) -> str | None: + """Return the argument argparse receives for a typed word, or None if the prompt splits it. + + The prompt splits a word where it is not quoted at whitespace, a redirection character or a terminator. It + takes off the quotation marks around the word, not those inside it, unless the command keeps them. + """ + try: + statement = self.statements.parse(f"command {word}") + except Cmd2ShlexError: # a quotation which is never closed + return None + if statement.args != word or len(statement.argv) != 2: + return None + return statement.arg_list[0] if self.keeps_quotes else statement.argv[1] + + def as_typed(self, name: str) -> str | None: + """Return a spelling that the prompt reads as this subcommand name, or None if none exists. + + It is typed as it is where the prompt takes it so, and otherwise quoted. A name with both quotation marks in + it and, say, a space cannot be typed at all, nor can a name with a space if the command keeps its quotes. + """ + return next((typed for typed in (name, f'"{name}"', f"'{name}'") if self.argument_for(typed) == name), None) + + +class _NotASubcommandError(Exception): + """Raised in place of argparse's error() by the copy of a parser which _needs_end_of_options() asks.""" + + +def _refuse(message: str) -> NoReturn: + raise _NotASubcommandError(message) + + +def _needs_end_of_options(parser: Cmd2ArgumentParser, name: str) -> bool: + """Whether argparse would treat this word as option syntax before the end-of-options marker.""" + if name == "--": + return True + # Python 3.11 reports an ambiguous abbreviation with error(), which would print and exit. + asked = copy.copy(parser) + asked.error = _refuse # type: ignore[method-assign] + try: + return asked._parse_optional(name) is not None + except _NotASubcommandError: + return True + + +@cache +def _subparser_consumes_separator() -> bool: + """Whether this argparse strips a leading -- from a subparser action. The fix was backported.""" + probe = argparse.ArgumentParser(prog="probe", add_help=False, exit_on_error=False) + probe.add_subparsers(dest="child", required=True).add_parser("-x") + try: + child: str = probe.parse_args(["--", "-x"]).child + except argparse.ArgumentError: + return False + return child == "-x" + + +def _preceding_positionals(parser: Cmd2ArgumentParser) -> list[argparse.Action]: + """Positionals that argparse assigns before handing the remaining words to a child parser.""" + preceding = itertools.takewhile(lambda action: not isinstance(action, argparse._SubParsersAction), parser._actions) + return [action for action in preceding if not action.option_strings] + + +def _reserved_positionals(rendered: Cmd2ArgumentParser) -> list[argparse.Action]: + """Render trailing parent positionals at their minimum arity. The subparser consumes all additional words.""" + subparsers_index = next(i for i, action in enumerate(rendered._actions) if isinstance(action, argparse._SubParsersAction)) + reserved = [] + for action in rendered._actions[subparsers_index + 1 :]: + if action.option_strings or action.help is argparse.SUPPRESS: + continue + minimum, maximum = _value_range(action) + if minimum == 0: + continue + if minimum == maximum: + reserved.append(action) + continue + display = copy.copy(action) + display.nargs = minimum + display.set_nargs_range(None) # type: ignore[attr-defined] # ty: ignore[missing-attribute] + if isinstance(display.metavar, tuple): + display.metavar = display.metavar[:minimum] + reserved.append(display) + return reserved + + +def _describe_subcommands( + parser: Cmd2ArgumentParser, reading: _Reading, file_prefixes: str +) -> tuple[bool, list[_ShownSubcommand]]: + """Return whether a subcommand is required, and each subcommand as its parent's description shows it. + + Subcommands added with add_subparsers(help=argparse.SUPPRESS) are all left out, since help and usage leave all of them + out. A subcommand added with help=argparse.SUPPRESS is left out, since help leaves it out of its list. So is one which + cannot be typed by any of its names, since no path to it could be typed. A name can be typed where it is served as + it is, without what plain_text() takes out of it, the prompt takes it whole, and argparse takes it for the name of + a subcommand, not an option. Of the others, a name which cannot be typed is left out; where that is the primary + name, the first alias which can be typed stands for the subcommand. + """ + try: + action = parser.get_subparsers_action() + except ValueError: + return False, [] + if action.help == argparse.SUPPRESS: + return bool(action.required), [] + # argparse has no public way to read the help a subcommand was added with: it keeps one pseudo action per + # subcommand, named for it, in _choices_actions (cmd2 reads it there too). + helps = {choice.dest: choice.help for choice in action._choices_actions} + by_parser: dict[int, list[str]] = {} + for name, subparser in action.choices.items(): + by_parser.setdefault(id(subparser), []).append(name) + prefixes = tuple(file_prefixes + (parser.fromfile_prefix_chars or "")) + can_end_options = "-" not in prefixes and (bool(_preceding_positionals(parser)) or _subparser_consumes_separator()) + shown: list[_ShownSubcommand] = [] + for names in by_parser.values(): + help_text = helps.get(names[0]) # argparse adds the primary name before its aliases + if isinstance(help_text, str) and help_text == argparse.SUPPRESS: + continue # with its aliases, as a hidden command is left out + typable = [] + for name in names: + if plain_text(name) != name or name.startswith(prefixes): + continue # it would be served as a different name, or expanded as a file before option parsing + typed = reading.as_typed(name) + if typed is None: + continue + needs_separator = _needs_end_of_options(parser, name) + if not needs_separator or can_end_options: + typable.append((name, typed, needs_separator)) + if not typable: + continue + subparser = action.choices[names[0]] + summary = _first_line(help_text) or _parser_summary(subparser) + (first, typed, needs_separator), *others = typable + subcommand = Subcommand(name=first, typed=typed, aliases=tuple(name for name, _, _ in others), summary=summary) + shown.append( + _ShownSubcommand( + names=tuple(names), + shown=tuple(name for name, _, _ in typable), + needs_separator=needs_separator, + parser=subparser, + subcommand=subcommand, + ) + ) + return bool(action.required), shown + + +def _child_prog_prefix(rendered: Cmd2ArgumentParser) -> str: + """Show the parent arguments needed before the child, using their display actions.""" + if rendered._custom_subparsers_prog: + return rendered.get_subparsers_action()._prog_prefix + groups = rendered._mutually_exclusive_groups + group_members = {id(action) for group in groups if group.required for action in group._group_actions} + required = [a for a in rendered._actions if a.option_strings and (a.required or id(a) in group_members)] + preceding = _preceding_positionals(rendered) + if not required and not preceding: + return rendered.prog + prog = rendered.prog + rendering = prog if _TAB_STAND_IN in prog else prog.replace("\t", _TAB_STAND_IN) + formatter = rendered.formatter_class(prog=rendering) + formatter.add_usage(None, [*required, *preceding], groups, prefix="") + usage = plain_text(formatter.format_help()).strip() + return usage if rendering == prog else usage.replace(_TAB_STAND_IN, "\t") + + +# A noncharacter: Unicode keeps these for a program's own use, out of text written for people, such as help. +_TAB_STAND_IN = "\ufdd0" + + +def _usage_and_help(rendered: Cmd2ArgumentParser) -> tuple[str, str]: + """Render the display parser, preserving tabs in quoted command paths.""" + prog = rendered.prog + rendering = prog if _TAB_STAND_IN in prog else prog.replace("\t", _TAB_STAND_IN) + if rendering != prog: + rendered = copy.copy(rendered) + rendered.prog = rendering + usage = plain_text(rendered.format_usage()).rstrip() + help_text = plain_text(rendered.format_help()).rstrip() + if rendering == prog: + return usage, help_text + return usage.replace(_TAB_STAND_IN, "\t"), help_text.replace(_TAB_STAND_IN, "\t") + + +def describe_parser( + parser: Cmd2ArgumentParser, + path: str, + summary: str, + terminators: Collection[str] = (MULTILINE_TERMINATOR,), + *, + keeps_quotes: bool = False, +) -> dict[str, Description]: + """Describe a parser under its path, and every subcommand under it at every depth under its own path. + + A subcommand is there once, under its path as it is typed: its parent's, then its name, as it is where the prompt + takes it whole and otherwise quoted, which the application's terminators and the command's preserve_quotes + (keeps_quotes) help decide. Its usage and help name it + the same way. A name which the prompt cannot take whole has no path which can be typed, and is left out wherever + it would be named, as a hidden subcommand is: an alias which can be typed stands for a subcommand whose name + cannot. answer_describe_command() finds one by an alias through its parent. + + The usage and help of the parser itself name it by its path, whatever its prog: cmd2 gives a command which is + another's function under a second name, as do_orate = do_speak makes it, the other's parser, prog and all. + """ + reading = _Reading(StatementParser(terminators=terminators), keeps_quotes) + return _describe_parser_as(parser, path, summary, reading, path, "") + + +def _describe_parser_as( + parser: Cmd2ArgumentParser, + path: str, + summary: str, + reading: _Reading, + prog: str, + file_prefixes: str, + trailing: Sequence[argparse.Action] = (), + trailing_groups: Sequence[argparse._MutuallyExclusiveGroup] = (), +) -> dict[str, Description]: + """describe_parser(), for a parser whose prog is rendered as the one given, under parsers with those file prefixes.""" + # argparse has no public way to list a parser's arguments or its mutually exclusive groups. + actions = [action for action in parser._actions if _is_described(action)] + described = {id(action): describe_argument(action) for action in actions} + groups: list[ExclusiveGroup] = [] + for group in parser._mutually_exclusive_groups: # private, as above + members = tuple(_exclusive_name(described[id(a)]) for a in group._group_actions if id(a) in described) + # A required group whose other members are hidden still requires its one visible member, as argparse does. + if len(members) >= 2 or (group.required and members): + groups.append(ExclusiveGroup(arguments=members, required=bool(group.required))) + required, shown = _describe_subcommands(parser, reading, file_prefixes) + omitted = [action for action in actions if described[id(action)].more_choices] + rendered = _to_render(parser, shown, omitted) + rendered.prog = prog + if trailing: + # argparse reserves these words for the parent after the child has parsed its own arguments. + # Include them in usage, but keep the child's argument help and the live parser untouched. + rendered._actions = [*rendered._actions, *trailing] + rendered._mutually_exclusive_groups = [*rendered._mutually_exclusive_groups, *trailing_groups] + if rendered.usage is not None and rendered.usage is not argparse.SUPPRESS: + formatter = rendered.formatter_class(prog="") + formatter.add_usage(None, trailing, trailing_groups, prefix="") + suffix = plain_text(formatter.format_help()).strip().replace("%", "%%") + rendered.usage = f"{rendered.usage} {suffix}".rstrip() + usage, help_text = _usage_and_help(rendered) + result = { + path: Description( + path=path, + summary=summary, + usage=usage, + help=help_text, + has_parser=True, + arguments=tuple(described.values()), + exclusive_groups=tuple(groups), + subcommands=tuple(each.subcommand for each in shown), + subcommand_required=required, + error=None, + ) + } + if not shown: + return result + prefix = _child_prog_prefix(rendered) + child_trailing = _reserved_positionals(rendered) + child_groups = [g for g in rendered._mutually_exclusive_groups if all(a in child_trailing for a in g._group_actions)] + original_prefix = parser.get_subparsers_action()._prog_prefix + inner_prefixes = file_prefixes + (parser.fromfile_prefix_chars or "") + for each in shown: + typed = each.subcommand.typed + child_prog = each.parser.prog + if child_prog == f"{original_prefix} {each.names[0]}": + separator = " -- " if each.needs_separator else " " + child_prog = f"{prefix}{separator}{typed}" + child_path = f"{path} {typed}" + result.update( + _describe_parser_as( + each.parser, + child_path, + each.subcommand.summary, + reading, + child_prog, + inner_prefixes, + child_trailing, + child_groups, + ) + ) + return result + + +@dataclass(frozen=True) +class Command: + """One command, as the list of commands shows it.""" + + name: str + category: str + summary: str + has_parser: bool + subcommands: tuple[str, ...] # the typed spellings of its first level of subcommands + error: str | None + + +@dataclass(frozen=True) +class Category: + """The commands of one help category.""" + + name: str + commands: tuple[Command, ...] + + +@dataclass(frozen=True) +class Shortcut: + """A shortcut, such as "?" for "help".""" + + shortcut: str + command: str + + +@dataclass(frozen=True) +class Alias: + """An alias and what it stands for.""" + + name: str + value: str + + +@dataclass(frozen=True) +class Macro: + """A macro and what it stands for.""" + + name: str + value: str + minimum_arg_count: int + + +@dataclass(frozen=True) +class TypingRules: + """The rules which decide how a line of input is split into commands.""" + + allow_redirection: bool + terminators: tuple[str, ...] + multiline_commands: tuple[str, ...] + + +@dataclass(frozen=True) +class Snapshot: + """Everything the server says about an application, as it was at one moment.""" + + generation: int + built_at: str # local time with its offset, ISO 8601, to the second + commands: tuple[Command, ...] # in the order help sorts them + categories: tuple[Category, ...] # grouped and ordered with the same help sort key + descriptions: Mapping[str, Description] # by path, every depth, each subcommand by its name and not its aliases + help_topics: tuple[str, ...] # the topics which are not commands + shortcuts: tuple[Shortcut, ...] + aliases: tuple[Alias, ...] + macros: tuple[Macro, ...] + typing: TypingRules + quotes_kept: frozenset[str] # the commands whose preserve_quotes is set; not served, but used to find a path + error: str | None # why the whole build failed; else None + stale_reason: str | None = None # latest rebuild failure when serving a previous successful build + + +def _now() -> str: + return datetime.now().astimezone().isoformat(timespec="seconds") + + +def _command_summary(doc: str | None, parser: Cmd2ArgumentParser | None) -> str: + """Return a command's one-line description: the first block of its docstring, else its parser's description.""" + if doc: + # What "help -v" shows. + return plain_text(utils.strip_doc_annotations(doc)) + if parser is not None: + return _parser_summary(parser) + return "" + + +def _unparsed_description(path: str, summary: str, help_text: str, error: str | None) -> Description: + """Return the description of a command which has no parser, or which could not be described.""" + return Description( + path=path, + summary=summary, + usage="", + help=help_text, + has_parser=False, + arguments=(), + exclusive_groups=(), + subcommands=(), + subcommand_required=False, + error=error, + ) + + +def _describe_command(app: "Cmd", name: str) -> tuple[Command, dict[str, Description], bool]: + """Describe one command. Raise whatever cmd2 raises when it cannot be done.""" + func = app.get_command_func(name) + if func is None: + raise LookupError("cmd2 has no function for the command") + category = plain_text(app.get_command_category(func)) + parser = app.command_parsers.get(func) + summary = _command_summary(func.__doc__, parser) + if parser is None: + keeps_quotes = False + text = plain_text(inspect.cleandoc(func.__doc__)) if func.__doc__ else "" + descriptions = {name: _unparsed_description(name, summary, text, None)} + else: + spec = app.get_argparse_command_spec(func) + keeps_quotes = spec is not None and spec.preserve_quotes + terminators = app.statement_parser.terminators + descriptions = describe_parser(parser, name, summary, terminators, keeps_quotes=keeps_quotes) + top = descriptions[name] + command = Command( + name=plain_text(name), + category=category, + summary=summary, + has_parser=top.has_parser, + subcommands=tuple(subcommand.typed for subcommand in top.subcommands), + error=None, + ) + return command, descriptions, keeps_quotes + + +def _failed_command(app: "Cmd", name: str, exc: Exception) -> tuple[Command, dict[str, Description]]: + """Return a command which could not be described, still listed, with the reason.""" + try: + func = app.get_command_func(name) + category = plain_text(app.get_command_category(func)) if func is not None else "" + except Exception: # noqa: BLE001 + category = "" + error = plain_text(f"This command could not be described: {type(exc).__name__}: {exc}") + command = Command(name=plain_text(name), category=category, summary="", has_parser=False, subcommands=(), error=error) + return command, {name: _unparsed_description(name, "", "", error)} + + +def build_snapshot(app: "Cmd", generation: int, leave_out: Collection[str] = ()) -> Snapshot: + """Describe the whole application. Call it on the main thread only: it asks cmd2 for every command's parser.""" + commands: list[Command] = [] + descriptions: dict[str, Description] = {} + quotes_kept: set[str] = set() + sort_key = utils.DEFAULT_STR_SORT_KEY + visible = sorted(app.get_visible_commands(), key=sort_key) + included = [name for name in visible if name not in leave_out] + by_category: dict[str, list[Command]] = {} + for name in included: + try: + command, found, keeps_quotes = _describe_command(app, name) + except Exception as exc: # noqa: BLE001 - one command's failure is its own + command, found = _failed_command(app, name, exc) + else: + if keeps_quotes: + quotes_kept.add(command.name) + commands.append(command) + by_category.setdefault(command.category, []).append(command) + descriptions.update(found) + parser = app.statement_parser + topics = sorted((topic for topic in app.get_help_topics() if topic not in visible), key=sort_key) + + def by_name(item: tuple[str, object]) -> str: + return sort_key(item[0]) + + return Snapshot( + generation=generation, + built_at=_now(), + commands=tuple(commands), + categories=tuple(Category(name, tuple(by_category[name])) for name in sorted(by_category, key=sort_key)), + descriptions=descriptions, + help_topics=tuple(plain_text(topic) for topic in topics), + shortcuts=tuple( + Shortcut(plain_text(shortcut), plain_text(command)) for shortcut, command in sorted(parser.shortcuts, key=by_name) + ), + aliases=tuple(Alias(plain_text(n), plain_text(v)) for n, v in sorted(app.aliases.items(), key=by_name)), + macros=tuple( + Macro(plain_text(n), plain_text(m.value), m.minimum_arg_count) for n, m in sorted(app.macros.items(), key=by_name) + ), + typing=TypingRules( + allow_redirection=bool(app.allow_redirection), + terminators=tuple(plain_text(t) for t in parser.terminators), + multiline_commands=tuple(plain_text(c) for c in parser.multiline_commands if c in included), + ), + quotes_kept=frozenset(quotes_kept), + error=None, + ) + + +# What is served until the first description has been built: before cmdloop() has run preloop(), for one. +_NOT_BUILT = "The description has not been built yet." + + +def failed_snapshot(generation: int, error: str) -> Snapshot: + """Return an empty snapshot which carries the reason the build failed.""" + return Snapshot( + generation=generation, + built_at=_now(), + commands=(), + categories=(), + descriptions={}, + help_topics=(), + shortcuts=(), + aliases=(), + macros=(), + typing=TypingRules(allow_redirection=False, terminators=(), multiline_commands=()), + quotes_kept=frozenset(), + error=plain_text(error), + ) + + +@dataclass(frozen=True) +class CommandList: + """The answer to "list the commands".""" + + generation: int + built_at: str + categories: tuple[Category, ...] # in the order help shows them + help_topics: tuple[str, ...] + typing: TypingRules + error: str | None # why there is no description to answer from: none has been built yet, or a build failed + stale_reason: str | None = None + + +@dataclass(frozen=True) +class CommandDescription: + """The answer to "describe a command".""" + + generation: int + built_at: str + description: Description + stale_reason: str | None = None + + +@dataclass(frozen=True) +class Tables: + """The answer to "list the shortcuts, aliases and macros".""" + + generation: int + built_at: str + shortcuts: tuple[Shortcut, ...] + aliases: tuple[Alias, ...] + macros: tuple[Macro, ...] + error: str | None # why there is no description to answer from: none has been built yet, or a build failed + stale_reason: str | None = None + + +class UnknownCommandError(LookupError): + """No such command or subcommand. str() says what is missing and names what exists.""" + + +class DescriptionUnavailableError(LookupError): + """No description to answer from: none has been built yet, or a build failed. str() says which.""" + + +def answer_list_commands(snapshot: Snapshot) -> CommandList: + """List the commands by category, in the order help shows them.""" + return CommandList( + generation=snapshot.generation, + built_at=snapshot.built_at, + categories=snapshot.categories, + help_topics=snapshot.help_topics, + typing=snapshot.typing, + error=snapshot.error, + stale_reason=snapshot.stale_reason, + ) + + +def answer_describe_command(snapshot: Snapshot, command: str) -> CommandDescription: + """Describe a command or a subcommand, given its path as typed ("server tag add"), or raise UnknownCommandError. + + Where the snapshot holds no description, raise DescriptionUnavailableError, which says why. + + The path is split into words as the prompt splits a command line. The first is a command's name, which the prompt + never takes quoted. Each word after it is a subcommand's name if the prompt would take it as that name: as it is + served, or quoted. + """ + if snapshot.error is not None: + raise DescriptionUnavailableError(f"No command can be described: {snapshot.error}") + try: + words = shlex_split(command) # with their quotes, as the prompt keeps them + except ValueError as error: # a quotation which is never closed + raise UnknownCommandError(f'"{command.strip()}" cannot be split into words as the prompt would: {error}.') from error + path = " ".join(words) + commands = {listed.name for listed in snapshot.commands} + description = snapshot.descriptions.get(words[0]) if words and words[0] in commands else None + if description is None: + names = ", ".join(listed.name for listed in snapshot.commands) + raise UnknownCommandError(f'There is no command "{path}". The commands are: {names}.') + reading = _Reading(StatementParser(terminators=snapshot.typing.terminators), words[0] in snapshot.quotes_kept) + # Each word after the first is a subcommand of the one before it, by its name or by an alias, as argparse takes it. + # The walk stops at the first word which is not, and that word's parent says what could have followed it. + for word in words[1:]: + parent = description + taken = reading.argument_for(word) + found = next((sub for sub in parent.subcommands if taken in (sub.name, *sub.aliases)), None) + description = None if found is None else snapshot.descriptions.get(f"{parent.path} {found.typed}") + if description is None: + names = ", ".join(sub.typed for sub in parent.subcommands) + if names: + raise UnknownCommandError(f'There is no subcommand "{path}". "{parent.path}" has: {names}.') + raise UnknownCommandError(f'There is no subcommand "{path}": "{parent.path}" has no subcommands.') + return CommandDescription( + generation=snapshot.generation, built_at=snapshot.built_at, description=description, stale_reason=snapshot.stale_reason + ) + + +def answer_tables(snapshot: Snapshot) -> Tables: + """Return the shortcuts, aliases and macros.""" + return Tables( + generation=snapshot.generation, + built_at=snapshot.built_at, + shortcuts=snapshot.shortcuts, + aliases=snapshot.aliases, + macros=snapshot.macros, + error=snapshot.error, + stale_reason=snapshot.stale_reason, + ) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 27ad738e6..072921910 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -50,6 +50,7 @@ from collections import deque from collections.abc import ( Callable, + Collection, Iterable, Mapping, Sequence, @@ -224,6 +225,8 @@ def __init__(self, msg: str = "") -> None: if TYPE_CHECKING: # pragma: no cover from prompt_toolkit.buffer import Buffer + from ._mcp_server import McpServer + # Errors raised when prompt-toolkit can't use a terminal. For example, GitHub Actions on Windows reports # isatty() as True but has no real console. @@ -397,6 +400,9 @@ def __init__( include_ipy: bool = False, include_py: bool = False, intro: RenderableType = "", + mcp_port: int | None = None, + mcp_name: str = "cmd2 application", + mcp_leave_out: Collection[str] = (), multiline_commands: Iterable[str] | None = None, persistent_history_file: str = "", persistent_history_length: int = 1000, @@ -441,6 +447,11 @@ def __init__( :param include_ipy: should the "ipy" command be included for an embedded IPython shell :param include_py: should the "py" command be included for an embedded Python shell :param intro: introduction to display at startup + :param mcp_port: enable the read-only, loopback MCP server on this port during cmdloop(). + Use 0 for an available port. The default, None, disables MCP. + Install the optional ``cmd2[mcp]`` extra to run the server. + :param mcp_name: application name reported to MCP clients + :param mcp_leave_out: command names to exclude from MCP discovery :param multiline_commands: Iterable of commands allowed to accept multi-line input :param persistent_history_file: file path to load a persistent cmd2 command history from :param persistent_history_length: max number of history items to write @@ -465,6 +476,8 @@ def __init__( and you want terminators to be treated as literals by the parser, then set this to None. """ + self._mcp: McpServer | None = None + # Check if py or ipy need to be disabled in this instance if not include_py: setattr(self, "do_py", None) # noqa: B010 @@ -754,6 +767,34 @@ def __init__( # the current command being executed self.current_command: Statement | None = None + if mcp_port is not None: + from . import _mcp_server + + self._mcp = _mcp_server.McpServer(self, port=mcp_port, name=mcp_name, leave_out=mcp_leave_out) + + def mcp_start(self) -> None: + """Start the configured read-only MCP server when driving commands without cmdloop(). + + Use [cmd2.Cmd.mcp_url][] or [cmd2.Cmd.mcp_status][] to check startup. + """ + if self._mcp is None: + raise ValueError("Configure mcp_port when constructing Cmd to enable the MCP server") + self._mcp.mcp_start() + + def mcp_stop(self) -> None: + """Stop this application's MCP server and release its listener. Safe to call repeatedly.""" + if self._mcp is not None: + self._mcp.mcp_stop() + + @property + def mcp_url(self) -> str | None: + """Loopback URL of the running MCP server, or None if it is not serving.""" + return self._mcp.mcp_url if self._mcp is not None else None + + def mcp_status(self) -> list[str]: + """Return human-readable lines describing the MCP listener and its latest snapshot.""" + return self._mcp.mcp_status() if self._mcp is not None else ["No MCP server: no port was configured"] + def _should_continue_multiline(self) -> bool: """Return whether prompt-toolkit should continue prompting the user for a multiline command.""" buffer: Buffer = get_app().current_buffer @@ -3105,6 +3146,9 @@ def onecmd_plus_hooks( stop = False statement = None + mcp = self._mcp + if mcp is not None: + mcp._mcp_depth += 1 try: # Convert the line into a Statement statement = self._input_line_to_statement(line) @@ -3208,6 +3252,10 @@ def onecmd_plus_hooks( raise ex.wrapped_ex from None except Exception as ex: # noqa: BLE001 self.pexcept(ex) + finally: + if mcp is not None: + mcp._mcp_depth -= 1 + mcp._mcp_rebuild() return stop @@ -4062,6 +4110,8 @@ def _pre_prompt() -> None: # pre_prompt() are considered current. self._alert_prompt_timestamp = time.monotonic() self.pre_prompt() + if self._mcp is not None: + self._mcp._mcp_rebuild() # Start alerter thread if it's not already running. if self._alert_thread is None or not self._alert_thread.is_alive(): @@ -6429,33 +6479,30 @@ def cmdloop(self, intro: RenderableType = "") -> int: original_sigterm_handler = signal.getsignal(signal.SIGTERM) signal.signal(signal.SIGTERM, self.termination_signal_handler) - # Always run the preloop first - for func in self._preloop_hooks: - func() - self.preloop() - - # If an intro was supplied in the method call, allow it to override the default - if intro: - self.intro = intro - - # Print the intro, if there is one, right after the preloop - if self.intro: - self.poutput(self.intro) - - # And then call _cmdloop() to enter the main loop - self._cmdloop() - - # Run the postloop() no matter what - for func in self._postloop_hooks: - func() - self.postloop() - - # Restore original signal handlers - signal.signal(signal.SIGINT, original_sigint_handler) - - if not sys.platform.startswith("win"): - signal.signal(signal.SIGHUP, original_sighup_handler) - signal.signal(signal.SIGTERM, original_sigterm_handler) + mcp = self._mcp + try: + with mcp.command_loop() if mcp is not None else contextlib.nullcontext(): + for func in self._preloop_hooks: + func() + self.preloop() + + if intro: + self.intro = intro + if self.intro: + self.poutput(self.intro) + + if mcp is not None: + mcp.preloop_finished() + self._cmdloop() + + for func in self._postloop_hooks: + func() + self.postloop() + finally: + signal.signal(signal.SIGINT, original_sigint_handler) + if not sys.platform.startswith("win"): + signal.signal(signal.SIGHUP, original_sighup_handler) + signal.signal(signal.SIGTERM, original_sigterm_handler) return self.exit_code diff --git a/docs/examples/index.md b/docs/examples/index.md index 476619176..ee03a4cbb 100644 --- a/docs/examples/index.md +++ b/docs/examples/index.md @@ -5,7 +5,7 @@ - [Getting Started](getting_started.md) - [Alternate Event Loops](alternate_event_loops.md) - [Embedding in Textual](embedding_in_textual.md) -- [MCP Server](mcp_server.md) +- [MCP Fleet Console](mcp_server.md) - [List of cmd2 examples](examples.md) diff --git a/docs/examples/mcp_server.md b/docs/examples/mcp_server.md index 3fb819d7c..26d1e3294 100644 --- a/docs/examples/mcp_server.md +++ b/docs/examples/mcp_server.md @@ -1,92 +1,43 @@ -# MCP Server +# MCP Fleet Console -The [Model Context Protocol](https://modelcontextprotocol.io) (MCP) is an open protocol through -which an AI assistant, such as Claude Code, calls tools which other programs provide. The -[mcp_server.py](https://github.com/python-cmd2/cmd2/blob/main/examples/mcp_server.py) example is a -`cmd2` application which, while its prompt is live, serves a description of its own commands over -MCP: which commands there are, what arguments each one takes, and which shortcuts, aliases and -macros can be typed. The person at the prompt asks an assistant connected to it for what they want -in plain English, and the assistant works out the command line from the application as it is at that -moment. The server never runs a command. It only describes them, and the person types the command -line which the assistant gives. - -The example is one file in three parts. The first describes a `cmd2` application's commands as plain -data, from the parsers which `cmd2` already holds. The second, `McpServerMixin`, keeps that -description up to date and serves it from a worker thread, and can be copied into your own -application. The third is a pretend "fleet console", with servers, deployments and a plugin, which -gives the other two every kind of command to describe. Its commands only print what they would have -done. The description follows the application while it runs, so loading a `CommandSet`, disabling a -command or creating an alias changes what the assistant is told. - -## Running the Example - -The example needs `cmd2` 4.5.0 or later, which added [cmd2.Cmd.get_command_category][] and -[cmd2.Cmd.get_argparse_command_spec][], and the -[MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk), version 2 or later. The SDK is -not a dependency of `cmd2`. In a `cmd2` checkout it is in the `examples` dependency group, which is -not installed by default, so run: +The [Fleet console](https://github.com/python-cmd2/cmd2/blob/main/examples/mcp_server.py) is a +pretend deployment CLI that enables the built-in [MCP server](../features/mcp_server.md). Its +commands operate on an in-memory fleet. Run it from a checkout. ```shell -uv run --group examples examples/mcp_server.py +uv run --extra mcp examples/mcp_server.py ``` -When it starts, it says where its server is: +The console prints the address a Streamable HTTP client can connect to. ```text Fleet console. MCP server: http://127.0.0.1:8765/mcp (describes commands, never runs them) ``` -That is the address an assistant connects to. The server runs for as long as the command loop does, -and stops when you leave with `quit` or ++ctrl+d++. Two switches change it: - -- `--mcp-port PORT` serves on another port. `0` lets the system choose a free one, and the intro - shows which one it chose. -- `--no-mcp` runs the application without a server, and then the SDK isn't needed. - -If the server can't start, for example because another program is using the port, the application -prints a warning which says why, and carries on without a server. Its intro then says -`Fleet console. No MCP server: see "mcp status".` At the prompt, `mcp status` says whether there is -a server, and which description it serves: its number, when it was built, and how many commands it -describes. - -The example has been tried by hand on macOS, with the MCP Inspector, Claude Code and Claude Desktop; -on Windows 11, in Windows Terminal, with the MCP Inspector, Claude Code and the MCP SDK's own -client; and on Linux, with the SDK's own client. - -## Connecting an Assistant +Try `--mcp-port 0` to have the system choose a port, or `--no-mcp` to run the CLI without the server +or its optional dependencies. At the `fleet>` prompt, `mcp status` prints the server state and +details about the current command description. Quit the console to stop the server. -Start the example first, since a client connects to the running application. Write the address with -`127.0.0.1`, as below, and not with `localhost`. The server listens on the IPv4 address only, and -`localhost` can resolve to the IPv6 address first, where nothing is listening. - -Three clients have been tried with the example, on macOS: Claude Code, Claude Desktop through the -`mcp-remote` bridge, and the MCP Inspector. Claude Code and the Inspector have also been tried on -Windows. - -A client which stays connected while you quit the application and start it again works again without -being told anything. The server keeps no session for a client, so there is nothing to lose. +## Connect a client ### Claude Code -Add the server to [Claude Code](https://code.claude.com/docs/en/mcp), then check that it is -connected: +With the console running, add the printed URL to an MCP client. For example, to connect +[Claude Code](https://code.claude.com/docs/en/mcp) on the default port, run these commands in +another terminal. ```shell claude mcp add --transport http fleet http://127.0.0.1:8765/mcp claude mcp list ``` -While the example is running, `claude mcp list` shows -`fleet: http://127.0.0.1:8765/mcp (HTTP) - ✔ Connected`. The first command adds the server at Claude -Code's default scope, which is local: it is available only in the project you run the command in. - ### Claude Desktop -Claude Desktop starts each MCP server in its configuration as a program, and talks to it over its -standard input and output. It reaches the example through -[mcp-remote](https://github.com/geelen/mcp-remote), a program which passes those messages on to an -HTTP server. Add this to Claude Desktop's configuration file, which Settings → Developer → Edit -Config opens. If the file already has other settings, put `mcpServers` beside them. +Claude Desktop can launch the [mcp-remote](https://github.com/geelen/mcp-remote) bridge to forward +requests to the console's HTTP listener. In **Settings → Developer → Edit Config**, add the `fleet` +entry to `mcpServers`. The example below uses the macOS configuration tested with Node.js 22. +Replace `/path/to/npx` with the full path printed by `which npx` and `/path/to` with the directory +containing `node`. ```json { @@ -106,298 +57,27 @@ Config opens. If the file already has other settings, put `mcpServers` beside th } ``` -`command` is the full path of `npx`, as `which npx` prints it, and `PATH` starts with the directory -it is in, so that `npx` finds `node` there. This is the form which was tried, with version 0.17.2 of -`mcp-remote` and Node.js 22 from nvm. - -Claude Desktop starts the bridge when it opens, so start the example first, then quit Claude Desktop -and open it again. If you quit the example, a question asked meanwhile fails, and Claude says that -the server isn't responding. Once the example is running again, the next question works, without -anything done in Claude Desktop. +Start the console before reopening Claude Desktop so the bridge can connect. ### MCP Inspector -The [MCP Inspector](https://github.com/modelcontextprotocol/inspector) checks the server without an -assistant. This lists the server's tools: +You can also list the tools with the +[MCP Inspector](https://github.com/modelcontextprotocol/inspector). ```shell npx @modelcontextprotocol/inspector@latest --cli http://127.0.0.1:8765/mcp --method tools/list ``` -It shows three tools, `list_commands`, `describe_command` and `list_shortcuts_aliases_macros`, each -marked `readOnlyHint: true`. Version 2 of the Inspector takes the server's address as an argument, -and its version 2.17.0 asks for Node.js `^22.23.4 || ^24.22.1 || >=26.12.1`; `@latest` keeps `npx` -from running an older version from its cache, which takes different switches. - -## Trying It - -With the example running and Claude Code connected, ask what to type at the fleet console's prompt -to do something. Each of these objectives was asked of Claude Code, which called `list_commands` and -`describe_command`, and answered with the command line below it. Claude Desktop, asked the same, -gave the same command lines. - -- "Deploy version 2.1.0 of the api service to staging, without changing anything." - - ```text - deploy api --version 2.1.0 --env staging --dry-run - ``` - -- "Add the tags web and eu to the server web-2." - - ```text - server tag add web-2 web eu - ``` - -- "Run four replicas of the api service." - - ```text - scale api 4 - ``` - -- "Restart the servers web-1, web-2 and db-1." - - ```text - restart web-1 web-2 db-1 - ``` - -- "Back up the site service." The `backup` command exists only once its plugin is loaded. Asked - before that, Claude Code answered `plugin load backups`, and said that the plugin's commands are - not described until it is loaded. Asked after `plugin load backups`, it answered: - - ```text - backup site - ``` - -## How It Works - -`cmd2` changes its command tables and parsers in place, on the main thread and without locks, and -builds a command's parser the first time it is asked for, so they are not safe to read from another -thread. The server answers requests on threads of its own, so it never reads them. Instead the mixin -builds a _snapshot_ on the main thread: a description of the whole application as plain data, in -frozen dataclasses. A snapshot is complete before it is published, by assigning it to the -application's `mcp_snapshot` attribute, and it is never changed afterwards. Each tool reads -`mcp_snapshot` once, and answers from that snapshot alone. - -The snapshot is rebuilt at three moments, by three methods of [cmd2.Cmd][] which the mixin -overrides: - -1. When the outermost [cmd2.Cmd.cmdloop][] has run the preloop hooks and `preloop()`, and printed - the intro, just before it runs the startup commands and reads the first line. This is the first - description. The server starts before the preloop hooks, and until this moment it answers that - the description has not been built yet, so nothing is described from before the application has - finished starting, such as a command which `preloop()` hides. `cmd2` has no public method at - this moment, so the mixin overrides `_cmdloop()`, which is private, and which `cmdloop()` calls - then. -1. Just before each top-level prompt, in [cmd2.Cmd.pre_prompt][]. This picks up what the - application's own `pre_prompt()` changes. -1. Whenever the outermost call of [cmd2.Cmd.onecmd_plus_hooks][] ends, whether it returns or - raises. Every command goes through that method: one typed at the prompt, a startup command, each - line of a script, and each command a Python script runs. A script is one outermost call, so the - snapshot is rebuilt once, when the script ends. `cmd2` calls `pre_prompt()` only when input is a - terminal, so when commands come from a pipe or a file, this is the only moment after the start. - -It is never rebuilt while a command is in progress. A command may change the application part of the -way through and then undo the change, and an assistant would answer from a state which the prompt -never saw. That includes the continuation prompts of a -[multiline command](../features/multiline_commands.md), where `cmd2` calls `pre_prompt()` from -inside the command. The mixin counts the calls of `onecmd_plus_hooks()` in progress, and the one -method which rebuilds does nothing unless the count is zero. It overrides these methods, and -registers no [hooks](../features/hooks.md), because `cmd2` does not call its postparsing and command -finalization hooks in pairs: a blank line reaches only the finalization hooks, and a finalization -hook which raises stops the ones after it, so a count kept with hooks could be left wrong for good. - -The outermost `cmdloop()` also calls `mcp_start()`, which serves the snapshot from a daemon thread -with the SDK's Streamable HTTP application and `uvicorn`, and calls `mcp_stop()` when the loop ends, -however it ends. A server which can't start is a warning, and the application carries on without -one. The server's threads never print. The records which `uvicorn` and the SDK log are kept by a -handler of the mixin's, and `mcp status` shows the last few of them. - -The server has three tools. Each one is marked read-only, and each answer carries the snapshot's -`generation`, which goes up by one with each rebuild, and `built_at`, the time it was built: - -- `list_commands` lists the commands by help category, in the order `help` shows them, each with its - summary, whether a parser checks its arguments, and its subcommands as typed. It also lists the - help topics which are not commands, and the rules for typing a command line: the terminators, the - multiline commands, and whether output can be redirected. -- `describe_command` describes one command, or one subcommand given by its path as typed, such as - `server tag add`. Append a subcommand's `typed` field to its parent's path for the next lookup. - For example, `report "list all"` describes one subcommand whose name contains a space. The usage - shows any positional arguments or `--` needed to run it at the prompt. A name which isn't there, - including a hidden or disabled command, is an error which names the commands or subcommands which - are. -- `list_shortcuts_aliases_macros` lists the shortcuts, the aliases and the macros, since each one - changes what can be typed. - -Until the first description has been built, or when a build fails and there is none, the answers of -`list_commands` and `list_shortcuts_aliases_macros` have an `error` which says why, and -`describe_command` is an error which says why. If a later rebuild fails, all three tools keep -serving the last successful description with its original `generation` and `built_at`. Their -`stale_reason` field reports the latest failure until a rebuild succeeds, when it returns to `null`. -A failed command lookup also tells the client when its description is out of date. - -The server's instructions, which a client gives its model, say that the server describes the -commands of an application which a person is using, that it can't run them, and that the answer is a -command line for the person to type. - -The snapshot holds the commands which `help` lists: hidden and disabled commands are left out, and -the built-in commands, such as `shell` and `history`, are described like any other, since they can -be typed too. Subcommands which `help` leaves out are left out too: one added with -`help=argparse.SUPPRESS`, and all of a command's subcommands where they were added with -`add_subparsers(help=argparse.SUPPRESS)`. A command's description holds its summary, its usage and -help as plain text wrapped at 100 columns without any escape sequence, its subcommands and whether -one of them must be given, which of its arguments exclude each other, and for each argument: - -- its name, its metavar and its flags, such as `-n` and `--lines`, and its help -- whether it is required, and the fewest and the most values it takes -- whether it takes the rest of the line, as the last argument of `shell` does -- its default, its choices, no more than the first 1000 of them, and the name of its type -- whether it has choices which aren't listed -- whether its choices come from a choices provider or a completer, which is never called -- whether it may be given more than once - -A command with no parser, such as a plain `do_*` method or one decorated with `@with_argument_list`, -is described by its docstring, and marked as having no parser: its arguments are free-form text. A -command which can't be described, for example because its parser can't be built, is still listed, -with the reason, and the others are described as usual. - -This is the start of `build_snapshot()`, which the mixin calls to build each snapshot, without its -docstring: - -```py -def build_snapshot(app: Cmd, generation: int, leave_out: Collection[str] = ()) -> Snapshot: - commands: list[Command] = [] - descriptions: dict[str, Description] = {} - quotes_kept: set[str] = set() - visible = sorted(app.get_visible_commands(), key=DEFAULT_STR_SORT_KEY) - included = [name for name in visible if name not in leave_out] - for name in included: - try: - command, found, keeps_quotes = _describe_command(app, name) - except Exception as exc: # noqa: BLE001 - one command's failure is its own - command, found = _failed_command(app, name, exc) - else: - if keeps_quotes: - quotes_kept.add(command.name) - commands.append(command) - descriptions.update(found) - # ... then the help topics, shortcuts, aliases, macros and the rules for typing a command line -``` - -`_describe_command()` finds each command's function, help category and parser with -[cmd2.Cmd.get_command_func][], [cmd2.Cmd.get_command_category][] and `command_parsers.get()`, and -whether argparse is given its arguments with their quotes with -[cmd2.Cmd.get_argparse_command_spec][], since that decides how a subcommand's name is typed. Then -`describe_parser()` walks the parser and its subcommands, describing each argument with -`describe_argument()`. All of it is in -[mcp_server.py](https://github.com/python-cmd2/cmd2/blob/main/examples/mcp_server.py). - -## Using It in Your Own Application +## Try it -Parts 1 and 2 of `mcp_server.py`, everything above "Part 3: The demonstration", are written to be -copied. Copy them into your application, add the MCP SDK, `mcp>=2`, to its dependencies, and put -`McpServerMixin` before `cmd2.Cmd` in the bases of your application's class: +Ask the assistant how to deploy version `2.1.0` of service `api` to staging as a dry run. It can +look up `deploy` and suggest a command for you to type. -```py -import sys - -import cmd2 - - -class MyApp(McpServerMixin, cmd2.Cmd): - def __init__(self) -> None: - super().__init__( - mcp_name="my-app", # the name the server gives itself to a client - mcp_port=8766, # the port to serve on; None runs without a server - mcp_leave_out=["shell", "run_pyscript"], # commands which are never described - ) - - -if __name__ == "__main__": - sys.exit(MyApp().cmdloop()) +```text +fleet> deploy api --version 2.1.0 --env staging --dry-run +Would deploy api 2.1.0 to staging (dry run). ``` -The three keyword arguments are the mixin's own, and it passes every other one on to `cmd2.Cmd`. -Each is kept in an attribute of the same name. Give your application a port of its own, so that a -client's configuration can be written once. While it serves, `mcp_url` is its address, which the -fleet console prints from its `preloop()`, since `cmd2` calls that after the server has started. -`mcp_status()` returns the lines which the fleet console's `mcp status` command prints. - -Each argument's default and each command's help text are served as they are, so in a command which -is described, don't default an argument to a secret, for example one read from the environment: read -the secret inside the command instead, or leave the command out with `mcp_leave_out`. - -The mixin asks a few things of your application: - -- It comes before `cmd2.Cmd` in the bases, so that its `cmdloop()`, `_cmdloop()`, `pre_prompt()` and - `onecmd_plus_hooks()` are the ones which are called. `_cmdloop()` is a private method of - `cmd2.Cmd`, which a later version of `cmd2` may change. -- If your application overrides `cmdloop()`, `pre_prompt()` or `onecmd_plus_hooks()`, the override - calls `super()`, and passes every argument on. -- Apart from setting `mcp_name`, `mcp_port` and `mcp_leave_out`, your application defines no method - or attribute whose name starts with `mcp_` or `_mcp_`, since the mixin's own names start that way. - The handler of an `mcp status` subcommand would usually be named `mcp_status()`, and would replace - the mixin's `mcp_status()`, so the fleet console names its handler `mcp_show_status()`. -- An override of `pre_prompt()` which changes which commands exist or are visible does so first, and - calls `super().pre_prompt()` last, because the mixin rebuilds the description inside its own - `pre_prompt()`: - - ```py - def pre_prompt(self) -> None: - if self.maintenance_due(): - self.disable_category("Deployments", "Deployments are disabled during maintenance.") - super().pre_prompt() # last: the description is rebuilt here - ``` - -- An override of `onecmd_plus_hooks()` leaves the commands alone after `super()` returns, since the - mixin rebuilds the description as its own `onecmd_plus_hooks()` ends. -- Logging is set up before the command loop starts. The mixin changes the `uvicorn` and `mcp` - loggers when the server starts, and puts back what it found when the server stops, so a logging - configuration applied in between can let the server's records reach the terminal, and is partly - undone when the server stops. -- An application which doesn't use `cmdloop()` calls `mcp_start()` itself before it runs commands, - and `mcp_stop()` when it has finished, in a `finally`. `mcp_start()` builds the first description - and starts the server. - -## Limits and Safety - -- **How fresh the description is.** The server rebuilds the description at each top-level prompt and - at the end of each outermost command. A change made part of the way through a long command or a - script, or at the continuation prompt of a multiline command, shows when the outermost command - ends and the rebuild succeeds. A change made by another thread shows at the next successful - rebuild. A command run by calling `onecmd()` directly, and not through `onecmd_plus_hooks()`, does - not refresh it. -- **A command loop inside a command.** An application which calls its own `cmdloop()` from inside - one of its commands is inside that command for as long as the inner loop runs. The description is - not refreshed until the outer command returns, and the inner loop neither starts nor stops the - server. -- **Your own `pre_prompt()`.** One which changes the commands after it calls `super().pre_prompt()` - has changed them too late for that prompt. The description catches up when the next command ends. -- **Logging.** While the server runs, the records which `uvicorn` and the SDK log, on the loggers - `uvicorn` and `mcp`, don't reach the handlers on the root logger. If you want them, attach a - handler to those loggers yourself. Such a handler keeps working, and **if it writes to the - terminal, the server's records appear on the terminal,** over the prompt or a running command. - Send it to a file. -- **Dynamic choices.** An argument whose choices come from a choices provider or a completer is - marked as having dynamic choices, but its choices aren't listed. The provider is your - application's code, and the describing code never calls it. -- **Long lists of choices.** No more than the first 1000 of an argument's choices are listed, so - that `choices=range(2**32)` costs no more to describe than a short list, and an argument with more - is marked as having choices which aren't listed. Choices which are an iterator aren't listed at - all, since listing them would use up what `argparse` checks each value against, and are marked the - same way. -- **Commands with no parser.** A command with no parser is described by its docstring alone. -- **The cost of rebuilding.** Rebuilding takes time in proportion to the number of parsers, and in a - terminal session it happens twice for each command: when the command ends, and before the next - prompt. It was measured at about 0.6 ms a parser on an Apple silicon Mac, which is about 20 ms a - command for a bare `cmd2.Cmd`. An application with hundreds of parsers may want to rebuild less - often. -- **No authentication.** The server listens on `127.0.0.1` only, so it can be reached from this - machine and not from the network, but any program or user on this machine can read what it serves. - That includes the values of your aliases and macros, which sometimes hold things a person wouldn't - want read. It also includes each argument's default and each command's help text, which are served - as they are. Don't default an argument of a command which is described to a secret, for example - one read from the environment: read the secret inside the command instead, or leave the command - out with `mcp_leave_out`. -- **It describes, and doesn't run.** A server which ran commands for an assistant would need the - person to confirm each one, and a list of the commands it is allowed to run. That is a different - design. +Try `plugin load backups`, then ask how to back up the site service. The new `backup` and `restore` +commands are now discoverable. Enter `maintenance on` and ask which deployment commands are +available. The disabled commands disappear until you enter `maintenance off`. diff --git a/docs/features/index.md b/docs/features/index.md index ff6122b60..8981e3101 100644 --- a/docs/features/index.md +++ b/docs/features/index.md @@ -16,6 +16,7 @@ - [History](history.md) - [Hooks](hooks.md) - [Initialization](initialization.md) +- [MCP Server](mcp_server.md) - [Miscellaneous Features](misc.md) - [Modular Commands](modular_commands.md) - [Multiline Commands](multiline_commands.md) diff --git a/docs/features/mcp_server.md b/docs/features/mcp_server.md new file mode 100644 index 000000000..8f4a51057 --- /dev/null +++ b/docs/features/mcp_server.md @@ -0,0 +1,96 @@ +# MCP Server + +A running `cmd2` application can tell an assistant which commands are available, how to call them, +and which aliases the person at the prompt can type. It exposes three read-only tools over the +[Model Context Protocol](https://modelcontextprotocol.io) (MCP). The assistant can use them to +suggest a command line for the person to review and run. + +## Enable the server + +Install the optional MCP extra in the application's environment. + +```shell +pip install "cmd2[mcp]" +``` + +Pass a port to [cmd2.Cmd][] to serve command descriptions over Streamable HTTP. + +```python +import cmd2 + + +class App(cmd2.Cmd): + def __init__(self) -> None: + super().__init__(mcp_port=8765, mcp_name="My console", mcp_leave_out={"internal"}) + + def preloop(self) -> None: + super().preloop() + if self.mcp_url: + self.poutput(f"Connect your MCP client to {self.mcp_url}") + + +if __name__ == "__main__": + App().cmdloop() +``` + +With these settings, the URL is `http://127.0.0.1:8765/mcp`. Specify port `0` to let the system +choose a free port. The default, `mcp_port=None`, disables MCP entirely, so a base installation can +run the same application without the extra. `mcp_name` identifies the server to clients. +`mcp_leave_out` excludes named top-level commands and their subcommands from discovery. + +The outermost [cmd2.Cmd.cmdloop][] starts the listener before the preloop hooks and stops it when +the loop exits. If startup fails, the application reports the reason and the prompt remains usable. +[cmd2.Cmd.mcp_url][] gives the URL while the server is listening. [cmd2.Cmd.mcp_status][] returns +lines suitable for display, including startup problems and the state of the command description. + +While any `cmd2` MCP server is running, records on the process-wide `mcp` and `uvicorn` loggers stop +propagating to the root logger so they do not interrupt the prompt. `mcp_status()` includes recent +records from these loggers across all server runs in the process. Handlers attached directly to +either logger still receive records. To keep a log, configure a file handler before starting the +server. When the last server worker exits, `cmd2` restores the original propagation settings. + +## Discover commands + +- `list_commands` groups visible commands by help category and includes summaries, subcommands, help + topics, and rules for entering command lines. +- `describe_command` takes a command or subcommand path such as `server tag add`. It returns usage, + help, and argument details such as required flags, static choices, and parser defaults. For + commands without a parser, it returns the docstring. It identifies dynamic choices without calling + application completers or choices providers. +- `list_shortcuts_aliases_macros` lists shortcuts and the current definitions of aliases and macros. + +Each tool reads a snapshot built on the application's command thread. The first snapshot includes +changes made in `preloop()`. It refreshes after the application's top-level `pre_prompt()` returns +and after the outermost [cmd2.Cmd.onecmd_plus_hooks][] finishes, including when input comes from a +file or pipe. When a script loads a command set, clients see its commands once the whole script +finishes. If a refresh fails, clients can still use the last successful snapshot and inspect its +`stale_reason`. + +Hidden, disabled, and explicitly excluded commands are omitted from command discovery. The listener +binds to IPv4 loopback and has no authentication. Other users and processes on the same machine can +read the published metadata, including help text, parser defaults, and alias and macro expansions. +Check those values for secrets before enabling discovery. Excluding a command does not redact an +alias or macro that mentions it. + +## Embedded command loops + +An application that supplies its own loop can manage the listener explicitly. Configure a port when +constructing the application, then call `mcp_start()` on the command thread so it can read the +application's parsers. Run commands through `onecmd_plus_hooks()` to refresh the snapshot after each +command. When you start the listener yourself, you also own its shutdown, including if you call +`cmdloop()` while it is running. + +```python +import cmd2 + +app = cmd2.Cmd(mcp_port=0) +try: + app.mcp_start() + print(app.mcp_url) + app.onecmd_plus_hooks("help") +finally: + app.mcp_stop() +``` + +To try a client against an application with nested subcommands and a plugin, run the +[Fleet console example](../examples/mcp_server.md). diff --git a/docs/overview/installation.md b/docs/overview/installation.md index e9da14ee0..4177c2a77 100644 --- a/docs/overview/installation.md +++ b/docs/overview/installation.md @@ -49,6 +49,9 @@ $ pip install cmd2 This will install the required 3rd-party dependencies, if necessary. +For applications that enable the [MCP server](../features/mcp_server.md), install the `mcp` extra +with `pip install "cmd2[mcp]"`. + ## Install from GitHub {: #github } The latest version of `cmd2` can be installed directly from the main branch on :simple-github: diff --git a/examples/README.md b/examples/README.md index 52c2e503c..31ebd9c50 100644 --- a/examples/README.md +++ b/examples/README.md @@ -65,11 +65,8 @@ each: - [hooks.py](https://github.com/python-cmd2/cmd2/blob/main/examples/hooks.py) - Shows how to use various `cmd2` application lifecycle hooks - [mcp_server.py](https://github.com/python-cmd2/cmd2/blob/main/examples/mcp_server.py) - - Serves a read-only description of a `cmd2` application's commands to an AI assistant over - [MCP](https://modelcontextprotocol.io) while its prompt is live, so that the assistant can - work out the command line for what the person asks. Requires the `mcp` package from the - `examples` dependency group (`uv run --group examples examples/mcp_server.py`), which is not a - `cmd2` dependency + - A fleet console that enables the built-in read-only MCP server. Run it with + `uv run --extra mcp examples/mcp_server.py` - [migrating.py](https://github.com/python-cmd2/cmd2/blob/main/examples/migrating.py) - A simple `cmd` application that you can migrate to `cmd2` by changing one line - [modular_commandsets.py](https://github.com/python-cmd2/cmd2/blob/main/examples/modular_commandsets.py) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 589b68fa8..e2ae9f657 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -1,1647 +1,19 @@ -"""Describe a cmd2 application's commands as plain data, and serve that description over MCP. +"""A fleet console with read-only command discovery over the Model Context Protocol. -A cmd2 application which, while its prompt is live, serves a read-only description of its own commands to an AI -assistant over MCP (the Model Context Protocol). The server never runs a command: it tells the assistant which commands -exist, what arguments each takes, and which shortcuts, aliases and macros there are. The assistant works out the command -line, and the person types it at the prompt. - -The example is in three parts: describing a cmd2 application's commands as plain data, serving that description from a -worker thread (McpServerMixin, which can be copied into another application), and a pretend "fleet console" which gives -the describing code every kind of command to describe. - -It needs cmd2 4.5.0 or later, and the MCP SDK (version 2 or later), which is not a dependency of cmd2. From a checkout -of the cmd2 repository:: - - uv run --group examples examples/mcp_server.py - -The server listens on http://127.0.0.1:8765/mcp, and the intro printed at the start says so. Always use 127.0.0.1 and -not localhost: the server listens on the IPv4 address only. The switches are:: - - --mcp-port PORT serve on this port (0 lets the system choose one) - --no-mcp run without a server, and without the SDK - -At the prompt, "mcp status" says whether there is a server, and how recent its description is. A client which is -connected can call three tools: list_commands, describe_command and list_shortcuts_aliases_macros. To connect Claude -Code to the server, and check that it is connected:: - - claude mcp add --transport http fleet http://127.0.0.1:8765/mcp - claude mcp list - -The MCP Inspector can list the tools. Its version 2 takes the server's address as an argument:: - - npx @modelcontextprotocol/inspector@latest --cli http://127.0.0.1:8765/mcp --method tools/list - -Things to try with an assistant which is connected, and the command lines each should lead to:: - - "Deploy version 2.1.0 of the api service to staging, without changing anything." - deploy api --version 2.1.0 --env staging --dry-run - "Add the tags web and eu to the server web-2." - server tag add web-2 web eu - "Back up the site service." The backup command exists only once its plugin is loaded: - plugin load backups - backup site - -The page which documents the example: https://cmd2.readthedocs.io/en/latest/examples/mcp_server/ +Run `uv run --extra mcp examples/mcp_server.py` from a cmd2 checkout. Connect a Streamable HTTP client to +the address printed at startup. Use --mcp-port 0 to request an available port or --no-mcp to run without the server. +Try "plugin load backups" or "maintenance on", then ask the client to list the available commands again. """ import argparse -import contextlib -import copy import importlib -import inspect -import itertools -import json -import logging -import re -import signal -import socket import sys -import threading -import time -from collections import deque -from collections.abc import Collection, Iterator, Mapping, Sequence -from dataclasses import dataclass, replace -from datetime import datetime -from functools import cache, partial -from types import FrameType -from typing import TYPE_CHECKING, Any, NoReturn, TypeVar - -from rich.console import Console, RenderableType +from typing import Any import cmd2 -from cmd2 import Choices, Cmd, Cmd2ArgumentParser -from cmd2.constants import INFINITY, MULTILINE_TERMINATOR -from cmd2.exceptions import Cmd2ShlexError -from cmd2.parsing import StatementParser, shlex_split -from cmd2.rich_utils import HelpFormatterRenderable -from cmd2.utils import strip_doc_annotations - -# --------------------------------------------------------------------------------------------------------------------- -# Part 1: Describing -# -# Turn a command's parser into plain data: frozen dataclasses which hold tuples, strings, numbers and nothing else. -# --------------------------------------------------------------------------------------------------------------------- - -# Help text is wrapped at this many columns, whatever the size of the terminal. -HELP_WIDTH = 100 - -# Each sequence has a 7-bit form (ESC followed by a character) and an 8-bit form (one C1 character: CSI is \x9b, OSC is \x9d). -# An OSC sequence (a hyperlink is one) ends with BEL, with ST (ESC followed by a backslash, or \x9c). -_OSC_SEQUENCE = re.compile(r"(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x9c|\x1b\\)") -_CSI_SEQUENCE = re.compile(r"(?:\x1b\[|\x9b)[0-?]*[ -/]*[@-~]") -# Every control character (Unicode category Cc, which includes C1) except a tab (\x09) and a newline (\x0a). -_CONTROL_CHARACTERS = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]") - - -def plain_text(value: object) -> str: - """Return a string, a Rich renderable or None as text with no escape sequence. - - The result holds no control character other than a newline or a tab. None is "". - """ - if value is None: - return "" - if isinstance(value, str): - text = value - else: - console = Console(force_terminal=False, color_system=None, width=HELP_WIDTH) - with console.capture() as capture: - console.print(value) - text = capture.get() - # cmd2.string_utils.strip_style() is not enough here: it leaves hyperlinks. - text = _OSC_SEQUENCE.sub("", text) - text = _CSI_SEQUENCE.sub("", text) - # A filesystem string may contain surrogate-escaped bytes. Preserve them visibly in UTF-8 JSON. - return _CONTROL_CHARACTERS.sub("", text).encode("utf-8", "backslashreplace").decode("utf-8") - - -@dataclass(frozen=True) -class Argument: - """One argument of a command, as plain data.""" - - name: str # the destination - metavar: str | None # where one is set; a tuple metavar joined with spaces - flags: tuple[str, ...] # ("-n", "--lines"); () for a positional - help: str - required: bool - min_values: int - max_values: int | None # None when unbounded - takes_rest_of_line: bool # nargs=argparse.REMAINDER, or argparse.PARSER, which takes one value first - parser_default: Any # declared on the action; a namespace provider can supply a different value - choices: tuple[str, ...] | None # None unless choices= was given; no more than MAX_CHOICES of them - more_choices: bool # choices which are not listed: past the first MAX_CHOICES, or all of them, which are an iterator - dynamic_choices: bool # a choices_provider or a completer; never called - type: str | None - repeatable: bool # append, append_const, count, extend - - -# The same four action classes which cmd2's tab completion treats as repeatable. -_REPEATABLE_ACTIONS = ( - argparse._AppendAction, - argparse._AppendConstAction, - argparse._CountAction, - argparse._ExtendAction, -) - - -def _value_range(action: argparse.Action) -> tuple[int, int | None]: - """Return the fewest and the most values an argument takes, with None for no most.""" - nargs_range = action.get_nargs_range() - if nargs_range is not None: - low, high = nargs_range - return int(low), None if high == INFINITY else int(high) - nargs = action.nargs - if nargs is None: - # Flags such as store_true have nargs=0 and take none, which is not the same as one. - return 1, 1 - if nargs == argparse.OPTIONAL: - return 0, 1 - if nargs in (argparse.ZERO_OR_MORE, argparse.REMAINDER): - return 0, None - if nargs in (argparse.ONE_OR_MORE, argparse.PARSER): # PARSER: one value, then the rest of the line - return 1, None - return int(nargs), int(nargs) - - -def _plain_data(value: Any) -> Any: - """Return plain data like the value, with every string (a dict's keys too) through plain_text().""" - if isinstance(value, str): - return plain_text(value) - if isinstance(value, list): - return [_plain_data(item) for item in value] - if isinstance(value, dict): - return {plain_text(key): _plain_data(item) for key, item in value.items()} - return value - - -def _describe_default(action: argparse.Action) -> Any: - """Return the default as data which JSON can hold: a copy, never the parser's own object.""" - default = action.default - if default is None or default is argparse.SUPPRESS: - return None - try: - # A round trip makes a copy of plain data, so a later change to the application's list does not reach it. NaN and - # an infinity, anywhere in the default, are refused: the SDK would send each as JSON null, which says there is no - # default. Such a default is described by its repr(), as a whole. - return _plain_data(json.loads(json.dumps(default, allow_nan=False))) - except (TypeError, ValueError): - return plain_text(repr(default)) - - -def _describe_type(action: argparse.Action) -> str | None: - """Return the name of the argument's type callable, or its repr when it has no name.""" - if action.type is None: - return None - return plain_text(getattr(action.type, "__name__", None) or repr(action.type)) - - -def describe_argument(action: argparse.Action) -> Argument: - """Describe one argument of a parser, without calling a choices provider or a completer.""" - low, high = _value_range(action) - choices, more_choices = _listed_choices(action.choices) - is_option = bool(action.option_strings) - metavar = action.metavar - if isinstance(metavar, tuple): - metavar = " ".join(metavar) - help_text = action.help if isinstance(action.help, str) and action.help != argparse.SUPPRESS else "" - return Argument( - name=plain_text(action.dest), - metavar=None if metavar is None else plain_text(metavar), - flags=tuple(plain_text(flag) for flag in action.option_strings), - help=plain_text(help_text), - required=bool(action.required) if is_option else low >= 1, - min_values=low, - max_values=high, - takes_rest_of_line=action.nargs in (argparse.REMAINDER, argparse.PARSER), - parser_default=_describe_default(action), - choices=choices, - more_choices=more_choices, - dynamic_choices=action.get_choices_provider() is not None or action.get_completer() is not None, - type=_describe_type(action), - repeatable=isinstance(action, _REPEATABLE_ACTIONS), - ) - - -# The most of an argument's choices which are listed. argparse checks a value against range(2**32) at once, but listing -# all of it would take minutes and gigabytes, on the main thread, before the first prompt. -MAX_CHOICES = 1000 - - -def _listed_choices(choices: Any) -> tuple[tuple[str, ...] | None, bool]: - """Return the first MAX_CHOICES of an argument's choices as plain text, or None for none, and whether there are more. - - No more of them are read than that. Choices which are an iterator are not listed at all: listing them would use up - what argparse checks each value against. - """ - if choices is None: - return None, False - if isinstance(choices, Iterator): - return None, True - first = list(itertools.islice(choices, MAX_CHOICES + 1)) - return tuple(plain_text(str(choice)) for choice in first[:MAX_CHOICES]), len(first) > MAX_CHOICES - - -@dataclass(frozen=True) -class ExclusiveGroup: - """Arguments of which at most one may be given. A required group may have one: the others are hidden.""" - - # The arguments which exclude each other: an option by its first flag ("--follow"), a positional by its name. Two - # options may share a destination, and so a name, but never a flag. - arguments: tuple[str, ...] - required: bool # one of them must be given - - -@dataclass(frozen=True) -class Subcommand: - """One subcommand, as its parent lists it.""" - - name: str - typed: str # append this spelling to the parent path for describe_command - aliases: tuple[str, ...] - summary: str - - -@dataclass(frozen=True) -class Description: - """One command or subcommand, as plain data.""" - - path: str # as typed: "server tag add" - summary: str - usage: str - help: str - has_parser: bool # False: the arguments are free-form text - arguments: tuple[Argument, ...] - exclusive_groups: tuple[ExclusiveGroup, ...] - subcommands: tuple[Subcommand, ...] - subcommand_required: bool - error: str | None # why it could not be described; else None - - -@dataclass(frozen=True) -class _ShownSubcommand: - """A subcommand as its parent's description shows it: by those of its names which can be typed.""" - - names: tuple[str, ...] # all of them, as argparse has them, the primary first - shown: tuple[str, ...] # those which can be typed, in the same order: the first stands for the subcommand - needs_separator: bool # the parent must consume -- before this name - parser: Cmd2ArgumentParser - subcommand: Subcommand - - -def _shown_subcommands(parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcommand]) -> dict[int, argparse.Action]: - """Return a copy of the parser's subcommands action which knows only the subcommands shown, by the names shown. - - It is returned under the id of the action, or nothing is where argparse would show the subcommands so already. - """ - try: - action = parser.get_subparsers_action() - except ValueError: - return {} - if [name for each in shown for name in each.shown] == list(action.choices): - return {} - # As in _describe_subcommands(), each subcommand added with help= has a pseudo action, named for it, here. - pseudo = {choice.dest: choice for choice in action._choices_actions} - shown_action = copy.copy(action) - shown_action.choices = {name: each.parser for each in shown for name in each.shown} - shown_action._choices_actions = [] - for each in shown: - choice = pseudo.get(each.names[0]) - if choice is None: - continue # one added without help= has no line in help - if each.shown != each.names: - # One as add_parser() makes it: named for the subcommand, with its aliases after the name in help. - choice = argparse._SubParsersAction._ChoicesPseudoAction(each.shown[0], each.shown[1:], choice.help) - shown_action._choices_actions.append(choice) - return {id(action): shown_action} - - -def _to_render( - parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcommand], omitted: Sequence[argparse.Action] -) -> Cmd2ArgumentParser: - """Return a display copy whose usage and help name only the subcommands shown, by the names shown. - - argparse would list every subcommand by every name: usage among the choices, and help with ==SUPPRESS== for the help - of a hidden one. It would also read all of an argument's choices, to list them or to expand %(choices)s in a help, - which uses up choices which are an iterator, though argparse reads them again to check each value given, and could - take minutes for range(2**32). Render those arguments with a marker for the omitted choices. - - The parser itself is never changed. The copy is shallow: its lists of actions and of groups are its own, and name a - copy of each action which is rendered differently. - """ - replaced = _shown_subcommands(parser, shown) - for action in omitted: - unlisted = replaced[id(action)] = copy.copy(action) - unlisted.choices = ("(choices omitted)",) - if unlisted.metavar is None: - # Keep the usual metavar in usage. The marker belongs in help that asks for %(choices)s. - formatter = parser._get_formatter() - if action.option_strings: - unlisted.metavar = formatter._get_default_metavar_for_optional(action) - else: - unlisted.metavar = formatter._get_default_metavar_for_positional(action) - rendered = copy.copy(parser) - rendered.formatter_class = partial(_snapshot_formatter, parser) - if not replaced: - return rendered - rendered._actions = [replaced.get(id(each), each) for each in parser._actions] - rendered._action_groups = _with_replaced(parser._action_groups, replaced) - rendered._mutually_exclusive_groups = _with_replaced(parser._mutually_exclusive_groups, replaced) - return rendered - - -_Group = TypeVar("_Group", bound=argparse._ArgumentGroup) - - -def _with_replaced(groups: list[_Group], replaced: Mapping[int, argparse.Action]) -> list[_Group]: - """Return the groups, with a copy in place of each which holds an action replaced, holding its replacement.""" - result = [] - for group in groups: - if any(id(each) in replaced for each in group._group_actions): - own = copy.copy(group) - own._group_actions = [replaced.get(id(each), each) for each in group._group_actions] - result.append(own) - else: - result.append(group) - return result - - -def _snapshot_formatter(parser: Cmd2ArgumentParser, prog: str, **kwargs: Any) -> cmd2.Cmd2HelpFormatter: - """Build the configured formatter and render at a fixed width without changing the prompt or process environment.""" - factory = parser.formatter_class - if "width" in inspect.signature(factory).parameters: - kwargs["width"] = HELP_WIDTH - formatter = factory(prog=prog, **kwargs) - formatter._width = HELP_WIDTH # also supports custom formatters which take only prog and file - formatter.console = copy.copy(formatter.console) - formatter.console.width = HELP_WIDTH - return formatter - - -def _first_line(value: object) -> str: - """Return the first non-blank line of a string or a Rich renderable as plain text.""" - for line in plain_text(value).splitlines(): - if line.strip(): - return line.strip() - return "" - - -def _parser_summary(parser: Cmd2ArgumentParser) -> str: - """Return the first line of the description as text, using the parser's formatter when required.""" - if isinstance(parser.description, HelpFormatterRenderable): - formatter = _snapshot_formatter(parser, parser.prog) - formatter.add_text(parser.description) - return _first_line(formatter.format_help()) - return _first_line(parser.description) - - -def _is_described(action: argparse.Action) -> bool: - """Return whether the action is an argument of the command, not the help, the subcommands or a hidden one.""" - if isinstance(action, (argparse._HelpAction, argparse._SubParsersAction)): - return False - return action.help != argparse.SUPPRESS - - -def _exclusive_name(argument: Argument) -> str: - """Name an argument as an exclusive group does: an option by its first flag, a positional by its name.""" - return argument.flags[0] if argument.flags else argument.name - - -@dataclass(frozen=True) -class _Reading: - """How the prompt reads the words typed after a command's name, and gives them to its parser.""" - - statements: StatementParser # with the application's terminators, which is all that such a word depends on - keeps_quotes: bool # the command's preserve_quotes: argparse is given each word with its quotation marks - - def argument_for(self, word: str) -> str | None: - """The argument which argparse is given for a word typed after the command, or None where it is not one whole. - - The prompt splits a word where it is not quoted at whitespace, a redirection character or a terminator. It - takes off the quotation marks around the word, not those inside it, unless the command keeps them. - """ - try: - statement = self.statements.parse(f"command {word}") - except Cmd2ShlexError: # a quotation which is never closed - return None - if statement.args != word or len(statement.argv) != 2: - return None - return statement.arg_list[0] if self.keeps_quotes else statement.argv[1] - - def as_typed(self, name: str) -> str | None: - """A subcommand's name as it is typed at the prompt, or None where the prompt cannot take it whole. - - It is typed as it is where the prompt takes it so, and otherwise quoted. A name with both quotation marks in - it and, say, a space cannot be typed at all, nor can a name with a space if the command keeps its quotes. - """ - return next((typed for typed in (name, f'"{name}"', f"'{name}'") if self.argument_for(typed) == name), None) - - -class _NotASubcommandError(Exception): - """Raised in place of argparse's error() by the copy of a parser which _needs_end_of_options() asks.""" - - -def _refuse(message: str) -> NoReturn: - raise _NotASubcommandError(message) - - -def _needs_end_of_options(parser: Cmd2ArgumentParser, name: str) -> bool: - """Whether argparse would treat this word as option syntax before the end-of-options marker.""" - if name == "--": - return True - # Python 3.11 reports an ambiguous abbreviation with error(), which would print and exit. - asked = copy.copy(parser) - asked.error = _refuse # the copy's own: the parser which the prompt uses is never changed - try: - return asked._parse_optional(name) is not None - except _NotASubcommandError: - return True - - -@cache -def _subparser_consumes_separator() -> bool: - """Whether this argparse strips a leading -- from a subparser action. The fix was backported.""" - probe = argparse.ArgumentParser(prog="probe", add_help=False, exit_on_error=False) - probe.add_subparsers(dest="child", required=True).add_parser("-x") - try: - return probe.parse_args(["--", "-x"]).child == "-x" - except argparse.ArgumentError: - return False - - -def _preceding_positionals(parser: Cmd2ArgumentParser) -> list[argparse.Action]: - """Positionals that argparse assigns before handing the remaining words to a child parser.""" - preceding = itertools.takewhile(lambda action: not isinstance(action, argparse._SubParsersAction), parser._actions) - return [action for action in preceding if not action.option_strings] - - -def _reserved_positionals(rendered: Cmd2ArgumentParser) -> list[argparse.Action]: - """Render trailing parent positionals at their minimum arity. The subparser consumes all additional words.""" - subparsers_index = next(i for i, action in enumerate(rendered._actions) if isinstance(action, argparse._SubParsersAction)) - reserved = [] - for action in rendered._actions[subparsers_index + 1 :]: - if action.option_strings or action.help is argparse.SUPPRESS: - continue - minimum, maximum = _value_range(action) - if minimum == 0: - continue - if minimum == maximum: - reserved.append(action) - continue - display = copy.copy(action) - display.nargs = minimum - display.set_nargs_range(None) - if isinstance(display.metavar, tuple): - display.metavar = display.metavar[:minimum] - reserved.append(display) - return reserved - - -def _describe_subcommands( - parser: Cmd2ArgumentParser, reading: _Reading, file_prefixes: str -) -> tuple[bool, list[_ShownSubcommand]]: - """Return whether a subcommand is required, and each subcommand as its parent's description shows it. - - Subcommands added with add_subparsers(help=argparse.SUPPRESS) are all left out, since help and usage leave all of them - out. A subcommand added with help=argparse.SUPPRESS is left out, since help leaves it out of its list. So is one which - cannot be typed by any of its names, since no path to it could be typed. A name can be typed where it is served as - it is, without what plain_text() takes out of it, the prompt takes it whole, and argparse takes it for the name of - a subcommand, not an option. Of the others, a name which cannot be typed is left out; where that is the primary - name, the first alias which can be typed stands for the subcommand. - """ - try: - action = parser.get_subparsers_action() - except ValueError: - return False, [] - if action.help == argparse.SUPPRESS: - return bool(action.required), [] - # argparse has no public way to read the help a subcommand was added with: it keeps one pseudo action per - # subcommand, named for it, in _choices_actions (cmd2 reads it there too). - helps = {choice.dest: choice.help for choice in action._choices_actions} - by_parser: dict[int, list[str]] = {} - for name, subparser in action.choices.items(): - by_parser.setdefault(id(subparser), []).append(name) - prefixes = tuple(file_prefixes + (parser.fromfile_prefix_chars or "")) - can_end_options = "-" not in prefixes and (bool(_preceding_positionals(parser)) or _subparser_consumes_separator()) - shown: list[_ShownSubcommand] = [] - for names in by_parser.values(): - help_text = helps.get(names[0]) # argparse adds the primary name before its aliases - if isinstance(help_text, str) and help_text == argparse.SUPPRESS: - continue # with its aliases, as a hidden command is left out - typable = [] - for name in names: - if plain_text(name) != name or name.startswith(prefixes): - continue # it would be served as a different name, or expanded as a file before option parsing - typed = reading.as_typed(name) - if typed is None: - continue - needs_separator = _needs_end_of_options(parser, name) - if not needs_separator or can_end_options: - typable.append((name, typed, needs_separator)) - if not typable: - continue - subparser = action.choices[names[0]] - summary = _first_line(help_text) or _parser_summary(subparser) - (first, typed, needs_separator), *others = typable - subcommand = Subcommand(name=first, typed=typed, aliases=tuple(name for name, _, _ in others), summary=summary) - shown.append( - _ShownSubcommand( - names=tuple(names), - shown=tuple(name for name, _, _ in typable), - needs_separator=needs_separator, - parser=subparser, - subcommand=subcommand, - ) - ) - return bool(action.required), shown - - -def _child_prog_prefix(rendered: Cmd2ArgumentParser) -> str: - """Show the parent arguments needed before the child, using their display actions.""" - if rendered._custom_subparsers_prog: - return rendered.get_subparsers_action()._prog_prefix - groups = rendered._mutually_exclusive_groups - group_members = {id(action) for group in groups if group.required for action in group._group_actions} - required = [a for a in rendered._actions if a.option_strings and (a.required or id(a) in group_members)] - preceding = _preceding_positionals(rendered) - if not required and not preceding: - return rendered.prog - prog = rendered.prog - rendering = prog if _TAB_STAND_IN in prog else prog.replace("\t", _TAB_STAND_IN) - formatter = rendered.formatter_class(prog=rendering) - formatter.add_usage(None, [*required, *preceding], groups, prefix="") - usage = plain_text(formatter.format_help()).strip() - return usage if rendering == prog else usage.replace(_TAB_STAND_IN, "\t") - - -# A noncharacter: Unicode keeps these for a program's own use, out of text written for people, such as help. -_TAB_STAND_IN = "\ufdd0" - - -def _usage_and_help(rendered: Cmd2ArgumentParser) -> tuple[str, str]: - """Render the display parser, preserving tabs in quoted command paths.""" - prog = rendered.prog - rendering = prog if _TAB_STAND_IN in prog else prog.replace("\t", _TAB_STAND_IN) - if rendering != prog: - rendered = copy.copy(rendered) - rendered.prog = rendering - usage = plain_text(rendered.format_usage()).rstrip() - help_text = plain_text(rendered.format_help()).rstrip() - if rendering == prog: - return usage, help_text - return usage.replace(_TAB_STAND_IN, "\t"), help_text.replace(_TAB_STAND_IN, "\t") - - -def describe_parser( - parser: Cmd2ArgumentParser, - path: str, - summary: str, - terminators: Collection[str] = (MULTILINE_TERMINATOR,), - *, - keeps_quotes: bool = False, -) -> dict[str, Description]: - """Describe a parser under its path, and every subcommand under it at every depth under its own path. - - A subcommand is there once, under its path as it is typed: its parent's, then its name, as it is where the prompt - takes it whole and otherwise quoted, which the application's terminators and the command's preserve_quotes - (keeps_quotes) help decide. Its usage and help name it - the same way. A name which the prompt cannot take whole has no path which can be typed, and is left out wherever - it would be named, as a hidden subcommand is: an alias which can be typed stands for a subcommand whose name - cannot. answer_describe_command() finds one by an alias through its parent. - - The usage and help of the parser itself name it by its path, whatever its prog: cmd2 gives a command which is - another's function under a second name, as do_orate = do_speak makes it, the other's parser, prog and all. - """ - reading = _Reading(StatementParser(terminators=terminators), keeps_quotes) - return _describe_parser_as(parser, path, summary, reading, path, "") - - -def _describe_parser_as( - parser: Cmd2ArgumentParser, - path: str, - summary: str, - reading: _Reading, - prog: str, - file_prefixes: str, - trailing: Sequence[argparse.Action] = (), - trailing_groups: Sequence[argparse._MutuallyExclusiveGroup] = (), -) -> dict[str, Description]: - """describe_parser(), for a parser whose prog is rendered as the one given, under parsers with those file prefixes.""" - # argparse has no public way to list a parser's arguments or its mutually exclusive groups. - actions = [action for action in parser._actions if _is_described(action)] - described = {id(action): describe_argument(action) for action in actions} - groups: list[ExclusiveGroup] = [] - for group in parser._mutually_exclusive_groups: # private, as above - members = tuple(_exclusive_name(described[id(a)]) for a in group._group_actions if id(a) in described) - # A required group whose other members are hidden still requires its one visible member, as argparse does. - if len(members) >= 2 or (group.required and members): - groups.append(ExclusiveGroup(arguments=members, required=bool(group.required))) - required, shown = _describe_subcommands(parser, reading, file_prefixes) - omitted = [action for action in actions if described[id(action)].more_choices] - rendered = _to_render(parser, shown, omitted) - rendered.prog = prog - if trailing: - # argparse reserves these words for the parent after the child has parsed its own arguments. - # Include them in usage, but keep the child's argument help and the live parser untouched. - rendered._actions = [*rendered._actions, *trailing] - rendered._mutually_exclusive_groups = [*rendered._mutually_exclusive_groups, *trailing_groups] - if rendered.usage is not None and rendered.usage is not argparse.SUPPRESS: - formatter = rendered.formatter_class(prog="") - formatter.add_usage(None, trailing, trailing_groups, prefix="") - suffix = plain_text(formatter.format_help()).strip().replace("%", "%%") - rendered.usage = f"{rendered.usage} {suffix}".rstrip() - usage, help_text = _usage_and_help(rendered) - result = { - path: Description( - path=path, - summary=summary, - usage=usage, - help=help_text, - has_parser=True, - arguments=tuple(described.values()), - exclusive_groups=tuple(groups), - subcommands=tuple(each.subcommand for each in shown), - subcommand_required=required, - error=None, - ) - } - if not shown: - return result - prefix = _child_prog_prefix(rendered) - child_trailing = _reserved_positionals(rendered) - child_groups = [g for g in rendered._mutually_exclusive_groups if all(a in child_trailing for a in g._group_actions)] - original_prefix = parser.get_subparsers_action()._prog_prefix - inner_prefixes = file_prefixes + (parser.fromfile_prefix_chars or "") - for each in shown: - typed = each.subcommand.typed - child_prog = each.parser.prog - if child_prog == f"{original_prefix} {each.names[0]}": - separator = " -- " if each.needs_separator else " " - child_prog = f"{prefix}{separator}{typed}" - child_path = f"{path} {typed}" - result.update( - _describe_parser_as( - each.parser, - child_path, - each.subcommand.summary, - reading, - child_prog, - inner_prefixes, - child_trailing, - child_groups, - ) - ) - return result - - -@dataclass(frozen=True) -class Command: - """One command, as the list of commands shows it.""" - - name: str - category: str - summary: str - has_parser: bool - subcommands: tuple[str, ...] # the typed spellings of its first level of subcommands - error: str | None - - -@dataclass(frozen=True) -class Category: - """The commands of one help category.""" - - name: str - commands: tuple[Command, ...] - - -@dataclass(frozen=True) -class Shortcut: - """A shortcut, such as "?" for "help".""" - - shortcut: str - command: str - - -@dataclass(frozen=True) -class Alias: - """An alias and what it stands for.""" - - name: str - value: str - - -@dataclass(frozen=True) -class Macro: - """A macro and what it stands for.""" - - name: str - value: str - minimum_arg_count: int - - -@dataclass(frozen=True) -class TypingRules: - """The rules which decide how a line of input is split into commands.""" - - allow_redirection: bool - terminators: tuple[str, ...] - multiline_commands: tuple[str, ...] - - -@dataclass(frozen=True) -class Snapshot: - """Everything the server says about an application, as it was at one moment.""" - - generation: int - built_at: str # local time with its offset, ISO 8601, to the second - commands: tuple[Command, ...] # in the order help sorts them - categories: tuple[Category, ...] # grouped and ordered with the same help sort key - descriptions: Mapping[str, Description] # by path, every depth, each subcommand by its name and not its aliases - help_topics: tuple[str, ...] # the topics which are not commands - shortcuts: tuple[Shortcut, ...] - aliases: tuple[Alias, ...] - macros: tuple[Macro, ...] - typing: TypingRules - quotes_kept: frozenset[str] # the commands whose preserve_quotes is set; not served, but used to find a path - error: str | None # why the whole build failed; else None - stale_reason: str | None = None # latest rebuild failure when serving a previous successful build - - -def _now() -> str: - return datetime.now().astimezone().isoformat(timespec="seconds") - - -def _command_summary(doc: str | None, parser: Cmd2ArgumentParser | None) -> str: - """Return a command's one-line description: the first block of its docstring, else its parser's description.""" - if doc: - # What "help -v" shows. - return plain_text(strip_doc_annotations(doc)) - if parser is not None: - return _parser_summary(parser) - return "" - - -def _unparsed_description(path: str, summary: str, help_text: str, error: str | None) -> Description: - """Return the description of a command which has no parser, or which could not be described.""" - return Description( - path=path, - summary=summary, - usage="", - help=help_text, - has_parser=False, - arguments=(), - exclusive_groups=(), - subcommands=(), - subcommand_required=False, - error=error, - ) +from cmd2 import Choices, Cmd2ArgumentParser - -def _describe_command(app: Cmd, name: str) -> tuple[Command, dict[str, Description], bool]: - """Describe one command. Raise whatever cmd2 raises when it cannot be done.""" - func = app.get_command_func(name) - if func is None: - raise LookupError("cmd2 has no function for the command") - category = plain_text(app.get_command_category(func)) - parser = app.command_parsers.get(func) - summary = _command_summary(func.__doc__, parser) - if parser is None: - keeps_quotes = False - text = plain_text(inspect.cleandoc(func.__doc__)) if func.__doc__ else "" - descriptions = {name: _unparsed_description(name, summary, text, None)} - else: - spec = app.get_argparse_command_spec(func) - keeps_quotes = spec is not None and spec.preserve_quotes - terminators = app.statement_parser.terminators - descriptions = describe_parser(parser, name, summary, terminators, keeps_quotes=keeps_quotes) - top = descriptions[name] - command = Command( - name=plain_text(name), - category=category, - summary=summary, - has_parser=top.has_parser, - subcommands=tuple(subcommand.typed for subcommand in top.subcommands), - error=None, - ) - return command, descriptions, keeps_quotes - - -def _failed_command(app: Cmd, name: str, exc: Exception) -> tuple[Command, dict[str, Description]]: - """Return a command which could not be described, still listed, with the reason.""" - try: - func = app.get_command_func(name) - category = plain_text(app.get_command_category(func)) if func is not None else "" - except Exception: # noqa: BLE001 - category = "" - error = plain_text(f"This command could not be described: {type(exc).__name__}: {exc}") - command = Command(name=plain_text(name), category=category, summary="", has_parser=False, subcommands=(), error=error) - return command, {name: _unparsed_description(name, "", "", error)} - - -def build_snapshot(app: Cmd, generation: int, leave_out: Collection[str] = ()) -> Snapshot: - """Describe the whole application. Call it on the main thread only: it asks cmd2 for every command's parser.""" - commands: list[Command] = [] - descriptions: dict[str, Description] = {} - quotes_kept: set[str] = set() - sort_key = cmd2.utils.DEFAULT_STR_SORT_KEY - visible = sorted(app.get_visible_commands(), key=sort_key) - included = [name for name in visible if name not in leave_out] - by_category: dict[str, list[Command]] = {} - for name in included: - try: - command, found, keeps_quotes = _describe_command(app, name) - except Exception as exc: # noqa: BLE001 - one command's failure is its own - command, found = _failed_command(app, name, exc) - else: - if keeps_quotes: - quotes_kept.add(command.name) - commands.append(command) - by_category.setdefault(command.category, []).append(command) - descriptions.update(found) - parser = app.statement_parser - topics = sorted((topic for topic in app.get_help_topics() if topic not in visible), key=sort_key) - - def by_name(item: tuple[str, Any]) -> Any: - return sort_key(item[0]) - - return Snapshot( - generation=generation, - built_at=_now(), - commands=tuple(commands), - categories=tuple(Category(name, tuple(by_category[name])) for name in sorted(by_category, key=sort_key)), - descriptions=descriptions, - help_topics=tuple(plain_text(topic) for topic in topics), - shortcuts=tuple( - Shortcut(plain_text(shortcut), plain_text(command)) for shortcut, command in sorted(parser.shortcuts, key=by_name) - ), - aliases=tuple(Alias(plain_text(n), plain_text(v)) for n, v in sorted(app.aliases.items(), key=by_name)), - macros=tuple( - Macro(plain_text(n), plain_text(m.value), m.minimum_arg_count) for n, m in sorted(app.macros.items(), key=by_name) - ), - typing=TypingRules( - allow_redirection=bool(app.allow_redirection), - terminators=tuple(plain_text(t) for t in parser.terminators), - multiline_commands=tuple(plain_text(c) for c in parser.multiline_commands if c in included), - ), - quotes_kept=frozenset(quotes_kept), - error=None, - ) - - -# What is served until the first description has been built: before cmdloop() has run preloop(), for one. -_NOT_BUILT = "The description has not been built yet." - - -def failed_snapshot(generation: int, error: str) -> Snapshot: - """Return an empty snapshot which carries the reason the build failed.""" - return Snapshot( - generation=generation, - built_at=_now(), - commands=(), - categories=(), - descriptions={}, - help_topics=(), - shortcuts=(), - aliases=(), - macros=(), - typing=TypingRules(allow_redirection=False, terminators=(), multiline_commands=()), - quotes_kept=frozenset(), - error=plain_text(error), - ) - - -@dataclass(frozen=True) -class CommandList: - """The answer to "list the commands".""" - - generation: int - built_at: str - categories: tuple[Category, ...] # in the order help shows them - help_topics: tuple[str, ...] - typing: TypingRules - error: str | None # why there is no description to answer from: none has been built yet, or a build failed - stale_reason: str | None = None - - -@dataclass(frozen=True) -class CommandDescription: - """The answer to "describe a command".""" - - generation: int - built_at: str - description: Description - stale_reason: str | None = None - - -@dataclass(frozen=True) -class Tables: - """The answer to "list the shortcuts, aliases and macros".""" - - generation: int - built_at: str - shortcuts: tuple[Shortcut, ...] - aliases: tuple[Alias, ...] - macros: tuple[Macro, ...] - error: str | None # why there is no description to answer from: none has been built yet, or a build failed - stale_reason: str | None = None - - -class UnknownCommandError(LookupError): - """No such command or subcommand. str() says what is missing and names what exists.""" - - -class DescriptionUnavailableError(LookupError): - """No description to answer from: none has been built yet, or a build failed. str() says which.""" - - -def answer_list_commands(snapshot: Snapshot) -> CommandList: - """List the commands by category, in the order help shows them.""" - return CommandList( - generation=snapshot.generation, - built_at=snapshot.built_at, - categories=snapshot.categories, - help_topics=snapshot.help_topics, - typing=snapshot.typing, - error=snapshot.error, - stale_reason=snapshot.stale_reason, - ) - - -def answer_describe_command(snapshot: Snapshot, command: str) -> CommandDescription: - """Describe a command or a subcommand, given its path as typed ("server tag add"), or raise UnknownCommandError. - - Where the snapshot holds no description, raise DescriptionUnavailableError, which says why. - - The path is split into words as the prompt splits a command line. The first is a command's name, which the prompt - never takes quoted. Each word after it is a subcommand's name if the prompt would take it as that name: as it is - served, or quoted. - """ - if snapshot.error is not None: - raise DescriptionUnavailableError(f"No command can be described: {snapshot.error}") - try: - words = shlex_split(command) # with their quotes, as the prompt keeps them - except ValueError as error: # a quotation which is never closed - raise UnknownCommandError(f'"{command.strip()}" cannot be split into words as the prompt would: {error}.') from error - path = " ".join(words) - commands = {listed.name for listed in snapshot.commands} - description = snapshot.descriptions.get(words[0]) if words and words[0] in commands else None - if description is None: - names = ", ".join(listed.name for listed in snapshot.commands) - raise UnknownCommandError(f'There is no command "{path}". The commands are: {names}.') - reading = _Reading(StatementParser(terminators=snapshot.typing.terminators), words[0] in snapshot.quotes_kept) - # Each word after the first is a subcommand of the one before it, by its name or by an alias, as argparse takes it. - # The walk stops at the first word which is not, and that word's parent says what could have followed it. - for word in words[1:]: - parent = description - taken = reading.argument_for(word) - found = next((sub for sub in parent.subcommands if taken in (sub.name, *sub.aliases)), None) - description = None if found is None else snapshot.descriptions.get(f"{parent.path} {found.typed}") - if description is None: - names = ", ".join(sub.typed for sub in parent.subcommands) - if names: - raise UnknownCommandError(f'There is no subcommand "{path}". "{parent.path}" has: {names}.') - raise UnknownCommandError(f'There is no subcommand "{path}": "{parent.path}" has no subcommands.') - return CommandDescription( - generation=snapshot.generation, built_at=snapshot.built_at, description=description, stale_reason=snapshot.stale_reason - ) - - -def answer_tables(snapshot: Snapshot) -> Tables: - """Return the shortcuts, aliases and macros.""" - return Tables( - generation=snapshot.generation, - built_at=snapshot.built_at, - shortcuts=snapshot.shortcuts, - aliases=snapshot.aliases, - macros=snapshot.macros, - error=snapshot.error, - stale_reason=snapshot.stale_reason, - ) - - -# --------------------------------------------------------------------------------------------------------------------- -# Part 2: Serving -# -# Keep the latest description of a cmd2 application, rebuilt on the main thread and never while a command is in progress, -# and serve it over MCP from a worker thread. -# --------------------------------------------------------------------------------------------------------------------- - -HOST = "127.0.0.1" DEFAULT_PORT = 8765 -LIBRARY_LOGGERS = ("uvicorn", "mcp") # the top-level logger of each library the server uses -RECORDS_KEPT = 50 -RECORDS_SHOWN = 5 # by mcp_status() - -# What a client gives its model about this server. -INSTRUCTIONS = ( - "This server describes the commands of an interactive command-line application which a person is using. It cannot " - "run them. To help the person, answer with a command line for them to type. Call list_commands first, and " - "describe_command before giving a command's arguments. The description reflects the last successful rebuild. " - "If stale_reason is set, tell the person that the available commands may have changed." -) - - -class _KeepRecords(logging.Handler): - """Keeps the last RECORDS_KEPT records it is given, and writes them nowhere.""" - - def __init__(self) -> None: - super().__init__() - self.kept: deque[logging.LogRecord] = deque(maxlen=RECORDS_KEPT) - - def emit(self, record: logging.LogRecord) -> None: - self.kept.append(record) - - -class _SharedLogging: - """The changes to the libraries' loggers, owned by every run in the process together.""" - - def __init__(self) -> None: - self._lock = threading.Lock() - self._holds = 0 - self._saved: dict[str, bool] = {} # each library logger's propagate, as it was found - self._handler = _KeepRecords() # one for the process, so the records outlive any run - - def take(self) -> None: - """Take a hold. The first one saves what it finds and makes the changes.""" - with self._lock: - if self._holds == 0: - for name in LIBRARY_LOGGERS: - logger = logging.getLogger(name) - self._saved[name] = logger.propagate - logger.addHandler(self._handler) - logger.propagate = False - self._holds += 1 - - def release(self) -> None: - """Let go of a hold. The last one removes the handler it added and puts each propagate back.""" - with self._lock: - if self._holds == 0: - return - self._holds -= 1 - if self._holds == 0: - for name, propagate in self._saved.items(): - logger = logging.getLogger(name) - logger.removeHandler(self._handler) - logger.propagate = propagate - self._saved = {} - - @property - def holds(self) -> int: - """The number of runs holding the changes.""" - with self._lock: - return self._holds - - def records(self) -> list[logging.LogRecord]: - """The last RECORDS_KEPT records of the libraries, oldest first.""" - with self._handler.lock: # emit() appends under the same lock, on a server's thread - return list(self._handler.kept) - - -_shared_logging = _SharedLogging() # one for the module - - -@contextlib.contextmanager -def _root_logger_left_alone() -> Iterator[None]: - """Hold a temporary handler on the root logger, so that logging.basicConfig(), which MCPServer() calls, does nothing. - - The root logger's level is not touched. - """ - root = logging.getLogger() - placeholder = logging.NullHandler() - root.addHandler(placeholder) - try: - yield - finally: - root.removeHandler(placeholder) - - -@contextlib.contextmanager -def _sigint_deferred() -> Iterator[None]: - """Hold off Ctrl-C until the block has ended, then deliver it to the handler which was there before. - - A start takes something (the hold on the logging, the socket, the worker) and records it in its run inside one of - these, so that an interrupt never falls between the two: whatever the start has taken, its run knows of. cmd2's - sigint_protection cannot do this for the first start, because cmdloop() installs cmd2's handler after it. - - Off the main thread it does nothing: signal.signal() cannot be called there, and Python runs signal handlers on the - main thread alone. A handler which is not a function (SIG_IGN or SIG_DFL) is left as it is installed. - """ - saved = signal.getsignal(signal.SIGINT) if threading.current_thread() is threading.main_thread() else None - if not callable(saved): - yield - return - arrived: list[tuple[int, FrameType | None]] = [] # the first interrupt which arrived, if one did - - def defer(signum: int, frame: FrameType | None) -> None: - if not arrived: - arrived.append((signum, frame)) - - signal.signal(signal.SIGINT, defer) - try: - yield - finally: - signal.signal(signal.SIGINT, saved) - if arrived: - saved(*arrived[0]) # Python's own handler raises KeyboardInterrupt here: after the block, whatever it did - - -_run_numbers = itertools.count(1) # each run of a server in the process takes the next - - -class _Run: - """One run of the server, and everything it owns. A worker touches its own run and nothing else. - - The main thread and the worker both write to a run, and its lock decides which came first. The worker records its - detail and outcome together under it. mcp_stop() asks for the stop under it, and after its wait for the worker, gives - up on the worker if, under it, the worker has not recorded its outcome yet. mcp_status() - reads the fields together under it. Neither thread holds it while it waits for the other. It also makes the run's - hold on the logging taken and let go of once. It is reentrant, so that serving() can be asked while it is held. - """ - - def __init__(self, port: int) -> None: - self.number = next(_run_numbers) - self.port = port # the port asked for until the socket is bound; then the one read back from the socket - self.url = f"http://{HOST}:{port}/mcp" - self.sock: socket.socket | None = None - self.server: Any = None # the uvicorn.Server - self.worker: threading.Thread | None = None # a daemon, named f"mcp-server-{number}"; set once it has started - self.stop_requested = False # mcp_stop() was called for it - self.stop_finished = False # a call of mcp_stop() did all it does; Ctrl-C can cut one short before then - self.abandoned = False # mcp_stop()'s wait ended before the worker had recorded its outcome - self.outcome: str | None = None # "stopped", "failed" or "cancelled", set by the worker when it ends - self.detail: str | None = None # the error it ended with, as text - self.problem: str | None = None # why this run is not serving, for the person - self.lock = threading.RLock() - self._holds_logging = False - - def close_socket(self) -> None: - """Release the listener on either worker exit or stop, whichever comes first.""" - with self.lock, contextlib.suppress(OSError): - if self.sock is not None: - self.sock.close() # idempotent, including when uvicorn has already closed it - - def serving(self) -> bool: - """Whether it serves: no stop was asked for, the worker is alive and has recorded no outcome, and the server started. - - uvicorn's started stays set while it shuts down, after it has closed the listener, so it alone is not enough. - """ - with self.lock: - return ( - not self.stop_requested - and self.outcome is None - and self.worker is not None - and self.worker.is_alive() - and self.server is not None - and bool(self.server.started) - ) - - def take_logging(self) -> None: - """Take this run's hold on the changes to the libraries' logging.""" - with self.lock: - _shared_logging.take() - self._holds_logging = True - - def release_logging(self) -> None: - """Let go of this run's hold once, whoever calls it and however often. Nothing for a run which took none. - - Ctrl-C is held off until it is done, as a start holds it off while it takes the hold. An interrupt between the run - forgetting its hold and the hold being let go of would leave the libraries' logging changed for good. - """ - with _sigint_deferred(), self.lock: - if self._holds_logging: - self._holds_logging = False - _shared_logging.release() - - -class _NotServingError(Exception): - """A start which did not end with the server serving. str() is the reason, for the person.""" - - -def _record_line(record: logging.LogRecord) -> str: - """A log record on one line of plain text: its time, its thread's name, its level and its message.""" - when = time.strftime("%H:%M:%S", time.localtime(record.created)) - try: - message = record.getMessage() - except Exception: # noqa: BLE001 - a status never raises: logging's own handlers also catch whatever formatting raises - message = str(record.msg) # arguments which do not fit the format: the format, as it was logged - return plain_text(f"{when} {record.threadName} {record.levelname}: {message}") - - -if TYPE_CHECKING: # pragma: no cover - _Base = Cmd -else: - _Base = object - - -class McpServerMixin(_Base): - """Comes before cmd2.Cmd in the bases: class FleetConsole(McpServerMixin, cmd2.Cmd). - - The description is rebuilt at three moments: when the outermost cmdloop() starts, just before each top-level - prompt, and when the outermost call of onecmd_plus_hooks() ends, whether it returns or raises. It is never rebuilt - while a command is in progress, so a continuation prompt of a multiline command publishes nothing. - - An application which overrides pre_prompt() changes its commands before it calls super().pre_prompt(), and one - which overrides onecmd_plus_hooks() changes none after super() returns. A change made after the rebuild is not - seen until the next one. - - The outermost cmdloop() calls mcp_start(), which serves the description over MCP on 127.0.0.1 from a worker thread, - and mcp_stop() when the loop ends. An application which does not use cmdloop() calls the two itself. - """ - - MCP_START_TIMEOUT = 5.0 # seconds to wait for the server to begin serving - MCP_STOP_TIMEOUT = 3.0 # seconds to wait for the worker to end - MCP_SHUTDOWN_TIMEOUT = 2 # uvicorn's timeout_graceful_shutdown - - mcp_snapshot: Snapshot # the latest; replaced whole, never changed - mcp_port: int | None - mcp_name: str - mcp_leave_out: frozenset[str] # commands which are never described - mcp_build_error: str | None # why the latest build failed as a whole; None once one has succeeded - _mcp_depth: int # calls of onecmd_plus_hooks() in progress - _mcp_loops: int # calls of cmdloop() in progress - _mcp_starting: bool # from the start of the outermost cmdloop() until preloop() has returned: nothing is built - _mcp_run: _Run | None # the latest run of the server; it stays after it is stopped, to say what became of it - - def __init__( - self, - *args: Any, - mcp_port: int | None = DEFAULT_PORT, - mcp_name: str = "cmd2 application", - mcp_leave_out: Collection[str] = (), - **kwargs: Any, - ) -> None: - """Take the mixin's own arguments, and pass every other one to the next class in the bases. - - :param mcp_port: the port to serve on; None for no server - :param mcp_name: the name the server gives itself to a client - :param mcp_leave_out: the names of commands which are never described - """ - self.mcp_port = mcp_port - self.mcp_name = mcp_name - self.mcp_leave_out = frozenset(mcp_leave_out) - self.mcp_snapshot = failed_snapshot(0, _NOT_BUILT) - self.mcp_build_error = None - self._mcp_depth = 0 - self._mcp_loops = 0 - self._mcp_starting = False - self._mcp_run = None - # The next constructor may call our command hooks while it is still configuring the application. - self._mcp_initializing = True - super().__init__(*args, **kwargs) - self._mcp_initializing = False - - def cmdloop(self, intro: RenderableType = "") -> int: - """Start before the loop starts, describe the application once preloop() has returned, and stop when it ends. - - Until preloop() has returned, the application may still change which commands there are and how. Nothing from - before then is served, a description left from an earlier loop included: the server answers that the - description has not been built yet. _cmdloop() builds the first one. - """ - outermost = self._mcp_loops == 0 and self._mcp_depth == 0 and not self._mcp_initializing - self._mcp_loops += 1 - try: - if outermost: - self._mcp_starting = True - if self.mcp_snapshot.error != _NOT_BUILT: - self.mcp_snapshot = failed_snapshot(self.mcp_snapshot.generation + 1, _NOT_BUILT) - self.mcp_build_error = None - self.mcp_start() # the server, which serves no description until _cmdloop() builds the first - return super().cmdloop(intro) - finally: - self._mcp_loops -= 1 - if outermost: - self._mcp_starting = False - self.mcp_stop() # safe to call twice, and after a start which failed - - def _cmdloop(self) -> None: - """Build the first description once cmdloop() has run preloop(), before the first line is read. - - cmd2 has no public method there. Its cmdloop() runs the preloop hooks and preloop(), prints the intro and calls - this private one, which runs the startup commands and then reads each line. pre_prompt() runs only when input - is a terminal, so it cannot be the moment: with input from a pipe, nothing would be described until a command - had run. A loop run inside a command, or inside preloop(), calls this too, and builds nothing: only the outermost - loop's call ends the start. - """ - if self._mcp_starting and self._mcp_loops == 1: - self._mcp_starting = False - self._mcp_rebuild() - super()._cmdloop() - - def pre_prompt(self) -> None: - """Rebuild the description just before a top-level prompt appears.""" - super().pre_prompt() - self._mcp_rebuild() # does nothing at the continuation prompt of a multiline command - - def onecmd_plus_hooks(self, line: str, *args: Any, **kwargs: Any) -> bool: - """Run the line as cmd2 does, then rebuild the description if this call is the outermost one.""" - self._mcp_depth += 1 - try: - return super().onecmd_plus_hooks(line, *args, **kwargs) - finally: - self._mcp_depth -= 1 - self._mcp_rebuild() # returns at once when a command is still in progress - - def mcp_start(self) -> None: - """Build the first description, then serve it from a worker thread. - - When cmdloop() calls it, it does not build: cmdloop() builds the first description once preloop() has returned. - - Does no more than build when mcp_port is None or this application is serving already. A start which fails is one - warning, and the application carries on without a server: it never raises an Exception. - - Ctrl-C during a start is another matter. Before cmdloop() has installed cmd2's handler, nothing holds it off for - long, so a KeyboardInterrupt can arise anywhere in a start. The start then undoes what it got done, through - mcp_stop(), and raises the KeyboardInterrupt again, whether cmdloop() or the application called it; cmdloop()'s - own mcp_stop() afterwards finds nothing left to do. While the start takes the logging, binds its socket and - starts its worker, Ctrl-C is held off until the run has recorded what was taken, so that the undoing knows of it. - """ - self._mcp_rebuild() - if self.mcp_port is None or (self._mcp_run is not None and self._mcp_run.serving()): - return - if self._mcp_run is not None: - # A run which is neither serving nor stopped (its worker ended by itself, perhaps with an error) may still hold - # its socket. Undo it before it is replaced. A run which was stopped is replaced at once, while its worker, if - # it has one still alive, finishes with that run alone. - self.mcp_stop() - # The attempt is recorded before anything can fail: from here on, whatever goes wrong, mcp_status() has a run to - # report and mcp_stop() has a run to undo. - run = self._mcp_run = _Run(self.mcp_port) - try: - self._mcp_start_serving(run) - except KeyboardInterrupt: - self.mcp_stop() - raise - except Exception as error: # noqa: BLE001 - a start which fails is a warning, and the application carries on - why = str(error) if isinstance(error, _NotServingError) else f"{type(error).__name__}: {error}" - run.problem = plain_text(f"MCP server not started on port {run.port}: {why.rstrip('.')}. Continuing without it.") - self.mcp_stop() - # A warning which cannot be written has nowhere else to go, and a start which fails never raises. - with contextlib.suppress(Exception): - self.pwarning(run.problem) - - def _mcp_start_serving(self, run: _Run) -> None: - """Take each step of a start in turn, recording in the run what it has done. Raise if the server is not serving.""" - try: - # Neither is a dependency of cmd2, so neither is imported at the top of this file. The SDK comes first, so that - # a missing one is the one named; mcp.server.mcpserver is new in its version 2. _mcp_asgi_app() imports from it. - importlib.import_module("mcp.server.mcpserver") - import uvicorn - except ImportError as error: - raise _NotServingError( - f"the MCP SDK cannot be imported ({error}). Install it with: uv sync --group examples" - ) from error - # Each of the three steps which take something is held together with its recording in the run. - with _sigint_deferred(): - run.take_logging() # before anything of the server can log - with _sigint_deferred(): - run.sock = socket.create_server((HOST, run.port)) - run.port = run.sock.getsockname()[1] # the one the system chose, when 0 was asked for - run.url = f"http://{HOST}:{run.port}/mcp" - # Neither log_level nor access_log=False: each changes loggers which are not the server's to change. - config = uvicorn.Config(self._mcp_asgi_app(), log_config=None, timeout_graceful_shutdown=self.MCP_SHUTDOWN_TIMEOUT) - run.server = uvicorn.Server(config) - worker = threading.Thread(target=self._mcp_serve, args=(run,), name=f"mcp-server-{run.number}", daemon=True) - with _sigint_deferred(): - worker.start() - # Only once it has started, so that a thread which could not be started is never joined; and before Ctrl-C, - # so that a worker which runs is always one its run knows of, which mcp_stop() can wait for or give up on. - run.worker = worker - deadline = time.monotonic() + self.MCP_START_TIMEOUT - while not run.server.started and worker.is_alive() and time.monotonic() < deadline: - time.sleep(0.02) - if not run.serving(): - with run.lock: - ended = run.detail or run.outcome - if ended is not None or not worker.is_alive(): - raise _NotServingError(f"the server ended before it began serving: {ended}") - raise _NotServingError(f"the server did not begin serving within {self.MCP_START_TIMEOUT} seconds") - - @staticmethod - def _mcp_serve(run: _Run) -> None: - """The worker's target: serve until the server is told to stop, then record how it ended. Never prints. - - It is given its run and touches nothing else, so a worker which outlives its command loop does no harm. - """ - try: - detail: str | None = None - try: - run.server.run(sockets=[run.sock]) - except BaseException as error: # noqa: BLE001 - SystemExit too: nothing may reach threading.excepthook - detail = plain_text(f"{type(error).__name__}: {error}") - else: - if not run.server.started: - detail = "the server returned before it had started" - # The detail and the outcome are recorded together, under the lock under which mcp_stop() decides whether it - # has given up on this worker. If it has, this worker was cancelled, whatever happened. If this comes first, - # mcp_stop() keeps what is recorded here, and does not give up on the worker. - with run.lock: - run.detail = detail - if run.abandoned: - run.outcome = "cancelled" # the detail, if any, is kept: it is the expected result of being cancelled - elif detail is None: - run.outcome = "stopped" - else: - run.outcome = "failed" - finally: - try: - run.close_socket() - finally: - run.release_logging() - - def mcp_stop(self) -> None: - """Stop serving: undo what the start got done, in whatever state it finds the run. - - Does nothing when there is no run, or when a stop of it has finished already. A stop which Ctrl-C cut short before - it had finished is finished by the next one, so stopping again is always enough. Otherwise it asks the server to - stop, and waits a while for the worker. Whether the worker has ended or not, it then closes the socket, and lets go - of the logging where no worker started; a worker always lets go of it itself, as its last act. Ctrl-C during the - wait does not prevent that; it is raised once it is done. The run stays, so that mcp_status() can say what became - of it; the next start replaces it. - """ - run = self._mcp_run - if run is None: - return - with run.lock: - if run.stop_finished: - return - run.stop_requested = True # from now on run.serving() is false and mcp_url is None - if run.server is not None: - run.server.should_exit = True - try: - if run.worker is not None: - run.worker.join(self.MCP_STOP_TIMEOUT) # never with the lock held: the worker takes it to record its outcome - finally: - # This happens even when Ctrl-C ends the wait: whatever the worker is doing, the port is let go of. - # Whether the worker has ended is never asked of the thread: on Python 3.11 and 3.12, a join() which Ctrl-C - # interrupted leaves is_alive() false while the worker runs on. What the worker recorded, under the lock, says. - worker = run.worker - with run.lock: - if worker is not None and run.outcome is None: - # The one place a run is given up on. The worker records that it was cancelled when it ends, and lets go - # of the logging then. A worker which recorded its outcome first keeps it, however long it lives on. - run.abandoned = True - run.close_socket() - if worker is None: - run.release_logging() # a start which failed before its worker started: nobody else will - with run.lock: - run.stop_finished = True # only now: a stop which an interrupt ended before this line is done again - - @property - def mcp_url(self) -> str | None: - """The URL a client connects to while this application is serving; else None.""" - run = self._mcp_run - return run.url if run is not None and run.serving() else None - - def mcp_status(self) -> list[str]: - """Return lines which tell the person whether there is a server, and what it serves. - - They are made from the current run and this application's own state. A log record never decides what they say: - the records are every run's in the process, so they are shown apart, under a heading which says so. - - Why there is no server is, of the reasons which hold, the first of: the problem the start met; the worker's - failure; a stop which was asked for; how the worker ended by itself; and, with no run, --no-mcp or no start. - """ - run = self._mcp_run - lines = [f"No MCP server: {'--no-mcp was given' if self.mcp_port is None else 'it has not been started'}"] - if run is not None: - with run.lock: # read together, as the worker records them together - serving = run.serving() - problem, outcome, detail, stop_requested = run.problem, run.outcome, run.detail, run.stop_requested - cancelled = run.abandoned and run.worker is not None - worker_alive = run.worker is not None and outcome is None # it records one as it ends; see mcp_stop() - if serving: - lines[0] = f"Serving {run.url}" - elif problem is not None: - lines[0] = f"No MCP server: {problem}" - elif outcome == "failed": - lines[0] = f"No MCP server: it failed ({detail})" - elif stop_requested: - lines[0] = "No MCP server: it was stopped" - elif outcome is not None: - lines[0] = f"No MCP server: it ended by itself ({outcome})" - if cancelled and worker_alive: - lines.append(f"The worker of run {run.number} was cancelled, and has not ended yet") - elif cancelled: - ended = f"{outcome}: {detail}" if detail else outcome - lines.append(f"The worker of run {run.number} was cancelled, and has ended ({ended})") - snapshot = self.mcp_snapshot - built = datetime.fromisoformat(snapshot.built_at).strftime("%H:%M:%S") - count = f"{len(snapshot.commands)} commands in {len(snapshot.categories)} categories" - lines.append(f"Description {snapshot.generation}, built {built}: {count}") - failed = [command.name for command in snapshot.commands if command.error is not None] - if failed: - lines.append(f"{len(failed)} of them could not be described: {', '.join(failed)}") - if self.mcp_build_error is not None: - lines.append(f"The description is out of date: the last rebuild failed: {self.mcp_build_error}") - records = _shared_logging.records()[-RECORDS_SHOWN:] - if records: - lines.append("Recent log records from every MCP server this process has run:") - lines.extend(f" {_record_line(record)}" for record in records) - return lines - - def _mcp_asgi_app(self) -> Any: - """Return the SDK's application, which serves the three tools. A seam for tests. - - Each tool reads the latest snapshot once, into a local, and answers from that alone: the main thread may publish a - new one at any moment, and a snapshot never changes once it has been published. - """ - from mcp.server import MCPServer - from mcp.server.mcpserver.exceptions import ToolError - from mcp.types import ToolAnnotations - - with _root_logger_left_alone(): # MCPServer() calls logging.basicConfig() - server = MCPServer(self.mcp_name, instructions=INSTRUCTIONS, version=getattr(cmd2, "__version__", "")) - read_only = ToolAnnotations(read_only_hint=True, open_world_hint=False) - - @server.tool(annotations=read_only) - def list_commands() -> CommandList: - """List the application's commands by category, in the order its help shows them. - - Each command includes its summary, whether a parser checks its arguments, and its subcommands as typed. - Also listed: the help topics which are not commands, and the rules for typing a command line (which - characters end a command, which commands go on over several lines, and whether output can be redirected). - """ - snapshot = self.mcp_snapshot - return answer_list_commands(snapshot) - - @server.tool(annotations=read_only) - def describe_command(command: str) -> CommandDescription: - """Describe one command: its usage, its help, its arguments, and its subcommands by name. - - command is a command's name, or a path with spaces, such as "server add", which names a subcommand. Each - subcommand's typed field is the spelling to append to this path for the next lookup. See usage for arguments - or an end-of-options marker needed to run the command at the prompt. - Each argument's parser_default is declared by argparse. The application can supply a different value - when the argument is omitted. - """ - snapshot = self.mcp_snapshot - try: - return answer_describe_command(snapshot, command) - except (UnknownCommandError, DescriptionUnavailableError) as error: - if snapshot.stale_reason is not None: - raise ToolError(f"{error} The description is out of date: {snapshot.stale_reason}") from error - raise ToolError(str(error)) from error - - @server.tool(annotations=read_only) - def list_shortcuts_aliases_macros() -> Tables: - """List the shortcuts, aliases and macros: other words the person can type, which stand for commands.""" - snapshot = self.mcp_snapshot - return answer_tables(snapshot) - - return server.streamable_http_app(host=HOST, json_response=True, stateless_http=True) - - def _mcp_rebuild(self) -> None: - """Publish a new description, unless a command is in progress or preloop() has not returned. Never raises an Exception. - - A build which fails as a whole keeps the description there is, or, when there is none yet, publishes an empty one - which carries the error. Each failure is reported once, and again only if it comes back after a success. - - It holds cmd2's sigint_protection while it builds, which holds off Ctrl-C once cmdloop() has installed cmd2's - handler: before the first line is read, before each prompt, and at the end of each command. A build in an - mcp_start() which the application calls itself, before cmdloop() or without it, comes before that, so Ctrl-C there - raises KeyboardInterrupt, which leaves the start before it has taken anything. - """ - if self._mcp_depth != 0 or self._mcp_starting or self._mcp_initializing: - return - with self.sigint_protection: - warnings: list[str] = [] - try: - snapshot = self._mcp_build() - except Exception as error: # noqa: BLE001 - a rebuild never raises - message = plain_text(f"{type(error).__name__}: {error}") - previous = self.mcp_snapshot - if previous.error is None: - if previous.stale_reason != message: - self.mcp_snapshot = replace(previous, stale_reason=message) - elif previous.error != message: - self.mcp_snapshot = failed_snapshot(previous.generation + 1, message) - if message != self.mcp_build_error: - warnings.append(f"MCP: the description could not be built: {message}") - self.mcp_build_error = message - else: - reported = {(command.name, command.error) for command in self.mcp_snapshot.commands} - self.mcp_snapshot = snapshot - self.mcp_build_error = None - warnings.extend( - f'MCP: "{command.name}": {command.error}' - for command in snapshot.commands - if command.error is not None and (command.name, command.error) not in reported - ) - for warning in warnings: - # A warning which cannot be written has nowhere else to go, and a rebuild never raises. - with contextlib.suppress(Exception): - self.pwarning(warning) - - def _mcp_build(self) -> Snapshot: - """Describe the application as the next generation. A seam for tests.""" - return build_snapshot(self, self.mcp_snapshot.generation + 1, self.mcp_leave_out) - - -# --------------------------------------------------------------------------------------------------------------------- -# Part 3: The demonstration -# -# A pretend fleet console: servers, services and deployments held in memory. No command does anything outside the -# process; each prints what it would have done. It is here to give the describing code every kind of thing to describe. -# --------------------------------------------------------------------------------------------------------------------- - SERVERS = "Servers" DEPLOYMENTS = "Deployments" PLUGINS = "Plugins" @@ -1670,7 +42,7 @@ def do_restore(self, args: argparse.Namespace) -> None: self._cmd.poutput(f"Would restore {args.service} from its latest backup.") -class FleetConsole(McpServerMixin, cmd2.Cmd): +class FleetConsole(cmd2.Cmd): """A pretend fleet console, which serves a description of its own commands over MCP.""" def __init__(self, *args: Any, **kwargs: Any) -> None: @@ -1686,7 +58,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.backups = BackupCommands() def preloop(self) -> None: - """Say where the server is. cmd2 calls this after the mixin has started it, so the address is the real one.""" + """Show the address assigned to the running server, including when the port was chosen automatically.""" super().preloop() url = self.mcp_url if url is not None: @@ -1874,7 +246,6 @@ def do_mcp(self, args: argparse.Namespace) -> None: mcp_status_parser = Cmd2ArgumentParser(description="Say whether there is a server, and what it serves.") - # Not mcp_status(), the usual name for the handler of "mcp status": that would replace the mixin's mcp_status(). @cmd2.as_subcommand_to("mcp", "status", mcp_status_parser, help="say whether there is a server") def mcp_show_status(self, _: argparse.Namespace) -> None: """Print the server's status.""" @@ -1898,11 +269,11 @@ def main(argv: list[str] | None = None) -> int: except ImportError: # No application exists yet, so there is no cmd2 output method to use. sys.stderr.write( - "This example needs version 2 of the MCP SDK: uv run --group examples examples/mcp_server.py " + "This example needs version 2 of the MCP SDK: uv run --extra mcp examples/mcp_server.py " "(or pass --no-mcp to run without the server)\n" ) return 1 - app = FleetConsole(mcp_port=None if args.no_mcp else args.mcp_port, allow_cli_args=False) + app = FleetConsole(mcp_port=None if args.no_mcp else args.mcp_port, mcp_name="Fleet console", allow_cli_args=False) return app.cmdloop() diff --git a/mkdocs.yml b/mkdocs.yml index 6f615e370..148daf6ae 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -170,6 +170,7 @@ nav: - features/history.md - features/hooks.md - features/initialization.md + - features/mcp_server.md - features/misc.md - features/modular_commands.md - features/multiline_commands.md diff --git a/pyproject.toml b/pyproject.toml index b4eabf204..c7ae8b262 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,6 +34,9 @@ dependencies = [ "rich-argparse>=1.7.2", ] +[project.optional-dependencies] +mcp = ["mcp>=2,<3", "uvicorn>=0.31.1"] + [dependency-groups] build = ["build>=1.3.0", "setuptools>=80.8.0", "setuptools-scm>=9.2.1"] dev = [ @@ -59,8 +62,6 @@ docs = [ "setuptools_scm>=8", "zensical>=0.0.57", ] -# What the examples need and cmd2 does not. Not installed by default: "uv run --group examples ...". -examples = ["mcp>=2"] quality = ["prek>=0.3.5"] test = [ "codecov>=2.1", diff --git a/tests/test_example_mcp_server.py b/tests/test_mcp_server.py similarity index 82% rename from tests/test_example_mcp_server.py rename to tests/test_mcp_server.py index d06718292..addc99dce 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_mcp_server.py @@ -1,4 +1,4 @@ -"""Tests of the MCP server example, examples/mcp_server.py.""" +"""Tests of optional MCP command discovery and the fleet example.""" import argparse import asyncio @@ -35,6 +35,8 @@ from rich.text import Text import cmd2 +from cmd2 import _mcp_server as server_api +from cmd2 import _mcp_snapshot as snapshot_api from cmd2 import rich_utils as ru from cmd2 import string_utils as su @@ -79,15 +81,34 @@ def test_importing_the_example_does_not_import_the_sdk() -> None: subprocess.run([sys.executable, "-c", code], check=True) +def test_unconfigured_cmd_does_not_load_mcp_or_publish_snapshots() -> None: + code = ( + "import cmd2, io, sys\n" + "app = cmd2.Cmd(stdin=io.StringIO('quit\\n'), allow_cli_args=False)\n" + "app.onecmd_plus_hooks('alias create usage help')\n" + "app.cmdloop()\n" + "app.mcp_stop()\n" + "assert app.mcp_url is None\n" + "assert app.mcp_status() == ['No MCP server: no port was configured']\n" + "assert not {'cmd2._mcp_server', 'cmd2._mcp_snapshot', 'mcp', 'uvicorn'} & sys.modules.keys()\n" + ) + subprocess.run([sys.executable, "-c", code], check=True) + + +def test_start_requires_a_configured_port() -> None: + with pytest.raises(ValueError, match="mcp_port"): + cmd2.Cmd().mcp_start() + + def test_plain_text() -> None: styled = "\x1b[1mbold\x1b[0m \x1b]8;;https://example.com\x1b\\link\x1b]8;;\x1b\\" - assert ex.plain_text(styled) == "bold link" - assert ex.plain_text(None) == "" - assert ex.plain_text("\x9b31mred\x9b0m") == "red" # 8-bit CSI - assert ex.plain_text("\x9d8;;https://example.com\x07link\x9d8;;\x07") == "link" # 8-bit OSC, ended by BEL - assert ex.plain_text("\x9d8;;https://example.com\x9clink\x9d8;;\x9c") == "link" # 8-bit OSC, ended by ST - assert ex.plain_text("a\x85b\x80c\x9fd") == "abcd" # lone C1 characters - rendered = ex.plain_text(Group(Text("one", style="bold red"), "two")) + assert snapshot_api.plain_text(styled) == "bold link" + assert snapshot_api.plain_text(None) == "" + assert snapshot_api.plain_text("\x9b31mred\x9b0m") == "red" # 8-bit CSI + assert snapshot_api.plain_text("\x9d8;;https://example.com\x07link\x9d8;;\x07") == "link" # 8-bit OSC, ended by BEL + assert snapshot_api.plain_text("\x9d8;;https://example.com\x9clink\x9d8;;\x9c") == "link" # 8-bit OSC, ended by ST + assert snapshot_api.plain_text("a\x85b\x80c\x9fd") == "abcd" # lone C1 characters + rendered = snapshot_api.plain_text(Group(Text("one", style="bold red"), "two")) assert "one" in rendered assert "two" in rendered assert_plain(rendered) @@ -95,7 +116,7 @@ def test_plain_text() -> None: def _argument(*flags: str, **kwargs: Any) -> Any: parser = cmd2.Cmd2ArgumentParser() - return ex.describe_argument(parser.add_argument(*flags, **kwargs)) + return snapshot_api.describe_argument(parser.add_argument(*flags, **kwargs)) @pytest.mark.parametrize( @@ -304,7 +325,7 @@ def _descriptions(app: cmd2.Cmd, command: str) -> dict[str, Any]: assert func is not None parser = app.command_parsers.get(func) assert parser is not None - return ex.describe_parser(parser, command, "a summary") + return snapshot_api.describe_parser(parser, command, "a summary") def test_parser_subcommands_three_deep_by_path() -> None: @@ -364,14 +385,14 @@ def test_parser_usage_and_help_leave_out_a_suppressed_subcommand_without_changin def test_many_subcommand_names_do_not_restore_hidden_help(monkeypatch) -> None: - monkeypatch.setattr(ex, "MAX_CHOICES", 2) + monkeypatch.setattr(snapshot_api, "MAX_CHOICES", 2) parser = cmd2.Cmd2ArgumentParser() parser.add_argument("folder", choices=["a", "b", "c"]) parser.add_argument("--color", choices=["red", "blue", "green"], help="one of %(choices)s") subs = parser.add_subparsers() subs.add_parser("list", aliases=["ls"], help="List entries.") subs.add_parser("hidden", help=argparse.SUPPRESS) - root = ex.describe_parser(parser, "entries", "")["entries"] + root = snapshot_api.describe_parser(parser, "entries", "")["entries"] assert "[--color COLOR] folder" in root.usage assert "one of (choices omitted)" in root.help assert "{list,ls}" in root.usage @@ -383,8 +404,8 @@ def test_many_subcommand_names_do_not_restore_hidden_help(monkeypatch) -> None: def test_literal_end_of_options_as_a_subcommand_name(aliases) -> None: parser = cmd2.Cmd2ArgumentParser(prefix_chars="+") parser.add_subparsers(required=True).add_parser("--", aliases=aliases) - found = ex.describe_parser(parser, "p", "") - if ex._subparser_consumes_separator(): + found = snapshot_api.describe_parser(parser, "p", "") + if snapshot_api._subparser_consumes_separator(): assert parser.parse_args(["--", "--"]) == argparse.Namespace() assert found["p --"].usage == "Usage: p -- -- [-h]" assert found["p"].subcommands[0].aliases == tuple(aliases) @@ -402,7 +423,7 @@ def test_child_help_reuses_the_bounded_parent_positionals() -> None: child.add_subparsers().add_parser("all") parser.update_prog("pick") original = child.prog - found = ex.describe_parser(parser, "pick", "") + found = snapshot_api.describe_parser(parser, "pick", "") for path in ("pick show", "pick show all"): expected = path.replace("pick", "pick id") assert found[path].usage.startswith(f"Usage: {expected} ") @@ -415,7 +436,7 @@ def test_child_help_reuses_the_bounded_parent_positionals() -> None: def test_child_help_preserves_an_explicit_subparser_prefix(prefix: str) -> None: parser = cmd2.Cmd2ArgumentParser(prog="pick") parser.add_subparsers(prog=prefix).add_parser("show") - child = ex.describe_parser(parser, "pick", "")["pick show"] + child = snapshot_api.describe_parser(parser, "pick", "")["pick show"] assert child.usage == f"Usage: {prefix} show [-h]" @@ -427,7 +448,7 @@ def _build_subparsers_prog_prefix(self, positionals: list[argparse.Action]) -> s parser = CustomParser() parser.add_subparsers().add_parser("show") parser.update_prog("pick") - child = ex.describe_parser(parser, "pick", "")["pick show"] + child = snapshot_api.describe_parser(parser, "pick", "")["pick show"] assert child.usage == "Usage: custom invocation show [-h]" @@ -437,7 +458,7 @@ def test_child_help_reflects_changed_parent_choices() -> None: parser.add_subparsers().add_parser("go") choice.choices = ("baz",) assert parser.parse_args(["baz", "go"]).value == "baz" - child = ex.describe_parser(parser, "pick", "")["pick go"] + child = snapshot_api.describe_parser(parser, "pick", "")["pick go"] assert child.usage == "Usage: pick {baz} go [-h]" assert child.help.startswith(child.usage) @@ -454,7 +475,7 @@ def test_child_usage_orders_trailing_parent_positionals_at_each_depth() -> None: "section": "header", "file": "notes", } - found = ex.describe_parser(parser, "run", "") + found = snapshot_api.describe_parser(parser, "run", "") assert found["run show"].usage == "Usage: run show [-h] {line} ... section file" description = found["run show line"] assert description.usage == "Usage: run show line [-h] number section file" @@ -467,7 +488,7 @@ def test_child_custom_usage_includes_trailing_parent_positional() -> None: child = parser.add_subparsers().add_parser("show", usage="%(prog)s ROW") child.add_argument("row") parser.add_argument("file", metavar="FILE") - description = ex.describe_parser(parser, "run", "")["run show"] + description = snapshot_api.describe_parser(parser, "run", "")["run show"] assert description.usage == "Usage: run show ROW FILE" assert description.help.startswith(description.usage) @@ -484,7 +505,7 @@ def test_child_usage_shows_only_reserved_parent_words(nargs, reserved, suffix) - assert parser.parse_args(words).row == "1" with pytest.raises((argparse.ArgumentError, SystemExit)): parser.parse_args([*words, "extra"]) - description = ex.describe_parser(parser, "run", "")["run show"] + description = snapshot_api.describe_parser(parser, "run", "")["run show"] assert description.usage == f"Usage: run show [-h] row{suffix}" assert description.help.startswith(description.usage) @@ -497,7 +518,7 @@ def test_child_help_includes_required_parent_options(positional: bool) -> None: parser.add_argument("group") parser.add_subparsers().add_parser("show") parser.update_prog("pick") - description = ex.describe_parser(parser, "pick", "")["pick show"] + description = snapshot_api.describe_parser(parser, "pick", "")["pick show"] expected = "pick --id ID group show" if positional else "pick --id ID show" assert description.usage == f"Usage: {expected} [-h]" assert description.help.startswith(description.usage) @@ -511,7 +532,7 @@ def test_nested_child_usage_preserves_tabs_and_required_parent_group() -> None: group.add_argument("--name") parent.add_subparsers().add_parser("show") parser.update_prog("pick") - child = ex.describe_parser(parser, "pick", "")['pick "has\ttab" show'] + child = snapshot_api.describe_parser(parser, "pick", "")['pick "has\ttab" show'] assert child.usage == 'Usage: pick "has\ttab" (--id ID | --name NAME) show [-h]' @@ -521,14 +542,14 @@ def test_option_like_subcommand_after_a_positional_is_reachable(name) -> None: parser.add_argument("user") parser.add_subparsers(dest="action", required=True).add_parser(name) assert parser.parse_args(["--", "alice", name]).action == name - child = ex.describe_parser(parser, "owner", "")[f"owner {name}"] + child = snapshot_api.describe_parser(parser, "owner", "")[f"owner {name}"] assert child.usage == f"Usage: owner user -- {name} [-h]" def test_option_like_subcommand_without_a_positional_matches_running_argparse() -> None: parser = cmd2.Cmd2ArgumentParser(prog="run", exit_on_error=False) parser.add_subparsers(dest="sub", required=True).add_parser("-x") - found = ex.describe_parser(parser, "run", "") + found = snapshot_api.describe_parser(parser, "run", "") try: parsed = parser.parse_args(["--", "-x"]) except argparse.ArgumentError: @@ -550,15 +571,15 @@ def __cmd2_argparse_help__(self, formatter): monkeypatch.setenv("COLUMNS", "21") parser = cmd2.Cmd2ArgumentParser(description=ObserveWidth()) - assert "Width test." in ex.describe_parser(parser, "width", "")["width"].help - assert seen == [("21", ex.HELP_WIDTH)] + assert "Width test." in snapshot_api.describe_parser(parser, "width", "")["width"].help + assert seen == [("21", snapshot_api.HELP_WIDTH)] def test_parser_exclusive_groups() -> None: logs = _descriptions(ParserApp(), "logs")["logs"] - assert logs.exclusive_groups == (ex.ExclusiveGroup(arguments=("--follow", "--since"), required=False),) + assert logs.exclusive_groups == (snapshot_api.ExclusiveGroup(arguments=("--follow", "--since"), required=False),) pick = _descriptions(ParserApp(), "pick")["pick"] - assert pick.exclusive_groups == (ex.ExclusiveGroup(arguments=("--first", "--last"), required=True),) + assert pick.exclusive_groups == (snapshot_api.ExclusiveGroup(arguments=("--first", "--last"), required=True),) def test_parser_exclusive_groups_name_options_which_share_a_destination_apart() -> None: @@ -569,10 +590,10 @@ def test_parser_exclusive_groups_name_options_which_share_a_destination_apart() either = parser.add_mutually_exclusive_group() either.add_argument("target", nargs="?") either.add_argument("--all", action="store_true") - mode = ex.describe_parser(parser, "mode", "a summary")["mode"] + mode = snapshot_api.describe_parser(parser, "mode", "a summary")["mode"] assert mode.exclusive_groups == ( - ex.ExclusiveGroup(arguments=("-a", "--remove"), required=True), # not ("mode", "mode") - ex.ExclusiveGroup(arguments=("target", "--all"), required=False), # a positional by its name + snapshot_api.ExclusiveGroup(arguments=("-a", "--remove"), required=True), # not ("mode", "mode") + snapshot_api.ExclusiveGroup(arguments=("target", "--all"), required=False), # a positional by its name ) # Each one names exactly one argument: a flag of it, or the name of a positional. for named in (name for group in mode.exclusive_groups for name in group.arguments): @@ -588,10 +609,10 @@ def test_parser_keeps_a_required_exclusive_group_of_which_one_member_is_visible( optional = parser.add_mutually_exclusive_group() optional.add_argument("--fast", action="store_true") optional.add_argument("--old", action="store_true", help=argparse.SUPPRESS) - upgrade = ex.describe_parser(parser, "upgrade", "a summary")["upgrade"] + upgrade = snapshot_api.describe_parser(parser, "upgrade", "a summary")["upgrade"] # argparse refuses the command with neither --current nor --legacy, and --legacy is hidden: so --current must be given. # The optional group constrains nothing which can be seen, and is left out. - assert upgrade.exclusive_groups == (ex.ExclusiveGroup(arguments=("--current",), required=True),) + assert upgrade.exclusive_groups == (snapshot_api.ExclusiveGroup(arguments=("--current",), required=True),) def test_parser_leaves_out_a_suppressed_argument() -> None: @@ -690,7 +711,7 @@ def _names(snapshot: Any) -> set[str]: def test_snapshot_describes_every_built_in_command_of_a_bare_application() -> None: app = cmd2.Cmd() - snapshot = ex.build_snapshot(app, 1) + snapshot = snapshot_api.build_snapshot(app, 1) assert snapshot.error is None assert _names(snapshot) == set(app.get_visible_commands()) assert [command.name for command in snapshot.commands if command.error] == [] @@ -706,12 +727,12 @@ def test_snapshot_describes_every_built_in_command_of_a_bare_application() -> No def test_snapshot_holds_no_escape_character() -> None: app = SnapshotApp() app.onecmd_plus_hooks("alias create red echo \x1b[31mred\x1b[0m") # Review Focus 3 - assert_plain(ex.build_snapshot(app, 1)) - assert_plain(ex.build_snapshot(cmd2.Cmd(), 1)) + assert_plain(snapshot_api.build_snapshot(app, 1)) + assert_plain(snapshot_api.build_snapshot(cmd2.Cmd(), 1)) def test_snapshot_commands_with_no_parser() -> None: - snapshot = ex.build_snapshot(SnapshotApp(), 1) + snapshot = snapshot_api.build_snapshot(SnapshotApp(), 1) status = snapshot.descriptions["status"] assert (status.has_parser, status.arguments, status.summary) == (False, (), "Show the status.") assert status.help == "Show the status.\n\nNothing is contacted." @@ -721,22 +742,22 @@ def test_snapshot_commands_with_no_parser() -> None: def test_snapshot_annotated_command() -> None: - scale = ex.build_snapshot(SnapshotApp(), 1).descriptions["scale"] + scale = snapshot_api.build_snapshot(SnapshotApp(), 1).descriptions["scale"] assert [(argument.name, argument.type) for argument in scale.arguments] == [("service", None), ("replicas", "int")] def test_snapshot_leaves_out_hidden_and_disabled_commands() -> None: app = SnapshotApp() app.disable_command("gated", "not now") - snapshot = ex.build_snapshot(app, 1) + snapshot = snapshot_api.build_snapshot(app, 1) assert not {"secret", "gated"} & _names(snapshot) assert "gated" not in snapshot.descriptions app.enable_command("gated") - assert "gated" in _names(ex.build_snapshot(app, 2)) + assert "gated" in _names(snapshot_api.build_snapshot(app, 2)) def test_snapshot_lists_a_command_which_cannot_be_described() -> None: - snapshot = ex.build_snapshot(SnapshotApp(), 1) + snapshot = snapshot_api.build_snapshot(SnapshotApp(), 1) broken = next(command for command in snapshot.commands if command.name == "broken") assert "boom" in broken.error assert broken.category == "Snapshot Commands" @@ -748,8 +769,8 @@ def test_snapshot_lists_a_command_which_cannot_be_described() -> None: def test_multiline_rules_only_name_published_commands() -> None: app = SnapshotApp(multiline_commands=["note", "secret", "gated", "bare"]) app.disable_command("gated", "disabled") - snapshot = ex.build_snapshot(app, 1, leave_out=["bare"]) - assert ex.answer_list_commands(snapshot).typing.multiline_commands == ("note",) + snapshot = snapshot_api.build_snapshot(app, 1, leave_out=["bare"]) + assert snapshot_api.answer_list_commands(snapshot).typing.multiline_commands == ("note",) def test_quote_mode_is_looked_up_once_per_parsed_command() -> None: @@ -768,11 +789,11 @@ def do_parserless(self, _: cmd2.Statement) -> None: app = SpecApp() app.kept_lookups = 0 - snapshot = ex.build_snapshot(app, 1) + snapshot = snapshot_api.build_snapshot(app, 1) assert snapshot.descriptions["parserless"].error is None assert "broken spec" in snapshot.descriptions["report"].error assert app.kept_lookups == 1 - assert ex.answer_describe_command(snapshot, 'kept "list all"').description.path == 'kept "list all"' + assert snapshot_api.answer_describe_command(snapshot, 'kept "list all"').description.path == 'kept "list all"' def test_command_lookup_errors_are_reported_without_losing_other_descriptions() -> None: @@ -785,7 +806,7 @@ def get_command_category(self, func): raise LookupError("missing category") return super().get_command_category(func) - snapshot = ex.build_snapshot(IncompleteApp(), 1) + snapshot = snapshot_api.build_snapshot(IncompleteApp(), 1) listed = {command.name: command for command in snapshot.commands} for name, message in (("missing", "no function for the command"), ("status", "missing category")): assert listed[name].category == "" @@ -795,7 +816,7 @@ def get_command_category(self, func): def test_snapshot_summary_from_a_rich_description_when_there_is_no_docstring() -> None: - assert ex.build_snapshot(SnapshotApp(), 1).descriptions["rich"].summary == "Rich description." + assert snapshot_api.build_snapshot(SnapshotApp(), 1).descriptions["rich"].summary == "Rich description." def test_formatter_aware_descriptions_supply_command_and_subcommand_summaries() -> None: @@ -807,7 +828,7 @@ class NotesApp(cmd2.Cmd): def do_notes(self, _: argparse.Namespace) -> None: pass - snapshot = ex.build_snapshot(NotesApp(), 1) + snapshot = snapshot_api.build_snapshot(NotesApp(), 1) command = next(command for command in snapshot.commands if command.name == "notes") assert command.summary == "Notes:" root = snapshot.descriptions["notes"] @@ -815,15 +836,15 @@ def do_notes(self, _: argparse.Namespace) -> None: def test_snapshot_leaves_out_the_commands_it_is_told_to() -> None: - snapshot = ex.build_snapshot(SnapshotApp(), 1, leave_out={"shell", "broken"}) + snapshot = snapshot_api.build_snapshot(SnapshotApp(), 1, leave_out={"shell", "broken"}) assert not {"shell", "broken"} & _names(snapshot) assert not {"shell", "broken"} & set(snapshot.descriptions) - with pytest.raises(ex.UnknownCommandError): - ex.answer_describe_command(snapshot, "shell") + with pytest.raises(snapshot_api.UnknownCommandError): + snapshot_api.answer_describe_command(snapshot, "shell") def test_failed_snapshot() -> None: - snapshot = ex.failed_snapshot(4, "the build failed") + snapshot = snapshot_api.failed_snapshot(4, "the build failed") assert (snapshot.generation, snapshot.commands, snapshot.error) == (4, (), "the build failed") assert dict(snapshot.descriptions) == {} @@ -832,25 +853,27 @@ def test_snapshot_tables_help_topics_and_typing_rules() -> None: app = SnapshotApp(multiline_commands=["note"]) app.onecmd_plus_hooks("alias create ll shell ls -l") app.onecmd_plus_hooks("macro create twice {1} {1}") - snapshot = ex.build_snapshot(app, 1) - assert ex.Alias("ll", "shell ls -l") in snapshot.aliases - assert ex.Macro("twice", "{1} {1}", 1) in snapshot.macros - assert ex.Shortcut("?", "help") in snapshot.shortcuts + snapshot = snapshot_api.build_snapshot(app, 1) + assert snapshot_api.Alias("ll", "shell ls -l") in snapshot.aliases + assert snapshot_api.Macro("twice", "{1} {1}", 1) in snapshot.macros + assert snapshot_api.Shortcut("?", "help") in snapshot.shortcuts assert "extra" in snapshot.help_topics assert "status" not in snapshot.help_topics - assert snapshot.typing == ex.TypingRules(allow_redirection=True, terminators=(";",), multiline_commands=("note",)) + assert snapshot.typing == snapshot_api.TypingRules( + allow_redirection=True, terminators=(";",), multiline_commands=("note",) + ) def test_snapshot_generation_and_time() -> None: - snapshot = ex.build_snapshot(cmd2.Cmd(), 7) + snapshot = snapshot_api.build_snapshot(cmd2.Cmd(), 7) assert snapshot.generation == 7 assert datetime.fromisoformat(snapshot.built_at).tzinfo is not None def test_answer_list_commands() -> None: app = SnapshotApp() - snapshot = ex.build_snapshot(app, 3) - answer = ex.answer_list_commands(snapshot) + snapshot = snapshot_api.build_snapshot(app, 3) + answer = snapshot_api.answer_list_commands(snapshot) assert (answer.generation, answer.built_at) == (3, snapshot.built_at) names = [category.name for category in answer.categories] assert names == sorted(names, key=cmd2.utils.DEFAULT_STR_SORT_KEY) @@ -878,36 +901,38 @@ def help_topic10(self) -> None: with monkeypatch.context() as patch: patch.setattr(cmd2.utils, "DEFAULT_STR_SORT_KEY", cmd2.utils.NATURAL_SORT_KEY) - snapshot = ex.build_snapshot(Tasks(), 1) + snapshot = snapshot_api.build_snapshot(Tasks(), 1) assert [c.name for c in snapshot.commands if c.name.startswith("task")] == ["task2", "task10"] assert snapshot.help_topics == ("topic2", "topic10") - categories = ex.answer_list_commands(snapshot).categories + categories = snapshot_api.answer_list_commands(snapshot).categories assert [c.name for c in categories if c.name.startswith("Group")] == ["Group2", "Group10"] def test_answer_describe_command() -> None: # Review Focus 1 app = SnapshotApp() app.disable_command("gated", "not now") - snapshot = ex.build_snapshot(app, 3) - answer = ex.answer_describe_command(snapshot, " server tag add ") + snapshot = snapshot_api.build_snapshot(app, 3) + answer = snapshot_api.answer_describe_command(snapshot, " server tag add ") assert (answer.generation, answer.description.path) == (3, "server tag add") - assert ex.answer_describe_command(snapshot, "server ls").description.path == "server list" - assert ex.answer_describe_command(snapshot, "server t").description.path == "server tag" - assert ex.answer_describe_command(snapshot, "server t add").description.path == "server tag add" # an alias at any depth - with pytest.raises(ex.UnknownCommandError, match='"server tag" has: add, remove'): - ex.answer_describe_command(snapshot, "server t nonesuch") + assert snapshot_api.answer_describe_command(snapshot, "server ls").description.path == "server list" + assert snapshot_api.answer_describe_command(snapshot, "server t").description.path == "server tag" + assert ( + snapshot_api.answer_describe_command(snapshot, "server t add").description.path == "server tag add" + ) # an alias at any depth + with pytest.raises(snapshot_api.UnknownCommandError, match='"server tag" has: add, remove'): + snapshot_api.answer_describe_command(snapshot, "server t nonesuch") for missing in ("nonesuch", "", "gated", "secret"): - with pytest.raises(ex.UnknownCommandError) as raised: - ex.answer_describe_command(snapshot, missing) + with pytest.raises(snapshot_api.UnknownCommandError) as raised: + snapshot_api.answer_describe_command(snapshot, missing) assert "status" in str(raised.value) assert "server" in str(raised.value) - with pytest.raises(ex.UnknownCommandError) as raised: - ex.answer_describe_command(snapshot, "server nonesuch") + with pytest.raises(snapshot_api.UnknownCommandError) as raised: + snapshot_api.answer_describe_command(snapshot, "server nonesuch") assert {"list", "add", "tag"} <= set(re.findall(r"\w+", str(raised.value))) def test_describing_a_long_unknown_line_looks_up_no_further_than_the_path_which_exists() -> None: - snapshot = ex.build_snapshot(SnapshotApp(), 3) + snapshot = snapshot_api.build_snapshot(SnapshotApp(), 3) looked_up: list[str] = [] class Noting(dict): @@ -923,8 +948,8 @@ def __getitem__(self, key: str) -> Any: pasted = " word" * 5000 # a whole script, say, given in place of a command for line, known in (("server tag nonesuch" + pasted, 2), ("nonesuch" + pasted, 0)): looked_up.clear() - with pytest.raises(ex.UnknownCommandError): - ex.answer_describe_command(snapshot, line) + with pytest.raises(snapshot_api.UnknownCommandError): + snapshot_api.answer_describe_command(snapshot, line) assert len(looked_up) <= known + 1 # one for each word of the path which exists, and one more at most assert all(len(key.split()) <= known + 1 for key in looked_up) @@ -1023,23 +1048,23 @@ def do_files(self, args: argparse.Namespace) -> None: def test_describing_a_subcommand_whose_name_has_a_space_takes_it_quoted_as_the_prompt_does() -> None: - snapshot = ex.build_snapshot(SpacedApp(), 1) - root = ex.answer_describe_command(snapshot, "report").description + snapshot = snapshot_api.build_snapshot(SpacedApp(), 1) + root = snapshot_api.answer_describe_command(snapshot, "report").description listed = next(command for command in snapshot.commands if command.name == "report") assert '"list all"' in listed.subcommands for sub in root.subcommands: - child = ex.answer_describe_command(snapshot, f"report {sub.typed}").description + child = snapshot_api.answer_describe_command(snapshot, f"report {sub.typed}").description assert child.summary == sub.summary for typed in ('report "list all"', "report 'list all'", 'report "every one"'): - assert ex.answer_describe_command(snapshot, typed).description.path == 'report "list all"' # as it is typed + assert snapshot_api.answer_describe_command(snapshot, typed).description.path == 'report "list all"' # as it is typed # The prompt takes "list" and "all" as two words: the subcommand "all" of "list". - assert ex.answer_describe_command(snapshot, "report list all").description.path == "report list all" - with pytest.raises(ex.UnknownCommandError, match="quot"): - ex.answer_describe_command(snapshot, 'report "list all') # a quotation which is never closed + assert snapshot_api.answer_describe_command(snapshot, "report list all").description.path == "report list all" + with pytest.raises(snapshot_api.UnknownCommandError, match="quot"): + snapshot_api.answer_describe_command(snapshot, 'report "list all') # a quotation which is never closed def test_a_name_which_the_prompt_would_split_or_read_as_syntax_is_served_quoted_and_must_be_typed_so() -> None: - snapshot = ex.build_snapshot(SpacedApp(), 1) # whose terminators are ";" and "&" + snapshot = snapshot_api.build_snapshot(SpacedApp(), 1) # whose terminators are ";" and "&" paths = {path for path in snapshot.descriptions if path.startswith("report ")} assert paths == { 'report "list all"', @@ -1059,11 +1084,11 @@ def test_a_name_which_the_prompt_would_split_or_read_as_syntax_is_served_quoted_ "report list all", } for path in paths: - assert ex.answer_describe_command(snapshot, path).description.path == path # a path served can be asked for + assert snapshot_api.answer_describe_command(snapshot, path).description.path == path # a path served can be asked for # At the prompt these are "report per" piped to "site", "report a" and then "b", and so on. for unquoted in ("report per|site", "report a;b", "report this&that", "report tab\there"): - with pytest.raises(ex.UnknownCommandError) as raised: - ex.answer_describe_command(snapshot, unquoted) + with pytest.raises(snapshot_api.UnknownCommandError) as raised: + snapshot_api.answer_describe_command(snapshot, unquoted) assert ( '"report" has: "list all", "per|site", "a;b", "this&that", "tab\there", "tab here", today\'s, a\'b"c, "", ' "daily, weekly, show, list." in str(raised.value) @@ -1072,7 +1097,7 @@ def test_a_name_which_the_prompt_would_split_or_read_as_syntax_is_served_quoted_ def test_usage_for_each_lookup_path_invokes_the_described_subcommand() -> None: app = SpacedApp() - snapshot = ex.build_snapshot(app, 1) + snapshot = snapshot_api.build_snapshot(app, 1) for path, description in snapshot.descriptions.items(): if path.startswith(("report ", "kept ", "odd ", "files ")): app.ran = None @@ -1080,29 +1105,29 @@ def test_usage_for_each_lookup_path_invokes_the_described_subcommand() -> None: invocation = description.usage.removeprefix("Usage: ").split(" [-h]", 1)[0] app.onecmd_plus_hooks(invocation) assert app.ran == description.summary, path - assert ex.answer_describe_command(snapshot, path).description is description + assert snapshot_api.answer_describe_command(snapshot, path).description is description def test_a_name_with_quotation_marks_in_it_is_found_as_the_prompt_takes_it() -> None: - snapshot = ex.build_snapshot(SpacedApp(), 1) + snapshot = snapshot_api.build_snapshot(SpacedApp(), 1) for typed, path in ( ("report today's", "report today's"), ('report "today\'s"', "report today's"), # quoted, which the prompt takes too ("report a'b\"c", "report a'b\"c"), ("report ''", 'report ""'), ): - assert ex.answer_describe_command(snapshot, typed).description.path == path + assert snapshot_api.answer_describe_command(snapshot, typed).description.path == path # At the prompt this is the word 'a' and then the word b"c'. - with pytest.raises(ex.UnknownCommandError): - ex.answer_describe_command(snapshot, "report 'a'b\"c'") + with pytest.raises(snapshot_api.UnknownCommandError): + snapshot_api.answer_describe_command(snapshot, "report 'a'b\"c'") def test_a_subcommand_whose_name_cannot_be_typed_is_served_by_an_alias_which_can() -> None: - snapshot = ex.build_snapshot(SpacedApp(), 1) + snapshot = snapshot_api.build_snapshot(SpacedApp(), 1) daily = next(each for each in snapshot.descriptions["report"].subcommands if each.summary == "Report daily.") assert (daily.name, daily.aliases) == ("daily", ()) assert snapshot.descriptions["report daily"].usage == "Usage: report daily [-h] {summary} ..." - found = ex.answer_describe_command(snapshot, "report daily summary").description + found = snapshot_api.answer_describe_command(snapshot, "report daily summary").description assert (found.summary, found.usage) == ("Summarize the day.", "Usage: report daily summary [-h]") @@ -1113,7 +1138,7 @@ def test_usage_help_and_aliases_name_a_subcommand_only_by_the_names_which_can_be subcommands.add_parser("a' \"b", help="Report which the prompt cannot take.") subcommands.add_parser("d' \"y", aliases=["daily"], help="Report daily.") subcommands.add_parser("weekly", aliases=["w' \"k", "wk"], help="Report weekly.") - report = ex.describe_parser(parser, "report", "Reports.")["report"] + report = snapshot_api.describe_parser(parser, "report", "Reports.")["report"] assert [(each.name, each.aliases) for each in report.subcommands] == [("show", ()), ("daily", ()), ("weekly", ("wk",))] assert report.usage == "Usage: report [-h] {show,daily,weekly,wk} ..." for left_out in ("a' \"b", "d' \"y", "w' \"k", "cannot take"): @@ -1125,26 +1150,26 @@ def test_usage_help_and_aliases_name_a_subcommand_only_by_the_names_which_can_be def test_the_subcommands_of_a_command_which_keeps_its_quotes_are_typed_as_argparse_is_given_them() -> None: - snapshot = ex.build_snapshot(SpacedApp(), 1) + snapshot = snapshot_api.build_snapshot(SpacedApp(), 1) # argparse is given "list all" with its quotation marks, so that is the name it is typed for. No word reaches the # subcommand named list all without them. assert {path for path in snapshot.descriptions if path.startswith("kept ")} == {'kept "list all"', "kept show"} assert [each.name for each in snapshot.descriptions["kept"].subcommands] == ['"list all"', "show"] assert snapshot.descriptions["kept"].usage == 'Usage: kept [-h] {"list all",show} ...' - quoted = ex.answer_describe_command(snapshot, 'kept "list all"').description + quoted = snapshot_api.answer_describe_command(snapshot, 'kept "list all"').description assert (quoted.summary, quoted.usage) == ("List all, by a name with quotation marks in it.", 'Usage: kept "list all" [-h]') - with pytest.raises(ex.UnknownCommandError): - ex.answer_describe_command(snapshot, "kept 'list all'") # argparse is given 'list all', with these quotes + with pytest.raises(snapshot_api.UnknownCommandError): + snapshot_api.answer_describe_command(snapshot, "kept 'list all'") # argparse is given 'list all', with these quotes # A command which takes its quotes off is read as before. - assert ex.answer_describe_command(snapshot, "report 'list all'").description.path == 'report "list all"' + assert snapshot_api.answer_describe_command(snapshot, "report 'list all'").description.path == 'report "list all"' def test_subcommands_that_look_like_options_reflect_argparse_reachability(capsys: pytest.CaptureFixture[str]) -> None: - snapshot = ex.build_snapshot(SpacedApp(), 1) + snapshot = snapshot_api.build_snapshot(SpacedApp(), 1) odd = snapshot.descriptions["odd"] # -h is the parent's help option, -x an unknown option, --ver an abbreviation of two options, and -- the end of the # options. argparse takes -1 as a negative number, and a lone dash and a name with a space in it as positionals. - if ex._subparser_consumes_separator(): + if snapshot_api._subparser_consumes_separator(): expected = [("-h", ("expand",)), ("-x", ()), ("--ver", ()), ("--", ())] assert "-h (expand)" in odd.help else: @@ -1167,12 +1192,12 @@ def test_a_subcommand_name_which_argparse_reads_from_a_file_is_left_out() -> Non subcommands = parser.add_subparsers(title="subcommands") subcommands.add_parser("@all", aliases=["all"], help="Report on all.") subcommands.add_parser("show", help="Show one report.") - report = ex.describe_parser(parser, "report", "Reports.")["report"] + report = snapshot_api.describe_parser(parser, "report", "Reports.")["report"] assert [(each.name, each.aliases) for each in report.subcommands] == [("all", ()), ("show", ())] def test_a_subcommand_name_which_is_not_served_as_it_is_is_left_out() -> None: - snapshot = ex.build_snapshot(SpacedApp(), 1) + snapshot = snapshot_api.build_snapshot(SpacedApp(), 1) odd = snapshot.descriptions["odd"] # a\rb would be served as ab, the name of its sibling, and one would hide the other under the same path. assert [each.name for each in odd.subcommands].count("ab") == 1 @@ -1181,7 +1206,7 @@ def test_a_subcommand_name_which_is_not_served_as_it_is_is_left_out() -> None: def test_a_subcommand_name_which_an_ancestor_reads_from_a_file_is_left_out() -> None: - snapshot = ex.build_snapshot(SpacedApp(), 1) + snapshot = snapshot_api.build_snapshot(SpacedApp(), 1) # files has a from-file prefix, and group none, but files reads every word after it first. assert [(each.name, each.aliases) for each in snapshot.descriptions["files group"].subcommands] == [("all", ())] @@ -1200,15 +1225,15 @@ def do_vault(self, _: argparse.Namespace) -> None: def test_subcommands_whose_help_is_suppressed_together_are_left_out() -> None: - snapshot = ex.build_snapshot(HiddenSubcommandsApp(), 1) + snapshot = snapshot_api.build_snapshot(HiddenSubcommandsApp(), 1) vault = snapshot.descriptions["vault"] assert vault.subcommands == () assert [path for path in snapshot.descriptions if path.startswith("vault")] == ["vault"] assert vault.usage == "Usage: vault [-h] [--all]" assert "secret" not in vault.help assert [command.subcommands for command in snapshot.commands if command.name == "vault"] == [()] - with pytest.raises(ex.UnknownCommandError): - ex.answer_describe_command(snapshot, "vault secret") + with pytest.raises(snapshot_api.UnknownCommandError): + snapshot_api.answer_describe_command(snapshot, "vault secret") class EveryNumber: @@ -1247,10 +1272,10 @@ def do_get(self, args: argparse.Namespace) -> None: def test_no_more_choices_are_read_than_are_listed() -> None: app = IdApp() - get = ex.build_snapshot(app, 1).descriptions["get"] + get = snapshot_api.build_snapshot(app, 1).descriptions["get"] assert get.error is None arguments = {each.name: each for each in get.arguments} - assert arguments["id"].choices == tuple(str(number) for number in range(ex.MAX_CHOICES)) + assert arguments["id"].choices == tuple(str(number) for number in range(snapshot_api.MAX_CHOICES)) assert arguments["id"].more_choices is True assert "one of (choices omitted)" in get.help assert arguments["page"].more_choices is True @@ -1272,7 +1297,7 @@ def do_pick(self, args: argparse.Namespace) -> None: self.poutput(args.item) app = PickApp() - first = ex.build_snapshot(app, 1) + first = snapshot_api.build_snapshot(app, 1) assert first.descriptions["pick"].error is None assert first.descriptions["pick"].arguments[0].more_choices assert first.descriptions["pick show"].usage == "Usage: pick item show [-h]" @@ -1298,7 +1323,7 @@ def do_speak(self, _: argparse.Namespace) -> None: def test_a_command_which_is_another_commands_function_is_described_by_its_own_name() -> None: app = SynonymApp() - snapshot = ex.build_snapshot(app, 1) + snapshot = snapshot_api.build_snapshot(app, 1) for name in ("speak", "orate"): assert snapshot.descriptions[name].usage == f"Usage: {name} [-h] [-r REPEAT] {{loudly}} ..." assert snapshot.descriptions[name].help.startswith(f"Usage: {name} [-h]") @@ -1334,7 +1359,7 @@ def do_power(self, args: argparse.Namespace) -> None: def test_describing_choices_which_are_an_iterator_leaves_them_to_argparse() -> None: app = PowerApp() app.onecmd_plus_hooks("power on --fan slow") - snapshot = ex.build_snapshot(app, 1) + snapshot = snapshot_api.build_snapshot(app, 1) app.onecmd_plus_hooks("power off --fan fast") # what argparse has left of each iterator assert app.given is not None assert (app.given.mode, app.given.fan) == ("off", "fast") @@ -1348,17 +1373,17 @@ def test_describing_choices_which_are_an_iterator_leaves_them_to_argparse() -> N def test_every_answer_says_when_there_is_no_description() -> None: - snapshot = ex.failed_snapshot(1, "RuntimeError: a defect") - assert ex.answer_list_commands(snapshot).error == "RuntimeError: a defect" - assert ex.answer_tables(snapshot).error == "RuntimeError: a defect" - with pytest.raises(ex.DescriptionUnavailableError, match="RuntimeError: a defect"): - ex.answer_describe_command(snapshot, "help") - assert ex.answer_tables(ex.build_snapshot(cmd2.Cmd(), 1)).error is None + snapshot = snapshot_api.failed_snapshot(1, "RuntimeError: a defect") + assert snapshot_api.answer_list_commands(snapshot).error == "RuntimeError: a defect" + assert snapshot_api.answer_tables(snapshot).error == "RuntimeError: a defect" + with pytest.raises(snapshot_api.DescriptionUnavailableError, match="RuntimeError: a defect"): + snapshot_api.answer_describe_command(snapshot, "help") + assert snapshot_api.answer_tables(snapshot_api.build_snapshot(cmd2.Cmd(), 1)).error is None def test_a_subcommand_which_no_spelling_gets_through_the_prompt_whole_is_left_out() -> None: app = SpacedApp() - snapshot = ex.build_snapshot(app, 1) + snapshot = snapshot_api.build_snapshot(app, 1) # Its name has both quotation marks and a space: the prompt splits every spelling of it. name, summary = "a' \"b", "Report which the prompt cannot take." for typed in (name, f'"{name}"', f"'{name}'"): @@ -1371,7 +1396,7 @@ def test_a_subcommand_which_no_spelling_gets_through_the_prompt_whole_is_left_ou def test_usage_and_help_name_each_subcommand_as_it_is_typed() -> None: app = SpacedApp() - snapshot = ex.build_snapshot(app, 1) + snapshot = snapshot_api.build_snapshot(app, 1) spaced = snapshot.descriptions['report "list all"'] assert spaced.usage == 'Usage: report "list all" [-h]' assert spaced.help.startswith(spaced.usage) @@ -1396,26 +1421,26 @@ def test_usage_and_help_name_each_subcommand_as_it_is_typed() -> None: def test_describing_takes_the_first_word_as_the_prompt_does_as_the_name_of_a_command() -> None: - snapshot = ex.build_snapshot(SpacedApp(), 1) + snapshot = snapshot_api.build_snapshot(SpacedApp(), 1) # The prompt refuses each: a quoted word is not the name of a command, nor is the path of a subcommand. for typed in ('"report list" all', '"report" "list all"', "'report' show", '"report list all"'): - with pytest.raises(ex.UnknownCommandError, match="There is no command"): - ex.answer_describe_command(snapshot, typed) + with pytest.raises(snapshot_api.UnknownCommandError, match="There is no command"): + snapshot_api.answer_describe_command(snapshot, typed) def test_describing_a_suppressed_subcommand_is_an_error_as_for_a_hidden_command() -> None: - snapshot = ex.build_snapshot(SnapshotApp(), 3) + snapshot = snapshot_api.build_snapshot(SnapshotApp(), 3) account = next(command for command in snapshot.commands if command.name == "account") assert set(account.subcommands) == {"list", "show"} for missing in ("account purge", "account wipe"): - with pytest.raises(ex.UnknownCommandError) as raised: - ex.answer_describe_command(snapshot, missing) + with pytest.raises(snapshot_api.UnknownCommandError) as raised: + snapshot_api.answer_describe_command(snapshot, missing) assert set(re.findall(r"\w+", str(raised.value).partition(" has: ")[2])) == {"list", "show"} def test_answer_tables() -> None: - snapshot = ex.build_snapshot(SnapshotApp(), 3) - answer = ex.answer_tables(snapshot) + snapshot = snapshot_api.build_snapshot(SnapshotApp(), 3) + answer = snapshot_api.answer_tables(snapshot) assert (answer.generation, answer.shortcuts, answer.aliases, answer.macros) == ( 3, snapshot.shortcuts, @@ -1432,26 +1457,30 @@ def do_extra(self, _: cmd2.Statement) -> None: def test_commands_in_a_base_constructor_run_before_the_first_snapshot() -> None: class ExistingApp(cmd2.Cmd): def __init__(self) -> None: - super().__init__(allow_cli_args=False) + super().__init__(allow_cli_args=False, mcp_port=0) self.onecmd_plus_hooks("alias create usage help") - class App(ex.McpServerMixin, ExistingApp): - pass - - app = App(mcp_port=None) + app = ExistingApp() assert app.aliases["usage"] == "help" - assert app.mcp_snapshot.generation == 0 + assert app._mcp.mcp_snapshot.generation == 0 + app._mcp.mcp_port = None # Exercise snapshot publication without a listener. app.mcp_start() - assert app.mcp_snapshot.generation == 1 - assert ex.Alias("usage", "help") in app.mcp_snapshot.aliases + assert app._mcp.mcp_snapshot.generation == 1 + assert snapshot_api.Alias("usage", "help") in app._mcp.mcp_snapshot.aliases + +def _snapshot_only(app: cmd2.Cmd, leave_out=()) -> None: + """Exercise publication without binding a port or requiring the optional SDK.""" + app._mcp = server_api.McpServer(app, port=None, name="Test application", leave_out=leave_out) -class RebuildApp(ex.McpServerMixin, cmd2.Cmd): + +class RebuildApp(cmd2.Cmd): """Counts starts and stops, and has commands which change which commands there are.""" def __init__(self, **kwargs: Any) -> None: - kwargs.setdefault("mcp_port", None) super().__init__(allow_cli_args=False, multiline_commands=["multi"], **kwargs) + if self._mcp is None: + _snapshot_only(self, kwargs.get("mcp_leave_out", ())) self.extra = ExtraCommands() self.starts = 0 self.stops = 0 @@ -1483,19 +1512,19 @@ def do_fail(self, _: cmd2.Statement) -> None: def _listed(app: Any) -> set[str]: """The names of the commands the application's latest snapshot lists.""" - return _names(app.mcp_snapshot) + return _names(app._mcp.mcp_snapshot) def test_rebuilt_when_a_command_registers_and_unregisters_a_command_set() -> None: app = RebuildApp() app.mcp_start() - first = app.mcp_snapshot.generation + first = app._mcp.mcp_snapshot.generation app.onecmd_plus_hooks("load") assert "extra" in _listed(app) - assert app.mcp_snapshot.generation == first + 1 + assert app._mcp.mcp_snapshot.generation == first + 1 app.onecmd_plus_hooks("unload") assert "extra" not in _listed(app) - assert app.mcp_snapshot.generation == first + 2 + assert app._mcp.mcp_snapshot.generation == first + 2 def test_a_script_publishes_once(tmp_path: Path) -> None: @@ -1503,23 +1532,23 @@ def test_a_script_publishes_once(tmp_path: Path) -> None: script.write_text("# a comment\nload\n\nunload\n", encoding="utf-8") app = RebuildApp() app.mcp_start() - first = app.mcp_snapshot.generation + first = app._mcp.mcp_snapshot.generation app.onecmd_plus_hooks(f"run_script {su.quote(str(script))}") - assert app.mcp_snapshot.generation == first + 1 + assert app._mcp.mcp_snapshot.generation == first + 1 assert "extra" not in _listed(app) - assert app._mcp_depth == 0 + assert app._mcp._mcp_depth == 0 @pytest.mark.parametrize("line", ["", 'echo "no closing quote']) def test_a_blank_line_and_a_syntax_error_publish_once(line: str) -> None: app = RebuildApp() app.mcp_start() - first = app.mcp_snapshot.generation + first = app._mcp.mcp_snapshot.generation app.onecmd_plus_hooks(line) - assert (app.mcp_snapshot.generation, app._mcp_depth) == (first + 1, 0) + assert (app._mcp.mcp_snapshot.generation, app._mcp._mcp_depth) == (first + 1, 0) -@pytest.mark.parametrize("registered", ["before the mixin is set up", "after"]) +@pytest.mark.parametrize("registered", ["during construction", "after"]) def test_a_finalization_hook_which_raises_once_does_not_freeze_the_description(registered: str) -> None: calls = [] @@ -1530,16 +1559,17 @@ def hook(data: cmd2.plugin.CommandFinalizationData) -> cmd2.plugin.CommandFinali return data class RegistersEarly(cmd2.Cmd): - """Below the mixin in the bases, so its __init__ has finished before the mixin's has.""" + """Register a hook before the server starts.""" def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) - if registered == "before the mixin is set up": + if registered == "during construction": self.register_cmdfinalization_hook(hook) - class HookApp(ex.McpServerMixin, RegistersEarly): + class HookApp(RegistersEarly): def __init__(self) -> None: - super().__init__(mcp_port=None, allow_cli_args=False) + super().__init__(allow_cli_args=False) + _snapshot_only(self) self.extra = ExtraCommands() def do_load(self, _: cmd2.Statement) -> None: @@ -1550,7 +1580,7 @@ def do_load(self, _: cmd2.Statement) -> None: app.register_cmdfinalization_hook(hook) app.mcp_start() app.onecmd_plus_hooks("help") # the hook raises; cmd2 reports it and carries on - assert app._mcp_depth == 0 + assert app._mcp._mcp_depth == 0 app.onecmd_plus_hooks("load") assert "extra" in _listed(app) @@ -1558,10 +1588,10 @@ def do_load(self, _: cmd2.Statement) -> None: def test_a_command_which_raises_out_still_publishes() -> None: app = RebuildApp() app.mcp_start() - first = app.mcp_snapshot.generation + first = app._mcp.mcp_snapshot.generation with pytest.raises(RuntimeError, match="out of the command"): app.onecmd_plus_hooks("fail") - assert (app.mcp_snapshot.generation, app._mcp_depth) == (first + 1, 0) + assert (app._mcp.mcp_snapshot.generation, app._mcp._mcp_depth) == (first + 1, 0) def test_arguments_are_passed_through_unchanged() -> None: @@ -1571,18 +1601,18 @@ def test_arguments_are_passed_through_unchanged() -> None: assert len(app.history) == before -@pytest.mark.parametrize("moment", ["mcp_start", "the start of cmdloop", "pre_prompt", "the end of a command"]) +@pytest.mark.parametrize("moment", ["mcp_start", "the start of cmdloop", "the end of a command"]) def test_every_rebuild_is_protected_from_ctrl_c(moment: str, monkeypatch: pytest.MonkeyPatch) -> None: app = RebuildApp(stdin=io.StringIO("")) # cmd2 runs its _eof command at the end of the input, and quits + if moment == "the end of a command": + app.mcp_start() protected = [] - build = app._mcp_build - monkeypatch.setattr(app, "_mcp_build", lambda: (protected.append(bool(app.sigint_protection)), build())[1]) + build = app._mcp._mcp_build + monkeypatch.setattr(app._mcp, "_mcp_build", lambda: (protected.append(bool(app.sigint_protection)), build())[1]) if moment == "mcp_start": app.mcp_start() elif moment == "the start of cmdloop": app.cmdloop() - elif moment == "pre_prompt": - app.pre_prompt() else: app.onecmd_plus_hooks("help") # cmdloop() builds the first description, then one more when _eof ends. @@ -1593,71 +1623,75 @@ def test_every_rebuild_is_protected_from_ctrl_c(moment: str, monkeypatch: pytest @pytest.mark.usefixtures("signal_handlers_restored") def test_a_keyboard_interrupt_from_the_first_build_leaves_the_loop_and_still_stops(monkeypatch: pytest.MonkeyPatch) -> None: app = RebuildApp() - monkeypatch.setattr(app, "_mcp_build", mock.Mock(side_effect=KeyboardInterrupt)) + monkeypatch.setattr(app._mcp, "_mcp_build", mock.Mock(side_effect=KeyboardInterrupt)) with pytest.raises(KeyboardInterrupt): app.cmdloop() # the first build is in _cmdloop(), after cmd2's cmdloop() has installed its handlers - assert (app.starts, app.stops, app._mcp_loops, app._mcp_starting) == (1, 1, 0, False) + assert (app.starts, app.stops, app._mcp._mcp_loops, app._mcp._mcp_starting) == (1, 1, 0, False) def test_a_build_which_fails_keeps_the_previous_snapshot_and_is_reported_once(monkeypatch, capsys) -> None: app = RebuildApp() app.mcp_start() - previous = app.mcp_snapshot - monkeypatch.setattr(app, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) + previous = app._mcp.mcp_snapshot + monkeypatch.setattr(app._mcp, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) for _ in range(3): app.onecmd_plus_hooks("help") - assert app.mcp_snapshot.commands is previous.commands - assert app.mcp_snapshot.generation == previous.generation - assert app.mcp_snapshot.built_at == previous.built_at + assert app._mcp.mcp_snapshot.commands is previous.commands + assert app._mcp.mcp_snapshot.generation == previous.generation + assert app._mcp.mcp_snapshot.built_at == previous.built_at assert capsys.readouterr().err.count("a defect") == 1 def test_a_build_failure_is_kept_until_a_build_succeeds_and_is_reported_again_if_it_returns(monkeypatch, capsys) -> None: app = RebuildApp() app.mcp_start() - good = app.mcp_snapshot - assert app.mcp_build_error is None - build = app._mcp_build - monkeypatch.setattr(app, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) + good = app._mcp.mcp_snapshot + assert app._mcp.mcp_build_error is None + build = app._mcp._mcp_build + monkeypatch.setattr(app._mcp, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) app.onecmd_plus_hooks("help") def answers() -> tuple[Any, ...]: - snapshot = app.mcp_snapshot - return ex.answer_list_commands(snapshot), ex.answer_describe_command(snapshot, "help"), ex.answer_tables(snapshot) + snapshot = app._mcp.mcp_snapshot + return ( + snapshot_api.answer_list_commands(snapshot), + snapshot_api.answer_describe_command(snapshot, "help"), + snapshot_api.answer_tables(snapshot), + ) assert all(answer.stale_reason == "RuntimeError: a defect" for answer in answers()) - assert app.mcp_snapshot.descriptions is good.descriptions - assert "a defect" in app.mcp_build_error # and the mixin knows that it is stale - monkeypatch.setattr(app, "_mcp_build", build) + assert app._mcp.mcp_snapshot.descriptions is good.descriptions + assert "a defect" in app._mcp.mcp_build_error # and the server knows that it is stale + monkeypatch.setattr(app._mcp, "_mcp_build", build) app.onecmd_plus_hooks("help") - assert app.mcp_build_error is None + assert app._mcp.mcp_build_error is None assert all(answer.stale_reason is None for answer in answers()) - assert app.mcp_snapshot.generation == good.generation + 1 - monkeypatch.setattr(app, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) + assert app._mcp.mcp_snapshot.generation == good.generation + 1 + monkeypatch.setattr(app._mcp, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) app.onecmd_plus_hooks("help") assert capsys.readouterr().err.count("a defect") == 2 # once for each time it began to fail def test_a_first_build_which_fails_publishes_an_empty_snapshot_with_the_error(monkeypatch) -> None: app = RebuildApp() - monkeypatch.setattr(app, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) + monkeypatch.setattr(app._mcp, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) app.mcp_start() - assert app.mcp_snapshot.commands == () - assert "a defect" in app.mcp_snapshot.error + assert app._mcp.mcp_snapshot.commands == () + assert "a defect" in app._mcp.mcp_snapshot.error def test_a_changed_build_failure_is_served_until_the_first_success(monkeypatch) -> None: app = RebuildApp() errors = [ValueError("first"), RuntimeError("second"), RuntimeError("second")] - monkeypatch.setattr(app, "_mcp_build", mock.Mock(side_effect=errors)) + monkeypatch.setattr(app._mcp, "_mcp_build", mock.Mock(side_effect=errors)) app.mcp_start() - first = app.mcp_snapshot + first = app._mcp.mcp_snapshot app.onecmd_plus_hooks("help") - second = app.mcp_snapshot + second = app._mcp.mcp_snapshot assert second.generation == first.generation + 1 - assert ex.answer_list_commands(second).error == app.mcp_build_error == "RuntimeError: second" + assert snapshot_api.answer_list_commands(second).error == app._mcp.mcp_build_error == "RuntimeError: second" app.onecmd_plus_hooks("help") - assert app.mcp_snapshot is second + assert app._mcp.mcp_snapshot is second def test_a_command_which_cannot_be_described_is_reported_once(capsys) -> None: @@ -1674,7 +1708,7 @@ def do_broken(self, _: argparse.Namespace) -> None: assert "1 of them could not be described: broken" in app.mcp_status() -def test_the_mixin_leaves_out_the_commands_it_is_told_to() -> None: +def test_the_server_leaves_out_the_commands_it_is_told_to() -> None: app = RebuildApp(mcp_leave_out=["shell"]) app.mcp_start() app.onecmd_plus_hooks("load") @@ -1689,9 +1723,16 @@ def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) self.at_prompts: list[tuple[int, int, frozenset[str]]] = [] # depth, generation, names - def pre_prompt(self) -> None: - super().pre_prompt() - self.at_prompts.append((self._mcp_depth, self.mcp_snapshot.generation, frozenset(_listed(self)))) + def _read_raw_input(self, *args, **kwargs): + before_read = kwargs.get("pre_run") + if before_read is not None: + + def record_prompt(): + before_read() + self.at_prompts.append((self._mcp._mcp_depth, self._mcp.mcp_snapshot.generation, frozenset(_listed(self)))) + + kwargs["pre_run"] = record_prompt + return super()._read_raw_input(*args, **kwargs) class LoopApp(PromptApp): @@ -1706,12 +1747,12 @@ def onecmd_plus_hooks(self, line: str, *args: Any, **kwargs: Any) -> bool: try: return super().onecmd_plus_hooks(line, *args, **kwargs) finally: - if self._mcp_depth == 0: - self.at_ends.append((line, self.mcp_snapshot.generation, frozenset(_listed(self)))) + if self._mcp._mcp_depth == 0: + self.at_ends.append((line, self._mcp.mcp_snapshot.generation, frozenset(_listed(self)))) def do_outer(self, _: cmd2.Statement) -> None: """Enable gated, run a multiline command which needs a second line, and disable gated again.""" - self.seen["outer began"] = (len(self.at_prompts), self.mcp_snapshot.generation) + self.seen["outer began"] = (len(self.at_prompts), self._mcp.mcp_snapshot.generation) self.enable_command("gated") self.onecmd_plus_hooks("multi one") self.disable_command("gated", "not now") @@ -1720,7 +1761,7 @@ def do_outer(self, _: cmd2.Statement) -> None: def do_inner(self, _: cmd2.Statement) -> None: """Run a command loop inside this command.""" self.cmdloop() - self.seen["inner loop returned"] = (self._mcp_loops, frozenset(_listed(self))) + self.seen["inner loop returned"] = (self._mcp._mcp_loops, frozenset(_listed(self))) class PreloopApp(LoopApp): @@ -1778,32 +1819,6 @@ def signal_handlers_restored() -> Iterator[None]: signal.signal(signum, handler) -def test_pre_prompt_publishes_at_the_top_level() -> None: - app = RebuildApp() - app.mcp_start() - before = app.mcp_snapshot.generation - assert app._mcp_depth == 0 - app.pre_prompt() - assert app.mcp_snapshot.generation == before + 1 - - -def test_pre_prompt_publishes_nothing_while_a_command_is_in_progress() -> None: - class PromptsInside(PromptApp): - def do_prompt_inside(self, _: cmd2.Statement) -> None: - self.enable_command("gated") - self.pre_prompt() - - app = PromptsInside() - app.mcp_start() - before = app.mcp_snapshot.generation - app.onecmd_plus_hooks("prompt_inside") - [(depth, generation, names)] = app.at_prompts - assert (depth, generation) == (1, before) - assert "gated" not in names - assert app.mcp_snapshot.generation == before + 1 - assert "gated" in _listed(app) - - @needs_a_pipe_prompt def test_preloop_which_disables_a_command_is_seen_at_the_first_prompt() -> None: app = PreloopApp() @@ -1825,27 +1840,18 @@ def test_pre_prompt_override_which_changes_commands_before_super() -> None: assert "help" in app.at_prompts[1][2] -def test_pre_prompt_override_before_super_called_directly() -> None: - app = ChangesHelpBeforeSuper() - app.mcp_start() - app.pre_prompt() - app.pre_prompt() - assert "help" not in app.at_prompts[0][2] - assert "help" in app.at_prompts[1][2] - - -def test_pre_prompt_override_which_changes_commands_after_super_is_too_late() -> None: - class ChangesHelpAfterSuper(RebuildApp): +@needs_a_pipe_prompt +def test_real_prompt_publishes_changes_made_after_super_returns() -> None: + class ChangesHelpAfterSuper(PromptApp): def pre_prompt(self) -> None: super().pre_prompt() self.disable_command("help", "not now") app = ChangesHelpAfterSuper() - app.mcp_start() - app.pre_prompt() - assert "help" in _listed(app) # the rebuild came before the change - app.onecmd_plus_hooks("") - assert "help" not in _listed(app) + with piped(app) as pipe_input: + type_lines(pipe_input, "quit") + app.cmdloop() + assert "help" not in app.at_prompts[0][2] @needs_a_pipe_prompt @@ -1887,10 +1893,10 @@ class ReadsRecorded(io.StringIO): def __init__(self, text: str) -> None: super().__init__(text) self.app: Any = None - self.at_reads: list[ex.Snapshot] = [] + self.at_reads: list[snapshot_api.Snapshot] = [] def readline(self, *args: Any) -> str: - self.at_reads.append(self.app.mcp_snapshot) + self.at_reads.append(self.app._mcp.mcp_snapshot) return super().readline(*args) @@ -1899,12 +1905,12 @@ class StartsUp(PreloopApp): def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) - self.at_preloop_ends: list[ex.Snapshot] = [] + self.at_preloop_ends: list[snapshot_api.Snapshot] = [] def preloop(self) -> None: self.onecmd_plus_hooks("history") # a command run while the application starts super().preloop() - self.at_preloop_ends.append(self.mcp_snapshot) + self.at_preloop_ends.append(self._mcp.mcp_snapshot) class LoopsInPreloop(RebuildApp): @@ -1913,13 +1919,13 @@ class LoopsInPreloop(RebuildApp): def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) self.preloops = 0 - self.served_after_the_inner_loop: ex.Snapshot | None = None + self.served_after_the_inner_loop: snapshot_api.Snapshot | None = None def preloop(self) -> None: self.preloops += 1 if self.preloops == 1: self.cmdloop() # an inner loop, while the outer one starts - self.served_after_the_inner_loop = self.mcp_snapshot + self.served_after_the_inner_loop = self._mcp.mcp_snapshot self.disable_command("shell", "not now") @@ -1930,7 +1936,7 @@ def test_a_loop_run_inside_preloop_does_not_end_the_start() -> None: assert during is not None assert (during.commands, during.error) == ((), "The description has not been built yet.") assert "shell" not in _listed(app) - assert (app.starts, app.stops, app._mcp_loops, app._mcp_starting) == (1, 1, 0, False) + assert (app.starts, app.stops, app._mcp._mcp_loops, app._mcp._mcp_starting) == (1, 1, 0, False) def test_nothing_is_described_until_preloop_has_returned_when_input_is_not_a_terminal() -> None: @@ -1948,7 +1954,7 @@ def test_nothing_is_described_until_preloop_has_returned_when_input_is_not_a_ter def test_a_second_loop_serves_nothing_from_before_its_own_preloop() -> None: app = StartsUp(stdin=io.StringIO("quit\nquit\n")) app.cmdloop() - last = app.mcp_snapshot + last = app._mcp.mcp_snapshot assert last.error is None app.cmdloop() second = app.at_preloop_ends[1] @@ -1959,27 +1965,27 @@ def test_a_second_loop_serves_nothing_from_before_its_own_preloop() -> None: def test_new_loop_clears_the_previous_loops_build_error(monkeypatch: pytest.MonkeyPatch) -> None: app = StartsUp(stdin=io.StringIO("quit\nquit\n")) with monkeypatch.context() as patch: - patch.setattr(app, "_mcp_build", mock.Mock(side_effect=RuntimeError("previous failure"))) + patch.setattr(app._mcp, "_mcp_build", mock.Mock(side_effect=RuntimeError("previous failure"))) app.cmdloop() - last = app.mcp_snapshot + last = app._mcp.mcp_snapshot assert last.error == "RuntimeError: previous failure" observed = [] - monkeypatch.setattr(app, "preloop", lambda: observed.append((app.mcp_snapshot, app.mcp_build_error))) + monkeypatch.setattr(app, "preloop", lambda: observed.append((app._mcp.mcp_snapshot, app._mcp.mcp_build_error))) app.cmdloop() [(during, build_error)] = observed assert (during.error, build_error) == ("The description has not been built yet.", None) assert during.generation == last.generation + 1 - assert app.mcp_snapshot.error is None + assert app._mcp.mcp_snapshot.error is None def test_a_second_loop_whose_first_build_fails_serves_the_error(monkeypatch: pytest.MonkeyPatch) -> None: app = RebuildApp(stdin=io.StringIO("quit\n")) app.cmdloop() - monkeypatch.setattr(app, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) + monkeypatch.setattr(app._mcp, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) app.stdin = io.StringIO("quit\n") app.cmdloop() - assert app.mcp_snapshot.commands == () - assert app.mcp_snapshot.error == "RuntimeError: a defect" # not that the description has not been built yet + assert app._mcp.mcp_snapshot.commands == () + assert app._mcp.mcp_snapshot.error == "RuntimeError: a defect" # not that the description has not been built yet def test_preloop_which_disables_a_command_is_seen_when_input_is_not_a_terminal() -> None: @@ -2001,7 +2007,7 @@ def preloop(self) -> None: with pytest.raises(RuntimeError, match="in preloop"): app.cmdloop() assert (app.starts, app.stops) == (1, 1) - assert app._mcp_loops == 0 + assert app._mcp._mcp_loops == 0 app.mcp_stop() # again: nothing is raised RebuildApp().mcp_stop() # with no start: nothing is raised @@ -2029,27 +2035,47 @@ def test_cmdloop_in_an_embedded_command_preserves_the_manually_started_server() app = LoopApp(stdin=io.StringIO("load\nquit\n")) app.mcp_start() try: - previous = app.mcp_snapshot + previous = app._mcp.mcp_snapshot app.onecmd_plus_hooks("inner") assert app.seen["inner loop returned"] == (0, frozenset(_names(previous))) assert (app.starts, app.stops) == (1, 0) - assert app.mcp_snapshot.generation == previous.generation + 1 + assert app._mcp.mcp_snapshot.generation == previous.generation + 1 assert "extra" in _listed(app) finally: app.mcp_stop() -def test_a_reader_always_sees_a_whole_snapshot() -> None: # Review Focus 4 +def test_manually_started_listener_survives_a_top_level_cmdloop(sdk) -> None: + app = cmd2.Cmd( + mcp_port=0, mcp_leave_out="shell", allow_cli_args=False, stdin=io.StringIO("alias create usage help\nquit\n") + ) + try: + app.mcp_start() + url = app.mcp_url + assert url is not None + app.cmdloop() + assert app.mcp_url == url + assert "shell" not in names_listed(ask(url, "list_commands")["structured"]) + aliases = ask(url, "list_shortcuts_aliases_macros")["structured"]["aliases"] + assert {"name": "usage", "value": "help"} in aliases + finally: + app.mcp_stop() + stopped = app._mcp.mcp_snapshot + app.onecmd_plus_hooks("alias delete usage") + assert app._mcp.mcp_snapshot is stopped + + +def test_a_reader_always_sees_a_whole_snapshot() -> None: app = RebuildApp() app.mcp_start() - loaded = {app.mcp_snapshot.generation: False} # each generation, and whether it followed a load + loaded = {app._mcp.mcp_snapshot.generation: False} # each generation, and whether it followed a load seen: set[tuple[int, bool]] = set() # each generation the reader saw, and whether extra was listed done = threading.Event() def read() -> None: # The wait lets go of the GIL. A reader which never did would slow each build down many times over. while not done.wait(0.0005): - answer = ex.answer_list_commands(app.mcp_snapshot) + answer = snapshot_api.answer_list_commands(app._mcp.mcp_snapshot) names = {command.name for category in answer.categories for command in category.commands} seen.add((answer.generation, "extra" in names)) @@ -2061,7 +2087,7 @@ def read() -> None: for _ in range(20): for line in ("load", "unload"): app.onecmd_plus_hooks(line) - loaded[app.mcp_snapshot.generation] = line == "load" + loaded[app._mcp.mcp_snapshot.generation] = line == "load" finally: done.set() reading.result() # raises whatever the reader raised @@ -2084,30 +2110,30 @@ def logging_state() -> dict[str, tuple[tuple[logging.Handler, ...], int, bool]]: def no_hold_on_the_logging_is_left() -> Iterator[None]: """After each test, no run holds the logging. A hold which was left is let go first, so the next test starts clean.""" yield - left = ex._shared_logging.holds + left = server_api._shared_logging.holds for _ in range(left): - ex._shared_logging.release() + server_api._shared_logging.release() assert left == 0, f"the test left {left} hold(s) on the logging" def test_shared_logging_makes_its_changes_once_and_puts_them_back() -> None: before = logging_state() - ex._shared_logging.take() + server_api._shared_logging.take() during = logging_state() - for name in ex.LIBRARY_LOGGERS: + for name in server_api.LIBRARY_LOGGERS: assert during[name][2] is False # propagate assert len(during[name][0]) == len(before[name][0]) + 1 assert during[name][1] == before[name][1] # the level is not touched assert during[""] == before[""] - ex._shared_logging.take() + server_api._shared_logging.take() assert logging_state() == during # a second hold changes nothing more - ex._shared_logging.release() + server_api._shared_logging.release() assert logging_state() == during # the first to let go puts nothing back - ex._shared_logging.release() + server_api._shared_logging.release() assert logging_state() == before - ex._shared_logging.release() # redundant cleanup must leave the application's logging intact + server_api._shared_logging.release() # redundant cleanup must leave the application's logging intact assert logging_state() == before - assert ex._shared_logging.holds == 0 + assert server_api._shared_logging.holds == 0 def test_shared_logging_keeps_records_from_the_root_and_from_the_handler_of_last_resort(capsys) -> None: @@ -2115,18 +2141,18 @@ def test_shared_logging_keeps_records_from_the_root_and_from_the_handler_of_last handler = logging.Handler() handler.emit = root_saw.append logging.getLogger().addHandler(handler) - earlier = ex._shared_logging.records() - ex._shared_logging.take() + earlier = server_api._shared_logging.records() + server_api._shared_logging.take() try: logging.getLogger("uvicorn.error").error("from the server") logging.getLogger("mcp.server.lowlevel").warning("from the sdk") logging.getLogger("the.application").error("from the application") finally: - ex._shared_logging.release() + server_api._shared_logging.release() logging.getLogger().removeHandler(handler) assert [record.getMessage() for record in root_saw] == ["from the application"] # Only this test's records: one which another test left need not be one whose message can be formatted. - kept_here = [record for record in ex._shared_logging.records() if all(record is not old for old in earlier)] + kept_here = [record for record in server_api._shared_logging.records() if all(record is not old for old in earlier)] assert {"from the server", "from the sdk"} <= {record.getMessage() for record in kept_here} assert capsys.readouterr().err == "" @@ -2138,10 +2164,10 @@ def test_shared_logging_leaves_the_applications_own_handlers_alone() -> None: logger = logging.getLogger("mcp.server.streamable_http_manager") logger.addHandler(own) try: - ex._shared_logging.take() + server_api._shared_logging.take() logger.warning("asked for") assert own in logger.handlers - ex._shared_logging.release() + server_api._shared_logging.release() assert own in logger.handlers finally: logger.removeHandler(own) @@ -2153,7 +2179,7 @@ def test_root_logger_left_alone_when_it_has_no_handler() -> None: saved, root.handlers = root.handlers, [] try: level = root.level - with ex._root_logger_left_alone(): + with server_api._root_logger_left_alone(): logging.basicConfig(level=logging.INFO) # what MCPServer() does assert (root.handlers, root.level) == ([], level) finally: @@ -2163,9 +2189,9 @@ def test_root_logger_left_alone_when_it_has_no_handler() -> None: def test_shared_logging_release_is_safe_from_two_threads() -> None: before = logging_state() for _ in range(200): - ex._shared_logging.take() - ex._shared_logging.take() - threads = [threading.Thread(target=ex._shared_logging.release) for _ in range(2)] + server_api._shared_logging.take() + server_api._shared_logging.take() + threads = [threading.Thread(target=server_api._shared_logging.release) for _ in range(2)] for thread in threads: thread.start() for thread in threads: @@ -2175,12 +2201,12 @@ def test_shared_logging_release_is_safe_from_two_threads() -> None: def test_shared_logging_records_are_copied_under_the_handlers_lock() -> None: """A server's thread appends a record while holding the handler's lock; the copy waits for it to finish.""" - handler = ex._shared_logging._handler + handler = server_api._shared_logging._handler handler.acquire() held = True try: with ThreadPoolExecutor(max_workers=1) as executor: - copying = executor.submit(ex._shared_logging.records) + copying = executor.submit(server_api._shared_logging.records) with pytest.raises(TimeoutError): copying.result(timeout=0.2) handler.release() @@ -2192,7 +2218,7 @@ def test_shared_logging_records_are_copied_under_the_handlers_lock() -> None: # --------------------------------------------------------------------------------------------------------------------- -# The server itself. These tests need the MCP SDK: "uv run --group examples pytest ...". +# The server itself. These tests need the MCP SDK: "uv run --extra mcp pytest ...". # --------------------------------------------------------------------------------------------------------------------- @@ -2202,8 +2228,8 @@ def _require_sdk() -> None: mcp.server.mcpserver is new in version 2, and the example imports it, so it is what is asked for: "mcp" alone would let version 1 through, and the test would fail when the server started instead of being skipped. """ - if os.environ.get("CMD2_EXAMPLE_TESTS_NEED_SDK"): - import mcp.server.mcpserver # noqa: F401 (a failure here fails the test: the CI job of Task 10 sets the variable) + if os.environ.get("CMD2_MCP_TESTS_NEED_SDK"): + import mcp.server.mcpserver # noqa: F401 import uvicorn # noqa: F401 return @@ -2222,10 +2248,10 @@ def test_the_sdk_check_wants_version_2_of_the_sdk(monkeypatch: pytest.MonkeyPatc monkeypatch.setitem(sys.modules, "mcp", ModuleType("mcp")) monkeypatch.setitem(sys.modules, "uvicorn", ModuleType("uvicorn")) monkeypatch.setitem(sys.modules, "mcp.server.mcpserver", None) - monkeypatch.delenv("CMD2_EXAMPLE_TESTS_NEED_SDK", raising=False) + monkeypatch.delenv("CMD2_MCP_TESTS_NEED_SDK", raising=False) with pytest.raises(pytest.skip.Exception): _require_sdk() - monkeypatch.setenv("CMD2_EXAMPLE_TESTS_NEED_SDK", "1") + monkeypatch.setenv("CMD2_MCP_TESTS_NEED_SDK", "1") with pytest.raises(ImportError): _require_sdk() @@ -2299,6 +2325,7 @@ def run_without_sdk(body: str) -> subprocess.CompletedProcess[str]: "sys.modules['uvicorn'] = None\n" "import importlib.util, json, logging\n" "import cmd2\n" + "from cmd2 import _mcp_server as server_api, _mcp_snapshot as snapshot_api\n" f"spec = importlib.util.spec_from_file_location('ex', {str(EXAMPLE)!r})\n" "ex = importlib.util.module_from_spec(spec)\n" "sys.modules['ex'] = ex\n" @@ -2325,6 +2352,7 @@ def run_with_the_example(body: str, *args: str) -> subprocess.CompletedProcess[s preamble = ( "import importlib.util, json, logging, signal, sys, threading\n" "import cmd2\n" + "from cmd2 import _mcp_server as server_api, _mcp_snapshot as snapshot_api\n" f"spec = importlib.util.spec_from_file_location('ex', {str(EXAMPLE)!r})\n" "ex = importlib.util.module_from_spec(spec)\n" "sys.modules['ex'] = ex\n" @@ -2392,7 +2420,7 @@ def __init__(self, **kwargs: Any) -> None: def do_probe(self, _: cmd2.Statement) -> None: url = self.mcp_url - self.probes.append((self._mcp_run, url, ask(url, "list_commands")["structured"] if url else None)) + self.probes.append((self._mcp._mcp_run, url, ask(url, "list_commands")["structured"] if url else None)) def test_serves_three_read_only_tools(serving) -> None: @@ -2405,11 +2433,11 @@ def test_serves_three_read_only_tools(serving) -> None: def test_tools_return_what_the_snapshot_holds(serving) -> None: listed = ask(serving.mcp_url, "list_commands") assert listed["is_error"] is False - assert listed["structured"] == as_json(ex.answer_list_commands(serving.mcp_snapshot)) + assert listed["structured"] == as_json(snapshot_api.answer_list_commands(serving._mcp.mcp_snapshot)) described = ask(serving.mcp_url, "describe_command", {"command": "help"}) - assert described["structured"] == as_json(ex.answer_describe_command(serving.mcp_snapshot, "help")) + assert described["structured"] == as_json(snapshot_api.answer_describe_command(serving._mcp.mcp_snapshot, "help")) tables = ask(serving.mcp_url, "list_shortcuts_aliases_macros") - assert tables["structured"] == as_json(ex.answer_tables(serving.mcp_snapshot)) + assert tables["structured"] == as_json(snapshot_api.answer_tables(serving._mcp.mcp_snapshot)) def test_describe_command_preserves_a_nonfinite_default_over_mcp(sdk) -> None: @@ -2458,7 +2486,9 @@ def do_read(self, _: argparse.Namespace) -> None: def test_every_tool_says_when_there_is_no_description(serving) -> None: - serving.mcp_snapshot = ex.failed_snapshot(serving.mcp_snapshot.generation + 1, "RuntimeError: a defect") + serving._mcp.mcp_snapshot = snapshot_api.failed_snapshot( + serving._mcp.mcp_snapshot.generation + 1, "RuntimeError: a defect" + ) assert ask(serving.mcp_url, "list_commands")["structured"]["error"] == "RuntimeError: a defect" described = ask(serving.mcp_url, "describe_command", {"command": "help"}) assert described["is_error"] is True @@ -2474,7 +2504,7 @@ def test_describing_an_unknown_command_is_a_tool_error_which_names_what_exists(s def test_stale_snapshot_warns_clients_about_changes_until_recovery(serving, monkeypatch) -> None: with monkeypatch.context() as patch: - patch.setattr(serving, "_mcp_build", mock.Mock(side_effect=[RuntimeError("first"), RuntimeError("second")])) + patch.setattr(serving._mcp, "_mcp_build", mock.Mock(side_effect=[RuntimeError("first"), RuntimeError("second")])) serving.onecmd_plus_hooks("load") assert ask(serving.mcp_url, "list_commands")["structured"]["stale_reason"] == "RuntimeError: first" serving.onecmd_plus_hooks("") @@ -2515,7 +2545,7 @@ def test_stopping_ends_the_worker_frees_the_port_and_writes_nothing(sdk, capfd) before = logging_state() app = RebuildApp(mcp_port=0) app.mcp_start() - run = app._mcp_run + run = app._mcp._mcp_run ask(app.mcp_url, "list_commands") app.mcp_stop() assert not run.worker.is_alive() @@ -2548,12 +2578,12 @@ def test_an_inner_cmdloop_starts_no_second_server_and_leaves_the_first_serving(s (inside_run, inside_url, inside), (after_run, after_url, after) = app.probes assert inside is not None assert after is not None - assert inside_run is after_run is app._mcp_run - assert inside_url == after_url == app._mcp_run.url + assert inside_run is after_run is app._mcp._mcp_run + assert inside_url == after_url == app._mcp._mcp_run.url def test_a_second_application_on_the_same_port_warns_and_runs_without_a_server(serving, capsys) -> None: - port = serving._mcp_run.port + port = serving._mcp._mcp_run.port capsys.readouterr() second = RebuildApp(mcp_port=port) second.mcp_start() @@ -2563,7 +2593,7 @@ def test_a_second_application_on_the_same_port_warns_and_runs_without_a_server(s assert str(port) in err assert ask(serving.mcp_url, "list_commands")["is_error"] is False status = second.mcp_status() - assert status[0] == f"No MCP server: {second._mcp_run.problem}" + assert status[0] == f"No MCP server: {second._mcp._mcp_run.problem}" assert f"port {port}: OSError" in status[0] @@ -2571,7 +2601,7 @@ def test_a_replacement_binds_at_once_while_a_client_is_still_connected(sdk) -> N first = RebuildApp(mcp_port=0) first.mcp_start() assert first.mcp_url is not None, first.mcp_status() - port = first._mcp_run.port + port = first._mcp._mcp_run.port with socket.create_connection(("127.0.0.1", port), timeout=10): first.mcp_stop() second = RebuildApp(mcp_port=port) @@ -2603,10 +2633,10 @@ def test_without_the_sdk_the_application_warns_and_carries_on(monkeypatch, capsy app = RebuildApp(mcp_port=0) app.mcp_start() assert app.mcp_url is None - assert app.mcp_snapshot.commands + assert app._mcp.mcp_snapshot.commands err = capsys.readouterr().err assert err.count("MCP server not started") == 1 - assert "--group examples" in err + assert "pip install 'cmd2[mcp]'" in err assert app.mcp_status()[0].startswith("No MCP server") assert logging_state() == before @@ -2620,7 +2650,7 @@ def test_a_start_which_fails_part_of_the_way_is_undone(step: str, sdk, capsys, m handler = signal.getsignal(signal.SIGINT) app = RebuildApp(mcp_port=0) if step == "_mcp_asgi_app()": - monkeypatch.setattr(app, "_mcp_asgi_app", mock.Mock(side_effect=part_way)) + monkeypatch.setattr(app._mcp, "_mcp_asgi_app", mock.Mock(side_effect=part_way)) elif step == "uvicorn.Server": monkeypatch.setattr(uvicorn, "Server", mock.Mock(side_effect=part_way)) else: @@ -2633,10 +2663,10 @@ def start_any_but_a_worker(thread: threading.Thread) -> None: monkeypatch.setattr(threading.Thread, "start", start_any_but_a_worker) app.mcp_start() - run = app._mcp_run + run = app._mcp._mcp_run assert run.port != 0 # the socket was bound before the step failed assert can_bind(run.port) - assert ex._shared_logging.holds == 0 + assert server_api._shared_logging.holds == 0 assert logging_state() == before err = capsys.readouterr().err assert err.count("MCP server not started") == 1 @@ -2652,16 +2682,16 @@ def start_any_but_a_worker(thread: threading.Thread) -> None: def test_ctrl_c_part_of_the_way_through_a_start_is_undone_by_the_loop(sdk, monkeypatch) -> None: before = logging_state() app = RebuildApp(mcp_port=0) - monkeypatch.setattr(app, "_mcp_asgi_app", mock.Mock(side_effect=KeyboardInterrupt)) - releases = mock.Mock(wraps=ex._shared_logging.release) - monkeypatch.setattr(ex._shared_logging, "release", releases) - with pytest.raises(KeyboardInterrupt): + monkeypatch.setattr(app._mcp, "_mcp_asgi_app", mock.Mock(side_effect=KeyboardInterrupt)) + releases = mock.Mock(wraps=server_api._shared_logging.release) + monkeypatch.setattr(server_api._shared_logging, "release", releases) + with mock.patch.object(app._mcp, "mcp_stop", wraps=app._mcp.mcp_stop) as stop, pytest.raises(KeyboardInterrupt): app.cmdloop() - assert app.stops == 2 # the start undid what it got done, and then the loop's stop found nothing left to do + assert stop.call_count == 2 # the start undid what it got done, and then the loop's stop found nothing left to do releases.assert_called_once() # so the hold on the logging was let go of once - assert app._mcp_run.port != 0 # the socket was bound before the interrupt - assert can_bind(app._mcp_run.port) - assert ex._shared_logging.holds == 0 + assert app._mcp._mcp_run.port != 0 # the socket was bound before the interrupt + assert can_bind(app._mcp._mcp_run.port) + assert server_api._shared_logging.holds == 0 assert logging_state() == before @@ -2693,22 +2723,22 @@ def pre_prompt(self) -> None: def test_status_lines(serving, monkeypatch) -> None: - snapshot = serving.mcp_snapshot + snapshot = serving._mcp.mcp_snapshot categories = {command.category for command in snapshot.commands} status = serving.mcp_status() - assert status[0] == f"Serving http://127.0.0.1:{serving._mcp_run.port}/mcp" + assert status[0] == f"Serving http://127.0.0.1:{serving._mcp._mcp_run.port}/mcp" [description] = [line for line in status if line.startswith(f"Description {snapshot.generation}, built ")] assert re.fullmatch(rf"Description {snapshot.generation}, built \d\d:\d\d:\d\d: .*", description) assert description.endswith(f": {len(snapshot.commands)} commands in {len(categories)} categories") - build = serving._mcp_build - monkeypatch.setattr(serving, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) + build = serving._mcp._mcp_build + monkeypatch.setattr(serving._mcp, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) serving.onecmd_plus_hooks("help") failed = serving.mcp_status() assert failed[0] == status[0] [stale] = [line for line in failed if line.startswith("The description is out of date")] assert "a defect" in stale assert description in failed # the generation shown is unchanged - monkeypatch.setattr(serving, "_mcp_build", build) + monkeypatch.setattr(serving._mcp, "_mcp_build", build) serving.onecmd_plus_hooks("help") assert not any(line.startswith("The description is out of date") for line in serving.mcp_status()) serving.mcp_stop() @@ -2716,15 +2746,15 @@ def test_status_lines(serving, monkeypatch) -> None: def test_a_start_while_serving_makes_no_new_run_binds_nothing_and_warns_of_nothing(serving, capfd, monkeypatch) -> None: - run = serving._mcp_run + run = serving._mcp._mcp_run capfd.readouterr() binds = mock.Mock(wraps=socket.create_server) monkeypatch.setattr(socket, "create_server", binds) serving.mcp_start() - assert serving._mcp_run is run + assert serving._mcp._mcp_run is run assert serving.mcp_url == run.url binds.assert_not_called() - assert ex._shared_logging.holds == 1 + assert server_api._shared_logging.holds == 1 assert capfd.readouterr() == ("", "") @@ -2732,20 +2762,24 @@ def test_ctrl_c_part_of_the_way_through_a_direct_start_is_undone_by_the_start(sd before = logging_state() app = RebuildApp(mcp_port=0) try: - with mock.patch.object(app, "_mcp_asgi_app", side_effect=KeyboardInterrupt), pytest.raises(KeyboardInterrupt): + with ( + mock.patch.object(app._mcp, "mcp_stop", wraps=app._mcp.mcp_stop) as stop, + mock.patch.object(app._mcp, "_mcp_asgi_app", side_effect=KeyboardInterrupt), + pytest.raises(KeyboardInterrupt), + ): app.mcp_start() # called directly, so no cmdloop() is there to undo what it got done - interrupted = app._mcp_run - assert app.stops == 1 # the start's own + interrupted = app._mcp._mcp_run + stop.assert_called_once() assert interrupted.port != 0 # it had bound its socket and taken a hold on the logging assert interrupted.stop_requested assert can_bind(interrupted.port) - assert ex._shared_logging.holds == 0 + assert server_api._shared_logging.holds == 0 assert logging_state() == before assert app.mcp_status()[0] == "No MCP server: it was stopped" app.mcp_start() assert app.mcp_url is not None, app.mcp_status() - assert app._mcp_run is not interrupted - assert ex._shared_logging.holds == 1 # the new run's alone + assert app._mcp._mcp_run is not interrupted + assert server_api._shared_logging.holds == 1 # the new run's alone finally: app.mcp_stop() # whichever run is the last, even when an assertion above failed assert logging_state() == before @@ -2771,7 +2805,7 @@ def test_status_says_a_run_ended_by_itself_once_its_worker_has_recorded_how(sdk) entered, release = threading.Event(), threading.Event() app = RebuildApp(mcp_port=0) app.mcp_start() - run = app._mcp_run + run = app._mcp._mcp_run try: hold_the_worker_as_it_lets_go_of_the_logging(run, entered, release) assert app.mcp_status()[0] == f"Serving {run.url}" @@ -2791,10 +2825,11 @@ def test_status_says_a_run_ended_by_itself_once_its_worker_has_recorded_how(sdk) def test_status_prefers_a_problem_then_a_failure_then_a_stop_then_how_the_worker_ended() -> None: - assert RebuildApp(mcp_port=None).mcp_status()[0] == "No MCP server: --no-mcp was given" + assert RebuildApp(mcp_port=None).mcp_status()[0] == "No MCP server: no port was configured" app = RebuildApp(mcp_port=0) assert app.mcp_status()[0] == "No MCP server: it has not been started" - run = app._mcp_run = ex._Run(0) # a run with no worker, whose fields are set here as its threads would set them + # Set the fields as the worker would set them when it exits. + run = app._mcp._mcp_run = server_api._Run(0) assert app.mcp_status()[0] == "No MCP server: it has not been started" # nothing recorded: not "ended by itself" run.outcome = "stopped" assert app.mcp_status()[0] == "No MCP server: it ended by itself (stopped)" @@ -2808,7 +2843,7 @@ def test_status_prefers_a_problem_then_a_failure_then_a_stop_then_how_the_worker def test_a_stop_which_ctrl_c_cut_short_is_finished_by_the_next_stop() -> None: app = RebuildApp(mcp_port=0) - run = app._mcp_run = ex._Run(0) # a run whose fields are set here as a start would set them + run = app._mcp._mcp_run = server_api._Run(0) # a run whose fields are set here as a start would set them told = threading.Event() class Server: @@ -2835,7 +2870,7 @@ def run(self, sockets: list[socket.socket]) -> None: run.sock = socket.socket() run.take_logging() # The real worker's target, which records how it ended and lets go of the logging as its last act. - run.worker = threading.Thread(target=ex.McpServerMixin._mcp_serve, args=(run,), name="mcp-server-test", daemon=True) + run.worker = threading.Thread(target=server_api.McpServer._mcp_serve, args=(run,), name="mcp-server-test", daemon=True) run.worker.start() try: with pytest.raises(KeyboardInterrupt): @@ -2855,7 +2890,7 @@ def run(self, sockets: list[socket.socket]) -> None: def test_a_wait_which_ctrl_c_cut_short_leaves_the_logging_to_a_worker_which_runs_on() -> None: app = RebuildApp(mcp_port=0) - run = app._mcp_run = ex._Run(0) # a run whose fields are set here as a start would set them + run = app._mcp._mcp_run = server_api._Run(0) # a run whose fields are set here as a start would set them resume = threading.Event() class Server: @@ -2869,9 +2904,9 @@ def run(self, sockets: list[socket.socket]) -> None: run.server = Server() run.sock = socket.socket() - holds = ex._shared_logging.holds + holds = server_api._shared_logging.holds run.take_logging() - worker = threading.Thread(target=ex.McpServerMixin._mcp_serve, args=(run,), name="mcp-server-test", daemon=True) + worker = threading.Thread(target=server_api.McpServer._mcp_serve, args=(run,), name="mcp-server-test", daemon=True) worker.start() run.worker = worker @@ -2887,22 +2922,23 @@ def join_as_python_3_11_does(timeout: float | None = None) -> None: app.mcp_stop() assert run.abandoned is True # given up on: it had recorded no outcome assert run._holds_logging is True # still the worker's to let go of, as its last act - assert ex._shared_logging.holds == holds + 1 + assert server_api._shared_logging.holds == holds + 1 assert app.mcp_status()[1] == f"The worker of run {run.number} was cancelled, and has not ended yet" finally: resume.set() threading.Thread.join(worker, 30) run.sock.close() assert run.outcome == "cancelled" - assert (run._holds_logging, ex._shared_logging.holds) == (False, holds) + assert (run._holds_logging, server_api._shared_logging.holds) == (False, holds) def test_a_release_of_the_logging_which_ctrl_c_interrupts_is_finished_all_the_same(monkeypatch: pytest.MonkeyPatch) -> None: app = RebuildApp(mcp_port=0) - run = app._mcp_run = ex._Run(0) # a start which failed before it had a worker: the main thread lets go of the logging - holds = ex._shared_logging.holds + # Startup failed before a worker started, so the main thread must release the logging. + run = app._mcp._mcp_run = server_api._Run(0) + holds = server_api._shared_logging.holds run.take_logging() - release = ex._shared_logging.release + release = server_api._shared_logging.release interrupted: list[bool] = [] def interrupt_then_release() -> None: @@ -2911,16 +2947,16 @@ def interrupt_then_release() -> None: signal.raise_signal(signal.SIGINT) # Ctrl-C, just as the run lets go of its hold release() - monkeypatch.setattr(ex._shared_logging, "release", interrupt_then_release) + monkeypatch.setattr(server_api._shared_logging, "release", interrupt_then_release) handler = signal.signal(signal.SIGINT, signal.default_int_handler) # Python's own, whatever the test runner installed try: with pytest.raises(KeyboardInterrupt): app.mcp_stop() app.mcp_stop() # the stop was cut short, so this one finishes it - left = (run._holds_logging, ex._shared_logging.holds) # read before the clean-up below can change it + left = (run._holds_logging, server_api._shared_logging.holds) # read before the clean-up below can change it finally: signal.signal(signal.SIGINT, handler) - while ex._shared_logging.holds > holds: + while server_api._shared_logging.holds > holds: release() # so that no later test finds the logging changed assert interrupted == [True] assert left == (False, holds) @@ -2930,13 +2966,13 @@ def interrupt_then_release() -> None: def test_status_shows_a_library_record_whose_arguments_do_not_fit_its_format() -> None: app = RebuildApp() malformed = logging.LogRecord("uvicorn.error", logging.ERROR, __file__, 0, "%s and %s", ("only one",), None) - handler = ex._shared_logging._handler + handler = server_api._shared_logging._handler try: - ex._shared_logging.take() + server_api._shared_logging.take() try: logging.getLogger("uvicorn.error").handle(malformed) finally: - ex._shared_logging.release() + server_api._shared_logging.release() status = app.mcp_status() finally: # The kept records are the whole process's: take this one out again, so that no later test meets it. @@ -2950,7 +2986,14 @@ def test_status_shows_a_library_record_whose_arguments_do_not_fit_its_format() - # --------------------------------------------------------------------------------------------------------------------- -class FailsAtOnce(RebuildApp): +def _with_server(server_class: type[server_api.McpServer]) -> RebuildApp: + """Use a transport with controlled startup or shutdown in an otherwise ordinary cmd2 application.""" + app = RebuildApp(mcp_port=0) + app._mcp = server_class(app=app, port=0, name="test server", leave_out=()) + return app + + +class FailsAtOnce(server_api.McpServer): """Its server fails its startup, so uvicorn ends with SystemExit and never takes the socket.""" def _mcp_asgi_app(self) -> Any: @@ -2964,7 +3007,7 @@ async def lifespan(_: Starlette) -> AsyncIterator[None]: return Starlette(lifespan=lifespan) -class StartsTooSlowly(RebuildApp): +class StartsTooSlowly(server_api.McpServer): """Its server's startup is held until the test lets it go, past both of the main thread's waits.""" MCP_START_TIMEOUT = 0.3 @@ -3006,13 +3049,13 @@ def no_thread_exceptions(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: @pytest.fixture def given_up_on(sdk: None) -> Iterator[Any]: """A StartsTooSlowly whose start was given up on, with its worker still held.""" - app = StartsTooSlowly(mcp_port=0) + app = _with_server(StartsTooSlowly) app.mcp_start() - worker = app._mcp_run.worker + worker = app._mcp._mcp_run.worker try: yield app finally: - app.hold.set() + app._mcp.hold.set() worker.join(timeout=30) assert not worker.is_alive() @@ -3045,19 +3088,19 @@ def recorded_at_the_root(level: int) -> Iterator[list[logging.LogRecord]]: def from_the_libraries(records: list[logging.LogRecord]) -> list[str]: """The names of the loggers which logged those of the records that came from a library the server uses.""" - return [record.name for record in records if record.name.partition(".")[0] in ex.LIBRARY_LOGGERS] + return [record.name for record in records if record.name.partition(".")[0] in server_api.LIBRARY_LOGGERS] def propagating() -> list[str]: """The library loggers whose propagate is on.""" - return [name for name in ex.LIBRARY_LOGGERS if logging.getLogger(name).propagate] + return [name for name in server_api.LIBRARY_LOGGERS if logging.getLogger(name).propagate] def test_a_server_which_fails_at_once(sdk, capfd, no_thread_exceptions) -> None: before = logging_state() - app = FailsAtOnce(mcp_port=0) + app = _with_server(FailsAtOnce) app.mcp_start() - run = app._mcp_run + run = app._mcp._mcp_run assert run.port != 0 # the socket was bound, so can_bind() below is not vacuous assert not run.worker.is_alive() assert (run.outcome, run.abandoned) == ("failed", False) @@ -3072,9 +3115,9 @@ def test_a_server_which_fails_at_once(sdk, capfd, no_thread_exceptions) -> None: def test_a_server_which_starts_too_slowly_is_given_up_on(sdk, capfd, no_thread_exceptions) -> None: before = logging_state() - app = StartsTooSlowly(mcp_port=0) + app = _with_server(StartsTooSlowly) app.mcp_start() - run = app._mcp_run + run = app._mcp._mcp_run try: assert run.worker.is_alive() assert (run.stop_requested, run.abandoned, run.outcome) == (True, True, None) @@ -3089,19 +3132,19 @@ def test_a_server_which_starts_too_slowly_is_given_up_on(sdk, capfd, no_thread_e assert propagating() == [] assert capfd.readouterr() == ("", f"{run.problem}\n") finally: - app.hold.set() + app._mcp.hold.set() run.worker.join(timeout=30) assert not run.worker.is_alive() def test_the_worker_which_was_given_up_on_ends_quietly_when_released(sdk, capfd, no_thread_exceptions) -> None: before = logging_state() - app = StartsTooSlowly(mcp_port=0) + app = _with_server(StartsTooSlowly) app.mcp_start() - run = app._mcp_run + run = app._mcp._mcp_run try: capfd.readouterr() # the warning, which the test above looks at - app.hold.set() + app._mcp.hold.set() run.worker.join(timeout=30) assert not run.worker.is_alive() assert run.outcome == "cancelled" @@ -3113,7 +3156,7 @@ def test_the_worker_which_was_given_up_on_ends_quietly_when_released(sdk, capfd, assert f"The worker of run {run.number} was cancelled, and has ended (cancelled: {run.detail})" in status assert logging_state() == before finally: - app.hold.set() + app._mcp.hold.set() run.worker.join(timeout=30) assert not run.worker.is_alive() @@ -3121,9 +3164,9 @@ def test_the_worker_which_was_given_up_on_ends_quietly_when_released(sdk, capfd, def test_two_runs_alive_at_once_first_ends_first(sdk, no_thread_exceptions) -> None: with recorded_at_the_root(logging.DEBUG) as root_saw: before = logging_state() - first = StartsTooSlowly(mcp_port=0) + first = _with_server(StartsTooSlowly) first.mcp_start() - held = first._mcp_run.worker + held = first._mcp._mcp_run.worker try: assert held.is_alive() assert propagating() == [] # the held worker still holds the logging @@ -3131,16 +3174,16 @@ def test_two_runs_alive_at_once_first_ends_first(sdk, no_thread_exceptions) -> N second.mcp_start() try: assert ask(second.mcp_url, "list_commands")["is_error"] is False - first.hold.set() + first._mcp.hold.set() held.join(timeout=30) assert not held.is_alive() - assert first._mcp_run.outcome == "cancelled" + assert first._mcp._mcp_run.outcome == "cancelled" assert propagating() == [] # the second still holds it assert ask(second.mcp_url, "list_commands")["is_error"] is False finally: second.mcp_stop() finally: - first.hold.set() + first._mcp.hold.set() held.join(timeout=30) assert not held.is_alive() assert from_the_libraries(root_saw) == [] @@ -3150,9 +3193,9 @@ def test_two_runs_alive_at_once_first_ends_first(sdk, no_thread_exceptions) -> N def test_two_runs_alive_at_once_second_ends_first(sdk, no_thread_exceptions) -> None: with recorded_at_the_root(logging.DEBUG) as root_saw: before = logging_state() - first = StartsTooSlowly(mcp_port=0) + first = _with_server(StartsTooSlowly) first.mcp_start() - held = first._mcp_run.worker + held = first._mcp._mcp_run.worker try: second = RebuildApp(mcp_port=0) second.mcp_start() @@ -3160,14 +3203,14 @@ def test_two_runs_alive_at_once_second_ends_first(sdk, no_thread_exceptions) -> assert ask(second.mcp_url, "list_commands")["is_error"] is False finally: second.mcp_stop() - assert second._mcp_run.outcome == "stopped" + assert second._mcp._mcp_run.outcome == "stopped" assert held.is_alive() assert propagating() == [] # the first worker can still log, so it still holds the logging - first.hold.set() + first._mcp.hold.set() held.join(timeout=30) - assert first._mcp_run.outcome == "cancelled" + assert first._mcp._mcp_run.outcome == "cancelled" finally: - first.hold.set() + first._mcp.hold.set() held.join(timeout=30) assert not held.is_alive() assert from_the_libraries(root_saw) == [] @@ -3175,21 +3218,21 @@ def test_two_runs_alive_at_once_second_ends_first(sdk, no_thread_exceptions) -> def test_status_of_one_run_is_not_changed_by_another_runs_error(no_thread_exceptions, given_up_on) -> None: - first = given_up_on._mcp_run + first = given_up_on._mcp._mcp_run second = RebuildApp(mcp_port=0) second.mcp_start() try: assert ask(second.mcp_url, "list_commands")["is_error"] is False - given_up_on.hold.set() + given_up_on._mcp.hold.set() first.worker.join(timeout=30) assert first.outcome == "cancelled" status = second.mcp_status() - assert status[0] == f"Serving {second._mcp_run.url}" + assert status[0] == f"Serving {second._mcp._mcp_run.url}" heading = status.index("Recent log records from every MCP server this process has run:") from_first = [index for index, line in enumerate(status) if f" mcp-server-{first.number} ERROR: " in line] assert from_first # the error which the released worker logged: nothing has been logged since assert min(from_first) > heading - assert (second._mcp_run.problem, second._mcp_run.detail, second._mcp_run.outcome) == (None, None, None) + assert (second._mcp._mcp_run.problem, second._mcp._mcp_run.detail, second._mcp._mcp_run.outcome) == (None, None, None) assert ask(second.mcp_url, "list_commands")["is_error"] is False finally: second.mcp_stop() @@ -3204,14 +3247,14 @@ def test_no_other_library_logs_at_info_or_above(sdk, no_thread_exceptions) -> No assert ask(app.mcp_url, "describe_command", {"command": "nonesuch"})["is_error"] is True finally: app.mcp_stop() - FailsAtOnce(mcp_port=0).mcp_start() - slow = StartsTooSlowly(mcp_port=0) + _with_server(FailsAtOnce).mcp_start() + slow = _with_server(StartsTooSlowly) slow.mcp_start() - held = slow._mcp_run.worker + held = slow._mcp._mcp_run.worker try: assert held.is_alive() finally: - slow.hold.set() # what a worker logs when it resumes after it was given up on is looked at too + slow._mcp.hold.set() # what a worker logs when it resumes after it was given up on is looked at too held.join(timeout=30) assert not held.is_alive() assert [(record.name, record.levelname, record.getMessage()) for record in root_saw] == [] @@ -3242,9 +3285,10 @@ def test_logging_is_as_it_was(state: str, ending: str, sdk, capfd, no_thread_exc own_message = "" try: before = logging_state() - app = {"stopped": RebuildApp, "failed at once": FailsAtOnce, "started too slowly": StartsTooSlowly}[ending](mcp_port=0) + server_class = {"stopped": server_api.McpServer, "failed at once": FailsAtOnce, "started too slowly": StartsTooSlowly} + app = _with_server(server_class[ending]) app.mcp_start() - run = app._mcp_run + run = app._mcp._mcp_run try: assert (app.mcp_url is not None) == (ending == "stopped"), app.mcp_status() if state == "root with no handler": @@ -3262,8 +3306,8 @@ def test_logging_is_as_it_was(state: str, ending: str, sdk, capfd, no_thread_exc own_message = "the.application: its own message\n" finally: app.mcp_stop() - if isinstance(app, StartsTooSlowly): - app.hold.set() + if isinstance(app._mcp, StartsTooSlowly): + app._mcp.hold.set() run.worker.join(timeout=30) assert not run.worker.is_alive() if state == "handlers the application attached": @@ -3273,7 +3317,9 @@ def test_logging_is_as_it_was(state: str, ending: str, sdk, capfd, no_thread_exc # The application's handler received each of those records, as the server's own handler did. manager = attached["mcp.server.streamable_http_manager"].records kept = [ - record for record in ex._shared_logging.records() if record.name == "mcp.server.streamable_http_manager" + record + for record in server_api._shared_logging.records() + if record.name == "mcp.server.streamable_http_manager" ] assert manager assert kept[-len(manager) :] == manager @@ -3301,7 +3347,7 @@ def test_logging_is_as_it_was(state: str, ending: str, sdk, capfd, no_thread_exc hold = threading.Event() -class App(ex.McpServerMixin, cmd2.Cmd): +class HeldServer(server_api.McpServer): MCP_START_TIMEOUT = 0.3 MCP_STOP_TIMEOUT = 0.3 @@ -3319,6 +3365,12 @@ async def lifespan(starlette): return app +def make_app(**kwargs): + app = cmd2.Cmd(mcp_port=0, allow_cli_args=False, **kwargs) + app._mcp = HeldServer(app, port=0, name="interrupt test", leave_out=()) + return app + + def logging_state(): loggers = [logging.getLogger(name) for name in ("", "uvicorn", "mcp")] return [(list(logger.handlers), logger.level, logger.propagate) for logger in loggers] @@ -3350,7 +3402,7 @@ def start_then_interrupt(thread): threading.Thread.start = start_then_interrupt -app = App(mcp_port=0, allow_cli_args=False, stdin=io.StringIO("quit\\n")) +app = make_app(stdin=io.StringIO("quit\\n")) try: getattr(app, sys.argv[1])() except KeyboardInterrupt: @@ -3359,7 +3411,7 @@ def start_then_interrupt(thread): interrupted = False finally: threading.Thread.start = start -run = app._mcp_run +run = app._mcp._mcp_run found = { "interrupted": interrupted, "handler restored": signal.getsignal(signal.SIGINT) is handler, @@ -3368,8 +3420,8 @@ def start_then_interrupt(thread): "alive": launched[0].is_alive() if launched else None, "port bound": run.port != 0, "can bind": can_bind(run.port), - "holds": ex._shared_logging.holds, - "propagating": [name for name in ex.LIBRARY_LOGGERS if logging.getLogger(name).propagate], + "holds": server_api._shared_logging.holds, + "propagating": [name for name in server_api.LIBRARY_LOGGERS if logging.getLogger(name).propagate], "stop requested, abandoned, outcome": [run.stop_requested, run.abandoned, run.outcome], } hold.set() @@ -3383,7 +3435,7 @@ def start_then_interrupt(thread): # Ctrl-C just after the start has taken the logging, or bound its socket: sys.argv[1] says which. INTERRUPTED_AS_IT_TAKES = """ -take, create_server = ex._shared_logging.take, socket.create_server +take, create_server = server_api._shared_logging.take, socket.create_server def take_then_interrupt(): @@ -3398,10 +3450,10 @@ def bind_then_interrupt(*args, **kwargs): if sys.argv[1] == "taking the logging": - ex._shared_logging.take = take_then_interrupt + server_api._shared_logging.take = take_then_interrupt else: socket.create_server = bind_then_interrupt -app = App(mcp_port=0, allow_cli_args=False) +app = make_app() try: app.mcp_start() except KeyboardInterrupt: @@ -3409,12 +3461,12 @@ def bind_then_interrupt(*args, **kwargs): else: interrupted = False finally: - ex._shared_logging.take, socket.create_server = take, create_server -run = app._mcp_run + server_api._shared_logging.take, socket.create_server = take, create_server +run = app._mcp._mcp_run found = { "interrupted": interrupted, "handler restored": signal.getsignal(signal.SIGINT) is handler, - "holds": ex._shared_logging.holds, + "holds": server_api._shared_logging.holds, "logging as it was": logging_state() == before, "socket": None if run.sock is None else run.sock.fileno(), "can bind": can_bind(run.port) if run.port != 0 else None, @@ -3466,7 +3518,7 @@ def test_ctrl_c_as_a_start_takes_what_it_owns_is_delivered_once_the_run_has_reco } -class HoldsItsFirstShutdown(RebuildApp): +class HoldsItsFirstShutdown(server_api.McpServer): """The lifespan shutdown of its first server, which uvicorn begins once it has closed the listener, is held. It is held until the test sets release. Every later server of the application shuts down as usual. @@ -3498,15 +3550,15 @@ async def lifespan(starlette: Any) -> AsyncIterator[None]: def test_abandonment_wins_and_a_restart_serves_on_the_same_port_while_the_old_worker_ends(sdk, no_thread_exceptions) -> None: before = logging_state() - app = HoldsItsFirstShutdown(mcp_port=0) + app = _with_server(HoldsItsFirstShutdown) app.mcp_start() - first = app._mcp_run + first = app._mcp._mcp_run try: assert app.mcp_url is not None, app.mcp_status() - app.MCP_STOP_TIMEOUT = 0.3 # for this stop alone, whose wait is meant to end while the worker is held + app._mcp.MCP_STOP_TIMEOUT = 0.3 # for this stop alone, whose wait is meant to end while the worker is held app.mcp_stop() # its wait ends while the shutdown is held, before the worker can record how it ended - app.MCP_STOP_TIMEOUT = ex.McpServerMixin.MCP_STOP_TIMEOUT # the second run's stop is meant to complete - assert app.shutting_down.wait(30) # uvicorn has closed the listener + app._mcp.MCP_STOP_TIMEOUT = server_api.McpServer.MCP_STOP_TIMEOUT # the second run's stop is meant to complete + assert app._mcp.shutting_down.wait(30) # uvicorn has closed the listener assert first.worker.is_alive() assert first.server.started # uvicorn still says it started assert (first.stop_requested, first.abandoned, first.outcome) == (True, True, None) @@ -3514,26 +3566,26 @@ def test_abandonment_wins_and_a_restart_serves_on_the_same_port_while_the_old_wo status = app.mcp_status() assert status[0] == "No MCP server: it was stopped" assert f"The worker of run {first.number} was cancelled, and has not ended yet" in status - app.mcp_port = first.port + app._mcp.mcp_port = first.port app.mcp_start() - second = app._mcp_run + second = app._mcp._mcp_run assert second is not first assert app.mcp_url == f"http://127.0.0.1:{first.port}/mcp", app.mcp_status() assert ask(app.mcp_url, "list_commands")["is_error"] is False # while the old worker is still alive assert first.worker.is_alive() - app.release.set() + app._mcp.release.set() first.worker.join(timeout=30) assert not first.worker.is_alive() assert first.outcome == "cancelled" assert ask(app.mcp_url, "list_commands")["is_error"] is False - assert ex._shared_logging.holds == 1 # the new run's + assert server_api._shared_logging.holds == 1 # the new run's assert propagating() == [] app.mcp_stop() assert (second.outcome, second.abandoned) == ("stopped", False) finally: - app.release.set() + app._mcp.release.set() app.mcp_stop() # the current run's: the second's, once the restart has made it - for run in (first, app._mcp_run): # so that no worker, nor the hold one still has, outlives the test on any path + for run in (first, app._mcp._mcp_run): # so that no worker, nor the hold one still has, outlives the test on any path if run.worker is not None: run.worker.join(timeout=30) assert not first.worker.is_alive() @@ -3545,13 +3597,13 @@ def test_completion_wins_when_the_worker_recorded_how_it_ended_before_the_wait_e sdk, no_thread_exceptions, monkeypatch ) -> None: before = logging_state() - releases = mock.Mock(wraps=ex._shared_logging.release) - monkeypatch.setattr(ex._shared_logging, "release", releases) + releases = mock.Mock(wraps=server_api._shared_logging.release) + monkeypatch.setattr(server_api._shared_logging, "release", releases) entered, release = threading.Event(), threading.Event() app = RebuildApp(mcp_port=0) - app.MCP_STOP_TIMEOUT = 0.3 + app._mcp.MCP_STOP_TIMEOUT = 0.3 app.mcp_start() - run = app._mcp_run + run = app._mcp._mcp_run worker = run.worker join = worker.join try: @@ -3566,7 +3618,7 @@ def join_once_it_has_recorded(timeout: float | None = None) -> None: assert entered.is_set() assert worker.is_alive() assert (run.outcome, run.abandoned) == ("stopped", False) # it recorded how it ended first: not given up on - assert ex._shared_logging.holds == 1 # the worker's, which it lets go of itself + assert server_api._shared_logging.holds == 1 # the worker's, which it lets go of itself releases.assert_not_called() status = app.mcp_status() assert status[0] == "No MCP server: it was stopped" @@ -3603,7 +3655,7 @@ async def fails_once_released(server: Any) -> None: before = logging_state() app = RebuildApp(mcp_port=0) app.mcp_start() - first = app._mcp_run + first = app._mcp._mcp_run try: assert app.mcp_url is not None, app.mcp_status() # mcp_start() returned with the server serving assert entered.wait(30) @@ -3615,13 +3667,13 @@ async def fails_once_released(server: Any) -> None: assert (first.outcome, first.detail, first.abandoned) == ("failed", "RuntimeError: after startup", False) assert app.mcp_status()[0] == "No MCP server: it failed (RuntimeError: after startup)" assert can_bind(first.port) # the worker has ended, but nobody has stopped or restarted the server yet - app.mcp_port = first.port + app._mcp.mcp_port = first.port app.mcp_start() - assert app._mcp_run is not first + assert app._mcp._mcp_run is not first assert first.stop_requested # the start undid the old run first assert app.mcp_url == f"http://127.0.0.1:{first.port}/mcp", app.mcp_status() assert ask(app.mcp_url, "list_commands")["is_error"] is False - assert ex._shared_logging.holds == 1 # the new run's + assert server_api._shared_logging.holds == 1 # the new run's finally: fail.set() app.mcp_stop() @@ -3649,7 +3701,7 @@ def run(self, sockets: Any = None) -> None: app = RebuildApp(mcp_port=0) try: app.mcp_start() - run = app._mcp_run + run = app._mcp._mcp_run run.worker.join(timeout=30) assert not run.worker.is_alive() assert (run.outcome, run.abandoned) == ("failed", False) @@ -3683,7 +3735,7 @@ def __exit__(self, *exc_info: object) -> Any: def test_the_worker_records_how_it_ended_under_the_runs_lock(sdk, no_thread_exceptions) -> None: app = RebuildApp(mcp_port=0) app.mcp_start() - run = app._mcp_run + run = app._mcp._mcp_run try: lock = run.lock watched = run.lock = NotesTheWorkersAsking(run) @@ -3704,7 +3756,7 @@ def test_the_worker_records_how_it_ended_under_the_runs_lock(sdk, no_thread_exce def test_a_stop_waits_for_the_worker_without_holding_the_runs_lock(sdk, no_thread_exceptions) -> None: app = RebuildApp(mcp_port=0) app.mcp_start() - run = app._mcp_run + run = app._mcp._mcp_run worker = run.worker join = worker.join held_while_waiting: list[bool] = [] @@ -3727,20 +3779,21 @@ def join_and_note(timeout: float | None = None) -> None: @pytest.fixture def fleet() -> Any: app = ex.FleetConsole(mcp_port=None, allow_cli_args=False) + _snapshot_only(app) app.mcp_start() return app def test_the_demonstration_is_described_without_an_error(fleet) -> None: - snapshot = fleet.mcp_snapshot + snapshot = fleet._mcp.mcp_snapshot assert snapshot.error is None assert [command.name for command in snapshot.commands if command.error] == [] assert_plain(snapshot) def test_the_demonstration_has_every_kind_of_thing_to_describe(fleet) -> None: - found = fleet.mcp_snapshot.descriptions - categories = {command.category for command in fleet.mcp_snapshot.commands} + found = fleet._mcp.mcp_snapshot.descriptions + categories = {command.category for command in fleet._mcp.mcp_snapshot.commands} assert {"Servers", "Deployments", "Plugins", "MCP"} <= categories assert {"server list", "server add", "server tag add"} <= set(found) deploy = {argument.name: argument for argument in found["deploy"].arguments} @@ -3750,7 +3803,7 @@ def test_the_demonstration_has_every_kind_of_thing_to_describe(fleet) -> None: assert deploy["dry_run"].max_values == 0 lines = next(argument for argument in found["logs"].arguments if argument.name == "lines") assert (lines.type, lines.flags) == ("int", ("-n", "--lines")) - assert found["logs"].exclusive_groups == (ex.ExclusiveGroup(arguments=("--follow", "--since"), required=False),) + assert found["logs"].exclusive_groups == (snapshot_api.ExclusiveGroup(arguments=("--follow", "--since"), required=False),) restart = found["restart"].arguments[0] assert (restart.min_values, restart.max_values) == (1, 3) assert any(argument.dynamic_choices for description in found.values() for argument in description.arguments) @@ -3761,14 +3814,14 @@ def test_the_demonstration_has_every_kind_of_thing_to_describe(fleet) -> None: def test_the_demonstration_loads_and_unloads_a_command_set(fleet) -> None: - before = {command.name for command in fleet.mcp_snapshot.commands} + before = {command.name for command in fleet._mcp.mcp_snapshot.commands} fleet.onecmd_plus_hooks("plugin load backups") - loaded = {command.name for command in fleet.mcp_snapshot.commands} + loaded = {command.name for command in fleet._mcp.mcp_snapshot.commands} assert loaded > before assert run_cmd(fleet, "backup api") == (["Would back up api."], []) assert run_cmd(fleet, "restore api") == (["Would restore api from its latest backup."], []) fleet.onecmd_plus_hooks("plugin unload backups") - assert {command.name for command in fleet.mcp_snapshot.commands} == before + assert {command.name for command in fleet._mcp.mcp_snapshot.commands} == before def test_the_demonstration_says_when_the_plugin_is_loaded_already_or_is_not_loaded(fleet) -> None: @@ -3781,9 +3834,9 @@ def test_the_demonstration_says_when_the_plugin_is_loaded_already_or_is_not_load def test_the_demonstration_disables_and_enables_a_category(fleet) -> None: fleet.onecmd_plus_hooks("maintenance on") - assert "deploy" not in {command.name for command in fleet.mcp_snapshot.commands} + assert "deploy" not in {command.name for command in fleet._mcp.mcp_snapshot.commands} fleet.onecmd_plus_hooks("maintenance off") - assert "deploy" in {command.name for command in fleet.mcp_snapshot.commands} + assert "deploy" in {command.name for command in fleet._mcp.mcp_snapshot.commands} def test_added_server_is_listed_counted_and_offered_for_completion(fleet) -> None: @@ -3829,18 +3882,18 @@ def test_demonstration_commands_run_at_the_prompt(fleet, command: str, output: s def test_mcp_status_prints_the_status_lines(fleet) -> None: expected = fleet.mcp_status() # before: the command sees this description, and its end publishes the next - generation = fleet.mcp_snapshot.generation + generation = fleet._mcp.mcp_snapshot.generation out, _ = run_cmd(fleet, "mcp status") # A log record kept from an earlier test in this process is shown too, and it may be several lines: compare as lines. assert out == "\n".join(expected).splitlines() assert out[0].startswith("No MCP server") - assert fleet.mcp_snapshot.generation == generation + 1 + assert fleet._mcp.mcp_snapshot.generation == generation + 1 def test_main_without_the_sdk_says_how_to_install_it() -> None: done = run_without_sdk("raise SystemExit(ex.main([]))\n") assert done.returncode not in (0, 2) - assert "uv run --group examples examples/mcp_server.py" in done.stderr + assert "uv run --extra mcp examples/mcp_server.py" in done.stderr assert len(done.stderr.strip().splitlines()) == 1 @@ -3852,7 +3905,7 @@ def test_main_with_version_1_of_the_sdk_says_how_to_install_version_2(monkeypatc monkeypatch.setattr(sys, "stdin", io.StringIO("quit\n")) # were the console to start, it would end at once assert ex.main([]) == 1 captured = capsys.readouterr() - assert "uv run --group examples examples/mcp_server.py" in captured.err + assert "uv run --extra mcp examples/mcp_server.py" in captured.err assert captured.out == "" # the console never started @@ -3877,3 +3930,43 @@ def test_main_refuses_a_port_which_is_not_a_number() -> None: with pytest.raises(SystemExit) as stopped: ex.main(["--mcp-port", "x"]) assert stopped.value.code == 2 + + +def test_concurrent_stop_releases_a_listener_still_starting(sdk, monkeypatch) -> None: + app = cmd2.Cmd(mcp_port=0, allow_cli_args=False) + start_entered = threading.Event() + stop_attempted = threading.Event() + stop_finished = threading.Event() + start_serving = app._mcp._mcp_start_serving + + def pause_start(run) -> None: + # The run exists but has not yet acquired its listener, worker or logging hold. + start_entered.set() + assert stop_attempted.wait(10) + stop_finished.wait(0.2) # Give an unsynchronized stop time to abandon the empty run. + start_serving(run) + + def concurrent_stop() -> None: + assert start_entered.wait(10) + stop_attempted.set() + app.mcp_stop() + stop_finished.set() + + monkeypatch.setattr(app._mcp, "_mcp_start_serving", pause_start) + with ThreadPoolExecutor(max_workers=1) as executor: + stopped = executor.submit(concurrent_stop) + app.mcp_start() + stopped.result(timeout=10) + + run = app._mcp._mcp_run + try: + assert run.worker is not None + assert not run.worker.is_alive() + assert can_bind(run.port) + assert app.mcp_url is None + assert server_api._shared_logging.holds == 0 + finally: + # Release a leaked worker even if this regression returns. + if run.worker is not None and run.worker.is_alive(): + run.server.should_exit = True + run.worker.join(10) From 945c2900b55fdfbb4d414cc11d1c62fcc42af43b Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:49:51 -0500 Subject: [PATCH 2/2] Cover interrupted MCP starts and trailing positional metavars --- tests/test_mcp_server.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index addc99dce..d77f2b72f 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -493,6 +493,19 @@ def test_child_custom_usage_includes_trailing_parent_positional() -> None: assert description.help.startswith(description.usage) +def test_reserved_positionals_keep_only_the_first_metavar_for_one_or_more_values() -> None: + parser = cmd2.Cmd2ArgumentParser(prog="run") + child = parser.add_subparsers().add_parser("show") + child.add_argument("row") + parser.add_argument("--verbose", action="store_true") + files = parser.add_argument("files", nargs="+", metavar=("FIRST", "MORE")) + + assert vars(parser.parse_args(["--verbose", "show", "1", "notes"])) == {"row": "1", "files": ["notes"], "verbose": True} + [reserved] = snapshot_api._reserved_positionals(parser) + assert (reserved.dest, reserved.nargs, reserved.metavar) == ("files", 1, ("FIRST",)) + assert (files.nargs, files.metavar) == ("+", ("FIRST", "MORE")) + + @pytest.mark.parametrize( ("nargs", "reserved", "suffix"), [("?", 0, ""), ("*", 0, ""), ("+", 1, " file"), ((2, 4), 2, " file{2}")] ) @@ -1629,6 +1642,22 @@ def test_a_keyboard_interrupt_from_the_first_build_leaves_the_loop_and_still_sto assert (app.starts, app.stops, app._mcp._mcp_loops, app._mcp._mcp_starting) == (1, 1, 0, False) +@pytest.mark.parametrize("already_active", [False, True]) +def test_interrupted_manual_start_preserves_previous_publication_state(already_active, monkeypatch) -> None: + app = RebuildApp() + if already_active: + app.mcp_start() + previous = app._mcp.mcp_snapshot + with monkeypatch.context() as patch: + patch.setattr(app._mcp, "_mcp_build", mock.Mock(side_effect=KeyboardInterrupt)) + with pytest.raises(KeyboardInterrupt): + app.mcp_start() + + assert app._mcp.mcp_snapshot is previous + app.onecmd_plus_hooks("load") + assert ("extra" in _listed(app)) == already_active + + def test_a_build_which_fails_keeps_the_previous_snapshot_and_is_reported_once(monkeypatch, capsys) -> None: app = RebuildApp() app.mcp_start()