diff --git a/.github/workflows/rerun-unacquired.yml b/.github/workflows/rerun-unacquired.yml index b75859b63..b24a34263 100644 --- a/.github/workflows/rerun-unacquired.yml +++ b/.github/workflows/rerun-unacquired.yml @@ -45,7 +45,8 @@ 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 (")) | select(.conclusion != "success")] as $bad + [.jobs[] | select(.name | startswith("tests (") or startswith("example-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))"') read -r unacquired failed <<< "$counts" diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index e729d546a..83424ecf0 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -92,14 +92,52 @@ 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: + strategy: + matrix: + os: [ubuntu-latest, windows-latest] + python-version: ["3.11", "3.15"] + fail-fast: false + runs-on: ${{ matrix.os }} + 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" + defaults: + run: + shell: bash + steps: + - name: Check out + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 # Needed for setuptools_scm to work correctly + - name: Install uv + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + 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: Run the example's tests + run: >- + uv run --no-default-groups --group test --group examples python -Xutf8 -m pytest + tests/test_example_mcp_server.py --no-cov -rs + # 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] + needs: [tests, example-tests] runs-on: ubuntu-latest steps: - name: Fail if any matrix job did not succeed - if: needs.tests.result != 'success' + if: needs.tests.result != 'success' || needs.example-tests.result != 'success' run: exit 1 diff --git a/CHANGELOG.md b/CHANGELOG.md index e8f30f407..ccdbbb2e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,13 @@ 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. ## 4.4.5 (2026-12-02) diff --git a/README.md b/README.md index 6fc7e4b29..fd32549d7 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,11 @@ dashboards and panels that show realtime status and other information. See [Embedding in Textual](https://cmd2.readthedocs.io/en/latest/examples/embedding_in_textual/) for an 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. + ## Quick start Install `cmd2`: diff --git a/cmd2/argparse_utils.py b/cmd2/argparse_utils.py index cee16a398..e61a17dfa 100644 --- a/cmd2/argparse_utils.py +++ b/cmd2/argparse_utils.py @@ -226,6 +226,8 @@ def get_choices(self) -> Choices: import argparse import contextlib +import copy +import itertools import re import sys import threading @@ -234,6 +236,7 @@ def get_choices(self) -> Choices: Callable, Generator, Iterable, + Iterator, Sequence, ) from dataclasses import dataclass @@ -693,6 +696,17 @@ class Cmd2ArgumentParser(argparse.ArgumentParser): # Thread-local storage shared by all parser instances (including subparsers) _thread_locals: ClassVar[_ParserThreadLocals] = _ParserThreadLocals() + _custom_subparsers_prog: bool = False + + # Keep argparse's overloads for callers. At runtime argparse caches both explicit and + # generated prefixes in the same attribute, so remember which came from the application. + if not TYPE_CHECKING: + + def add_subparsers(self, **kwargs: Any) -> "argparse._SubParsersAction": + """Add a subparsers action and remember any explicitly supplied usage prefix.""" + action = super().add_subparsers(**kwargs) + self._custom_subparsers_prog = kwargs.get("prog") is not None + return action @contextlib.contextmanager def output_to(self, file: IO[str] | None) -> Generator[None]: @@ -836,8 +850,28 @@ def _build_subparsers_prog_prefix(self, positionals: list[argparse.Action]) -> s ) # Inject the current positional state so add_subparsers() has the right context - temp_parser._actions = positionals - temp_parser._mutually_exclusive_groups = self._mutually_exclusive_groups + # Formatting a prefix can otherwise exhaust an iterator used for validation or enumerate + # billions of choices just to name a child parser. Bound the formatter's input without + # changing the actions used to parse commands. + max_prefix_choices = 1000 + replacements = {} + for action in positionals: + if action.metavar is not None or action.choices is None: + continue + display = copy.copy(action) + display.choices = None # let the formatter choose its usual metavar + if not isinstance(action.choices, Iterator): + sample = tuple(itertools.islice(action.choices, max_prefix_choices + 1)) + if len(sample) <= max_prefix_choices: + display.choices = sample + replacements[id(action)] = display + + temp_parser._actions = [replacements.get(id(action), action) for action in positionals] + for group in self._mutually_exclusive_groups: + # argparse matches group members by action identity. + display_group = copy.copy(group) + display_group._group_actions = [replacements.get(id(action), action) for action in group._group_actions] + temp_parser._mutually_exclusive_groups.append(display_group) # Call add_subparsers() to build _prog_prefix return temp_parser.add_subparsers()._prog_prefix @@ -869,6 +903,9 @@ def update_prog(self, prog: str) -> None: # Update _prog_prefix. This ensures that any subcommands added later via # add_parser() will have the correct prog value. subparsers_action._prog_prefix = self._build_subparsers_prog_prefix(positionals) + self._custom_subparsers_prog = ( + type(self)._build_subparsers_prog_prefix is not Cmd2ArgumentParser._build_subparsers_prog_prefix + ) # subparsers_action._name_parser_map includes aliases. Since primary names are inserted # first, we skip already updated parsers to ensure primary names are used in 'prog'. diff --git a/docs/examples/index.md b/docs/examples/index.md index 201cd1023..476619176 100644 --- a/docs/examples/index.md +++ b/docs/examples/index.md @@ -5,6 +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) - [List of cmd2 examples](examples.md) diff --git a/docs/examples/mcp_server.md b/docs/examples/mcp_server.md new file mode 100644 index 000000000..3fb819d7c --- /dev/null +++ b/docs/examples/mcp_server.md @@ -0,0 +1,403 @@ +# MCP Server + +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: + +```shell +uv run --group examples examples/mcp_server.py +``` + +When it starts, it says where its server is: + +```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 + +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. + +### Claude Code + +Add the server to [Claude Code](https://code.claude.com/docs/en/mcp), then check that it is +connected: + +```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. + +```json +{ + "mcpServers": { + "fleet": { + "command": "/path/to/npx", + "args": [ + "-y", + "mcp-remote@0.17.2", + "http://127.0.0.1:8765/mcp", + "--transport", + "http-only" + ], + "env": { "PATH": "/path/to:/usr/bin:/bin" } + } + } +} +``` + +`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. + +### MCP Inspector + +The [MCP Inspector](https://github.com/modelcontextprotocol/inspector) checks the server without an +assistant. This lists the server's tools: + +```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 + +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: + +```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()) +``` + +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. diff --git a/examples/README.md b/examples/README.md index 955e8cbd4..52c2e503c 100644 --- a/examples/README.md +++ b/examples/README.md @@ -64,6 +64,12 @@ each: command - [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 - [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 new file mode 100644 index 000000000..589b68fa8 --- /dev/null +++ b/examples/mcp_server.py @@ -0,0 +1,1910 @@ +"""Describe a cmd2 application's commands as plain data, and serve that description over MCP. + +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/ +""" + +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 + +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, + ) + + +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" +MCP = "MCP" + + +class BackupCommands(cmd2.CommandSet): + """Two commands which exist only while "plugin load backups" is in effect.""" + + DEFAULT_CATEGORY = PLUGINS + + backup_parser = Cmd2ArgumentParser(description="Back up a service.") + backup_parser.add_argument("service", help="the service to back up") + + @cmd2.with_argparser(backup_parser) + def do_backup(self, args: argparse.Namespace) -> None: + """Back up a service.""" + self._cmd.poutput(f"Would back up {args.service}.") + + restore_parser = Cmd2ArgumentParser(description="Restore a service from its latest backup.") + restore_parser.add_argument("service", help="the service to restore") + + @cmd2.with_argparser(restore_parser) + def do_restore(self, args: argparse.Namespace) -> None: + """Restore a service from its latest backup.""" + self._cmd.poutput(f"Would restore {args.service} from its latest backup.") + + +class FleetConsole(McpServerMixin, cmd2.Cmd): + """A pretend fleet console, which serves a description of its own commands over MCP.""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + """Pass every argument on; the CommandSet is loaded by "plugin load", so none is loaded at the start.""" + super().__init__(*args, auto_load_commands=False, **kwargs) + self.prompt = "fleet> " + self.servers: dict[str, dict[str, Any]] = { + "web-1": {"region": "us-east", "tags": {"web"}}, + "web-2": {"region": "eu-west", "tags": {"web"}}, + "db-1": {"region": "us-east", "tags": {"db"}}, + } + self.deployments: dict[str, str] = {"api": "1.4.2", "site": "2.0.0"} # service -> the version which is deployed + 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.""" + super().preloop() + url = self.mcp_url + if url is not None: + self.poutput(f"Fleet console. MCP server: {url} (describes commands, never runs them)") + else: + self.poutput('Fleet console. No MCP server: see "mcp status".') + + def server_names(self) -> Choices: + """Complete a server's name from the pretend fleet. A choices provider, so it is flagged and never called.""" + return Choices.from_values(sorted(self.servers)) + + # -- Servers: subcommands, one nested two deep, and a choices provider ---------------------------------------------- + + server_parser = Cmd2ArgumentParser(description="Manage the servers of the fleet.") + server_parser.add_subparsers(title="subcommands", required=True) + + @cmd2.with_argparser(server_parser) + @cmd2.with_category(SERVERS) + def do_server(self, args: argparse.Namespace) -> None: + """Manage the servers of the fleet.""" + args.cmd2_subcommand_func(args) + + server_list_parser = Cmd2ArgumentParser(description="List the servers.") + + @cmd2.as_subcommand_to("server", "list", server_list_parser, help="list the servers") + def server_list(self, _: argparse.Namespace) -> None: + """List the servers.""" + for name, server in sorted(self.servers.items()): + self.poutput(f"{name} {server['region']} {','.join(sorted(server['tags']))}") + + server_add_parser = Cmd2ArgumentParser(description="Add a server.") + server_add_parser.add_argument("name", help="the new server's name") + server_add_parser.add_argument("--region", default="us-east", help="where the server runs") + + @cmd2.as_subcommand_to("server", "add", server_add_parser, help="add a server") + def server_add(self, args: argparse.Namespace) -> None: + """Add a server.""" + self.servers[args.name] = {"region": args.region, "tags": set()} + self.poutput(f"Would add {args.name} in {args.region}.") + + server_tag_parser = Cmd2ArgumentParser(description="Change a server's tags.") + server_tag_parser.add_subparsers(title="subcommands", required=True) + + @cmd2.as_subcommand_to("server", "tag", server_tag_parser, help="change a server's tags") + def server_tag(self, args: argparse.Namespace) -> None: + """Change a server's tags.""" + args.cmd2_subcommand_func(args) + + server_tag_add_parser = Cmd2ArgumentParser(description="Add tags to a server.") + server_tag_add_parser.add_argument("name", choices_provider=server_names, help="the server") + server_tag_add_parser.add_argument("tag", nargs="+", help="the tags to add") + + @cmd2.as_subcommand_to("server tag", "add", server_tag_add_parser, help="add tags") + def server_tag_add(self, args: argparse.Namespace) -> None: + """Add tags to a server.""" + self.poutput(f"Would tag {args.name} with {', '.join(args.tag)}.") + + server_tag_remove_parser = Cmd2ArgumentParser(description="Remove a tag from a server.") + server_tag_remove_parser.add_argument("name", choices_provider=server_names, help="the server") + server_tag_remove_parser.add_argument("tag", help="the tag to remove") + + @cmd2.as_subcommand_to("server tag", "remove", server_tag_remove_parser, help="remove a tag") + def server_tag_remove(self, args: argparse.Namespace) -> None: + """Remove a tag from a server.""" + self.poutput(f"Would remove the tag {args.tag} from {args.name}.") + + # -- Servers: an nargs range ----------------------------------------------------------------------------------------- + + restart_parser = Cmd2ArgumentParser(description="Restart one to three servers.") + restart_parser.add_argument("name", nargs=(1, 3), choices_provider=server_names, help="the servers to restart") + + @cmd2.with_argparser(restart_parser) + @cmd2.with_category(SERVERS) + def do_restart(self, args: argparse.Namespace) -> None: + """Restart one to three servers.""" + self.poutput(f"Would restart {', '.join(args.name)}.") + + # -- Servers: @with_argument_list, and a plain do_* command ----------------------------------------------------------- + + @cmd2.with_argument_list + @cmd2.with_category(SERVERS) + def do_note(self, args: list[str]) -> None: + """Keep a note about the fleet. Takes the rest of the line.""" + self.poutput(f"Would keep the note: {' '.join(args)}") + + @cmd2.with_category(SERVERS) + def do_status(self, _: cmd2.Statement) -> None: + """Show how big the fleet is.""" + self.poutput(f"{len(self.servers)} servers, {len(self.deployments)} deployed services.") + + # -- Deployments: a positional, a required option, choices with a default, a flag; a type and exclusive options ----- + + deploy_parser = Cmd2ArgumentParser(description="Deploy a version of a service.") + deploy_parser.add_argument("service", help="the service to deploy") + deploy_parser.add_argument("--version", required=True, help="the version to deploy") + deploy_parser.add_argument("--env", choices=["dev", "staging", "prod"], default="dev", help="where to deploy it") + deploy_parser.add_argument("--dry-run", action="store_true", help="only say what would happen") + + @cmd2.with_argparser(deploy_parser) + @cmd2.with_category(DEPLOYMENTS) + def do_deploy(self, args: argparse.Namespace) -> None: + """Deploy a version of a service.""" + self.poutput(f"Would deploy {args.service} {args.version} to {args.env}{' (dry run)' if args.dry_run else ''}.") + + logs_parser = Cmd2ArgumentParser(description="Show a service's logs.") + logs_parser.add_argument("service", help="the service whose logs to show") + logs_parser.add_argument("-n", "--lines", type=int, default=10, help="how many lines to show") + logs_group = logs_parser.add_mutually_exclusive_group() + logs_group.add_argument("--follow", action="store_true", help="keep showing new lines") + logs_group.add_argument("--since", help="show lines since this time, such as 10m") + + @cmd2.with_argparser(logs_parser) + @cmd2.with_category(DEPLOYMENTS) + def do_logs(self, args: argparse.Namespace) -> None: + """Show a service's logs.""" + what = "follow" if args.follow else f"since {args.since}" if args.since else f"last {args.lines} lines" + self.poutput(f"Would show the logs of {args.service}: {what}.") + + @cmd2.with_annotated + @cmd2.with_category(DEPLOYMENTS) + def do_scale(self, service: str, replicas: int) -> None: + """Set how many replicas of a service run.""" + self.poutput(f"Would scale {service} to {replicas} replicas.") + + # -- Plugins: a CommandSet loaded and unloaded while the application runs; a category disabled and enabled --------- + + plugin_parser = Cmd2ArgumentParser(description="Load and unload plugins.") + plugin_parser.add_subparsers(title="subcommands", required=True) + + @cmd2.with_argparser(plugin_parser) + @cmd2.with_category(PLUGINS) + def do_plugin(self, args: argparse.Namespace) -> None: + """Load and unload plugins.""" + args.cmd2_subcommand_func(args) + + plugin_load_parser = Cmd2ArgumentParser(description="Load a plugin, which adds commands.") + plugin_load_parser.add_argument("name", choices=["backups"], help="the plugin to load") + + @cmd2.as_subcommand_to("plugin", "load", plugin_load_parser, help="load a plugin") + def plugin_load(self, _: argparse.Namespace) -> None: + """Load the backups plugin, which adds "backup" and "restore".""" + # Asked first, so that any error which registering raises is a real one, and reaches cmd2's handler as it is. + if self.backups in self.find_commandsets(BackupCommands): + self.pwarning("The backups plugin is loaded already.") + return + self.register_command_set(self.backups) + self.poutput("Loaded the backups plugin: backup, restore.") + + plugin_unload_parser = Cmd2ArgumentParser(description="Unload a plugin, which removes its commands.") + plugin_unload_parser.add_argument("name", choices=["backups"], help="the plugin to unload") + + @cmd2.as_subcommand_to("plugin", "unload", plugin_unload_parser, help="unload a plugin") + def plugin_unload(self, _: argparse.Namespace) -> None: + """Unload the backups plugin.""" + # Asked first: unregistering a command set which is not registered does nothing, and says nothing. + if self.backups not in self.find_commandsets(BackupCommands): + self.pwarning("The backups plugin is not loaded.") + return + self.unregister_command_set(self.backups) + self.poutput("Unloaded the backups plugin.") + + maintenance_parser = Cmd2ArgumentParser(description="Turn maintenance on, which disables the deployment commands.") + maintenance_parser.add_argument("state", choices=["on", "off"], help="on disables the Deployments category") + + @cmd2.with_argparser(maintenance_parser) + @cmd2.with_category(PLUGINS) + def do_maintenance(self, args: argparse.Namespace) -> None: + """Turn maintenance on or off. While it is on, the Deployments commands are disabled.""" + if args.state == "on": + self.disable_category(DEPLOYMENTS, "Deployments are disabled during maintenance.") + else: + self.enable_category(DEPLOYMENTS) + self.poutput(f"Maintenance is {args.state}.") + + # -- MCP: the server's own command ------------------------------------------------------------------------------------- + + mcp_parser = Cmd2ArgumentParser(description="The MCP server which describes these commands.") + mcp_parser.add_subparsers(title="subcommands", required=True) + + @cmd2.with_argparser(mcp_parser) + @cmd2.with_category(MCP) + def do_mcp(self, args: argparse.Namespace) -> None: + """The MCP server which describes these commands.""" + args.cmd2_subcommand_func(args) + + 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.""" + for line in self.mcp_status(): + self.poutput(line) + + +def main(argv: list[str] | None = None) -> int: + """Run the fleet console, with the server unless --no-mcp is given. Returns the exit status of the program.""" + parser = argparse.ArgumentParser( + description="A pretend fleet console which serves a description of its commands over MCP." + ) + parser.add_argument("--mcp-port", type=int, default=DEFAULT_PORT, help=f"the port to serve on (default {DEFAULT_PORT})") + parser.add_argument("--no-mcp", action="store_true", help="run without the server") + args = parser.parse_args(argv) + if not args.no_mcp: + try: + # mcp.server.mcpserver, which only version 2 of the SDK has, as the start asks for it: "mcp" alone lets + # version 1 through, and the console would start without a server. + importlib.import_module("mcp.server.mcpserver") + 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 " + "(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) + return app.cmdloop() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/mkdocs.yml b/mkdocs.yml index 13631c2cb..6f615e370 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -189,6 +189,7 @@ nav: - examples/getting_started.md - examples/alternate_event_loops.md - examples/embedding_in_textual.md + - examples/mcp_server.md - examples/examples.md - Mixins: - mixins/index.md diff --git a/pyproject.toml b/pyproject.toml index 6531dc394..b4eabf204 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -59,6 +59,8 @@ 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_argparse_utils.py b/tests/test_argparse_utils.py index 0bed9a979..fe97ddc9d 100644 --- a/tests/test_argparse_utils.py +++ b/tests/test_argparse_utils.py @@ -633,6 +633,25 @@ def test_update_prog() -> None: assert action.choices["alias1"].prog == sub1.prog +def test_update_prog_lists_finite_choices_in_child_usage() -> None: + parser = Cmd2ArgumentParser() + parser.add_argument("color", choices=("red", "blue")) + child = parser.add_subparsers().add_parser("show") + parser.update_prog("pick") + assert child.prog == "pick {red,blue} show" + assert parser.parse_args(["blue", "show"]).color == "blue" + + +def test_update_prog_leaves_one_shot_choices_for_parsing() -> None: + parser = Cmd2ArgumentParser() + color = parser.add_argument("color") + child = parser.add_subparsers().add_parser("show") + color.choices = iter(["red", "blue"]) + parser.update_prog("pick") + assert child.prog == "pick color show" + assert parser.parse_args(["red", "show"]).color == "red" + + def test_parser_output_to_context_manager() -> None: """Test that output_to() correctly shadows and restores current_output_file.""" import io diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py new file mode 100644 index 000000000..d06718292 --- /dev/null +++ b/tests/test_example_mcp_server.py @@ -0,0 +1,3879 @@ +"""Tests of the MCP server example, examples/mcp_server.py.""" + +import argparse +import asyncio +import contextlib +import dataclasses +import functools +import importlib.util +import io +import itertools +import json +import logging +import os +import re +import signal +import socket +import subprocess +import sys +import threading +import urllib.error +import urllib.request +from collections.abc import AsyncIterator, Iterator +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime +from pathlib import Path +from types import ModuleType +from typing import Any +from unittest import mock + +import pytest +from prompt_toolkit import PromptSession +from prompt_toolkit.input import PipeInput, create_pipe_input +from prompt_toolkit.output import DummyOutput +from rich.console import Group +from rich.text import Text + +import cmd2 +from cmd2 import rich_utils as ru +from cmd2 import string_utils as su + +from .conftest import run_cmd, with_ansi_style + +EXAMPLE = Path(__file__).parent.parent / "examples" / "mcp_server.py" +MODULE_NAME = "cmd2_example_mcp_server" + + +def _load_example() -> ModuleType: + """Load the example once for the process. Two copies would be two owners of the logging changes.""" + if MODULE_NAME in sys.modules: + return sys.modules[MODULE_NAME] + spec = importlib.util.spec_from_file_location(MODULE_NAME, EXAMPLE) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[MODULE_NAME] = module # before it runs, or its dataclasses cannot find their module + spec.loader.exec_module(module) + return module + + +ex = _load_example() + + +def assert_plain(value: object) -> None: + """Fail if any string anywhere in the value holds an escape or another control character.""" + text = repr(dataclasses.asdict(value)) if dataclasses.is_dataclass(value) else repr(value) + assert "\\x1b" not in text + assert not re.search(r"\\x(0[0-8bcef]|1[0-9a-f]|7f|[89][0-9a-f])", text) + + +def test_importing_the_example_does_not_import_the_sdk() -> None: + code = ( + "import importlib.util, sys\n" + f"spec = importlib.util.spec_from_file_location('m', {str(EXAMPLE)!r})\n" + "module = importlib.util.module_from_spec(spec)\n" + "sys.modules['m'] = module\n" + "spec.loader.exec_module(module)\n" + "assert not {'mcp', 'uvicorn', 'starlette', 'pydantic'} & set(sys.modules)\n" + ) + subprocess.run([sys.executable, "-c", code], check=True) + + +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 "one" in rendered + assert "two" in rendered + assert_plain(rendered) + + +def _argument(*flags: str, **kwargs: Any) -> Any: + parser = cmd2.Cmd2ArgumentParser() + return ex.describe_argument(parser.add_argument(*flags, **kwargs)) + + +@pytest.mark.parametrize( + ("flags", "kwargs", "low", "high", "rest", "required"), + [ + (("name",), {}, 1, 1, False, True), + (("name",), {"nargs": "?"}, 0, 1, False, False), + (("names",), {"nargs": "*"}, 0, None, False, False), + (("names",), {"nargs": "+"}, 1, None, False, True), + (("pair",), {"nargs": 2}, 2, 2, False, True), + (("names",), {"nargs": (1, 3)}, 1, 3, False, True), + (("names",), {"nargs": (2,)}, 2, None, False, True), + (("rest",), {"nargs": argparse.REMAINDER}, 0, None, True, False), + (("words",), {"nargs": argparse.PARSER}, 1, None, True, True), # one value, then the rest of the line, flags too + (("--dry-run",), {"action": "store_true"}, 0, 0, False, False), + (("--version",), {"required": True}, 1, 1, False, True), + (("--env",), {}, 1, 1, False, False), + ], +) +def test_argument_values(flags, kwargs, low, high, rest, required) -> None: + argument = _argument(*flags, **kwargs) + assert (argument.min_values, argument.max_values) == (low, high) + assert argument.takes_rest_of_line is rest + assert argument.required is required + + +def test_argument_names_flags_type_and_default() -> None: + argument = _argument("-n", "--lines", type=int, default=10, metavar="COUNT", help="how many") + assert (argument.name, argument.metavar, argument.flags) == ("lines", "COUNT", ("-n", "--lines")) + assert (argument.type, argument.parser_default, argument.help) == ("int", 10, "how many") + assert _argument("name").flags == () + assert _argument("name").parser_default is None # none worth stating + assert _argument("pair", nargs=2, metavar=("A", "B")).metavar == "A B" + + +def test_argument_default_which_json_cannot_hold() -> None: + assert _argument("--out", default=Path("out")).parser_default == repr(Path("out")) + + +def test_default_with_non_scalar_equality_uses_repr() -> None: + class ArrayDefault: + __hash__ = None + + def __eq__(self, other: object) -> bool: + raise ValueError("equality has no scalar truth value") + + default = ArrayDefault() + assert _argument("--values", default=default).parser_default == repr(default) + + +def test_argument_default_is_a_copy_which_later_changes_do_not_reach() -> None: + default = {"tags": ["a", "\x1b[31mred\x1b[0m"]} + argument = _argument("--meta", default=default) + default["tags"].append("later") + assert argument.parser_default == {"tags": ["a", "red"]} + assert_plain(argument) + + +@pytest.mark.parametrize("value", [float("inf"), float("-inf"), float("nan"), {"limits": [float("inf")]}]) +def test_argument_nonfinite_default_uses_plain_repr(value: Any) -> None: + assert _argument("--limit", default=value).parser_default == repr(value) + + +def test_argument_choices_are_strings() -> None: + assert _argument("--env", choices=["dev", "staging", "prod"]).choices == ("dev", "staging", "prod") + assert _argument("--count", type=int, choices=[1, 2]).choices == ("1", "2") + assert _argument("--env").choices is None + + +def test_argument_dynamic_choices_are_flagged_and_never_called() -> None: + def provider(_: cmd2.Cmd) -> list[str]: + raise AssertionError("the provider was called") + + assert _argument("server", choices_provider=provider).dynamic_choices is True + assert _argument("path", completer=cmd2.Cmd.path_complete).dynamic_choices is True + assert _argument("server").dynamic_choices is False + + +@pytest.mark.parametrize( + "kwargs", + [{"action": "append"}, {"action": "append_const", "const": 1}, {"action": "count"}, {"action": "extend", "nargs": "+"}], +) +def test_argument_repeatable(kwargs) -> None: + assert _argument("--tag", **kwargs).repeatable is True + assert _argument("--one").repeatable is False + + +def test_argument_of_an_awkward_shape() -> None: # Review Focus 5 + partial = _argument("--mask", type=functools.partial(int, base=16)) + assert isinstance(partial.type, str) + assert partial.type + styled = _argument( + "--color", + dest="\x1b[1mcolor\x1b[0m", + choices=["\x1b[31mred\x1b[0m"], + default="\x1b[31mred\x1b[0m", + help="\x1b[1mpick\x1b[0m", + ) + assert styled.name == "color" + assert styled.choices == ("red",) # Review Focus 3 + assert styled.parser_default == "red" + assert styled.help == "pick" + assert_plain(styled) + + +class ParserApp(cmd2.Cmd): + """An application whose commands exercise describe_parser().""" + + server_parser = cmd2.Cmd2ArgumentParser(description="Manage servers.") + server_parser.add_subparsers(title="subcommands", required=True) + + @cmd2.with_argparser(server_parser) + def do_server(self, ns: argparse.Namespace) -> None: + ns.cmd2_subcommand_func(ns) + + server_list_parser = cmd2.Cmd2ArgumentParser(description="List the servers.") + + @cmd2.as_subcommand_to("server", "list", server_list_parser, help="List the servers.", aliases=["ls"]) + def server_list(self, _: argparse.Namespace) -> None: + pass + + server_add_parser = cmd2.Cmd2ArgumentParser() + server_add_parser.add_argument("name") + + @cmd2.as_subcommand_to("server", "add", server_add_parser, help="Add a server.") + def server_add(self, _: argparse.Namespace) -> None: + pass + + server_tag_parser = cmd2.Cmd2ArgumentParser() + server_tag_parser.add_subparsers(title="subcommands") + + @cmd2.as_subcommand_to("server", "tag", server_tag_parser, help="Change a server's tags.", aliases=["t"]) + def server_tag(self, ns: argparse.Namespace) -> None: + ns.cmd2_subcommand_func(ns) + + server_tag_add_parser = cmd2.Cmd2ArgumentParser() + server_tag_add_parser.add_argument("name") + server_tag_add_parser.add_argument("tag", nargs="+") + + @cmd2.as_subcommand_to("server tag", "add", server_tag_add_parser, help="Add tags.") + def server_tag_add(self, _: argparse.Namespace) -> None: + pass + + server_tag_remove_parser = cmd2.Cmd2ArgumentParser() + server_tag_remove_parser.add_argument("name") + + @cmd2.as_subcommand_to("server tag", "remove", server_tag_remove_parser, help="Remove tags.") + def server_tag_remove(self, _: argparse.Namespace) -> None: + pass + + logs_parser = cmd2.Cmd2ArgumentParser() + logs_parser.add_argument("service") + logs_group = logs_parser.add_mutually_exclusive_group() + logs_group.add_argument("--follow", action="store_true") + logs_group.add_argument("--since") + + @cmd2.with_argparser(logs_parser) + def do_logs(self, _: argparse.Namespace) -> None: + pass + + pick_parser = cmd2.Cmd2ArgumentParser() + pick_group = pick_parser.add_mutually_exclusive_group(required=True) + pick_group.add_argument("--first", action="store_true") + pick_group.add_argument("--last", action="store_true") + + @cmd2.with_argparser(pick_parser) + def do_pick(self, _: argparse.Namespace) -> None: + pass + + quiet_parser = cmd2.Cmd2ArgumentParser() + quiet_parser.add_argument("visible") + quiet_parser.add_argument("--internal", help=argparse.SUPPRESS) + + @cmd2.with_argparser(quiet_parser) + def do_quiet(self, _: argparse.Namespace) -> None: + pass + + rich_parser = cmd2.Cmd2ArgumentParser(description=Group(Text("Rich description.", style="bold"), "Second line.")) + + @cmd2.with_argparser(rich_parser) + def do_rich(self, _: argparse.Namespace) -> None: + pass + + account_parser = cmd2.Cmd2ArgumentParser() + account_parser.add_subparsers(title="subcommands") + + @cmd2.with_argparser(account_parser) + def do_account(self, ns: argparse.Namespace) -> None: + ns.cmd2_subcommand_func(ns) + + @cmd2.as_subcommand_to("account", "list", cmd2.Cmd2ArgumentParser(), help="List the accounts.") + def account_list(self, _: argparse.Namespace) -> None: + pass + + @cmd2.as_subcommand_to("account", "purge", cmd2.Cmd2ArgumentParser(), help=argparse.SUPPRESS, aliases=["wipe"]) + def account_purge(self, _: argparse.Namespace) -> None: + pass + + @cmd2.as_subcommand_to("account", "show", cmd2.Cmd2ArgumentParser(description="Show one account.")) # no help= + def account_show(self, _: argparse.Namespace) -> None: + pass + + +def _descriptions(app: cmd2.Cmd, command: str) -> dict[str, Any]: + func = app.get_command_func(command) + assert func is not None + parser = app.command_parsers.get(func) + assert parser is not None + return ex.describe_parser(parser, command, "a summary") + + +def test_parser_subcommands_three_deep_by_path() -> None: + found = _descriptions(ParserApp(), "server") + assert set(found) == { + "server", + "server list", + "server add", + "server tag", + "server tag add", + "server tag remove", + } + assert found["server list"].path == "server list" # each subcommand once, by its name: not by "ls" or "t" + assert [argument.name for argument in found["server tag add"].arguments] == ["name", "tag"] # no -h + assert found["server"].summary == "a summary" + assert found["server tag"].summary == "Change a server's tags." + + +def test_parser_names_its_subcommands_and_says_whether_one_is_required() -> None: + found = _descriptions(ParserApp(), "server") + by_name = {subcommand.name: subcommand for subcommand in found["server"].subcommands} + assert set(by_name) == {"list", "add", "tag"} + assert by_name["list"].aliases == ("ls",) + assert by_name["list"].summary == "List the servers." + assert found["server"].subcommand_required is True + assert found["server tag"].subcommand_required is False + assert found["server add"].subcommands == () + + +def test_parser_leaves_out_a_suppressed_subcommand_with_its_alias() -> None: + found = _descriptions(ParserApp(), "account") + by_name = {subcommand.name: subcommand for subcommand in found["account"].subcommands} + assert set(by_name) == {"list", "show"} # not "purge", which help=argparse.SUPPRESS hides from help + assert by_name["list"].summary == "List the accounts." + assert by_name["show"].summary == "Show one account." # added with no help=: its parser's description + assert set(found) == {"account", "account list", "account show"} # neither "account purge" nor "account wipe" + summaries = [description.summary for description in found.values()] + summaries += [subcommand.summary for description in found.values() for subcommand in description.subcommands] + assert argparse.SUPPRESS not in summaries + + +def test_parser_usage_and_help_leave_out_a_suppressed_subcommand_without_changing_the_parser() -> None: + app = ParserApp() + account = _descriptions(app, "account")["account"] + for text in (account.usage, account.help): + assert "purge" not in text + assert "wipe" not in text + assert argparse.SUPPRESS not in text # argparse itself shows "purge (wipe) ==SUPPRESS==" in help + assert "{list,show}" in account.usage + assert "List the accounts." in account.help # the subcommands which help lists are still there + func = app.get_command_func("account") + assert func is not None + parser = app.command_parsers.get(func) + assert parser is not None + assert "{list,purge,wipe,show}" in parser.format_usage() # the parser which "help account" uses is as it was + assert "purge" in parser.get_subparsers_action().choices + + +def test_many_subcommand_names_do_not_restore_hidden_help(monkeypatch) -> None: + monkeypatch.setattr(ex, "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"] + assert "[--color COLOR] folder" in root.usage + assert "one of (choices omitted)" in root.help + assert "{list,ls}" in root.usage + assert "List entries." in root.help + assert "hidden" not in root.help + + +@pytest.mark.parametrize("aliases", [[], ["end"]]) +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(): + assert parser.parse_args(["--", "--"]) == argparse.Namespace() + assert found["p --"].usage == "Usage: p -- -- [-h]" + assert found["p"].subcommands[0].aliases == tuple(aliases) + else: + assert [child.name for child in found["p"].subcommands] == aliases + assert "p --" not in found + if aliases: + assert parser.parse_args(["end"]) == argparse.Namespace() + + +def test_child_help_reuses_the_bounded_parent_positionals() -> None: + parser = cmd2.Cmd2ArgumentParser(prog="pick") + parser.add_argument("id", type=int, choices=range(1010)) + child = parser.add_subparsers().add_parser("show") + child.add_subparsers().add_parser("all") + parser.update_prog("pick") + original = child.prog + found = ex.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} ") + assert found[path].help.startswith(found[path].usage) + assert "{0,1," not in found[path].help + assert child.prog == original + + +@pytest.mark.parametrize("prefix", ["custom invocation", "pick custom"]) +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"] + assert child.usage == f"Usage: {prefix} show [-h]" + + +def test_child_help_preserves_a_custom_prefix_built_by_update_prog() -> None: + class CustomParser(cmd2.Cmd2ArgumentParser): + def _build_subparsers_prog_prefix(self, positionals: list[argparse.Action]) -> str: + return "custom invocation" + + parser = CustomParser() + parser.add_subparsers().add_parser("show") + parser.update_prog("pick") + child = ex.describe_parser(parser, "pick", "")["pick show"] + assert child.usage == "Usage: custom invocation show [-h]" + + +def test_child_help_reflects_changed_parent_choices() -> None: + parser = cmd2.Cmd2ArgumentParser(prog="pick") + choice = parser.add_argument("value", choices=("foo", "bar")) + 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"] + assert child.usage == "Usage: pick {baz} go [-h]" + assert child.help.startswith(child.usage) + + +def test_child_usage_orders_trailing_parent_positionals_at_each_depth() -> None: + parser = cmd2.Cmd2ArgumentParser(prog="run") + child = parser.add_subparsers().add_parser("show") + leaf = child.add_subparsers().add_parser("line") + leaf.add_argument("number") + child.add_argument("section") + parser.add_argument("file") + assert vars(parser.parse_args(["show", "line", "5", "header", "notes"])) == { + "number": "5", + "section": "header", + "file": "notes", + } + found = ex.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" + assert description.help.startswith(description.usage) + assert leaf.format_usage().strip() == "Usage: run show line [-h] number" + + +def test_child_custom_usage_includes_trailing_parent_positional() -> None: + parser = cmd2.Cmd2ArgumentParser(prog="run") + 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"] + assert description.usage == "Usage: run show ROW FILE" + assert description.help.startswith(description.usage) + + +@pytest.mark.parametrize( + ("nargs", "reserved", "suffix"), [("?", 0, ""), ("*", 0, ""), ("+", 1, " file"), ((2, 4), 2, " file{2}")] +) +def test_child_usage_shows_only_reserved_parent_words(nargs, reserved, suffix) -> None: + parser = cmd2.Cmd2ArgumentParser(prog="run", exit_on_error=False) + child = parser.add_subparsers().add_parser("show") + child.add_argument("row") + parser.add_argument("file", nargs=nargs) + words = ["show", "1", *(["notes"] * reserved)] + 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"] + assert description.usage == f"Usage: run show [-h] row{suffix}" + assert description.help.startswith(description.usage) + + +@pytest.mark.parametrize("positional", [False, True]) +def test_child_help_includes_required_parent_options(positional: bool) -> None: + parser = cmd2.Cmd2ArgumentParser(prog="pick") + parser.add_argument("--id", type=int, choices=range(1010), required=True) + if positional: + parser.add_argument("group") + parser.add_subparsers().add_parser("show") + parser.update_prog("pick") + description = ex.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) + + +def test_nested_child_usage_preserves_tabs_and_required_parent_group() -> None: + parser = cmd2.Cmd2ArgumentParser(prog="pick") + parent = parser.add_subparsers().add_parser("has\ttab") + group = parent.add_mutually_exclusive_group(required=True) + group.add_argument("--id") + group.add_argument("--name") + parent.add_subparsers().add_parser("show") + parser.update_prog("pick") + child = ex.describe_parser(parser, "pick", "")['pick "has\ttab" show'] + assert child.usage == 'Usage: pick "has\ttab" (--id ID | --name NAME) show [-h]' + + +@pytest.mark.parametrize("name", ["-x", "--"]) +def test_option_like_subcommand_after_a_positional_is_reachable(name) -> None: + parser = cmd2.Cmd2ArgumentParser(prog="owner") + 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}"] + 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", "") + try: + parsed = parser.parse_args(["--", "-x"]) + except argparse.ArgumentError: + assert found["run"].subcommands == () + assert "run -x" not in found + else: + assert parsed.sub == "-x" + assert [s.typed for s in found["run"].subcommands] == ["-x"] + assert found["run -x"].usage == "Usage: run -- -x [-h]" + + +def test_help_width_is_local_to_the_formatter(monkeypatch) -> None: + seen = [] + + class ObserveWidth: + def __cmd2_argparse_help__(self, formatter): + seen.append((os.environ["COLUMNS"], formatter.console.width)) + return "Width test." + + 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)] + + +def test_parser_exclusive_groups() -> None: + logs = _descriptions(ParserApp(), "logs")["logs"] + assert logs.exclusive_groups == (ex.ExclusiveGroup(arguments=("--follow", "--since"), required=False),) + pick = _descriptions(ParserApp(), "pick")["pick"] + assert pick.exclusive_groups == (ex.ExclusiveGroup(arguments=("--first", "--last"), required=True),) + + +def test_parser_exclusive_groups_name_options_which_share_a_destination_apart() -> None: + parser = cmd2.Cmd2ArgumentParser() + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("-a", "--add", dest="mode", action="store_const", const="add") + group.add_argument("--remove", dest="mode", action="store_const", const="remove") + 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"] + 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 + ) + # 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): + matches = [argument for argument in mode.arguments if named in argument.flags or named == argument.name] + assert len(matches) == 1 + + +def test_parser_keeps_a_required_exclusive_group_of_which_one_member_is_visible() -> None: + parser = cmd2.Cmd2ArgumentParser() + required = parser.add_mutually_exclusive_group(required=True) + required.add_argument("--current", action="store_true") + required.add_argument("--legacy", action="store_true", help=argparse.SUPPRESS) + 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"] + # 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),) + + +def test_parser_leaves_out_a_suppressed_argument() -> None: + quiet = _descriptions(ParserApp(), "quiet")["quiet"] + assert [argument.name for argument in quiet.arguments] == ["visible"] + + +def test_parser_usage_and_help_are_plain_text() -> None: + add = _descriptions(ParserApp(), "server")["server tag add"] + assert "server tag add" in add.usage + assert "tag" in add.help.lower() + assert (add.has_parser, add.error) == (True, None) + + +def test_parser_usage_and_help_have_no_trailing_newline() -> None: + # argparse ends usage with a newline and help with two, so a client which printed them would print empty lines after. + found = _descriptions(ParserApp(), "server") + for description in found.values(): + assert description.usage + assert description.help + assert description.usage == description.usage.rstrip() + assert description.help == description.help.rstrip() + + +def test_parser_description_which_is_a_rich_renderable() -> None: + rich = _descriptions(ParserApp(), "rich")["rich"] + assert "Rich description." in rich.help + assert "Second line." in rich.help + assert_plain(rich) + + +@with_ansi_style(ru.AllowStyle.ALWAYS) +def test_parser_text_is_plain_when_styles_are_always_on() -> None: + for description in _descriptions(ParserApp(), "server").values(): + assert_plain(description) + + +def test_parser_help_does_not_follow_the_terminal(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(os, "get_terminal_size", lambda fd=1: os.terminal_size((40, 24))) + narrow = _descriptions(ParserApp(), "logs")["logs"] + monkeypatch.setattr(os, "get_terminal_size", lambda fd=1: os.terminal_size((200, 24))) + assert _descriptions(ParserApp(), "logs")["logs"] == narrow + + +def _raises_boom() -> cmd2.Cmd2ArgumentParser: + raise RuntimeError("boom") + + +class SnapshotApp(ParserApp): + """An application whose commands exercise build_snapshot().""" + + DEFAULT_CATEGORY = "Snapshot Commands" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.hidden_commands.append("secret") + + def do_status(self, _: cmd2.Statement) -> None: + """Show the status. + + Nothing is contacted. + """ + + @cmd2.with_argument_list + def do_note(self, _: list[str]) -> None: + """Keep a note.""" + + def do_bare(self, _: cmd2.Statement) -> None: + pass + + @cmd2.with_annotated + def do_scale(self, service: str, replicas: int) -> None: + pass + + def do_secret(self, _: cmd2.Statement) -> None: + """A hidden command.""" + + @cmd2.with_category("Gated") + def do_gated(self, _: cmd2.Statement) -> None: + """A command which is disabled and enabled.""" + + @cmd2.with_argparser(_raises_boom) + def do_broken(self, _: argparse.Namespace) -> None: + pass + + def help_extra(self) -> None: + pass + + def help_status(self) -> None: + pass + + +def _names(snapshot: Any) -> set[str]: + return {command.name for command in snapshot.commands} + + +def test_snapshot_describes_every_built_in_command_of_a_bare_application() -> None: + app = cmd2.Cmd() + snapshot = ex.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] == [] + assert {command.category for command in snapshot.commands} == {"Cmd2 Commands"} + assert snapshot.descriptions["shell"].arguments[-1].takes_rest_of_line is True + assert snapshot.descriptions["help"].arguments[-1].takes_rest_of_line is True + assert snapshot.descriptions["alias"].subcommand_required is True + assert snapshot.descriptions["history"].exclusive_groups != () + assert "alias create" in snapshot.descriptions + + +@with_ansi_style(ru.AllowStyle.ALWAYS) +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)) + + +def test_snapshot_commands_with_no_parser() -> None: + snapshot = ex.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." + assert snapshot.descriptions["note"].has_parser is False + bare = snapshot.descriptions["bare"] # Review Focus 5 + assert (bare.summary, bare.help, bare.error) == ("", "", None) + + +def test_snapshot_annotated_command() -> None: + scale = ex.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) + 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)) + + +def test_snapshot_lists_a_command_which_cannot_be_described() -> None: + snapshot = ex.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" + assert "boom" in snapshot.descriptions["broken"].error + assert snapshot.error is None + assert snapshot.descriptions["status"].error is 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",) + + +def test_quote_mode_is_looked_up_once_per_parsed_command() -> None: + class SpecApp(SpacedApp): + def get_argparse_command_spec(self, func): + if func == self.do_parserless: + raise ValueError("parserless command has no spec") + if func == self.do_report: + raise ValueError("broken spec") + if func == self.do_kept: + self.kept_lookups += 1 + return super().get_argparse_command_spec(func) + + def do_parserless(self, _: cmd2.Statement) -> None: + """A free-form command.""" + + app = SpecApp() + app.kept_lookups = 0 + snapshot = ex.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"' + + +def test_command_lookup_errors_are_reported_without_losing_other_descriptions() -> None: + class IncompleteApp(SnapshotApp): + def get_visible_commands(self) -> list[str]: + return [*super().get_visible_commands(), "missing"] + + def get_command_category(self, func): + if func == self.do_status: + raise LookupError("missing category") + return super().get_command_category(func) + + snapshot = ex.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 == "" + assert message in listed[name].error + assert snapshot.descriptions[name].error == listed[name].error + assert snapshot.descriptions["note"].error is None + + +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." + + +def test_formatter_aware_descriptions_supply_command_and_subcommand_summaries() -> None: + class NotesApp(cmd2.Cmd): + notes = cmd2.Cmd2ArgumentParser(description=cmd2.TextGroup("Notes", "Manage notes.")) + notes.add_subparsers().add_parser("add", description=cmd2.TextGroup("Add", "Create a note.")) + + @cmd2.with_argparser(notes) + def do_notes(self, _: argparse.Namespace) -> None: + pass + + snapshot = ex.build_snapshot(NotesApp(), 1) + command = next(command for command in snapshot.commands if command.name == "notes") + assert command.summary == "Notes:" + root = snapshot.descriptions["notes"] + assert root.subcommands[0].summary == snapshot.descriptions["notes add"].summary == "Add:" + + +def test_snapshot_leaves_out_the_commands_it_is_told_to() -> None: + snapshot = ex.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") + + +def test_failed_snapshot() -> None: + snapshot = ex.failed_snapshot(4, "the build failed") + assert (snapshot.generation, snapshot.commands, snapshot.error) == (4, (), "the build failed") + assert dict(snapshot.descriptions) == {} + + +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 + 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",)) + + +def test_snapshot_generation_and_time() -> None: + snapshot = ex.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) + 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) + assert {"Cmd2 Commands", "Gated", "Snapshot Commands"} <= set(names) + server = next(command for category in answer.categories for command in category.commands if command.name == "server") + assert set(server.subcommands) == {"list", "add", "tag"} + assert (answer.help_topics, answer.typing) == (snapshot.help_topics, snapshot.typing) + + +def test_snapshot_preserves_the_configured_help_sort_order(monkeypatch: pytest.MonkeyPatch) -> None: + class Tasks(cmd2.Cmd): + @cmd2.with_category("Group10") + def do_task2(self, _: cmd2.Statement) -> None: + pass + + @cmd2.with_category("Group2") + def do_task10(self, _: cmd2.Statement) -> None: + pass + + def help_topic2(self) -> None: + pass + + def help_topic10(self) -> None: + pass + + with monkeypatch.context() as patch: + patch.setattr(cmd2.utils, "DEFAULT_STR_SORT_KEY", cmd2.utils.NATURAL_SORT_KEY) + snapshot = ex.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 + 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 ") + 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") + for missing in ("nonesuch", "", "gated", "secret"): + with pytest.raises(ex.UnknownCommandError) as raised: + ex.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") + 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) + looked_up: list[str] = [] + + class Noting(dict): + def get(self, key: str, default: Any = None) -> Any: + looked_up.append(key) + return super().get(key, default) + + def __getitem__(self, key: str) -> Any: + looked_up.append(key) + return super().__getitem__(key) + + snapshot = dataclasses.replace(snapshot, descriptions=Noting(snapshot.descriptions)) + 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) + 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) + + +def _recorded(subcommands: Any, name: str, summary: str, **kwargs: Any) -> cmd2.Cmd2ArgumentParser: + """Add a subcommand which, when it runs, records its summary in the namespace as "ran".""" + parser = subcommands.add_parser(name, help=summary, **kwargs) + parser.set_defaults(ran=summary) + return parser + + +class SpacedApp(cmd2.Cmd): + """An application with subcommands whose names have in them what the prompt splits a line at, or reads as syntax. + + Running report records the summary of the subcommand which ran in ran. + """ + + report_parser = cmd2.Cmd2ArgumentParser() + # The metavar keeps the usage on one line. On Python 3.11 and 3.12, argparse fails an assertion wrapping a usage + # line whose choices have a tab or a run of spaces in them. + report_subcommands = report_parser.add_subparsers(title="subcommands", metavar="SUBCOMMAND") + _recorded(report_subcommands, "list all", "List every report.", aliases=["every one"]) + _recorded(report_subcommands, "per|site", "Report per site.") + _recorded(report_subcommands, "a;b", "Report on a, then on b.") + _recorded(report_subcommands, "this&that", "Report on this and that.") + _recorded(report_subcommands, "tab\there", "Report with a tab.") + _recorded(report_subcommands, "tab here", "Report with six spaces.") + _recorded(report_subcommands, "today's", "Report on today.") + _recorded(report_subcommands, "a'b\"c", "Report on a, b and c.") + _recorded(report_subcommands, "", "Report with no name.") + _recorded(report_subcommands, "a' \"b", "Report which the prompt cannot take.") + report_daily = _recorded(report_subcommands, "d' \"y", "Report daily.", aliases=["daily"]) + _recorded(report_daily.add_subparsers(title="subcommands"), "summary", "Summarize the day.") + _recorded(report_subcommands, "weekly", "Report weekly.", aliases=["w' \"k"]) + _recorded(report_subcommands, "show", "Show one report.") + report_list = _recorded(report_subcommands, "list", "List some reports.") + _recorded(report_list.add_subparsers(title="subcommands"), "all", "List all of some reports.") + + owner_parser = cmd2.Cmd2ArgumentParser() + owner_parser.add_argument("name") + owner_subcommands = owner_parser.add_subparsers(title="subcommands") + owner_list = owner_subcommands.add_parser("list all", help="List all of an owner's reports.") + owner_list.add_subparsers(title="subcommands").add_parser("x y", help="Go deeper.") + + # argparse is given each word of kept with its quotation marks. + kept_parser = cmd2.Cmd2ArgumentParser() + kept_subcommands = kept_parser.add_subparsers(title="subcommands") + _recorded(kept_subcommands, '"list all"', "List all, by a name with quotation marks in it.") + _recorded(kept_subcommands, "list all", "List all, by a name without them.") + _recorded(kept_subcommands, "show", "Show one.") + + # Names which the prompt passes to argparse whole, but which argparse takes as an option, and names which would be + # served as another's: ab is added before a\rb, which would be served as ab, under the same path. + odd_parser = cmd2.Cmd2ArgumentParser() + odd_parser.add_argument("--verbose", action="store_true") + odd_parser.add_argument("--version", action="store_true") + odd_subcommands = odd_parser.add_subparsers(title="subcommands", metavar="SUBCOMMAND") + _recorded(odd_subcommands, "-h", "Expand, by the name of the help option, or by its alias.", aliases=["expand"]) + _recorded(odd_subcommands, "-x", "Report by a name which argparse reads as an unknown option.") + _recorded(odd_subcommands, "--ver", "Report by a name which abbreviates two options.") + _recorded(odd_subcommands, "--", "Report by the name which ends the options.") + _recorded(odd_subcommands, "-1", "Report by a name which argparse reads as a negative number.") + _recorded(odd_subcommands, "-", "Report by a lone dash.") + _recorded(odd_subcommands, "- x", "Report by a name with a space after its dash.") + _recorded(odd_subcommands, "ab", "Report on ab.") + _recorded(odd_subcommands, "a\rb", "Report on a, a carriage return and b.") + + # The root parser reads a word which begins with @ as a file of arguments, before group's parser is given it. + files_parser = cmd2.Cmd2ArgumentParser(fromfile_prefix_chars="@") + files_group = _recorded(files_parser.add_subparsers(title="subcommands"), "group", "Report on a group.") + _recorded(files_group.add_subparsers(title="subcommands"), "@all", "Report on all of the group.", aliases=["all"]) + + def __init__(self) -> None: + super().__init__(terminators=[";", "&"]) + self.ran: str | None = None + + @cmd2.with_argparser(report_parser) + def do_report(self, args: argparse.Namespace) -> None: + self.ran = getattr(args, "ran", None) + + @cmd2.with_argparser(owner_parser) + def do_owner(self, _: argparse.Namespace) -> None: + pass + + @cmd2.with_argparser(kept_parser, preserve_quotes=True) + def do_kept(self, args: argparse.Namespace) -> None: + self.ran = getattr(args, "ran", None) + + @cmd2.with_argparser(odd_parser) + def do_odd(self, args: argparse.Namespace) -> None: + self.ran = getattr(args, "ran", None) + + @cmd2.with_argparser(files_parser) + def do_files(self, args: argparse.Namespace) -> None: + self.ran = getattr(args, "ran", 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 + 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 + 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 + # 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 + + +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 "&" + paths = {path for path in snapshot.descriptions if path.startswith("report ")} + assert paths == { + 'report "list all"', + 'report "per|site"', + 'report "a;b"', + 'report "this&that"', + 'report "tab\there"', + 'report "tab here"', + "report today's", # a quotation mark inside a word is part of it, as at the prompt + "report a'b\"c", + 'report ""', # the empty name, which the prompt takes only quoted + "report daily", # by its alias, since its name cannot be typed + "report daily summary", + "report weekly", + "report show", + "report list", + "report list all", + } + for path in paths: + assert ex.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) + 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) + ) + + +def test_usage_for_each_lookup_path_invokes_the_described_subcommand() -> None: + app = SpacedApp() + snapshot = ex.build_snapshot(app, 1) + for path, description in snapshot.descriptions.items(): + if path.startswith(("report ", "kept ", "odd ", "files ")): + app.ran = None + # These commands take no required arguments. The usage prefix includes any necessary --. + 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 + + +def test_a_name_with_quotation_marks_in_it_is_found_as_the_prompt_takes_it() -> None: + snapshot = ex.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 + # 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'") + + +def test_a_subcommand_whose_name_cannot_be_typed_is_served_by_an_alias_which_can() -> None: + snapshot = ex.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 + assert (found.summary, found.usage) == ("Summarize the day.", "Usage: report daily summary [-h]") + + +def test_usage_help_and_aliases_name_a_subcommand_only_by_the_names_which_can_be_typed() -> None: + parser = cmd2.Cmd2ArgumentParser(prog="report") + subcommands = parser.add_subparsers(title="subcommands") + subcommands.add_parser("show", help="Show one report.") + 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"] + 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"): + assert left_out not in report.help + assert re.search(r"daily +Report daily\.", report.help) + assert re.search(r"weekly \(wk\) +Report weekly\.", report.help) + # The parser which the prompt uses is as it was. + assert list(parser.get_subparsers_action().choices) == ["show", "a' \"b", "d' \"y", "daily", "weekly", "w' \"k", "wk"] + + +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) + # 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 + 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 + # 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"' + + +def test_subcommands_that_look_like_options_reflect_argparse_reachability(capsys: pytest.CaptureFixture[str]) -> None: + snapshot = ex.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(): + expected = [("-h", ("expand",)), ("-x", ()), ("--ver", ()), ("--", ())] + assert "-h (expand)" in odd.help + else: + expected = [("expand", ())] + assert re.search(r"expand +Expand, by the name", odd.help) + for left_out in ("unknown option", "abbreviates", "ends the options"): + assert left_out not in odd.help + assert [(each.name, each.aliases) for each in odd.subcommands] == [ + *expected, + ("-1", ()), + ("-", ()), + ("- x", ()), + ("ab", ()), + ] + assert capsys.readouterr().err == "" # Python 3.11 reports an ambiguous abbreviation with error(), which prints + + +def test_a_subcommand_name_which_argparse_reads_from_a_file_is_left_out() -> None: + parser = cmd2.Cmd2ArgumentParser(prog="report", fromfile_prefix_chars="@") + 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"] + 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) + 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 + assert snapshot.descriptions["odd ab"].summary == "Report on ab." + assert "carriage return" not in odd.help + + +def test_a_subcommand_name_which_an_ancestor_reads_from_a_file_is_left_out() -> None: + snapshot = ex.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", ())] + + +class HiddenSubcommandsApp(cmd2.Cmd): + """Has vault, whose subcommands were added with help=argparse.SUPPRESS: help and usage leave out all of them.""" + + vault_parser = cmd2.Cmd2ArgumentParser() + vault_parser.add_argument("--all", action="store_true") + vault_subcommands = vault_parser.add_subparsers(help=argparse.SUPPRESS) + vault_subcommands.add_parser("secret", help="Show the secret.").add_argument("--token", default="s3cr3t") + + @cmd2.with_argparser(vault_parser) + def do_vault(self, _: argparse.Namespace) -> None: + pass + + +def test_subcommands_whose_help_is_suppressed_together_are_left_out() -> None: + snapshot = ex.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") + + +class EveryNumber: + """Choices of every whole number from 0. A value is checked at once, but they never end, unlike range(2**32).""" + + def __contains__(self, value: object) -> bool: + return isinstance(value, int) and value >= 0 + + def __iter__(self) -> Iterator[int]: + for number in itertools.count(): + if number == 100_000: + raise AssertionError("far more choices were read than are ever listed") + yield number + + +def _id_parser() -> cmd2.Cmd2ArgumentParser: + parser = cmd2.Cmd2ArgumentParser() + parser.add_argument("id", type=int, choices=EveryNumber(), metavar="ID") + page = parser.add_argument("--page", type=int, choices=EveryNumber(), metavar="PAGE") + page.help = "one of %(choices)s" # which help would read to expand; given after, since add_argument() reads it on 3.14 + parser.add_argument("--color", choices=["red", "green"]) + return parser + + +class IdApp(cmd2.Cmd): + """Has get, whose choices never end, and records the arguments it was given.""" + + def __init__(self) -> None: + super().__init__() + self.given: argparse.Namespace | None = None + + @cmd2.with_argparser(_id_parser) + def do_get(self, args: argparse.Namespace) -> None: + self.given = args + + +def test_no_more_choices_are_read_than_are_listed() -> None: + app = IdApp() + get = ex.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"].more_choices is True + assert "one of (choices omitted)" in get.help + assert arguments["page"].more_choices is True + assert (arguments["color"].choices, arguments["color"].more_choices) == (("red", "green"), False) + app.onecmd_plus_hooks("get 4000000000 --page 7") + assert app.given is not None + assert (app.given.id, app.given.page) == (4000000000, 7) + + +def test_first_snapshot_bounds_choices_before_a_subcommand() -> None: + class PickApp(cmd2.Cmd): + parser = cmd2.Cmd2ArgumentParser() + item = parser.add_argument("item", type=int) + parser.add_subparsers().add_parser("show") + item.choices = EveryNumber() + + @cmd2.with_argparser(parser) + def do_pick(self, args: argparse.Namespace) -> None: + self.poutput(args.item) + + app = PickApp() + first = ex.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]" + assert run_cmd(app, "pick 4000000000 show") == (["4000000000"], []) + + +class SynonymApp(cmd2.Cmd): + """Has orate, the function of speak under a second name, which cmd2 gives the parser of speak, prog and all.""" + + speak_parser = cmd2.Cmd2ArgumentParser(description="Speak.") + speak_parser.add_argument("-r", "--repeat", type=int) + speak_parser.add_subparsers(title="subcommands").add_parser("loudly", help="Speak loudly.") + + def __init__(self) -> None: + super().__init__(multiline_commands=["orate"]) + + @cmd2.with_argparser(speak_parser) + def do_speak(self, _: argparse.Namespace) -> None: + pass + + do_orate = do_speak + + +def test_a_command_which_is_another_commands_function_is_described_by_its_own_name() -> None: + app = SynonymApp() + snapshot = ex.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]") + assert snapshot.descriptions[f"{name} loudly"].usage == f"Usage: {name} loudly [-h]" + assert app.command_parsers.get(app.do_orate).prog == "speak" # the parser which the prompt uses is as it was + + +def _power_parser() -> cmd2.Cmd2ArgumentParser: + """A parser whose choices are iterators, which argparse reads up to the value given each time it checks one. + + argparse reads them itself, when the argument is added, where it has no metavar, or on Python 3.14 and later a help + with %(choices)s in it. So each has a metavar, and the help of --fan is given after it is added. + """ + parser = cmd2.Cmd2ArgumentParser() + parser.add_argument("mode", choices=iter(["on", "off"]), metavar="MODE") + fan = parser.add_argument("--fan", choices=iter(["slow", "fast"]), metavar="SPEED") + fan.help = "one of %(choices)s" # which help would read the choices to expand + return parser + + +class PowerApp(cmd2.Cmd): + """Has power, whose choices are iterators, and records the arguments it was given.""" + + def __init__(self) -> None: + super().__init__() + self.given: argparse.Namespace | None = None + + @cmd2.with_argparser(_power_parser) + def do_power(self, args: argparse.Namespace) -> None: + self.given = args + + +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) + 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") + power = snapshot.descriptions["power"] + assert [(each.name, each.choices, each.more_choices) for each in power.arguments] == [ + ("mode", None, True), + ("fan", None, True), + ] + assert "one of (choices omitted)" in power.help + assert power.usage == "Usage: power [-h] [--fan SPEED] MODE" + + +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 + + +def test_a_subcommand_which_no_spelling_gets_through_the_prompt_whole_is_left_out() -> None: + app = SpacedApp() + snapshot = ex.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}'"): + app.ran = None + app.onecmd_plus_hooks(f"report {typed}") + assert app.ran != summary + assert name not in {subcommand.name for subcommand in snapshot.descriptions["report"].subcommands} + assert not [d for d in snapshot.descriptions.values() if d.summary == summary] + + +def test_usage_and_help_name_each_subcommand_as_it_is_typed() -> None: + app = SpacedApp() + snapshot = ex.build_snapshot(app, 1) + spaced = snapshot.descriptions['report "list all"'] + assert spaced.usage == 'Usage: report "list all" [-h]' + assert spaced.help.startswith(spaced.usage) + assert snapshot.descriptions["report list all"].usage == "Usage: report list all [-h]" # the other one + assert snapshot.descriptions['report "per|site"'].usage == 'Usage: report "per|site" [-h]' + # Help would make the tab spaces, as many as reach the next tab stop: here, the name of the sibling with six. + tabbed = snapshot.descriptions['report "tab\there"'] + assert tabbed.usage == 'Usage: report "tab\there" [-h]' + assert tabbed.help.startswith(tabbed.usage) + assert snapshot.descriptions['report "tab here"'].usage == 'Usage: report "tab here" [-h]' + assert snapshot.descriptions['report ""'].usage == 'Usage: report "" [-h]' + assert snapshot.descriptions["report today's"].usage == "Usage: report today's [-h]" + # A positional before the subcommands stays where argparse puts it, at every depth. + assert snapshot.descriptions['owner "list all"'].usage == 'Usage: owner name "list all" [-h] {x y} ...' + assert snapshot.descriptions['owner "list all" "x y"'].usage == 'Usage: owner name "list all" "x y" [-h]' + # The parsers which the prompt uses are as they were. + func = app.get_command_func("report") + assert func is not None + parser = app.command_parsers.get(func) + assert parser is not None + assert parser.get_subparsers_action().choices["list all"].prog == "report list all" + + +def test_describing_takes_the_first_word_as_the_prompt_does_as_the_name_of_a_command() -> None: + snapshot = ex.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) + + +def test_describing_a_suppressed_subcommand_is_an_error_as_for_a_hidden_command() -> None: + snapshot = ex.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) + 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) + assert (answer.generation, answer.shortcuts, answer.aliases, answer.macros) == ( + 3, + snapshot.shortcuts, + snapshot.aliases, + snapshot.macros, + ) + + +class ExtraCommands(cmd2.CommandSet): + def do_extra(self, _: cmd2.Statement) -> None: + """A command which comes and goes.""" + + +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) + self.onecmd_plus_hooks("alias create usage help") + + class App(ex.McpServerMixin, ExistingApp): + pass + + app = App(mcp_port=None) + assert app.aliases["usage"] == "help" + assert app.mcp_snapshot.generation == 0 + app.mcp_start() + assert app.mcp_snapshot.generation == 1 + assert ex.Alias("usage", "help") in app.mcp_snapshot.aliases + + +class RebuildApp(ex.McpServerMixin, 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) + self.extra = ExtraCommands() + self.starts = 0 + self.stops = 0 + self.disable_command("gated", "not now") + + def mcp_start(self) -> None: + self.starts += 1 + super().mcp_start() + + def mcp_stop(self) -> None: + self.stops += 1 + super().mcp_stop() + + def do_load(self, _: cmd2.Statement) -> None: + self.register_command_set(self.extra) + + def do_unload(self, _: cmd2.Statement) -> None: + self.unregister_command_set(self.extra) + + def do_gated(self, _: cmd2.Statement) -> None: + """Disabled until something enables it.""" + + def do_multi(self, statement: cmd2.Statement) -> None: + """A multiline command.""" + + def do_fail(self, _: cmd2.Statement) -> None: + raise cmd2.exceptions.PassThroughException(wrapped_ex=RuntimeError("out of the command")) + + +def _listed(app: Any) -> set[str]: + """The names of the commands the application's latest snapshot lists.""" + return _names(app.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 + app.onecmd_plus_hooks("load") + assert "extra" in _listed(app) + assert app.mcp_snapshot.generation == first + 1 + app.onecmd_plus_hooks("unload") + assert "extra" not in _listed(app) + assert app.mcp_snapshot.generation == first + 2 + + +def test_a_script_publishes_once(tmp_path: Path) -> None: + script = tmp_path / "script.txt" + script.write_text("# a comment\nload\n\nunload\n", encoding="utf-8") + app = RebuildApp() + app.mcp_start() + first = app.mcp_snapshot.generation + app.onecmd_plus_hooks(f"run_script {su.quote(str(script))}") + assert app.mcp_snapshot.generation == first + 1 + assert "extra" not in _listed(app) + assert app._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 + app.onecmd_plus_hooks(line) + assert (app.mcp_snapshot.generation, app._mcp_depth) == (first + 1, 0) + + +@pytest.mark.parametrize("registered", ["before the mixin is set up", "after"]) +def test_a_finalization_hook_which_raises_once_does_not_freeze_the_description(registered: str) -> None: + calls = [] + + def hook(data: cmd2.plugin.CommandFinalizationData) -> cmd2.plugin.CommandFinalizationData: + calls.append(1) + if len(calls) == 1: + raise RuntimeError("once") + return data + + class RegistersEarly(cmd2.Cmd): + """Below the mixin in the bases, so its __init__ has finished before the mixin's has.""" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + if registered == "before the mixin is set up": + self.register_cmdfinalization_hook(hook) + + class HookApp(ex.McpServerMixin, RegistersEarly): + def __init__(self) -> None: + super().__init__(mcp_port=None, allow_cli_args=False) + self.extra = ExtraCommands() + + def do_load(self, _: cmd2.Statement) -> None: + self.register_command_set(self.extra) + + app = HookApp() + if registered == "after": + 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 + app.onecmd_plus_hooks("load") + assert "extra" in _listed(app) + + +def test_a_command_which_raises_out_still_publishes() -> None: + app = RebuildApp() + app.mcp_start() + first = app.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) + + +def test_arguments_are_passed_through_unchanged() -> None: + app = RebuildApp() + before = len(app.history) + assert app.onecmd_plus_hooks("help", add_to_history=False, py_bridge_call=True) is False + assert len(app.history) == before + + +@pytest.mark.parametrize("moment", ["mcp_start", "the start of cmdloop", "pre_prompt", "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 + protected = [] + build = app._mcp_build + monkeypatch.setattr(app, "_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. + assert protected == ([True, True] if moment == "the start of cmdloop" else [True]) + assert not app.sigint_protection + + +@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)) + 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) + + +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"))) + 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 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"))) + 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) + + 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) + app.onecmd_plus_hooks("help") + assert app.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"))) + 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"))) + app.mcp_start() + assert app.mcp_snapshot.commands == () + assert "a defect" in app.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)) + app.mcp_start() + first = app.mcp_snapshot + app.onecmd_plus_hooks("help") + second = app.mcp_snapshot + assert second.generation == first.generation + 1 + assert ex.answer_list_commands(second).error == app.mcp_build_error == "RuntimeError: second" + app.onecmd_plus_hooks("help") + assert app.mcp_snapshot is second + + +def test_a_command_which_cannot_be_described_is_reported_once(capsys) -> None: + class BrokenApp(RebuildApp): + @cmd2.with_argparser(_raises_boom) # the parser factory of Task 4 which raises RuntimeError("boom") + def do_broken(self, _: argparse.Namespace) -> None: + """A command whose parser cannot be built.""" + + app = BrokenApp() + app.mcp_start() + for _ in range(3): + app.onecmd_plus_hooks("help") + assert capsys.readouterr().err.count("boom") == 1 + 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: + app = RebuildApp(mcp_leave_out=["shell"]) + app.mcp_start() + app.onecmd_plus_hooks("load") + assert "shell" not in _listed(app) + assert "extra" in _listed(app) + + +class PromptApp(RebuildApp): + """Records what is published each time cmd2 is about to prompt.""" + + 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)))) + + +class LoopApp(PromptApp): + """Records what each outermost command left published, and has commands which run other commands.""" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.at_ends: list[tuple[str, int, frozenset[str]]] = [] # line, generation, names + self.seen: dict[str, Any] = {} # what the commands below saw while they ran + + 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)))) + + 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.enable_command("gated") + self.onecmd_plus_hooks("multi one") + self.disable_command("gated", "not now") + self.seen["outer ended"] = len(self.at_prompts) + + 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))) + + +class PreloopApp(LoopApp): + """Disables help in preloop(): after the server has started, and before the first description is built.""" + + def preloop(self) -> None: + super().preloop() + self.disable_command("help", "not now") + + +class ChangesHelpBeforeSuper(PromptApp): + """Disables help before its first prompt and enables it before its second, each before super().pre_prompt().""" + + def pre_prompt(self) -> None: + if len(self.at_prompts) == 0: + self.disable_command("help", "not now") + elif len(self.at_prompts) == 1: + self.enable_command("help") + super().pre_prompt() + + +# The same condition and reason as tests/test_cmd2.py::test_pre_prompt_running_loop. +needs_a_pipe_prompt = pytest.mark.skipif( + sys.platform.startswith("win"), + reason="Don't have a real Windows console with how we are currently running tests in GitHub Actions", +) + + +@contextlib.contextmanager +def piped(app: cmd2.Cmd) -> Iterator[PipeInput]: + """Give the application a prompt session on a pipe, as tests/test_cmd2.py::test_pre_prompt_running_loop does.""" + with create_pipe_input() as pipe_input: + app.main_session = PromptSession( + input=pipe_input, + output=DummyOutput(), + history=app.main_session.history, + completer=app.main_session.completer, + ) + yield pipe_input + + +def type_lines(pipe_input: PipeInput, *lines: str) -> None: + """Type the lines, then end the input: a test which goes wrong then ends, instead of waiting for more.""" + pipe_input.send_text("".join(f"{line}\n" for line in lines)) + pipe_input.close() + + +@pytest.fixture +def signal_handlers_restored() -> Iterator[None]: + """Put back the handlers which cmd2's cmdloop() installs, and does not restore when an exception leaves it.""" + signums = [signal.SIGINT] if sys.platform.startswith("win") else [signal.SIGINT, signal.SIGHUP, signal.SIGTERM] + saved = {signum: signal.getsignal(signum) for signum in signums} + yield + for signum, handler in saved.items(): + 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() + with piped(app) as pipe_input: + type_lines(pipe_input, "quit") + app.cmdloop() + depth, _, names = app.at_prompts[0] + assert "help" not in names + assert depth == 0 + + +@needs_a_pipe_prompt +def test_pre_prompt_override_which_changes_commands_before_super() -> None: + app = ChangesHelpBeforeSuper() + with piped(app) as pipe_input: + type_lines(pipe_input, "help", "quit") + app.cmdloop() + assert "help" not in app.at_prompts[0][2] + 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): + 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) + + +@needs_a_pipe_prompt +def test_nothing_is_published_at_a_continuation_prompt() -> None: + app = LoopApp() + with piped(app) as pipe_input: + type_lines(pipe_input, "outer", "two;", "quit") + app.cmdloop() + began, before = app.seen["outer began"] + ended = app.seen["outer ended"] + during = app.at_prompts[began:ended] + assert len(during) == 1 # the continuation prompt of "multi one", run by outer + assert all(depth > 0 and generation == before for depth, generation, _ in during) + [(_, at_end, listed_at_end)] = [entry for entry in app.at_ends if entry[0] == "outer"] + assert "gated" not in listed_at_end + assert not any("gated" in names for _, _, names in app.at_prompts) + assert app.at_prompts[began - 1][:2] == (0, before) # the top-level prompt before outer published this one, + assert before == 2 # which raised the generation 1 built once preloop() had returned, + assert app.at_prompts[ended][:2] == (0, at_end + 1) # and the one after outer raised outer's + + +@needs_a_pipe_prompt +def test_a_multiline_command_at_the_top_level_publishes_at_its_end() -> None: + app = LoopApp() + with piped(app) as pipe_input: + type_lines(pipe_input, "multi one", "two", "three;", "quit") + app.cmdloop() + before, first_continuation, second_continuation, after = app.at_prompts + assert before[:2] == (0, 2) # one rise at the prompt before it, above the generation 1 built after preloop() + generation = before[1] + assert first_continuation[:2] == second_continuation[:2] == (1, generation) # none at its two continuation prompts + assert app.at_ends[0][:2] == ("multi one", generation + 1) # one when it ends + assert after[:2] == (0, generation + 2) + + +class ReadsRecorded(io.StringIO): + """Input which is not a terminal, and records what the application served each time cmd2 read a line of it.""" + + def __init__(self, text: str) -> None: + super().__init__(text) + self.app: Any = None + self.at_reads: list[ex.Snapshot] = [] + + def readline(self, *args: Any) -> str: + self.at_reads.append(self.app.mcp_snapshot) + return super().readline(*args) + + +class StartsUp(PreloopApp): + """Runs a command in preloop(), before it disables help, and records what was served when preloop() returned.""" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.at_preloop_ends: list[ex.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) + + +class LoopsInPreloop(RebuildApp): + """Runs a command loop of its own in its first preloop(), then disables shell, recording what was served then.""" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.preloops = 0 + self.served_after_the_inner_loop: ex.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.disable_command("shell", "not now") + + +def test_a_loop_run_inside_preloop_does_not_end_the_start() -> None: + app = LoopsInPreloop(stdin=io.StringIO("help\nquit\nquit\n")) # the inner loop runs help and quit + app.cmdloop() + during = app.served_after_the_inner_loop + 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) + + +def test_nothing_is_described_until_preloop_has_returned_when_input_is_not_a_terminal() -> None: + stdin = ReadsRecorded("help -v\nquit\n") + app = StartsUp(stdin=stdin) + stdin.app = app + app.cmdloop() + [during] = app.at_preloop_ends + assert (during.commands, during.error) == ((), "The description has not been built yet.") + first_read = stdin.at_reads[0] + assert first_read.error is None + assert "help" not in _names(first_read) # which preloop() disabled, after the server had started + + +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 + assert last.error is None + app.cmdloop() + second = app.at_preloop_ends[1] + assert (second.commands, second.error) == ((), "The description has not been built yet.") + assert second.generation == last.generation + 1 + + +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"))) + app.cmdloop() + last = app.mcp_snapshot + assert last.error == "RuntimeError: previous failure" + observed = [] + monkeypatch.setattr(app, "preloop", lambda: observed.append((app.mcp_snapshot, app.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 + + +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"))) + 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 + + +def test_preloop_which_disables_a_command_is_seen_when_input_is_not_a_terminal() -> None: + app = PreloopApp(stdin=io.StringIO("help -v\nquit\n")) + app.cmdloop() + assert app.at_prompts == [] # pre_prompt() was never called + line, _, names = app.at_ends[0] + assert line == "help -v" + assert "help" not in names + + +@pytest.mark.usefixtures("signal_handlers_restored") +def test_an_exception_which_escapes_the_loop_still_stops_once() -> None: + class FailsInPreloop(RebuildApp): + def preloop(self) -> None: + raise RuntimeError("in preloop") + + app = FailsInPreloop() + with pytest.raises(RuntimeError, match="in preloop"): + app.cmdloop() + assert (app.starts, app.stops) == (1, 1) + assert app._mcp_loops == 0 + app.mcp_stop() # again: nothing is raised + RebuildApp().mcp_stop() # with no start: nothing is raised + + +def test_only_the_outermost_cmdloop_starts_and_stops() -> None: + app = LoopApp(stdin=io.StringIO("inner\nload\nquit\nquit\n")) + app.cmdloop() + assert (app.starts, app.stops) == (1, 1) + loops, listed_then = app.seen["inner loop returned"] + assert loops == 1 # the outer loop's, which is still running + assert "extra" not in listed_then # nothing is published while inner is in progress + line, _, names = app.at_ends[0] + assert line == "inner" + assert "extra" in names + + +def test_cmdloop_twice_starts_and_stops_twice() -> None: + app = RebuildApp(stdin=io.StringIO("quit\nquit\n")) + app.cmdloop() + app.cmdloop() + assert (app.starts, app.stops) == (2, 2) + + +def test_cmdloop_in_an_embedded_command_preserves_the_manually_started_server() -> None: + app = LoopApp(stdin=io.StringIO("load\nquit\n")) + app.mcp_start() + try: + previous = app.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 "extra" in _listed(app) + finally: + app.mcp_stop() + + +def test_a_reader_always_sees_a_whole_snapshot() -> None: # Review Focus 4 + app = RebuildApp() + app.mcp_start() + loaded = {app.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) + names = {command.name for category in answer.categories for command in category.commands} + seen.add((answer.generation, "extra" in names)) + + with ThreadPoolExecutor(max_workers=1) as executor: + reading = executor.submit(read) + try: + # Each rebuild describes every command, so this is the slowest test of the suite: on a slow CI runner, 100 + # rounds took over a minute. 20 still give the reader dozens of generations to read while they change. + for _ in range(20): + for line in ("load", "unload"): + app.onecmd_plus_hooks(line) + loaded[app.mcp_snapshot.generation] = line == "load" + finally: + done.set() + reading.result() # raises whatever the reader raised + assert len({generation for generation, _ in seen}) > 1 # it read while the description changed + assert all(listed is loaded[generation] for generation, listed in seen) + + +WATCHED = ("", "uvicorn", "uvicorn.error", "uvicorn.access", "uvicorn.asgi", "mcp", "mcp.server.streamable_http_manager") + + +def logging_state() -> dict[str, tuple[tuple[logging.Handler, ...], int, bool]]: + """The handlers, level and propagate of every logger the server could touch.""" + return { + name: (tuple(logging.getLogger(name).handlers), logging.getLogger(name).level, logging.getLogger(name).propagate) + for name in WATCHED + } + + +@pytest.fixture(autouse=True) +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 + for _ in range(left): + ex._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() + during = logging_state() + for name in ex.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() + assert logging_state() == during # a second hold changes nothing more + ex._shared_logging.release() + assert logging_state() == during # the first to let go puts nothing back + ex._shared_logging.release() + assert logging_state() == before + ex._shared_logging.release() # redundant cleanup must leave the application's logging intact + assert logging_state() == before + assert ex._shared_logging.holds == 0 + + +def test_shared_logging_keeps_records_from_the_root_and_from_the_handler_of_last_resort(capsys) -> None: + root_saw = [] + handler = logging.Handler() + handler.emit = root_saw.append + logging.getLogger().addHandler(handler) + earlier = ex._shared_logging.records() + ex._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() + 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)] + assert {"from the server", "from the sdk"} <= {record.getMessage() for record in kept_here} + assert capsys.readouterr().err == "" + + +def test_shared_logging_leaves_the_applications_own_handlers_alone() -> None: + own_saw = [] + own = logging.Handler() + own.emit = own_saw.append + logger = logging.getLogger("mcp.server.streamable_http_manager") + logger.addHandler(own) + try: + ex._shared_logging.take() + logger.warning("asked for") + assert own in logger.handlers + ex._shared_logging.release() + assert own in logger.handlers + finally: + logger.removeHandler(own) + assert [record.getMessage() for record in own_saw] == ["asked for"] + + +def test_root_logger_left_alone_when_it_has_no_handler() -> None: + root = logging.getLogger() + saved, root.handlers = root.handlers, [] + try: + level = root.level + with ex._root_logger_left_alone(): + logging.basicConfig(level=logging.INFO) # what MCPServer() does + assert (root.handlers, root.level) == ([], level) + finally: + root.handlers = saved + + +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)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert logging_state() == before + + +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.acquire() + held = True + try: + with ThreadPoolExecutor(max_workers=1) as executor: + copying = executor.submit(ex._shared_logging.records) + with pytest.raises(TimeoutError): + copying.result(timeout=0.2) + handler.release() + held = False + assert isinstance(copying.result(timeout=10), list) + finally: + if held: + handler.release() + + +# --------------------------------------------------------------------------------------------------------------------- +# The server itself. These tests need the MCP SDK: "uv run --group examples pytest ...". +# --------------------------------------------------------------------------------------------------------------------- + + +def _require_sdk() -> None: + """Skip the test where version 2 of the MCP SDK is not installed, unless this run exists to run it. + + 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) + import uvicorn # noqa: F401 + + return + pytest.importorskip("mcp.server.mcpserver") + pytest.importorskip("uvicorn") + + +@pytest.fixture +def sdk() -> None: + _require_sdk() + + +def test_the_sdk_check_wants_version_2_of_the_sdk(monkeypatch: pytest.MonkeyPatch) -> None: + # Where version 1 of the SDK is installed, "mcp" and "uvicorn" import, but "mcp.server.mcpserver", which the example + # imports, does not. Empty modules stand in for the two, and None in sys.modules makes the third fail to import. + 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) + with pytest.raises(pytest.skip.Exception): + _require_sdk() + monkeypatch.setenv("CMD2_EXAMPLE_TESTS_NEED_SDK", "1") + with pytest.raises(ImportError): + _require_sdk() + + +CLIENT = """ +import asyncio, json, sys +from mcp import Client + + +async def main(url, tool, arguments): + async with Client(url) as client: + if not tool: + return [ + { + "name": found.name, + "read_only": found.annotations.read_only_hint, + "open_world": found.annotations.open_world_hint, + "has_output_schema": bool(found.output_schema), + } + for found in (await client.list_tools()).tools + ] + result = await client.call_tool(tool, arguments) + return { + "is_error": result.is_error, + "structured": result.structured_content, + "text": [getattr(part, "text", None) for part in result.content], + } + + +print(json.dumps(asyncio.run(main(sys.argv[1], sys.argv[2], json.loads(sys.argv[3]))))) +""" + + +def ask(url: str, tool: str = "", arguments: dict[str, Any] | None = None) -> Any: + """List the tools, or call one, from a process of its own, and return what it printed. + + A process, so that the client's own logging (its HTTP library logs each request at INFO) is not in + the application's process, where the tests measure what the server logs; and so that the deadline + is real, and it can be called from inside prompt-toolkit's running event loop. + """ + done = subprocess.run( + [sys.executable, "-c", CLIENT, url, tool, json.dumps(arguments or {})], + capture_output=True, + text=True, + timeout=60, + check=True, + ) + return json.loads(done.stdout) + + +def environment_without_coverage() -> dict[str, str]: + """This process's environment, less the variables which start coverage in a Python subprocess. + + With coverage on, pyproject.toml has it start in every Python subprocess, and on Python 3.11, which has no + sys.monitoring, it warns on the subprocess's stderr. The subprocesses which run the example check its own stderr. + They need no coverage: it measures only cmd2, which the rest of the suite measures. + """ + starts_coverage = {"COVERAGE_PROCESS_CONFIG", "COVERAGE_PROCESS_START"} + return {name: value for name, value in os.environ.items() if name not in starts_coverage} + + +def run_without_sdk(body: str) -> subprocess.CompletedProcess[str]: + """Run code in a fresh interpreter in which the SDK cannot be imported, installed or not, and without coverage. + + A fresh one, because hiding ``mcp`` in a process which has already imported it leaves its + submodules importable. The example is loaded as ``ex`` before the code runs. + """ + preamble = ( + "import sys\n" + "sys.modules['mcp'] = None\n" + "sys.modules['uvicorn'] = None\n" + "import importlib.util, json, logging\n" + "import cmd2\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" + "spec.loader.exec_module(ex)\n" + ) + return subprocess.run( + [sys.executable, "-c", preamble + body], + capture_output=True, + text=True, + timeout=60, + check=False, + env=environment_without_coverage(), + ) + + +def run_with_the_example(body: str, *args: str) -> subprocess.CompletedProcess[str]: + """Run code in a fresh interpreter, with the example loaded as ``ex`` before the code runs, and args in sys.argv[1:]. + + Without coverage, as run_without_sdk() runs it. + + For a test which delivers a real SIGINT: in a process of its own, pytest's handling of Ctrl-C is never involved, and + a handler left behind cannot reach another test. + """ + preamble = ( + "import importlib.util, json, logging, signal, sys, threading\n" + "import cmd2\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" + "spec.loader.exec_module(ex)\n" + ) + return subprocess.run( + [sys.executable, "-c", preamble + body, *args], + capture_output=True, + text=True, + timeout=60, + check=False, + env=environment_without_coverage(), + ) + + +def can_bind(port: int) -> bool: + """Whether the port can be bound again at once, the way the example binds it.""" + try: + socket.create_server(("127.0.0.1", port)).close() + except OSError: + return False + return True + + +def free_port() -> int: + """A port which nothing was listening on a moment ago.""" + with socket.create_server(("127.0.0.1", 0)) as sock: + return sock.getsockname()[1] + + +def as_json(value: Any) -> Any: + """An answer as a client receives it: dataclasses.asdict() with every tuple turned into a list, recursively.""" + + def lists(item: Any) -> Any: + if isinstance(item, dict): + return {key: lists(inner) for key, inner in item.items()} + if isinstance(item, (list, tuple)): + return [lists(inner) for inner in item] + return item + + return lists(dataclasses.asdict(value)) + + +def names_listed(answer: dict[str, Any]) -> set[str]: + """The names of the commands in a client's answer from list_commands.""" + return {command["name"] for category in answer["categories"] for command in category["commands"]} + + +@pytest.fixture +def serving(sdk: None) -> Iterator[Any]: + """A RebuildApp serving on a port the system chose; stopped afterwards.""" + app = RebuildApp(mcp_port=0) + app.mcp_start() + assert app.mcp_url is not None, app.mcp_status() + yield app + app.mcp_stop() + + +class ProbeApp(LoopApp): + """Asks its own server for the list of commands, from a client in another process, when told to.""" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.probes: list[tuple[Any, str | None, Any]] = [] # the run, the URL, and the answer + + 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)) + + +def test_serves_three_read_only_tools(serving) -> None: + tools = {tool["name"]: tool for tool in ask(serving.mcp_url)} + assert set(tools) == {"list_commands", "describe_command", "list_shortcuts_aliases_macros"} + for tool in tools.values(): + assert (tool["read_only"], tool["open_world"], tool["has_output_schema"]) == (True, False, True) + + +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)) + described = ask(serving.mcp_url, "describe_command", {"command": "help"}) + assert described["structured"] == as_json(ex.answer_describe_command(serving.mcp_snapshot, "help")) + tables = ask(serving.mcp_url, "list_shortcuts_aliases_macros") + assert tables["structured"] == as_json(ex.answer_tables(serving.mcp_snapshot)) + + +def test_describe_command_preserves_a_nonfinite_default_over_mcp(sdk) -> None: + class LimitApp(RebuildApp): + limit_parser = cmd2.Cmd2ArgumentParser() + limit_parser.add_argument("--limit", type=float, default=float("inf")) + + @cmd2.with_argparser(limit_parser) + def do_budget(self, args: argparse.Namespace) -> None: + """Show the limit.""" + + app = LimitApp(mcp_port=0) + try: + app.mcp_start() + result = ask(app.mcp_url, "describe_command", {"command": "budget"}) + assert result["is_error"] is False + [argument] = result["structured"]["description"]["arguments"] + assert (argument["name"], argument["parser_default"]) == ("limit", "inf") + finally: + app.mcp_stop() + + +def test_surrogate_escaped_paths_serialize_over_mcp(sdk) -> None: + path = b"caf\xc3\xa9-\xff".decode("utf-8", errors="surrogateescape") + expected = "café-" + r"\udcff" + + class PathApp(RebuildApp): + path_parser = cmd2.Cmd2ArgumentParser() + path_parser.add_argument("--file", default=path) + + @cmd2.with_argparser(path_parser) + def do_read(self, _: argparse.Namespace) -> None: + pass + + app = PathApp(mcp_port=0) + app.aliases["readfile"] = f"read --file {path}" + try: + app.mcp_start() + described = ask(app.mcp_url, "describe_command", {"command": "read"}) + assert described["is_error"] is False + assert described["structured"]["description"]["arguments"][0]["parser_default"] == expected + tables = ask(app.mcp_url, "list_shortcuts_aliases_macros")["structured"] + assert any(alias["value"] == f"read --file {expected}" for alias in tables["aliases"]) + finally: + app.mcp_stop() + + +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") + 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 + assert "RuntimeError: a defect" in described["text"][0] + assert ask(serving.mcp_url, "list_shortcuts_aliases_macros")["structured"]["error"] == "RuntimeError: a defect" + + +def test_describing_an_unknown_command_is_a_tool_error_which_names_what_exists(serving) -> None: + result = ask(serving.mcp_url, "describe_command", {"command": "nonesuch"}) + assert result["is_error"] is True + assert "help" in result["text"][0] + + +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")])) + serving.onecmd_plus_hooks("load") + assert ask(serving.mcp_url, "list_commands")["structured"]["stale_reason"] == "RuntimeError: first" + serving.onecmd_plus_hooks("") + missing = ask(serving.mcp_url, "describe_command", {"command": "extra"}) + assert missing["is_error"] + assert "out of date: RuntimeError: second" in missing["text"][0] + serving.onecmd_plus_hooks("") + current = ask(serving.mcp_url, "describe_command", {"command": "extra"}) + assert current["structured"]["stale_reason"] is None + assert current["structured"]["description"]["path"] == "extra" + + +def test_the_next_call_shows_a_command_set_which_a_command_registered(serving) -> None: + before = ask(serving.mcp_url, "list_commands")["structured"] + serving.onecmd_plus_hooks("load") + after = ask(serving.mcp_url, "list_commands")["structured"] + assert after["generation"] == before["generation"] + 1 + assert "extra" in json.dumps(after) + assert "extra" not in json.dumps(before) + + +def test_a_request_from_another_origin_is_refused(serving) -> None: + request = urllib.request.Request( + serving.mcp_url, + data=b'{"jsonrpc":"2.0","id":1,"method":"tools/list"}', + headers={ + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + "Origin": "https://example.com", + }, + ) + with pytest.raises(urllib.error.HTTPError) as refused: + urllib.request.urlopen(request, timeout=10) + assert 400 <= refused.value.code < 500 + + +def test_stopping_ends_the_worker_frees_the_port_and_writes_nothing(sdk, capfd) -> None: + before = logging_state() + app = RebuildApp(mcp_port=0) + app.mcp_start() + run = app._mcp_run + ask(app.mcp_url, "list_commands") + app.mcp_stop() + assert not run.worker.is_alive() + assert (run.outcome, run.stop_requested, run.abandoned) == ("stopped", True, False) + assert can_bind(run.port) + assert app.mcp_url is None + assert logging_state() == before + assert capfd.readouterr() == ("", "") + app.mcp_stop() # again: nothing + + +def test_cmdloop_run_twice_serves_both_times(sdk) -> None: + port = free_port() + app = ProbeApp(mcp_port=port, stdin=io.StringIO("probe\nquit\nprobe\nquit\n")) + app.cmdloop() + app.cmdloop() + (first_run, _, first), (second_run, _, second) = app.probes + assert first is not None + assert second is not None + assert first_run is not second_run + assert first_run.number != second_run.number + assert first_run.port == second_run.port == port + assert can_bind(port) + + +def test_an_inner_cmdloop_starts_no_second_server_and_leaves_the_first_serving(sdk) -> None: + app = ProbeApp(mcp_port=0, stdin=io.StringIO("inner\nprobe\nquit\nprobe\nquit\n")) + app.cmdloop() + assert app.starts == 1 + (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 + + +def test_a_second_application_on_the_same_port_warns_and_runs_without_a_server(serving, capsys) -> None: + port = serving._mcp_run.port + capsys.readouterr() + second = RebuildApp(mcp_port=port) + second.mcp_start() + assert second.mcp_url is None + err = capsys.readouterr().err + assert err.count("MCP server not started") == 1 + 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 f"port {port}: OSError" in status[0] + + +def test_a_replacement_binds_at_once_while_a_client_is_still_connected(sdk) -> None: + first = RebuildApp(mcp_port=0) + first.mcp_start() + assert first.mcp_url is not None, first.mcp_status() + port = first._mcp_run.port + with socket.create_connection(("127.0.0.1", port), timeout=10): + first.mcp_stop() + second = RebuildApp(mcp_port=port) + second.mcp_start() + try: + assert second.mcp_url == f"http://127.0.0.1:{port}/mcp", second.mcp_status() + assert ask(second.mcp_url, "list_commands")["is_error"] is False + finally: + second.mcp_stop() + + +@pytest.mark.parametrize("port", [70000, -1]) +def test_a_port_which_is_not_a_port_is_a_warning(port: int, sdk, capsys) -> None: # Review Focus 2 + before = logging_state() + handler = signal.getsignal(signal.SIGINT) + app = RebuildApp(mcp_port=port) + app.mcp_start() + assert app.mcp_url is None + err = capsys.readouterr().err + assert err.count("MCP server not started") == 1 + assert f"port {port}:" in err + assert logging_state() == before + assert signal.getsignal(signal.SIGINT) is handler # the bind raised while Ctrl-C was held off: put back all the same + + +def test_without_the_sdk_the_application_warns_and_carries_on(monkeypatch, capsys) -> None: + monkeypatch.setitem(sys.modules, "mcp.server.mcpserver", None) + before = logging_state() + app = RebuildApp(mcp_port=0) + app.mcp_start() + assert app.mcp_url is None + assert app.mcp_snapshot.commands + err = capsys.readouterr().err + assert err.count("MCP server not started") == 1 + assert "--group examples" in err + assert app.mcp_status()[0].startswith("No MCP server") + assert logging_state() == before + + +@pytest.mark.parametrize("step", ["_mcp_asgi_app()", "uvicorn.Server", "threading.Thread.start"]) +def test_a_start_which_fails_part_of_the_way_is_undone(step: str, sdk, capsys, monkeypatch) -> None: + import uvicorn + + part_way = RuntimeError("part way") + before = logging_state() + 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)) + elif step == "uvicorn.Server": + monkeypatch.setattr(uvicorn, "Server", mock.Mock(side_effect=part_way)) + else: + start = threading.Thread.start + + def start_any_but_a_worker(thread: threading.Thread) -> None: + if thread.name.startswith("mcp-server-"): + raise part_way + start(thread) + + monkeypatch.setattr(threading.Thread, "start", start_any_but_a_worker) + app.mcp_start() + run = app._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 logging_state() == before + err = capsys.readouterr().err + assert err.count("MCP server not started") == 1 + assert "part way" in err + assert app.mcp_url is None + status = app.mcp_status() + assert status[0].startswith("No MCP server") + assert "part way" in status[0] + assert run.worker is None + assert signal.getsignal(signal.SIGINT) is handler # Thread.start() raised while Ctrl-C was held off: put back all the same + + +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): + app.cmdloop() + assert app.stops == 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 logging_state() == before + + +@needs_a_pipe_prompt +def test_nothing_is_published_at_a_continuation_prompt_as_a_client_sees_it(sdk) -> None: + class AsksAtPrompts(LoopApp): + """Asks its own server for the list of commands at each prompt, as a client in another process.""" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.asked: list[dict[str, Any]] = [] # one for each entry of at_prompts + + def pre_prompt(self) -> None: + super().pre_prompt() + self.asked.append(ask(self.mcp_url, "list_commands")["structured"]) + + app = AsksAtPrompts(mcp_port=0) + with piped(app) as pipe_input: + type_lines(pipe_input, "outer", "two;", "quit") + app.cmdloop() + began, before = app.seen["outer began"] + ended = app.seen["outer ended"] + assert ended == began + 1 # one prompt while outer ran: the continuation prompt of "multi one" + at_continuation, after_outer = app.asked[began], app.asked[ended] + assert at_continuation["generation"] == before + assert "gated" not in names_listed(at_continuation) + assert after_outer["generation"] > before + assert "gated" not in names_listed(after_outer) + + +def test_status_lines(serving, monkeypatch) -> None: + snapshot = serving.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" + [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"))) + 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) + 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() + assert serving.mcp_status()[0] == "No MCP server: it was stopped" + + +def test_a_start_while_serving_makes_no_new_run_binds_nothing_and_warns_of_nothing(serving, capfd, monkeypatch) -> None: + run = serving._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_url == run.url + binds.assert_not_called() + assert ex._shared_logging.holds == 1 + assert capfd.readouterr() == ("", "") + + +def test_ctrl_c_part_of_the_way_through_a_direct_start_is_undone_by_the_start(sdk) -> None: + before = logging_state() + app = RebuildApp(mcp_port=0) + try: + with mock.patch.object(app, "_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 + 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 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 + finally: + app.mcp_stop() # whichever run is the last, even when an assertion above failed + assert logging_state() == before + + +def hold_the_worker_as_it_lets_go_of_the_logging(run: Any, entered: threading.Event, release: threading.Event) -> None: + """Make the run's worker wait as it enters release_logging(): it has recorded how it ended, and still holds the logging. + + It waits until release is set, or 30 seconds. The test sets it in a finally. + """ + let_go = run.release_logging + + def held() -> None: + if threading.current_thread() is run.worker: + entered.set() + release.wait(30) + let_go() + + run.release_logging = held + + +def test_status_says_a_run_ended_by_itself_once_its_worker_has_recorded_how(sdk) -> None: + entered, release = threading.Event(), threading.Event() + app = RebuildApp(mcp_port=0) + app.mcp_start() + run = app._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}" + run.server.should_exit = True # as if the server had ended for a reason of its own + assert entered.wait(30) + assert run.worker.is_alive() # it has not let go of the logging yet, + assert run.server.started # and uvicorn still says it started, + assert (run.stop_requested, run.outcome) == (False, "stopped") # but it has recorded how it ended + assert app.mcp_url is None + assert app.mcp_status()[0] == "No MCP server: it ended by itself (stopped)" + finally: + release.set() + app.mcp_stop() + if run.worker is not None: + run.worker.join(timeout=30) + assert not run.worker.is_alive() + + +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" + 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 + 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)" + run.stop_requested = True + assert app.mcp_status()[0] == "No MCP server: it was stopped" + run.outcome, run.detail = "failed", "RuntimeError: a defect" + assert app.mcp_status()[0] == "No MCP server: it failed (RuntimeError: a defect)" + run.problem = "MCP server not started on port 0: the reason. Continuing without it." + assert app.mcp_status()[0] == f"No MCP server: {run.problem}" + + +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 + told = threading.Event() + + class Server: + """Stands in for uvicorn's: Ctrl-C arrives just as the first stop tells it to exit.""" + + started = True + interrupted = False + + @property + def should_exit(self) -> bool: + return told.is_set() + + @should_exit.setter + def should_exit(self, value: bool) -> None: + if not self.interrupted: + self.interrupted = True + raise KeyboardInterrupt + told.set() + + def run(self, sockets: list[socket.socket]) -> None: + told.wait(30) # serves until it is told to exit + + run.server = Server() + 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.start() + try: + with pytest.raises(KeyboardInterrupt): + app.mcp_stop() + app.mcp_stop() # not "stopped already": the first stop did not get as far as telling the server + assert told.is_set() + run.worker.join(30) + assert not run.worker.is_alive() + assert run.sock.fileno() == -1 + assert (run.abandoned, run.outcome, run._holds_logging) == (False, "stopped", False) + assert app.mcp_url is None + finally: + told.set() + run.sock.close() + run.release_logging() + + +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 + resume = threading.Event() + + class Server: + """Stands in for uvicorn's: it serves until the test lets it end.""" + + started = True + should_exit = False + + def run(self, sockets: list[socket.socket]) -> None: + resume.wait(30) + + run.server = Server() + run.sock = socket.socket() + holds = ex._shared_logging.holds + run.take_logging() + worker = threading.Thread(target=ex.McpServerMixin._mcp_serve, args=(run,), name="mcp-server-test", daemon=True) + worker.start() + run.worker = worker + + def join_as_python_3_11_does(timeout: float | None = None) -> None: + # On Python 3.11 and 3.12, Ctrl-C during join() raises KeyboardInterrupt and leaves is_alive() false after it, + # though the thread runs on. Python 3.13 and later do not, so the two are made to behave so here. + worker.is_alive = lambda: False + raise KeyboardInterrupt + + worker.join = join_as_python_3_11_does + try: + with pytest.raises(KeyboardInterrupt): + 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 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) + + +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 + run.take_logging() + release = ex._shared_logging.release + interrupted: list[bool] = [] + + def interrupt_then_release() -> None: + if not interrupted: + interrupted.append(True) + 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) + 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 + finally: + signal.signal(signal.SIGINT, handler) + while ex._shared_logging.holds > holds: + release() # so that no later test finds the logging changed + assert interrupted == [True] + assert left == (False, holds) + assert run.stop_finished is True + + +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 + try: + ex._shared_logging.take() + try: + logging.getLogger("uvicorn.error").handle(malformed) + finally: + ex._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. + with handler.lock, contextlib.suppress(ValueError): + handler.kept.remove(malformed) + assert status[-1].endswith(f" {threading.current_thread().name} ERROR: %s and %s") + + +# --------------------------------------------------------------------------------------------------------------------- +# The server when it cannot start, a worker which was given up on, and two runs alive at once. These need the SDK too. +# --------------------------------------------------------------------------------------------------------------------- + + +class FailsAtOnce(RebuildApp): + """Its server fails its startup, so uvicorn ends with SystemExit and never takes the socket.""" + + def _mcp_asgi_app(self) -> Any: + from starlette.applications import Starlette + + @contextlib.asynccontextmanager + async def lifespan(_: Starlette) -> AsyncIterator[None]: + raise RuntimeError("the startup failed") + yield + + return Starlette(lifespan=lifespan) + + +class StartsTooSlowly(RebuildApp): + """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 + MCP_STOP_TIMEOUT = 0.3 + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.hold = threading.Event() + + def _mcp_asgi_app(self) -> Any: + app = super()._mcp_asgi_app() + inner = app.router.lifespan_context + + @contextlib.asynccontextmanager + async def lifespan(starlette: Any) -> AsyncIterator[None]: + await asyncio.to_thread(self.hold.wait) # in a thread of its own, so the worker's event loop is not blocked + async with inner(starlette): + yield + + app.router.lifespan_context = lifespan + return app + + +@pytest.fixture +def no_thread_exceptions(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + """Fail the test if an exception reached threading.excepthook, which would print a traceback, while it ran.""" + seen: list[threading.ExceptHookArgs] = [] + monkeypatch.setattr(threading, "excepthook", seen.append) + yield + assert not seen, [ + f"{args.thread.name if args.thread else None}: {args.exc_type.__name__}: {args.exc_value}" for args in seen + ] + + +# A test which compares logging_state() before a start with after it starts its own StartsTooSlowly in its body, and lets the +# worker go in a finally of its own. At the start of each phase of a test, pytest (9.2 here) attaches its capture handlers to +# every logger whose propagate is off, so a hold taken while this fixture is set up shows in the test's body as two handlers +# more on each library logger. +@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.mcp_start() + worker = app._mcp_run.worker + try: + yield app + finally: + app.hold.set() + worker.join(timeout=30) + assert not worker.is_alive() + + +class RecordingHandler(logging.Handler): + """Keeps every record it is given, and writes nothing.""" + + def __init__(self) -> None: + super().__init__() + self.records: list[logging.LogRecord] = [] + + def emit(self, record: logging.LogRecord) -> None: + self.records.append(record) + + +@contextlib.contextmanager +def recorded_at_the_root(level: int) -> Iterator[list[logging.LogRecord]]: + """Every record which reaches the root logger's handlers, with the root logger at the level given. Both put back.""" + root = logging.getLogger() + saved_level = root.level + recording = RecordingHandler() + root.addHandler(recording) + root.setLevel(level) + try: + yield recording.records + finally: + root.setLevel(saved_level) + root.removeHandler(recording) + + +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] + + +def propagating() -> list[str]: + """The library loggers whose propagate is on.""" + return [name for name in ex.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.mcp_start() + run = app._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) + assert run.detail.startswith("SystemExit") + assert can_bind(run.port) + status = app.mcp_status() + assert status[0] == f"No MCP server: {run.problem}" + assert f"the server ended before it began serving: {run.detail}" in status[0] + assert logging_state() == before + assert capfd.readouterr() == ("", f"{run.problem}\n") # one warning, and nothing else + + +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.mcp_start() + run = app._mcp_run + try: + assert run.worker.is_alive() + assert (run.stop_requested, run.abandoned, run.outcome) == (True, True, None) + assert run.port != 0 + assert can_bind(run.port) # at once: the socket was closed, though the worker is alive + assert app.mcp_url is None + assert f"did not begin serving within {StartsTooSlowly.MCP_START_TIMEOUT} seconds" in run.problem + status = app.mcp_status() + assert status[0] == f"No MCP server: {run.problem}" + assert f"The worker of run {run.number} was cancelled, and has not ended yet" in status + assert logging_state() != before # not yet: a worker can still log, so it still holds the logging + assert propagating() == [] + assert capfd.readouterr() == ("", f"{run.problem}\n") + finally: + app.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.mcp_start() + run = app._mcp_run + try: + capfd.readouterr() # the warning, which the test above looks at + app.hold.set() + run.worker.join(timeout=30) + assert not run.worker.is_alive() + assert run.outcome == "cancelled" + assert run.detail.startswith("OSError") # it found its socket closed + assert capfd.readouterr() == ("", "") + assert can_bind(run.port) + status = app.mcp_status() + assert status[0] == f"No MCP server: {run.problem}" + 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() + run.worker.join(timeout=30) + assert not run.worker.is_alive() + + +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.mcp_start() + held = first._mcp_run.worker + try: + assert held.is_alive() + assert propagating() == [] # the held worker still holds the logging + second = RebuildApp(mcp_port=0) + second.mcp_start() + try: + assert ask(second.mcp_url, "list_commands")["is_error"] is False + first.hold.set() + held.join(timeout=30) + assert not held.is_alive() + assert first._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() + held.join(timeout=30) + assert not held.is_alive() + assert from_the_libraries(root_saw) == [] + assert logging_state() == before + + +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.mcp_start() + held = first._mcp_run.worker + try: + second = RebuildApp(mcp_port=0) + second.mcp_start() + try: + assert ask(second.mcp_url, "list_commands")["is_error"] is False + finally: + second.mcp_stop() + assert second._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() + held.join(timeout=30) + assert first._mcp_run.outcome == "cancelled" + finally: + first.hold.set() + held.join(timeout=30) + assert not held.is_alive() + assert from_the_libraries(root_saw) == [] + assert logging_state() == before + + +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 + 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() + first.worker.join(timeout=30) + assert first.outcome == "cancelled" + status = second.mcp_status() + assert status[0] == f"Serving {second._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 ask(second.mcp_url, "list_commands")["is_error"] is False + finally: + second.mcp_stop() + + +def test_no_other_library_logs_at_info_or_above(sdk, no_thread_exceptions) -> None: + with recorded_at_the_root(logging.INFO) as root_saw: + app = RebuildApp(mcp_port=0) + app.mcp_start() + try: + assert ask(app.mcp_url, "list_commands")["is_error"] is False + 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) + slow.mcp_start() + held = slow._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 + held.join(timeout=30) + assert not held.is_alive() + assert [(record.name, record.levelname, record.getMessage()) for record in root_saw] == [] + + +@pytest.mark.parametrize("ending", ["stopped", "failed at once", "started too slowly"]) +@pytest.mark.parametrize( + "state", ["root handler on stderr at INFO", "root with no handler", "handlers the application attached"] +) +def test_logging_is_as_it_was(state: str, ending: str, sdk, capfd, no_thread_exceptions) -> None: + root = logging.getLogger() + saved_handlers, saved_level = root.handlers[:], root.level + attached = {"mcp.server.streamable_http_manager": RecordingHandler(), "uvicorn.access": RecordingHandler()} + saved_levels = {name: logging.getLogger(name).level for name in attached} + if state == "root handler on stderr at INFO": + on_stderr = logging.StreamHandler(sys.stderr) + on_stderr.setFormatter(logging.Formatter("%(name)s: %(message)s")) + root.addHandler(on_stderr) + root.setLevel(logging.INFO) + elif state == "root with no handler": + root.handlers = [] + else: + # As an application which asks for these records does: a handler of its own, and a level which lets them through. + logging.getLogger("mcp.server.streamable_http_manager").setLevel(logging.DEBUG) + logging.getLogger("uvicorn.access").setLevel(logging.INFO) + for name, handler in attached.items(): + logging.getLogger(name).addHandler(handler) + own_message = "" + try: + before = logging_state() + app = {"stopped": RebuildApp, "failed at once": FailsAtOnce, "started too slowly": StartsTooSlowly}[ending](mcp_port=0) + app.mcp_start() + run = app._mcp_run + try: + assert (app.mcp_url is not None) == (ending == "stopped"), app.mcp_status() + if state == "root with no handler": + assert (root.handlers, root.level) == ([], saved_level) + if state == "handlers the application attached": + assert all(handler in logging.getLogger(name).handlers for name, handler in attached.items()) + if ending == "stopped": + access = attached["uvicorn.access"].records + received = len(access) + assert ask(app.mcp_url, "list_commands")["is_error"] is False + if state == "handlers the application attached": + assert len(access) > received # the lines logged there while a request was served + if state == "root handler on stderr at INFO": + logging.getLogger("the.application").info("its own message") + own_message = "the.application: its own message\n" + finally: + app.mcp_stop() + if isinstance(app, StartsTooSlowly): + app.hold.set() + run.worker.join(timeout=30) + assert not run.worker.is_alive() + if state == "handlers the application attached": + assert all(handler in logging.getLogger(name).handlers for name, handler in attached.items()) + if ending == "stopped": + # The SDK logs there as its server starts and stops, and nothing while its own client's requests are served. + # 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" + ] + assert manager + assert kept[-len(manager) :] == manager + assert logging_state() == before + warning = "" if ending == "stopped" else f"{run.problem}\n" + assert capfd.readouterr() == ("", warning + own_message) + finally: + root.handlers = saved_handlers + root.setLevel(saved_level) + for name, handler in attached.items(): + logging.getLogger(name).removeHandler(handler) + logging.getLogger(name).setLevel(saved_levels[name]) + + +# --------------------------------------------------------------------------------------------------------------------- +# Which comes first: Ctrl-C or what a start takes; a worker's outcome or the end of the main thread's wait for it. Each +# test establishes the order with threading.Event waits, each of them bounded, and lets every gate go in a finally. +# --------------------------------------------------------------------------------------------------------------------- + +# The start of a run_with_the_example() program which delivers a real SIGINT. Its application's server startup is held +# until the program sets hold, past both of the main thread's waits, as StartsTooSlowly's is. +HELD_IN_A_SUBPROCESS = """ +import asyncio, contextlib, io, socket + +hold = threading.Event() + + +class App(ex.McpServerMixin, cmd2.Cmd): + MCP_START_TIMEOUT = 0.3 + MCP_STOP_TIMEOUT = 0.3 + + def _mcp_asgi_app(self): + app = super()._mcp_asgi_app() + inner = app.router.lifespan_context + + @contextlib.asynccontextmanager + async def lifespan(starlette): + await asyncio.to_thread(hold.wait, 30) + async with inner(starlette): + yield + + app.router.lifespan_context = lifespan + 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] + + +def can_bind(port): + try: + socket.create_server(("127.0.0.1", port)).close() + except OSError: + return False + return True + + +before, handler = logging_state(), signal.getsignal(signal.SIGINT) +""" + +# Ctrl-C as the worker is launched: the real Thread.start(), then SIGINT on the main thread before start() returns. +# sys.argv[1] names the method which starts: cmdloop or mcp_start. +INTERRUPTED_AT_LAUNCH = """ +launched = [] +start = threading.Thread.start + + +def start_then_interrupt(thread): + start(thread) + if thread.name.startswith("mcp-server-"): + launched.append(thread) + signal.raise_signal(signal.SIGINT) + + +threading.Thread.start = start_then_interrupt +app = App(mcp_port=0, allow_cli_args=False, stdin=io.StringIO("quit\\n")) +try: + getattr(app, sys.argv[1])() +except KeyboardInterrupt: + interrupted = True +else: + interrupted = False +finally: + threading.Thread.start = start +run = app._mcp_run +found = { + "interrupted": interrupted, + "handler restored": signal.getsignal(signal.SIGINT) is handler, + "launched": len(launched), + "the run's worker": run.worker is launched[0] if launched else None, + "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], + "stop requested, abandoned, outcome": [run.stop_requested, run.abandoned, run.outcome], +} +hold.set() +for thread in launched: + thread.join(30) +found["ended"] = not any(thread.is_alive() for thread in launched) +found["outcome"] = run.outcome +found["logging as it was"] = logging_state() == before +print(json.dumps(found)) +""" + +# 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 + + +def take_then_interrupt(): + take() + signal.raise_signal(signal.SIGINT) + + +def bind_then_interrupt(*args, **kwargs): + sock = create_server(*args, **kwargs) + signal.raise_signal(signal.SIGINT) + return sock + + +if sys.argv[1] == "taking the logging": + ex._shared_logging.take = take_then_interrupt +else: + socket.create_server = bind_then_interrupt +app = App(mcp_port=0, allow_cli_args=False) +try: + app.mcp_start() +except KeyboardInterrupt: + interrupted = True +else: + interrupted = False +finally: + ex._shared_logging.take, socket.create_server = take, create_server +run = app._mcp_run +found = { + "interrupted": interrupted, + "handler restored": signal.getsignal(signal.SIGINT) is handler, + "holds": ex._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, + "worker": run.worker is not None, +} +hold.set() +if run.worker is not None: + run.worker.join(30) +print(json.dumps(found)) +""" + + +@pytest.mark.parametrize("starts", ["cmdloop", "mcp_start"]) +def test_ctrl_c_at_launch_is_delivered_once_the_run_has_its_worker(starts: str, sdk) -> None: + done = run_with_the_example(HELD_IN_A_SUBPROCESS + INTERRUPTED_AT_LAUNCH, starts) + assert done.returncode == 0, done.stderr + assert done.stderr == "" # nothing reached threading.excepthook, and the libraries' records reached no handler + assert json.loads(done.stdout) == { + "interrupted": True, # the interrupt reached the caller, + "handler restored": True, # and the handler it found is back, + "launched": 1, + "the run's worker": True, # but only once the worker which was launched had been recorded in its run, + "alive": True, # which, while that worker is still held, + "stop requested, abandoned, outcome": [True, True, None], # has given up on it, + "port bound": True, + "can bind": True, # has let go of the port, + "holds": 1, # and has left the hold on the logging to it, + "propagating": [], + "ended": True, # which, once released, ends, + "outcome": "cancelled", # records that it was cancelled, + "logging as it was": True, # and lets go of the logging. + } + + +@pytest.mark.parametrize("moment", ["taking the logging", "binding the socket"]) +def test_ctrl_c_as_a_start_takes_what_it_owns_is_delivered_once_the_run_has_recorded_it(moment: str, sdk) -> None: + done = run_with_the_example(HELD_IN_A_SUBPROCESS + INTERRUPTED_AS_IT_TAKES, moment) + assert done.returncode == 0, done.stderr + assert done.stderr == "" + bound = moment == "binding the socket" + assert json.loads(done.stdout) == { + "interrupted": True, + "handler restored": True, + "holds": 0, # the run knew of its hold on the logging, so the start's cleanup let go of it + "logging as it was": True, + "socket": -1 if bound else None, # the run knew of its socket, so the cleanup closed it + "can bind": True if bound else None, + "worker": False, + } + + +class HoldsItsFirstShutdown(RebuildApp): + """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. + """ + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.shutting_down = threading.Event() # the first server's shutdown has reached the hold + self.release = threading.Event() + self.servers = 0 + + def _mcp_asgi_app(self) -> Any: + app = super()._mcp_asgi_app() + self.servers += 1 + if self.servers > 1: + return app + inner = app.router.lifespan_context + + @contextlib.asynccontextmanager + async def lifespan(starlette: Any) -> AsyncIterator[None]: + async with inner(starlette): + yield + self.shutting_down.set() + await asyncio.to_thread(self.release.wait, 30) # in a thread of its own, so the worker's event loop is not blocked + + app.router.lifespan_context = lifespan + return app + + +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.mcp_start() + first = app._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_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 + 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) + assert app.mcp_url is None + 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_start() + second = app._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() + 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 propagating() == [] + app.mcp_stop() + assert (second.outcome, second.abandoned) == ("stopped", False) + finally: + app.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 + if run.worker is not None: + run.worker.join(timeout=30) + assert not first.worker.is_alive() + assert not second.worker.is_alive() + assert logging_state() == before + + +def test_completion_wins_when_the_worker_recorded_how_it_ended_before_the_wait_ended( + sdk, no_thread_exceptions, monkeypatch +) -> None: + before = logging_state() + releases = mock.Mock(wraps=ex._shared_logging.release) + monkeypatch.setattr(ex._shared_logging, "release", releases) + entered, release = threading.Event(), threading.Event() + app = RebuildApp(mcp_port=0) + app.MCP_STOP_TIMEOUT = 0.3 + app.mcp_start() + run = app._mcp_run + worker = run.worker + join = worker.join + try: + hold_the_worker_as_it_lets_go_of_the_logging(run, entered, release) + + def join_once_it_has_recorded(timeout: float | None = None) -> None: + entered.wait(30) # the worker has recorded "stopped", and waits before it lets go of the logging + join(timeout) # so this wait ends with the worker alive + + worker.join = join_once_it_has_recorded + app.mcp_stop() + 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 + releases.assert_not_called() + status = app.mcp_status() + assert status[0] == "No MCP server: it was stopped" + assert not any("was cancelled" in line for line in status) + finally: + release.set() + app.mcp_stop() + join(timeout=30) + assert not worker.is_alive() + assert (run.outcome, run.abandoned) == ("stopped", False) + releases.assert_called_once() + assert logging_state() == before + + +def test_a_failure_after_readiness_is_reported_and_a_restart_serves_on_the_same_port( + sdk, no_thread_exceptions, monkeypatch +) -> None: + import uvicorn + + main_loop = uvicorn.Server.main_loop + entered, fail = threading.Event(), threading.Event() + gated: list[Any] = [] + + async def fails_once_released(server: Any) -> None: + if gated: # every server after the first runs as usual + await main_loop(server) + return + gated.append(server) + entered.set() + await asyncio.to_thread(fail.wait, 30) # in a thread of its own, so the worker's event loop is not blocked + raise RuntimeError("after startup") + + monkeypatch.setattr(uvicorn.Server, "main_loop", fails_once_released) + before = logging_state() + app = RebuildApp(mcp_port=0) + app.mcp_start() + first = app._mcp_run + try: + assert app.mcp_url is not None, app.mcp_status() # mcp_start() returned with the server serving + assert entered.wait(30) + assert gated == [first.server] + fail.set() + first.worker.join(timeout=30) + assert not first.worker.is_alive() + assert app.mcp_url is 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_start() + assert app._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 + finally: + fail.set() + app.mcp_stop() + if first.worker is not None: + first.worker.join(timeout=30) + assert not first.worker.is_alive() + assert logging_state() == before + + +def test_a_server_which_returns_before_it_has_started_has_failed(sdk, capsys, monkeypatch, no_thread_exceptions) -> None: + import uvicorn + + class ReturnsAtOnce: + """Stands in for uvicorn.Server: its run() returns at once, and it never starts.""" + + def __init__(self, config: Any) -> None: + self.config = config + self.started = False + self.should_exit = False + + def run(self, sockets: Any = None) -> None: + return None + + monkeypatch.setattr(uvicorn, "Server", ReturnsAtOnce) + app = RebuildApp(mcp_port=0) + try: + app.mcp_start() + run = app._mcp_run + run.worker.join(timeout=30) + assert not run.worker.is_alive() + assert (run.outcome, run.abandoned) == ("failed", False) + assert run.detail == "the server returned before it had started" + assert app.mcp_url is None + assert app.mcp_status()[0] == f"No MCP server: {run.problem}" + assert f"the server ended before it began serving: {run.detail}" in run.problem + assert can_bind(run.port) + assert capsys.readouterr().err == f"{run.problem}\n" + finally: + app.mcp_stop() # the failed start stopped the run already; this matters only if it somehow did not + + +class NotesTheWorkersAsking: + """Stands in for a run's lock, and notes when the run's worker asks for it.""" + + def __init__(self, run: Any) -> None: + self.run = run + self.lock = run.lock + self.worker_asked = threading.Event() + + def __enter__(self) -> Any: + if threading.current_thread() is self.run.worker: + self.worker_asked.set() + return self.lock.__enter__() + + def __exit__(self, *exc_info: object) -> Any: + return self.lock.__exit__(*exc_info) + + +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 + try: + lock = run.lock + watched = run.lock = NotesTheWorkersAsking(run) + with lock: # as mcp_stop() holds it while it decides whether it has given up on the worker + run.server.should_exit = True + assert watched.worker_asked.wait(30) + assert run.outcome is None # it asked for the lock before it recorded anything + assert run.worker.is_alive() + run.worker.join(timeout=30) + assert not run.worker.is_alive() + assert (run.outcome, run.detail) == ("stopped", None) + finally: + app.mcp_stop() + if run.worker is not None: + run.worker.join(timeout=30) + + +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 + worker = run.worker + join = worker.join + held_while_waiting: list[bool] = [] + + def join_and_note(timeout: float | None = None) -> None: + held_while_waiting.append(run.lock._is_owned()) # by this thread, the one which waits + join(timeout) + + try: + worker.join = join_and_note + app.mcp_stop() + assert held_while_waiting == [False] # so the worker could record how it ended while it was waited for + finally: + app.mcp_stop() + join(timeout=30) + assert not worker.is_alive() + assert (run.outcome, run.abandoned) == ("stopped", False) + + +@pytest.fixture +def fleet() -> Any: + app = ex.FleetConsole(mcp_port=None, allow_cli_args=False) + app.mcp_start() + return app + + +def test_the_demonstration_is_described_without_an_error(fleet) -> None: + snapshot = fleet.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} + 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} + assert deploy["version"].required is True + assert deploy["env"].choices == ("dev", "staging", "prod") + assert deploy["env"].parser_default == "dev" + 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),) + 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) + assert [argument.name for argument in found["scale"].arguments] == ["service", "replicas"] + assert found["note"].has_parser is False + assert found["status"].has_parser is False + assert "mcp status" in found + + +def test_the_demonstration_loads_and_unloads_a_command_set(fleet) -> None: + before = {command.name for command in fleet.mcp_snapshot.commands} + fleet.onecmd_plus_hooks("plugin load backups") + loaded = {command.name for command in fleet.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 + + +def test_the_demonstration_says_when_the_plugin_is_loaded_already_or_is_not_loaded(fleet) -> None: + assert run_cmd(fleet, "plugin unload backups") == ([], ["The backups plugin is not loaded."]) + assert run_cmd(fleet, "plugin load backups") == (["Loaded the backups plugin: backup, restore."], []) + assert run_cmd(fleet, "plugin load backups") == ([], ["The backups plugin is loaded already."]) + assert run_cmd(fleet, "plugin unload backups") == (["Unloaded the backups plugin."], []) + assert run_cmd(fleet, "plugin unload backups") == ([], ["The backups plugin is not loaded."]) + + +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} + fleet.onecmd_plus_hooks("maintenance off") + assert "deploy" in {command.name for command in fleet.mcp_snapshot.commands} + + +def test_added_server_is_listed_counted_and_offered_for_completion(fleet) -> None: + assert run_cmd(fleet, "server add web-3 --region eu-west") == (["Would add web-3 in eu-west."], []) + servers, errors = run_cmd(fleet, "server list") + assert not errors + assert [line.rstrip() for line in servers] == [ + "db-1 us-east db", + "web-1 us-east web", + "web-2 eu-west web", + "web-3 eu-west", + ] + assert run_cmd(fleet, "status") == (["4 servers, 2 deployed services."], []) + assert fleet.complete("web", "restart web", 8, 11).to_strings() == ("web-1", "web-2", "web-3") + + +def test_server_tag_handler_dispatches_the_parsed_tag_operation() -> None: + output = io.StringIO() + fleet = ex.FleetConsole(stdout=output, mcp_port=None, allow_cli_args=False) + parser = fleet.command_parsers.get(fleet.do_server).find_parser(["tag"]) + fleet.server_tag(parser.parse_args(["add", "db-1", "canary"])) + assert output.getvalue().splitlines() == ["Would tag db-1 with canary."] + + +@pytest.mark.parametrize( + ("command", "output"), + [ + ("server tag add web-1 blue canary", "Would tag web-1 with blue, canary."), + ("server tag remove web-2 web", "Would remove the tag web from web-2."), + ("restart web-1 web-2", "Would restart web-1, web-2."), + ("note rollout finished", "Would keep the note: rollout finished"), + ("deploy api --version 2", "Would deploy api 2 to dev."), + ("deploy api --version 2 --env prod --dry-run", "Would deploy api 2 to prod (dry run)."), + ("logs api -n 5", "Would show the logs of api: last 5 lines."), + ("logs api --since 10m", "Would show the logs of api: since 10m."), + ("logs api --follow", "Would show the logs of api: follow."), + ("scale api 4", "Would scale api to 4 replicas."), + ], +) +def test_demonstration_commands_run_at_the_prompt(fleet, command: str, output: str) -> None: + assert run_cmd(fleet, command) == ([output], []) + + +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 + 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 + + +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 len(done.stderr.strip().splitlines()) == 1 + + +def test_main_with_version_1_of_the_sdk_says_how_to_install_version_2(monkeypatch, capsys) -> None: + # Where version 1 is installed, "mcp" imports but "mcp.server.mcpserver" does not, as in + # test_the_sdk_check_wants_version_2_of_the_sdk. + monkeypatch.setitem(sys.modules, "mcp", ModuleType("mcp")) + monkeypatch.setitem(sys.modules, "mcp.server.mcpserver", None) + 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 captured.out == "" # the console never started + + +def test_main_no_mcp_runs_without_a_server(monkeypatch, capsys) -> None: + monkeypatch.setattr(sys, "stdin", io.StringIO("quit\n")) + assert ex.main(["--no-mcp"]) == 0 + assert "No MCP server" in capsys.readouterr().out + + +def test_main_no_mcp_runs_where_the_sdk_is_missing() -> None: + done = run_without_sdk("import io\nsys.stdin = io.StringIO('quit\\n')\nraise SystemExit(ex.main(['--no-mcp']))\n") + assert (done.returncode, done.stderr) == (0, "") + + +def test_main_serves_on_the_port_it_is_given(sdk, monkeypatch, capsys) -> None: + monkeypatch.setattr(sys, "stdin", io.StringIO("quit\n")) + assert ex.main(["--mcp-port", "0"]) == 0 + assert "MCP server: http://127.0.0.1:" in capsys.readouterr().out + + +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