From 0be9e03c6251b78825823010f88e8a8a6d652e6b Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:15:23 -0500 Subject: [PATCH 01/35] Make a command's help category public as Cmd.get_command_category() --- CHANGELOG.md | 6 +++++ cmd2/cmd2.py | 26 +++++++++++++------- docs/features/help.md | 4 ++++ tests/test_categories.py | 51 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 79 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 212bcb8a3..1bf162110 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## 4.5.0 (TBD) + +- Enhancements + - Added `Cmd.get_command_category()`, which returns the help category a command is listed under. + It was the private `_get_command_category()`. + ## 4.4.5 (TBD) - Bug Fixes diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 653942444..b5b042922 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -1041,7 +1041,7 @@ def register_command_set(self, cmdset: CommandSet[Any]) -> None: self._cmd_to_command_sets[command] = cmdset # If this command is in a disabled category, then disable it - command_category = self._get_command_category(command_method) + command_category = self.get_command_category(command_method) if command_category in self.disabled_categories: message_to_print = self.disabled_categories[command_category] self.disable_command(command, message_to_print) @@ -3643,11 +3643,21 @@ def get_command_func(self, command: str) -> BoundCommandFunc[...] | None: command_func = getattr(self, command_func_name, None) return cast(BoundCommandFunc[...], command_func) if callable(command_func) else None - def _get_command_category(self, func: BoundCommandFunc[...]) -> str: - """Determine the category for a command. + def get_command_category(self, func: BoundCommandFunc[...]) -> str: + """Return the help category of a command. - :param func: the do_* function implementing the command - :return: category name + This is the heading which ``help`` lists the command under. It is, in this order: + + 1. the category given to the command with [@with_category][cmd2.with_category] or + [categorize()][cmd2.categorize] + 2. the ``DEFAULT_CATEGORY`` of the class which defines the command, which may be a + [CommandSet][cmd2.CommandSet] or a class your application inherits from + 3. this application's own ``DEFAULT_CATEGORY``, when the defining class has none, as with a + plain mixin + + :param func: the bound ``do_*`` method of the command, as returned by + [get_command_func()][cmd2.Cmd.get_command_func] + :return: the name of the category """ # Check if the command function has a category. if hasattr(func, constants.COMMAND_ATTR_HELP_CATEGORY): @@ -4610,7 +4620,7 @@ def _build_command_info(self) -> tuple[dict[str, list[str]], list[str]]: # Store the command within its category command_func = self.get_command_func(command) if command_func is not None: - category = self._get_command_category(command_func) + category = self.get_command_category(command_func) cmds_cats.setdefault(category, []).append(command) return cmds_cats, help_topics @@ -6251,7 +6261,7 @@ def enable_category(self, category: str) -> None: for command in list(self.disabled_commands): command_func = self.disabled_commands[command].command_func - if self._get_command_category(command_func) == category: + if self.get_command_category(command_func) == category: self.enable_command(command) del self.disabled_categories[category] @@ -6332,7 +6342,7 @@ def disable_category(self, category: str, message_to_print: str) -> None: for command in all_commands: command_func = self.get_command_func(command) - if command_func is not None and self._get_command_category(command_func) == category: + if command_func is not None and self.get_command_category(command_func) == category: self.disable_command(command, message_to_print) self.disabled_categories[category] = message_to_print diff --git a/docs/features/help.md b/docs/features/help.md index 8dee6fba5..d0f413b4e 100644 --- a/docs/features/help.md +++ b/docs/features/help.md @@ -159,6 +159,10 @@ def do_findleakers(self, _): categorize((do_undeploy, do_stop, do_findleakers), CMD_CAT_APP_MGMT) ``` +To find out which category a command is listed under, call +[get_command_category()][cmd2.Cmd.get_command_category] as `self.get_command_category(func)`. The +`func` argument comes from `self.get_command_func("name")`. + The `help` command also has a verbose option (`help -v` or `help --verbose`) that combines the help categories with per-command help messages: diff --git a/tests/test_categories.py b/tests/test_categories.py index eaf05641b..4bfdc12e1 100644 --- a/tests/test_categories.py +++ b/tests/test_categories.py @@ -128,3 +128,54 @@ def test_category_command_set() -> None: app.register_command_set(CategoryCommandSet()) cmds_cats, _help_topics = app._build_command_info() assert "cmdset_command" in cmds_cats[CategoryCommandSet.DEFAULT_CATEGORY] + + +class _PlainMixin: + """Defines a command and has no DEFAULT_CATEGORY of its own.""" + + def do_from_mixin(self, _: cmd2.Statement) -> None: + """A command from a plain mixin.""" + + +class _CategorySet(cmd2.CommandSet): + DEFAULT_CATEGORY = "Set Commands" + + def do_from_set(self, _: cmd2.Statement) -> None: + """A command from a command set.""" + + +class _CategoryApp(_PlainMixin, cmd2.Cmd): + DEFAULT_CATEGORY = "App Commands" + + @cmd2.with_category("Chosen") + def do_chosen(self, _: cmd2.Statement) -> None: + """A command with a category of its own.""" + + def do_own(self, _: cmd2.Statement) -> None: + """A command of the application's class.""" + + +def _category(app: cmd2.Cmd, command: str) -> str: + func = app.get_command_func(command) + assert func is not None + return app.get_command_category(func) + + +def test_get_command_category_given_by_the_command() -> None: + assert _category(_CategoryApp(), "chosen") == "Chosen" + + +def test_get_command_category_of_the_defining_class() -> None: + app = _CategoryApp(command_sets=[_CategorySet()]) + assert _category(app, "own") == "App Commands" + assert _category(app, "help") == "Cmd2 Commands" + assert _category(app, "from_set") == "Set Commands" + + +def test_get_command_category_falls_back_to_the_application() -> None: + # _PlainMixin has no DEFAULT_CATEGORY, so the application's class decides. + assert _category(_CategoryApp(), "from_mixin") == "App Commands" + + +def test_the_private_name_is_gone() -> None: + assert not hasattr(cmd2.Cmd, "_get_command_category") From 0e2ee9423f9f6ab1375fb8835010877ca1976c85 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:18:24 -0500 Subject: [PATCH 02/35] Begin the MCP server example: describe one argument of a command --- examples/mcp_server.py | 151 +++++++++++++++++++++++++++++++ tests/test_example_mcp_server.py | 150 ++++++++++++++++++++++++++++++ 2 files changed, 301 insertions(+) create mode 100644 examples/mcp_server.py create mode 100644 tests/test_example_mcp_server.py diff --git a/examples/mcp_server.py b/examples/mcp_server.py new file mode 100644 index 000000000..c6f9808ce --- /dev/null +++ b/examples/mcp_server.py @@ -0,0 +1,151 @@ +"""Describe a cmd2 application's commands as plain data, and serve that description over MCP. + +This is a placeholder: the finished docstring is written in a later task. The example needs cmd2 4.5.0. +""" + +import argparse +import json +import re +from dataclasses import dataclass +from typing import Any + +from rich.console import Console + +from cmd2.constants import INFINITY + +# --------------------------------------------------------------------------------------------------------------------- +# 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 + +# An OSC sequence (a hyperlink is one) ends with BEL or with ESC followed by a backslash. +_OSC_SEQUENCE = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)") +_CSI_SEQUENCE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]") +# Every control character except a tab (\x09) and a newline (\x0a). +_CONTROL_CHARACTERS = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]") + + +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) + return _CONTROL_CHARACTERS.sub("", text) + + +@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 + default: Any # None when there is none worth stating + choices: tuple[str, ...] | None # None unless choices= was given + 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 == argparse.ONE_OR_MORE: + 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 == 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. + return _plain_data(json.loads(json.dumps(default))) + 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) + 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=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 == argparse.REMAINDER, + default=_describe_default(action), + choices=None if action.choices is None else tuple(plain_text(str(choice)) for choice in action.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), + ) diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py new file mode 100644 index 000000000..18e7b9506 --- /dev/null +++ b/tests/test_example_mcp_server.py @@ -0,0 +1,150 @@ +"""Tests of the MCP server example, examples/mcp_server.py.""" + +import argparse +import dataclasses +import functools +import importlib.util +import re +import subprocess +import sys +from pathlib import Path +from types import ModuleType +from typing import Any + +import pytest +from rich.console import Group +from rich.text import Text + +import cmd2 + +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)", 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) == "" + 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), + (("--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.default, argument.help) == ("int", 10, "how many") + assert _argument("name").flags == () + assert _argument("name").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")).default == repr(Path("out")) + + +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.default == {"tags": ["a", "red"]} + assert_plain(argument) + + +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", choices=["\x1b[31mred\x1b[0m"], default="\x1b[31mred\x1b[0m", help="\x1b[1mpick\x1b[0m") + assert styled.choices == ("red",) # Review Focus 3 + assert styled.default == "red" + assert styled.help == "pick" + assert_plain(styled) From 17df518874c59613e564e77500bc4601a4c04f4d Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:20:17 -0500 Subject: [PATCH 03/35] Remove C1 control characters and 8-bit escape sequences from described text --- examples/mcp_server.py | 11 ++++++----- tests/test_example_mcp_server.py | 6 +++++- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index c6f9808ce..c7296cb2e 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -22,11 +22,12 @@ # Help text is wrapped at this many columns, whatever the size of the terminal. HELP_WIDTH = 100 -# An OSC sequence (a hyperlink is one) ends with BEL or with ESC followed by a backslash. -_OSC_SEQUENCE = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)") -_CSI_SEQUENCE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]") -# Every control character except a tab (\x09) and a newline (\x0a). -_CONTROL_CHARACTERS = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]") +# 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: diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 18e7b9506..fedf72395 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -41,7 +41,7 @@ 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)", 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: @@ -60,6 +60,10 @@ 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 From 0a70e0f283667c8f5b810d838388be4da2b4432c Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:22:37 -0500 Subject: [PATCH 04/35] Describe a command's parser and its subcommands to any depth --- examples/mcp_server.py | 130 +++++++++++++++++++++++++ tests/test_example_mcp_server.py | 159 +++++++++++++++++++++++++++++++ 2 files changed, 289 insertions(+) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index c7296cb2e..c70b10b1a 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -5,12 +5,14 @@ import argparse import json +import os import re from dataclasses import dataclass from typing import Any from rich.console import Console +from cmd2 import Cmd2ArgumentParser from cmd2.constants import INFINITY # --------------------------------------------------------------------------------------------------------------------- @@ -150,3 +152,131 @@ def describe_argument(action: argparse.Action) -> Argument: type=_describe_type(action), repeatable=isinstance(action, _REPEATABLE_ACTIONS), ) + + +@dataclass(frozen=True) +class ExclusiveGroup: + """Arguments of which at most one may be given.""" + + arguments: tuple[str, ...] # the names of the arguments which exclude each other + required: bool # one of them must be given + + +@dataclass(frozen=True) +class Subcommand: + """One subcommand, as its parent lists it.""" + + name: str + 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 + + +def _format_at_help_width(parser: Cmd2ArgumentParser) -> tuple[str, str]: + """Return the parser's usage and help as plain text, wrapped at HELP_WIDTH whatever the terminal reports. + + The COLUMNS environment variable overrides the terminal's width, so it is set for the two calls. This is not + thread safe: call it on the main thread only. + """ + saved = os.environ.get("COLUMNS") + os.environ["COLUMNS"] = str(HELP_WIDTH) + try: + return plain_text(parser.format_usage()), plain_text(parser.format_help()) + finally: + if saved is None: + os.environ.pop("COLUMNS", None) + else: + os.environ["COLUMNS"] = saved + + +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 _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 _describe_subcommands( + parser: Cmd2ArgumentParser, +) -> tuple[bool, tuple[Subcommand, ...], list[tuple[str, Cmd2ArgumentParser]]]: + """Return whether a subcommand is required, the subcommands, and each one's primary name with its parser.""" + try: + action = parser.get_subparsers_action() + except ValueError: + return False, (), [] + # 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) + subcommands: list[Subcommand] = [] + primaries: list[tuple[str, Cmd2ArgumentParser]] = [] + for names in by_parser.values(): + name, *aliases = names # argparse adds the primary name before its aliases + subparser = action.choices[name] + summary = _first_line(helps.get(name)) or _first_line(subparser.description) + subcommands.append(Subcommand(name=plain_text(name), aliases=tuple(plain_text(a) for a in aliases), summary=summary)) + primaries.append((name, subparser)) + return bool(action.required), tuple(subcommands), primaries + + +def describe_parser(parser: Cmd2ArgumentParser, path: str, summary: str) -> dict[str, Description]: + """Describe a parser under its path, and every subcommand under it at every depth under its own path. + + A subcommand's alias is a second key for the same object. + """ + # 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(described[id(a)].name for a in group._group_actions if id(a) in described) + if len(members) >= 2: + groups.append(ExclusiveGroup(arguments=members, required=bool(group.required))) + required, subcommands, children = _describe_subcommands(parser) + usage, help_text = _format_at_help_width(parser) + result = { + path: Description( + path=path, + summary=summary, + usage=usage, + help=help_text, + has_parser=True, + arguments=tuple(described.values()), + exclusive_groups=tuple(groups), + subcommands=subcommands, + subcommand_required=required, + error=None, + ) + } + for (name, subparser), subcommand in zip(children, subcommands, strict=True): + child_path = f"{path} {name}" + found = describe_parser(subparser, child_path, subcommand.summary) + result.update(found) + for alias in subcommand.aliases: + result[f"{path} {alias}"] = found[child_path] + return result diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index fedf72395..25e96f31c 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -4,6 +4,7 @@ import dataclasses import functools import importlib.util +import os import re import subprocess import sys @@ -16,6 +17,9 @@ from rich.text import Text import cmd2 +from cmd2 import rich_utils as ru + +from .conftest import with_ansi_style EXAMPLE = Path(__file__).parent.parent / "examples" / "mcp_server.py" MODULE_NAME = "cmd2_example_mcp_server" @@ -152,3 +156,158 @@ def test_argument_of_an_awkward_shape() -> None: # Review Focus 5 assert styled.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.") + 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 + + +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 ls", + "server add", + "server tag", + "server tag add", + "server tag remove", + } + assert found["server ls"] is found["server list"] + assert found["server list"].path == "server list" + 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_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_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_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 From cb7c6957359b8749fd6d664592e17c9277f92d88 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:26:15 -0500 Subject: [PATCH 05/35] Build a snapshot of an application's commands, and the answers made from it --- examples/mcp_server.py | 283 ++++++++++++++++++++++++++++++- tests/test_example_mcp_server.py | 188 ++++++++++++++++++++ 2 files changed, 470 insertions(+), 1 deletion(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index c70b10b1a..0e3d4efd7 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -4,16 +4,20 @@ """ import argparse +import inspect import json import os import re +from collections.abc import Collection, Mapping from dataclasses import dataclass +from datetime import datetime from typing import Any from rich.console import Console -from cmd2 import Cmd2ArgumentParser +from cmd2 import Cmd, Cmd2ArgumentParser from cmd2.constants import INFINITY +from cmd2.utils import DEFAULT_STR_SORT_KEY, strip_doc_annotations # --------------------------------------------------------------------------------------------------------------------- # Part 1: Describing @@ -280,3 +284,280 @@ def describe_parser(parser: Cmd2ArgumentParser, path: str, summary: str) -> dict for alias in subcommand.aliases: result[f"{path} {alias}"] = found[child_path] 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 names of its first level of subcommands + error: str | None + + +@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 + descriptions: Mapping[str, Description] # by path, every depth, alias paths included + help_topics: tuple[str, ...] # the topics which are not commands + shortcuts: tuple[Shortcut, ...] + aliases: tuple[Alias, ...] + macros: tuple[Macro, ...] + typing: TypingRules + error: str | None # why the whole build failed; else None + + +def _now() -> str: + return datetime.now().astimezone().isoformat(timespec="seconds") + + +def _by_name(item: tuple[str, Any]) -> Any: + return DEFAULT_STR_SORT_KEY(item[0]) + + +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 _first_line(parser.description) + 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]]: + """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: + text = plain_text(inspect.cleandoc(func.__doc__)) if func.__doc__ else "" + descriptions = {name: _unparsed_description(name, summary, text, None)} + else: + descriptions = describe_parser(parser, name, summary) + top = descriptions[name] + command = Command( + name=plain_text(name), + category=category, + summary=summary, + has_parser=top.has_parser, + subcommands=tuple(subcommand.name for subcommand in top.subcommands), + error=None, + ) + return command, descriptions + + +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] = {} + visible = sorted(app.get_visible_commands(), key=DEFAULT_STR_SORT_KEY) + for name in visible: + if name in leave_out: + continue + try: + command, found = _describe_command(app, name) + except Exception as exc: # noqa: BLE001 - one command's failure is its own + command, found = _failed_command(app, name, exc) + commands.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=DEFAULT_STR_SORT_KEY) + return Snapshot( + generation=generation, + built_at=_now(), + commands=tuple(commands), + 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), + ), + error=None, + ) + + +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=(), + descriptions={}, + help_topics=(), + shortcuts=(), + aliases=(), + macros=(), + typing=TypingRules(allow_redirection=False, terminators=(), multiline_commands=()), + error=plain_text(error), + ) + + +@dataclass(frozen=True) +class Category: + """The commands of one help category.""" + + name: str + commands: tuple[Command, ...] + + +@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 + + +@dataclass(frozen=True) +class CommandDescription: + """The answer to "describe a command".""" + + generation: int + built_at: str + description: Description + + +@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, ...] + + +class UnknownCommandError(LookupError): + """No such command or subcommand. str() says what is missing and names what exists.""" + + +def answer_list_commands(snapshot: Snapshot) -> CommandList: + """List the commands by category, in the order help shows them.""" + by_category: dict[str, list[Command]] = {} + for command in snapshot.commands: + by_category.setdefault(command.category, []).append(command) + categories = tuple(Category(name, tuple(by_category[name])) for name in sorted(by_category, key=DEFAULT_STR_SORT_KEY)) + return CommandList( + generation=snapshot.generation, + built_at=snapshot.built_at, + categories=categories, + help_topics=snapshot.help_topics, + typing=snapshot.typing, + error=snapshot.error, + ) + + +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.""" + words = command.split() + path = " ".join(words) + description = snapshot.descriptions.get(path) + if description is None: + # The longest part of the path which exists says what could have followed it. + for count in range(len(words) - 1, 0, -1): + parent = snapshot.descriptions.get(" ".join(words[:count])) + if parent is not None: + names = ", ".join(subcommand.name for subcommand 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.') + names = ", ".join(listed.name for listed in snapshot.commands) + raise UnknownCommandError(f'There is no command "{path}". The commands are: {names}.') + return CommandDescription(generation=snapshot.generation, built_at=snapshot.built_at, description=description) + + +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, + ) diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 25e96f31c..75382dcac 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -8,6 +8,7 @@ import re import subprocess import sys +from datetime import datetime from pathlib import Path from types import ModuleType from typing import Any @@ -311,3 +312,190 @@ def test_parser_help_does_not_follow_the_terminal(monkeypatch: pytest.MonkeyPatc 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_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_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_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" + 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_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, + ) From 5b87e77187a965ba5ab333f9ca31538fa10df5ac Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:05:52 -0500 Subject: [PATCH 06/35] Rebuild the description at the start, before each prompt and after each command --- examples/mcp_server.py | 137 ++++++++- tests/test_example_mcp_server.py | 494 +++++++++++++++++++++++++++++++ 2 files changed, 629 insertions(+), 2 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 0e3d4efd7..31ea2064f 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -4,6 +4,7 @@ """ import argparse +import contextlib import inspect import json import os @@ -11,9 +12,9 @@ from collections.abc import Collection, Mapping from dataclasses import dataclass from datetime import datetime -from typing import Any +from typing import TYPE_CHECKING, Any -from rich.console import Console +from rich.console import Console, RenderableType from cmd2 import Cmd, Cmd2ArgumentParser from cmd2.constants import INFINITY @@ -561,3 +562,135 @@ def answer_tables(snapshot: Snapshot) -> Tables: aliases=snapshot.aliases, macros=snapshot.macros, ) + + +# --------------------------------------------------------------------------------------------------------------------- +# Part 2: Serving +# +# Keep the latest description of a cmd2 application, rebuilt on the main thread and never while a command is in progress. +# --------------------------------------------------------------------------------------------------------------------- + +DEFAULT_PORT = 8765 + +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. + """ + + 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_in_cmdloop: bool + + 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 + """ + super().__init__(*args, **kwargs) + self.mcp_port = mcp_port + self.mcp_name = mcp_name + self.mcp_leave_out = frozenset(mcp_leave_out) + self.mcp_snapshot = failed_snapshot(0, "The description has not been built yet.") + self.mcp_build_error = None + self._mcp_depth = 0 + self._mcp_in_cmdloop = False + + def cmdloop(self, intro: RenderableType = "") -> int: + """Build the first description before the loop starts, and stop when the loop ends, however it ends.""" + outermost = not self._mcp_in_cmdloop # False for a call made from inside a command + self._mcp_in_cmdloop = True + try: + if outermost: + self.mcp_start() # the first description, then the server + return super().cmdloop(intro) + finally: + if outermost: + self._mcp_in_cmdloop = False + self.mcp_stop() # safe to call twice, and after a start which failed + + 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() # never raises; does nothing unless the depth is zero + + def mcp_start(self) -> None: + """Build the first description. Never raises an Exception; safe to call when already started. + + A KeyboardInterrupt is not caught: before cmdloop() has installed cmd2's handler, Ctrl-C cannot be held off. + """ + self._mcp_rebuild() + + def mcp_stop(self) -> None: + """Stop serving. Never raises; does nothing when there is nothing to stop.""" + + def _mcp_rebuild(self) -> None: + """Publish a new description, unless a command is in progress. 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. + """ + if self._mcp_depth != 0: + 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}") + if self.mcp_snapshot.generation == 0: + self.mcp_snapshot = failed_snapshot(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) diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 75382dcac..e342e9a48 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -1,24 +1,35 @@ """Tests of the MCP server example, examples/mcp_server.py.""" import argparse +import contextlib import dataclasses import functools import importlib.util +import io import os import re +import signal import subprocess import sys +import threading +from collections.abc import 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 with_ansi_style @@ -499,3 +510,486 @@ def test_answer_tables() -> None: snapshot.aliases, snapshot.macros, ) + + +class ExtraCommands(cmd2.CommandSet): + def do_extra(self, _: cmd2.Statement) -> None: + """A command which comes and goes.""" + + +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", "pre_prompt", "the end of a command"]) +def test_every_rebuild_is_protected_from_ctrl_c(moment: str, monkeypatch: pytest.MonkeyPatch) -> None: + app = RebuildApp() + 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 == "pre_prompt": + app.pre_prompt() + else: + app.onecmd_plus_hooks("help") + assert protected == [True] + assert not app.sigint_protection + + +def test_ctrl_c_before_cmd2_has_its_handler_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() + assert (app.starts, app.stops, app._mcp_in_cmdloop) == (1, 1, 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 is previous + 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") + assert app.mcp_snapshot is good # the last good one is still served + 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 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_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 + + +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_in_cmdloop, frozenset(_listed(self))) + + +class PreloopApp(LoopApp): + """Disables help in preloop(): after the first description is built, and before the first prompt.""" + + 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 mcp_start's generation 1, + 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 mcp_start's generation 1 + 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) + + +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_in_cmdloop is False + 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) + in_cmdloop, listed_then = app.seen["inner loop returned"] + assert in_cmdloop is True + 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_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: + for _ in range(100): + 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) From 75645a0fdd26fe4966ecf6adf4c733c9ca50185c Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:14:00 -0500 Subject: [PATCH 07/35] Own the changes to the server libraries' logging in one place --- examples/mcp_server.py | 82 ++++++++++++++++++++++++++++- tests/test_example_mcp_server.py | 90 ++++++++++++++++++++++++++++++++ 2 files changed, 171 insertions(+), 1 deletion(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 31ea2064f..df7c83222 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -7,9 +7,12 @@ import contextlib import inspect import json +import logging import os import re -from collections.abc import Collection, Mapping +import threading +from collections import deque +from collections.abc import Collection, Iterator, Mapping from dataclasses import dataclass from datetime import datetime from typing import TYPE_CHECKING, Any @@ -571,6 +574,83 @@ def answer_tables(snapshot: Snapshot) -> Tables: # --------------------------------------------------------------------------------------------------------------------- DEFAULT_PORT = 8765 +LIBRARY_LOGGERS = ("uvicorn", "mcp") # the top-level logger of each library the server uses +RECORDS_KEPT = 50 + + +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._lock: + 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) + if TYPE_CHECKING: # pragma: no cover _Base = Cmd diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index e342e9a48..6477c9000 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -6,6 +6,7 @@ import functools import importlib.util import io +import logging import os import re import signal @@ -993,3 +994,92 @@ def read() -> None: 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 + } + + +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 + 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) + 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"] + assert {"from the server", "from the sdk"} <= {record.getMessage() for record in ex._shared_logging.records()} + 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 From 7927352309243eb54b83c98c049d4b4f730f3381 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:53:39 -0500 Subject: [PATCH 08/35] Serve the description over MCP from a worker thread beside the prompt --- examples/mcp_server.py | 264 ++++++++++++++++++- pyproject.toml | 2 + tests/test_example_mcp_server.py | 437 +++++++++++++++++++++++++++++++ 3 files changed, 698 insertions(+), 5 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index df7c83222..0a067df78 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -5,12 +5,16 @@ import argparse import contextlib +import importlib import inspect +import itertools import json import logging import os import re +import socket import threading +import time from collections import deque from collections.abc import Collection, Iterator, Mapping from dataclasses import dataclass @@ -19,6 +23,7 @@ from rich.console import Console, RenderableType +import cmd2 from cmd2 import Cmd, Cmd2ArgumentParser from cmd2.constants import INFINITY from cmd2.utils import DEFAULT_STR_SORT_KEY, strip_doc_annotations @@ -570,12 +575,22 @@ def answer_tables(snapshot: Snapshot) -> Tables: # --------------------------------------------------------------------------------------------------------------------- # Part 2: Serving # -# Keep the latest description of a cmd2 application, rebuilt on the main thread and never while a command is in progress. +# 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 may be one command old." +) class _KeepRecords(logging.Handler): @@ -630,7 +645,7 @@ def holds(self) -> int: def records(self) -> list[logging.LogRecord]: """The last RECORDS_KEPT records of the libraries, oldest first.""" - with self._lock: + with self._handler.lock: # emit() appends under the same lock, on a server's thread return list(self._handler.kept) @@ -652,6 +667,61 @@ def _root_logger_left_alone() -> Iterator[None]: root.removeHandler(placeholder) +_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.""" + + 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.abandoned = False # the main thread gave up on its worker while the worker was still alive + 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.Lock() + self._holds_logging = False + + def serving(self) -> bool: + """Whether the worker is alive and the server has started, and nobody has asked it to stop.""" + return ( + not self.stop_requested + 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.""" + with 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)) + return plain_text(f"{when} {record.threadName} {record.levelname}: {record.getMessage()}") + + if TYPE_CHECKING: # pragma: no cover _Base = Cmd else: @@ -668,8 +738,15 @@ class McpServerMixin(_Base): 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 @@ -677,6 +754,7 @@ class McpServerMixin(_Base): 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_in_cmdloop: bool + _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, @@ -700,6 +778,7 @@ def __init__( self.mcp_build_error = None self._mcp_depth = 0 self._mcp_in_cmdloop = False + self._mcp_run = None def cmdloop(self, intro: RenderableType = "") -> int: """Build the first description before the loop starts, and stop when the loop ends, however it ends.""" @@ -729,14 +808,189 @@ def onecmd_plus_hooks(self, line: str, *args: Any, **kwargs: Any) -> bool: self._mcp_rebuild() # never raises; does nothing unless the depth is zero def mcp_start(self) -> None: - """Build the first description. Never raises an Exception; safe to call when already started. + """Build the first description, then serve it from a worker thread. Never raises an Exception. - A KeyboardInterrupt is not caught: before cmdloop() has installed cmd2's handler, Ctrl-C cannot be held off. + Does no more than build when mcp_port is None or this application is serving already. Whatever goes wrong is one + warning, and the application carries on without a server. A KeyboardInterrupt is not caught: before cmdloop() has + installed cmd2's handler, Ctrl-C cannot be held off, and cmdloop()'s call of mcp_stop() undoes what was done. """ self._mcp_rebuild() + if self.mcp_port is None or (self._mcp_run is not None and self._mcp_run.serving()): + return + # 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 Exception as error: # noqa: BLE001 - a start never raises + 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 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 + run.take_logging() # before anything of the server can log + 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) + worker.start() + run.worker = worker # only once it has started, so that a thread which could not be started is never joined + 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(): + if not worker.is_alive(): + raise _NotServingError(f"the server ended before it began serving: {run.detail or run.outcome}") + 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: + run.server.run(sockets=[run.sock]) + except BaseException as error: # noqa: BLE001 - SystemExit too: nothing may reach threading.excepthook + run.detail = plain_text(f"{type(error).__name__}: {error}") + run.outcome = "cancelled" if run.abandoned else "failed" + else: + run.outcome = "cancelled" if run.abandoned else "stopped" + finally: + run.release_logging() # its last act: a worker which was given up on can still log until it ends def mcp_stop(self) -> None: - """Stop serving. Never raises; does nothing when there is nothing to stop.""" + """Stop serving: undo exactly what the start got done, in whatever state it finds it. Never raises an Exception. + + Does nothing when there is no run, or when it has been stopped already. 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 or run.stop_requested: + return + run.stop_requested = True + try: + if run.server is not None: + run.server.should_exit = True + if run.worker is not None: + run.worker.join(self.MCP_STOP_TIMEOUT) + finally: + # This happens even when Ctrl-C ends the wait: whatever the worker is doing, the port is let go of. + if run.worker is not None and run.worker.is_alive(): + run.abandoned = True # the one place a run is given up on; its worker lets go of the logging when it ends + if run.sock is not None: + with contextlib.suppress(OSError): + run.sock.close() # uvicorn closes it too, unless it never took it + if run.worker is None or not run.worker.is_alive(): + run.release_logging() + + @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. + """ + run = self._mcp_run + if run is not None and run.serving(): + lines = [f"Serving {run.url}"] + elif run is not None and run.problem is not None: + lines = [f"No MCP server: {run.problem}"] + elif run is not None and run.stop_requested: + lines = ["No MCP server: it was stopped"] + elif run is not None: + lines = [f"No MCP server: it ended by itself ({run.detail or run.outcome})"] + elif self.mcp_port is None: + lines = ["No MCP server: --no-mcp was given"] + else: + lines = ["No MCP server: it has not been started"] + if run is not None and run.abandoned and run.worker is not None: + if run.worker.is_alive(): + lines.append(f"The worker of run {run.number} was cancelled, and has not ended yet") + else: + ended = f"{run.outcome}: {run.detail}" if run.detail else run.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({command.category for command in snapshot.commands})} 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 comes with its summary, whether a parser checks its arguments, and the names of its subcommands. + 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 is described by its own path. + """ + snapshot = self.mcp_snapshot + try: + return answer_describe_command(snapshot, command) + except UnknownCommandError as 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. Never raises an Exception. 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_example_mcp_server.py b/tests/test_example_mcp_server.py index 6477c9000..e2a895db4 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -6,13 +6,18 @@ import functools import importlib.util import io +import json import logging import os import re import signal +import socket import subprocess import sys +import textwrap import threading +import urllib.error +import urllib.request from collections.abc import Iterator from concurrent.futures import ThreadPoolExecutor from datetime import datetime @@ -1007,6 +1012,16 @@ def logging_state() -> dict[str, tuple[tuple[logging.Handler, ...], int, bool]]: } +@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() @@ -1083,3 +1098,425 @@ def test_shared_logging_release_is_safe_from_two_threads() -> None: 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 ...". +# --------------------------------------------------------------------------------------------------------------------- + + +@pytest.fixture +def sdk() -> None: + """Skip a test where the MCP SDK is not installed, unless this run exists to run it.""" + if os.environ.get("CMD2_EXAMPLE_TESTS_NEED_SDK"): + import mcp # 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") + pytest.importorskip("uvicorn") + + +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 run_without_sdk(body: str) -> subprocess.CompletedProcess[str]: + """Run code in a fresh interpreter in which the SDK cannot be imported, installed or not. + + 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) + + +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_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_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() + 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 + + +def test_without_the_sdk_the_application_warns_and_carries_on() -> None: + done = run_without_sdk( + textwrap.dedent( + """ + class App(ex.McpServerMixin, cmd2.Cmd): + pass + + + def state(): + loggers = [logging.getLogger(name) for name in ("", "uvicorn", "mcp")] + return [(list(logger.handlers), logger.level, logger.propagate) for logger in loggers] + + + before = state() + app = App(mcp_port=0, allow_cli_args=False) + app.mcp_start() + found = { + "url": app.mcp_url, + "commands": len(app.mcp_snapshot.commands), + "status": app.mcp_status()[0], + "logging as it was": state() == before, + } + print(json.dumps(found)) + """ + ) + ) + assert done.returncode == 0, done.stderr + found = json.loads(done.stdout.splitlines()[-1]) + assert found["url"] is None + assert found["commands"] > 0 + assert done.stderr.count("MCP server not started") == 1 + assert "--group examples" in done.stderr + assert found["status"].startswith("No MCP server") + assert found["logging as it was"] is True + + +@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() + 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 + + +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)) + with pytest.raises(KeyboardInterrupt): + app.cmdloop() + assert app.stops == 1 + 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" From 72b0e1b72343443231f644e1ae302f54e6e15885 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:05:40 -0500 Subject: [PATCH 09/35] Test the server when it cannot start, and with two runs alive at once --- examples/mcp_server.py | 12 +- tests/test_example_mcp_server.py | 410 ++++++++++++++++++++++++++++++- 2 files changed, 419 insertions(+), 3 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 0a067df78..972780e3a 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -719,7 +719,11 @@ class _NotServingError(Exception): 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)) - return plain_text(f"{when} {record.threadName} {record.levelname}: {record.getMessage()}") + 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 @@ -817,6 +821,10 @@ def mcp_start(self) -> None: 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, or a start of it was interrupted) may + # still hold its socket and the logging. Undo it before it is replaced; for a run which was stopped, nothing. + 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) @@ -919,7 +927,7 @@ def mcp_status(self) -> list[str]: lines = [f"No MCP server: {run.problem}"] elif run is not None and run.stop_requested: lines = ["No MCP server: it was stopped"] - elif run is not None: + elif run is not None and run.worker is not None and not run.worker.is_alive(): lines = [f"No MCP server: it ended by itself ({run.detail or run.outcome})"] elif self.mcp_port is None: lines = ["No MCP server: --no-mcp was given"] diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index e2a895db4..53df1a88f 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -1,6 +1,7 @@ """Tests of the MCP server example, examples/mcp_server.py.""" import argparse +import asyncio import contextlib import dataclasses import functools @@ -18,7 +19,7 @@ import threading import urllib.error import urllib.request -from collections.abc import Iterator +from collections.abc import AsyncIterator, Iterator from concurrent.futures import ThreadPoolExecutor from datetime import datetime from pathlib import Path @@ -1520,3 +1521,410 @@ def test_status_lines(serving, monkeypatch) -> None: 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_a_start_first_undoes_a_run_which_is_neither_serving_nor_stopped(sdk) -> None: + before = logging_state() + app = RebuildApp(mcp_port=0) + 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 interrupted.port != 0 # it had bound its socket and taken a hold on the logging + app.mcp_start() + try: + assert app.mcp_url is not None, app.mcp_status() + assert app._mcp_run is not interrupted + assert interrupted.stop_requested + assert can_bind(interrupted.port) + assert ex._shared_logging.holds == 1 # the new run's alone + finally: + app.mcp_stop() + assert logging_state() == before + + +def test_status_says_a_run_ended_by_itself_only_once_its_worker_has_ended(sdk) -> None: + app = RebuildApp(mcp_port=0) + with mock.patch.object(app, "_mcp_asgi_app", side_effect=KeyboardInterrupt), pytest.raises(KeyboardInterrupt): + app.mcp_start() + try: + assert app._mcp_run.worker is None + assert app.mcp_status()[0] == "No MCP server: it has not been started" + finally: + app.mcp_stop() + app.mcp_start() + try: + run = app._mcp_run + run.server.should_exit = True # as if the server had ended for a reason of its own + run.worker.join(timeout=30) + assert not run.worker.is_alive() + assert app.mcp_status()[0] == "No MCP server: it ended by itself (stopped)" + finally: + app.mcp_stop() + + +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) + ex._shared_logging.take() + try: + logging.getLogger("uvicorn.error").handle(malformed) + finally: + ex._shared_logging.release() + status = app.mcp_status() + 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]) From e86ffc6946400e677761c24d4140dd6d502d23d0 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:38:02 -0500 Subject: [PATCH 10/35] Keep the malformed log record of one test from reaching another --- tests/test_example_mcp_server.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 53df1a88f..2936d5c56 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -1046,6 +1046,7 @@ def test_shared_logging_keeps_records_from_the_root_and_from_the_handler_of_last handler = logging.Handler() handler.emit = root_saw.append logging.getLogger().addHandler(handler) + earlier = ex._shared_logging.records() ex._shared_logging.take() try: logging.getLogger("uvicorn.error").error("from the server") @@ -1055,7 +1056,9 @@ def test_shared_logging_keeps_records_from_the_root_and_from_the_handler_of_last ex._shared_logging.release() logging.getLogger().removeHandler(handler) assert [record.getMessage() for record in root_saw] == ["from the application"] - assert {"from the server", "from the sdk"} <= {record.getMessage() for record in ex._shared_logging.records()} + # 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 == "" @@ -1578,12 +1581,18 @@ def test_status_says_a_run_ended_by_itself_only_once_its_worker_has_ended(sdk) - 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) - ex._shared_logging.take() + handler = ex._shared_logging._handler try: - logging.getLogger("uvicorn.error").handle(malformed) + ex._shared_logging.take() + try: + logging.getLogger("uvicorn.error").handle(malformed) + finally: + ex._shared_logging.release() + status = app.mcp_status() finally: - ex._shared_logging.release() - status = app.mcp_status() + # 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") From da4296a300234b394e1b925c38c9974b70710276 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:42:36 -0500 Subject: [PATCH 11/35] Add the fleet console which demonstrates the MCP server, and its command line --- examples/mcp_server.py | 312 ++++++++++++++++++++++++++++++- tests/test_example_mcp_server.py | 94 +++++++++- 2 files changed, 403 insertions(+), 3 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 972780e3a..921e7b236 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -1,6 +1,41 @@ """Describe a cmd2 application's commands as plain data, and serve that description over MCP. -This is a placeholder: the finished docstring is written in a later task. The example needs cmd2 4.5.0. +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. The MCP Inspector can +list them: + + npx @modelcontextprotocol/inspector --cli --transport http --server-url http://127.0.0.1:8765/mcp --method tools/list + +Things to try with an assistant which is connected, and the command line 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 + "After I load the backups plugin, back up the site service." + plugin load backups, then: backup site + +The page which documents the example: https://cmd2.readthedocs.io/en/latest/examples/mcp_server/ """ import argparse @@ -13,6 +48,7 @@ import os import re import socket +import sys import threading import time from collections import deque @@ -24,7 +60,7 @@ from rich.console import Console, RenderableType import cmd2 -from cmd2 import Cmd, Cmd2ArgumentParser +from cmd2 import Choices, Cmd, Cmd2ArgumentParser from cmd2.constants import INFINITY from cmd2.utils import DEFAULT_STR_SORT_KEY, strip_doc_annotations @@ -1036,3 +1072,275 @@ def _mcp_rebuild(self) -> None: 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".""" + try: + self.register_command_set(self.backups) + except ValueError: # it is registered already + self.pwarning("The backups plugin is loaded already.") + else: + 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.""" + try: + self.unregister_command_set(self.backups) + except ValueError: # it is not registered + self.pwarning("The backups plugin is not loaded.") + else: + 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.") + + @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: + importlib.import_module("mcp") + except ImportError: + # No application exists yet, so there is no cmd2 output method to use. + sys.stderr.write( + "This example needs 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/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 2936d5c56..d5bae9e65 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -38,7 +38,7 @@ from cmd2 import rich_utils as ru from cmd2 import string_utils as su -from .conftest import with_ansi_style +from .conftest import run_cmd, with_ansi_style EXAMPLE = Path(__file__).parent.parent / "examples" / "mcp_server.py" MODULE_NAME = "cmd2_example_mcp_server" @@ -1937,3 +1937,95 @@ def test_logging_is_as_it_was(state: str, ending: str, sdk, capfd, no_thread_exc for name, handler in attached.items(): logging.getLogger(name).removeHandler(handler) logging.getLogger(name).setLevel(saved_levels[name]) + + +@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"].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 + fleet.onecmd_plus_hooks("plugin unload backups") + assert {command.name for command in fleet.mcp_snapshot.commands} == before + + +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_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_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 From b1c7b9225dad808e8982141e5c8e2fd0d6160224 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:46:08 -0500 Subject: [PATCH 12/35] Run the MCP server example's tests in CI with the MCP SDK installed --- .github/workflows/tests.yml | 42 +++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) 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 From c27bfe273d94aea75655160e8837c2e80fa76aa1 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:05:40 -0500 Subject: [PATCH 13/35] Document the MCP server example --- CHANGELOG.md | 7 + docs/examples/index.md | 1 + docs/examples/mcp_server.md | 323 ++++++++++++++++++++++++++++++++++++ examples/README.md | 6 + examples/mcp_server.py | 20 ++- mkdocs.yml | 1 + 6 files changed, 351 insertions(+), 7 deletions(-) create mode 100644 docs/examples/mcp_server.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bf162110..480010954 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,13 @@ - Enhancements - Added `Cmd.get_command_category()`, which returns the help category a command is listed under. It was the private `_get_command_category()`. + - 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 (TBD) 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..2c7236332 --- /dev/null +++ b/docs/examples/mcp_server.md @@ -0,0 +1,323 @@ +# 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 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 and on Linux. It has not been tried by hand on Windows. + +## 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. + +Two clients have been tried with the example: Claude Code and the MCP Inspector. Claude Desktop, +through the `mcp-remote` bridge, has not been tried. + +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. + +### 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. + +- "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][] starts, before the server does, so that there is always + a description to serve. +1. Just before each top-level prompt, in [cmd2.Cmd.pre_prompt][]. This picks up what the + application changed while it started up, and what its 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 the names of its subcommands. 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`. A command's subcommands are listed by name and summary, and the assistant asks + again with a longer path to have one of them described. 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. + +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. 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 and the name of its type +- 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] = {} + visible = sorted(app.get_visible_commands(), key=DEFAULT_STR_SORT_KEY) + for name in visible: + if name in leave_out: + continue + try: + command, found = _describe_command(app, name) + except Exception as exc: # noqa: BLE001 - one command's failure is its own + command, found = _failed_command(app, name, exc) + 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 +`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. + +The mixin asks a few things of your application: + +- It comes before `cmd2.Cmd` in the bases, so that its `cmdloop()`, `pre_prompt()` and + `onecmd_plus_hooks()` are the ones which are called. +- If your application overrides `cmdloop()`, `pre_prompt()` or `onecmd_plus_hooks()`, the override + calls `super()`, and passes every argument on. +- 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.** It is as of the last top-level prompt or the end of the last + outermost command, whichever came later. 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. A change made by another thread shows at the next of those two moments. 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. +- **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 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 index 921e7b236..67d0649fa 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -21,19 +21,25 @@ --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. The MCP Inspector can -list them: +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:: - npx @modelcontextprotocol/inspector --cli --transport http --server-url http://127.0.0.1:8765/mcp --method tools/list + claude mcp add --transport http fleet http://127.0.0.1:8765/mcp + claude mcp list -Things to try with an assistant which is connected, and the command line each should lead to: +The MCP Inspector can list the tools. Its version 2 takes the server's address as an argument:: - "Deploy version 2.1.0 of the api service to staging without changing anything." + 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 - "After I load the backups plugin, back up the site service." - plugin load backups, then: backup site + "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/ """ 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 From 1db209a4e67e1122aa6583bb4f81573aafab4b06 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:03:16 -0500 Subject: [PATCH 14/35] Undo a start which Ctrl-C interrupts, decide under a run's lock how it ended, and describe a non-finite default by its repr --- examples/mcp_server.py | 225 ++++++++---- tests/test_example_mcp_server.py | 566 +++++++++++++++++++++++++++++-- 2 files changed, 706 insertions(+), 85 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 67d0649fa..17de2989f 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -53,6 +53,7 @@ import logging import os import re +import signal import socket import sys import threading @@ -61,6 +62,7 @@ from collections.abc import Collection, Iterator, Mapping from dataclasses import dataclass from datetime import datetime +from types import FrameType from typing import TYPE_CHECKING, Any from rich.console import Console, RenderableType @@ -171,8 +173,10 @@ def _describe_default(action: argparse.Action) -> Any: if default is None or default == 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. - return _plain_data(json.loads(json.dumps(default))) + # 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)) @@ -709,11 +713,48 @@ def _root_logger_left_alone() -> Iterator[None]: 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.""" + """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 a worker which is still alive only 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) @@ -723,32 +764,37 @@ def __init__(self, port: int) -> 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.abandoned = False # the main thread gave up on its worker while the worker was still alive + 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.Lock() + self.lock = threading.RLock() self._holds_logging = False def serving(self) -> bool: - """Whether the worker is alive and the server has started, and nobody has asked it to stop.""" - return ( - not self.stop_requested - and self.worker is not None - and self.worker.is_alive() - and self.server is not None - and bool(self.server.started) - ) + """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: + 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.""" - with self._lock: + with self.lock: if self._holds_logging: self._holds_logging = False _shared_logging.release() @@ -851,32 +897,41 @@ def onecmd_plus_hooks(self, line: str, *args: Any, **kwargs: Any) -> bool: return super().onecmd_plus_hooks(line, *args, **kwargs) finally: self._mcp_depth -= 1 - self._mcp_rebuild() # never raises; does nothing unless the depth is zero + 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. Never raises an Exception. + """Build the first description, then serve it from a worker thread. + + 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. - Does no more than build when mcp_port is None or this application is serving already. Whatever goes wrong is one - warning, and the application carries on without a server. A KeyboardInterrupt is not caught: before cmdloop() has - installed cmd2's handler, Ctrl-C cannot be held off, and cmdloop()'s call of mcp_stop() undoes what was done. + 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, or a start of it was interrupted) may - # still hold its socket and the logging. Undo it before it is replaced; for a run which was stopped, nothing. + # 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 Exception as error: # noqa: BLE001 - a start never raises + 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 never raises. + # 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) @@ -891,22 +946,30 @@ def _mcp_start_serving(self, run: _Run) -> None: raise _NotServingError( f"the MCP SDK cannot be imported ({error}). Install it with: uv sync --group examples" ) from error - run.take_logging() # before anything of the server can log - 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" + # 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) - worker.start() - run.worker = worker # only once it has started, so that a thread which could not be started is never joined + 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(): - if not worker.is_alive(): - raise _NotServingError(f"the server ended before it began serving: {run.detail or run.outcome}") + 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 @@ -916,38 +979,61 @@ def _mcp_serve(run: _Run) -> None: It is given its run and touches nothing else, so a worker which outlives its command loop does no harm. """ try: - run.server.run(sockets=[run.sock]) - except BaseException as error: # noqa: BLE001 - SystemExit too: nothing may reach threading.excepthook - run.detail = plain_text(f"{type(error).__name__}: {error}") - run.outcome = "cancelled" if run.abandoned else "failed" - else: - run.outcome = "cancelled" if run.abandoned else "stopped" + 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: - run.release_logging() # its last act: a worker which was given up on can still log until it ends + # Its last act, with the lock let go of: a worker which was given up on can still log until it ends. + run.release_logging() def mcp_stop(self) -> None: - """Stop serving: undo exactly what the start got done, in whatever state it finds it. Never raises an Exception. + """Stop serving: undo what the start got done, in whatever state it finds the run. - Does nothing when there is no run, or when it has been stopped already. The run stays, so that mcp_status() can - say what became of it; the next start replaces it. + Does nothing when there is no run, or when it has been stopped already. 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, or leaves that to a worker which is still alive. 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 or run.stop_requested: + if run is None: return - run.stop_requested = True + with run.lock: + if run.stop_requested: + return + run.stop_requested = True # from now on run.serving() is false and mcp_url is None try: if run.server is not None: run.server.should_exit = True if run.worker is not None: - run.worker.join(self.MCP_STOP_TIMEOUT) + 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. - if run.worker is not None and run.worker.is_alive(): - run.abandoned = True # the one place a run is given up on; its worker lets go of the logging when it ends + worker = run.worker + with run.lock: + if worker is not None and worker.is_alive() 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 if run.sock is not None: with contextlib.suppress(OSError): run.sock.close() # uvicorn closes it too, unless it never took it - if run.worker is None or not run.worker.is_alive(): + if worker is None or not worker.is_alive(): run.release_logging() @property @@ -961,25 +1047,32 @@ def mcp_status(self) -> list[str]: 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 - if run is not None and run.serving(): - lines = [f"Serving {run.url}"] - elif run is not None and run.problem is not None: - lines = [f"No MCP server: {run.problem}"] - elif run is not None and run.stop_requested: - lines = ["No MCP server: it was stopped"] - elif run is not None and run.worker is not None and not run.worker.is_alive(): - lines = [f"No MCP server: it ended by itself ({run.detail or run.outcome})"] - elif self.mcp_port is None: - lines = ["No MCP server: --no-mcp was given"] - else: - lines = ["No MCP server: it has not been started"] - if run is not None and run.abandoned and run.worker is not None: - if run.worker.is_alive(): + 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 run.worker.is_alive() + 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") - else: - ended = f"{run.outcome}: {run.detail}" if run.detail else run.outcome + 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") @@ -1047,6 +1140,10 @@ def _mcp_rebuild(self) -> None: 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 each prompt, and at the end of each command. The first build, in mcp_start(), comes before that, + so Ctrl-C there raises KeyboardInterrupt, which leaves the start before it has taken anything. """ if self._mcp_depth != 0: return diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index d5bae9e65..9ed8bb59d 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -142,6 +142,11 @@ def test_argument_default_is_a_copy_which_later_changes_do_not_reach() -> None: 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).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") @@ -1205,6 +1210,25 @@ def run_without_sdk(body: str) -> subprocess.CompletedProcess[str]: return subprocess.run([sys.executable, "-c", preamble + body], capture_output=True, text=True, timeout=60, check=False) +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:]. + + 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 + ) + + def can_bind(port: int) -> bool: """Whether the port can be bound again at once, the way the example binds it.""" try: @@ -1277,6 +1301,26 @@ def test_tools_return_what_the_snapshot_holds(serving) -> None: 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["default"]) == ("limit", "inf") + finally: + app.mcp_stop() + + 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 @@ -1382,6 +1426,7 @@ def test_a_replacement_binds_at_once_while_a_client_is_still_connected(sdk) -> N @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 @@ -1389,6 +1434,7 @@ def test_a_port_which_is_not_a_port_is_a_warning(port: int, sdk, capsys) -> None 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() -> None: @@ -1433,6 +1479,7 @@ def test_a_start_which_fails_part_of_the_way_is_undone(step: str, sdk, capsys, m 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)) @@ -1461,15 +1508,19 @@ def start_any_but_a_worker(thread: threading.Thread) -> None: 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 == 1 + 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 @@ -1539,43 +1590,82 @@ def test_a_start_while_serving_makes_no_new_run_binds_nothing_and_warns_of_nothi assert capfd.readouterr() == ("", "") -def test_a_start_first_undoes_a_run_which_is_neither_serving_nor_stopped(sdk) -> None: +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) - 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 interrupted.port != 0 # it had bound its socket and taken a hold on the logging - app.mcp_start() try: - assert app.mcp_url is not None, app.mcp_status() - assert app._mcp_run is not interrupted + 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() + app.mcp_stop() # whichever run is the last, even when an assertion above failed assert logging_state() == before -def test_status_says_a_run_ended_by_itself_only_once_its_worker_has_ended(sdk) -> None: +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) - with mock.patch.object(app, "_mcp_asgi_app", side_effect=KeyboardInterrupt), pytest.raises(KeyboardInterrupt): - app.mcp_start() - try: - assert app._mcp_run.worker is None - assert app.mcp_status()[0] == "No MCP server: it has not been started" - finally: - app.mcp_stop() app.mcp_start() + run = app._mcp_run try: - run = app._mcp_run + 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 - run.worker.join(timeout=30) - assert not run.worker.is_alive() + 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_status_shows_a_library_record_whose_arguments_do_not_fit_its_format() -> None: @@ -1939,6 +2029,440 @@ def test_logging_is_as_it_was(state: str, ending: str, sdk, capfd, no_thread_exc 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. + """ + + MCP_STOP_TIMEOUT = 0.3 + + 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() # its wait ends while the shutdown is held, before the worker can record how it ended + 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() + if first.worker is not None: + first.worker.join(timeout=30) + assert not first.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 not can_bind(first.port) # uvicorn did not shut down, so its listener is still open + 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) From d29c7b10f47a19ddac45b938c98cd3526c5dcc0b Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:24:16 -0500 Subject: [PATCH 15/35] Give only the stop meant to give up on a worker a short wait in the abandonment test, and join the replacement's worker too --- tests/test_example_mcp_server.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 9ed8bb59d..70fd32a68 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -2213,8 +2213,6 @@ class HoldsItsFirstShutdown(RebuildApp): It is held until the test sets release. Every later server of the application shuts down as usual. """ - MCP_STOP_TIMEOUT = 0.3 - def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) self.shutting_down = threading.Event() # the first server's shutdown has reached the hold @@ -2246,7 +2244,9 @@ def test_abandonment_wins_and_a_restart_serves_on_the_same_port_while_the_old_wo 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 @@ -2273,10 +2273,12 @@ def test_abandonment_wins_and_a_restart_serves_on_the_same_port_while_the_old_wo assert (second.outcome, second.abandoned) == ("stopped", False) finally: app.release.set() - app.mcp_stop() - if first.worker is not None: - first.worker.join(timeout=30) + 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 From 8e83ba0023d7570838dd498aefeddfa1e78e889f Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:37:47 -0500 Subject: [PATCH 16/35] Leave out a subcommand which help hides, warn against a secret as a default, say where the example was tried, and fix its tests on Python 3.11 with coverage and on Windows --- docs/examples/mcp_server.md | 20 ++++++-- examples/mcp_server.py | 11 ++++- tests/test_example_mcp_server.py | 78 ++++++++++++++++++++++++++++++-- 3 files changed, 99 insertions(+), 10 deletions(-) diff --git a/docs/examples/mcp_server.md b/docs/examples/mcp_server.md index 2c7236332..5d62d39ed 100644 --- a/docs/examples/mcp_server.md +++ b/docs/examples/mcp_server.md @@ -48,7 +48,8 @@ prints a warning which says why, and carries on without a server. Its intro then 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 and on Linux. It has not been tried by hand on Windows. +The example has been tried by hand on macOS, with the MCP Inspector and Claude Code, and on Linux, +with the MCP SDK's own client. It has not been tried by hand on Windows. ## Connecting an Assistant @@ -56,8 +57,8 @@ Start the example first, since a client connects to the running application. Wri `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. -Two clients have been tried with the example: Claude Code and the MCP Inspector. Claude Desktop, -through the `mcp-remote` bridge, has not been tried. +Two clients have been tried with the example, on macOS: Claude Code and the MCP Inspector. Claude +Desktop, through the `mcp-remote` bridge, has not been tried. 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. @@ -260,12 +261,20 @@ client's configuration can be written once. While it serves, `mcp_url` is its ad 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()`, `pre_prompt()` and `onecmd_plus_hooks()` are the ones which are called. - 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()`: @@ -317,7 +326,10 @@ The mixin asks a few things of your application: - **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. + 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/mcp_server.py b/examples/mcp_server.py index 17de2989f..e4a8a4bfd 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -281,7 +281,10 @@ def _is_described(action: argparse.Action) -> bool: def _describe_subcommands( parser: Cmd2ArgumentParser, ) -> tuple[bool, tuple[Subcommand, ...], list[tuple[str, Cmd2ArgumentParser]]]: - """Return whether a subcommand is required, the subcommands, and each one's primary name with its parser.""" + """Return whether a subcommand is required, the subcommands, and each one's primary name with its parser. + + A subcommand added with help=argparse.SUPPRESS is left out, since help leaves it out of its list. + """ try: action = parser.get_subparsers_action() except ValueError: @@ -296,8 +299,11 @@ def _describe_subcommands( primaries: list[tuple[str, Cmd2ArgumentParser]] = [] for names in by_parser.values(): name, *aliases = names # argparse adds the primary name before its aliases + help_text = helps.get(name) + if isinstance(help_text, str) and help_text == argparse.SUPPRESS: + continue # with its aliases, as a hidden command is left out subparser = action.choices[name] - summary = _first_line(helps.get(name)) or _first_line(subparser.description) + summary = _first_line(help_text) or _first_line(subparser.description) subcommands.append(Subcommand(name=plain_text(name), aliases=tuple(plain_text(a) for a in aliases), summary=summary)) primaries.append((name, subparser)) return bool(action.required), tuple(subcommands), primaries @@ -1416,6 +1422,7 @@ def do_mcp(self, args: argparse.Namespace) -> None: mcp_status_parser = Cmd2ArgumentParser(description="Say whether there is a server, and what it serves.") + # Not mcp_status(), the usual name for the handler of "mcp status": that would replace the mixin's mcp_status(). @cmd2.as_subcommand_to("mcp", "status", mcp_status_parser, help="say whether there is a server") def mcp_show_status(self, _: argparse.Namespace) -> None: """Print the server's status.""" diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 70fd32a68..1a8ed0bf6 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -260,6 +260,25 @@ def do_quiet(self, _: argparse.Namespace) -> None: 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) @@ -298,6 +317,18 @@ def test_parser_names_its_subcommands_and_says_whether_one_is_required() -> None 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_exclusive_groups() -> None: logs = _descriptions(ParserApp(), "logs")["logs"] assert logs.exclusive_groups == (ex.ExclusiveGroup(arguments=("follow", "since"), required=False),) @@ -513,6 +544,16 @@ def test_answer_describe_command() -> None: # Review Focus 1 assert {"list", "add", "tag"} <= set(re.findall(r"\w+", str(raised.value))) +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) @@ -1190,8 +1231,19 @@ def ask(url: str, tool: str = "", arguments: dict[str, Any] | None = None) -> An 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. + """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. @@ -1207,12 +1259,21 @@ def run_without_sdk(body: str) -> subprocess.CompletedProcess[str]: "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) + 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. """ @@ -1225,7 +1286,12 @@ def run_with_the_example(body: str, *args: str) -> subprocess.CompletedProcess[s "spec.loader.exec_module(ex)\n" ) return subprocess.run( - [sys.executable, "-c", preamble + body, *args], capture_output=True, text=True, timeout=60, check=False + [sys.executable, "-c", preamble + body, *args], + capture_output=True, + text=True, + timeout=60, + check=False, + env=environment_without_coverage(), ) @@ -2355,7 +2421,11 @@ async def fails_once_released(server: Any) -> None: 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 not can_bind(first.port) # uvicorn did not shut down, so its listener is still open + if sys.platform != "win32": + # uvicorn did not shut down, and asyncio.run() closed the worker's event loop, which on Unix is a selector loop: + # its close() leaves the listener open, so the port is still taken until the restart undoes this run. On + # Windows uvicorn runs a proactor loop, whose close() cancels its accept loop, which closes the listener. + assert not can_bind(first.port) app.mcp_port = first.port app.mcp_start() assert app._mcp_run is not first From 95b62be6049d2a7fb640bdbaea2f41fae83721d0 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:05:25 -0500 Subject: [PATCH 17/35] Show finding a command's category from the visible commands, since a disabled command's function is its replacement --- cmd2/cmd2.py | 4 +++- docs/features/help.md | 17 ++++++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index b5b042922..89fbe315d 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -3656,7 +3656,9 @@ def get_command_category(self, func: BoundCommandFunc[...]) -> str: plain mixin :param func: the bound ``do_*`` method of the command, as returned by - [get_command_func()][cmd2.Cmd.get_command_func] + [get_command_func()][cmd2.Cmd.get_command_func] for a command which is not + disabled. While a command is disabled, ``get_command_func()`` returns the + function which reports that, not the command's own. :return: the name of the category """ # Check if the command function has a category. diff --git a/docs/features/help.md b/docs/features/help.md index d0f413b4e..983d93b78 100644 --- a/docs/features/help.md +++ b/docs/features/help.md @@ -159,9 +159,20 @@ def do_findleakers(self, _): categorize((do_undeploy, do_stop, do_findleakers), CMD_CAT_APP_MGMT) ``` -To find out which category a command is listed under, call -[get_command_category()][cmd2.Cmd.get_command_category] as `self.get_command_category(func)`. The -`func` argument comes from `self.get_command_func("name")`. +To find out which category a command is listed under, pass its function to +[get_command_category()][cmd2.Cmd.get_command_category]. Take the command's name from +[get_visible_commands()][cmd2.Cmd.get_visible_commands], as `help` does. Get its function from +[get_command_func()][cmd2.Cmd.get_command_func], and skip a name for which there is none: + +```py +for name in self.get_visible_commands(): + func = self.get_command_func(name) + if func is not None: + category = self.get_command_category(func) +``` + +A disabled command is not among the visible ones. While it is disabled, `get_command_func()` returns +the function which reports that, so the category found from it may not be the command's own. The `help` command also has a verbose option (`help -v` or `help --verbose`) that combines the help categories with per-command help messages: From 7777733b8cec1fb7f92cb7c2874f62c5f7c3e4c4 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:32:09 -0500 Subject: [PATCH 18/35] Document connecting Claude Desktop to the MCP server example through mcp-remote, which was tried --- docs/examples/mcp_server.md | 46 +++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/docs/examples/mcp_server.md b/docs/examples/mcp_server.md index 5d62d39ed..3ead2119d 100644 --- a/docs/examples/mcp_server.md +++ b/docs/examples/mcp_server.md @@ -48,8 +48,8 @@ prints a warning which says why, and carries on without a server. Its intro then 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 and Claude Code, and on Linux, -with the MCP SDK's own client. It has not been tried by hand on Windows. +The example has been tried by hand on macOS, with the MCP Inspector, Claude Code and Claude Desktop, +and on Linux, with the MCP SDK's own client. It has not been tried by hand on Windows. ## Connecting an Assistant @@ -57,8 +57,8 @@ Start the example first, since a client connects to the running application. Wri `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. -Two clients have been tried with the example, on macOS: Claude Code and the MCP Inspector. Claude -Desktop, through the `mcp-remote` bridge, has not been tried. +Three clients have been tried with the example, on macOS: Claude Code, Claude Desktop through the +`mcp-remote` bridge, and the MCP Inspector. 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. @@ -77,6 +77,41 @@ 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 @@ -95,7 +130,8 @@ from running an older version from its cache, which takes different switches. 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. +`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." From 2664dcdabcf24b521fe9323a979092c0093aa190 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:00:32 -0500 Subject: [PATCH 19/35] Leave off the newlines which argparse ends a command's usage and help with, so that a client printing them prints no empty lines --- examples/mcp_server.py | 4 ++-- tests/test_example_mcp_server.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index e4a8a4bfd..c394b1395 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -250,12 +250,12 @@ def _format_at_help_width(parser: Cmd2ArgumentParser) -> tuple[str, str]: """Return the parser's usage and help as plain text, wrapped at HELP_WIDTH whatever the terminal reports. The COLUMNS environment variable overrides the terminal's width, so it is set for the two calls. This is not - thread safe: call it on the main thread only. + thread safe: call it on the main thread only. The newlines which argparse puts at the end of both are left off. """ saved = os.environ.get("COLUMNS") os.environ["COLUMNS"] = str(HELP_WIDTH) try: - return plain_text(parser.format_usage()), plain_text(parser.format_help()) + return plain_text(parser.format_usage()).rstrip(), plain_text(parser.format_help()).rstrip() finally: if saved is None: os.environ.pop("COLUMNS", None) diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 1a8ed0bf6..07333cc26 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -348,6 +348,16 @@ def test_parser_usage_and_help_are_plain_text() -> None: 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 From 23706fd01c9bbdac67d0c0ae67821f4671ecaefe Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:01:09 -0500 Subject: [PATCH 20/35] Say that the MCP server example was tried by hand on Windows, and with which clients --- docs/examples/mcp_server.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/examples/mcp_server.md b/docs/examples/mcp_server.md index 3ead2119d..1c3294926 100644 --- a/docs/examples/mcp_server.md +++ b/docs/examples/mcp_server.md @@ -48,8 +48,9 @@ prints a warning which says why, and carries on without a server. Its intro then 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, -and on Linux, with the MCP SDK's own client. It has not been tried by hand on Windows. +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 @@ -58,7 +59,8 @@ Start the example first, since a client connects to the running application. Wri `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. +`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. From a1526d36ff92bd165f74ad58210a1d45ef1c1421 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:10:37 -0500 Subject: [PATCH 21/35] Address the review of the MCP server example - describe_command finds a subcommand by an alias at any depth ("server t add"). It walks the path from the command, matching each word to its parent's subcommands, and stops at the first unknown word, so a long line is no longer looked up prefix by prefix. Each subcommand is described once, under its name. - A subcommand added with help=argparse.SUPPRESS is left out of the usage and help served, not only of the list of subcommands. They are rendered from a shallow copy of the parser; the parser itself is not changed. - An exclusive group names an option by its first flag and a positional by its name, since two options may share a destination. - A stop which Ctrl-C cut short is finished by the next mcp_stop(). Only a stop which has finished makes a later one return at once. - "plugin load" and "plugin unload" ask whether the plugin is loaded before they register or unregister it, and catch nothing. - An argument with nargs=argparse.PARSER is described as one value or more, which take the rest of the line. - The tests which need the MCP SDK ask for mcp.server.mcpserver, which only version 2 has. --- examples/mcp_server.py | 117 ++++++++++++++++------- tests/test_example_mcp_server.py | 159 ++++++++++++++++++++++++++++--- 2 files changed, 227 insertions(+), 49 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index c394b1395..63a36f362 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -46,6 +46,7 @@ import argparse import contextlib +import copy import importlib import inspect import itertools @@ -120,7 +121,7 @@ class Argument: required: bool min_values: int max_values: int | None # None when unbounded - takes_rest_of_line: bool # nargs=argparse.REMAINDER + takes_rest_of_line: bool # nargs=argparse.REMAINDER, or argparse.PARSER, which takes one value first default: Any # None when there is none worth stating choices: tuple[str, ...] | None # None unless choices= was given dynamic_choices: bool # a choices_provider or a completer; never called @@ -151,7 +152,7 @@ def _value_range(action: argparse.Action) -> tuple[int, int | None]: return 0, 1 if nargs in (argparse.ZERO_OR_MORE, argparse.REMAINDER): return 0, None - if nargs == argparse.ONE_OR_MORE: + 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) @@ -204,7 +205,7 @@ def describe_argument(action: argparse.Action) -> Argument: required=bool(action.required) if is_option else low >= 1, min_values=low, max_values=high, - takes_rest_of_line=action.nargs == argparse.REMAINDER, + takes_rest_of_line=action.nargs in (argparse.REMAINDER, argparse.PARSER), default=_describe_default(action), choices=None if action.choices is None else tuple(plain_text(str(choice)) for choice in action.choices), dynamic_choices=action.get_choices_provider() is not None or action.get_completer() is not None, @@ -217,7 +218,9 @@ def describe_argument(action: argparse.Action) -> Argument: class ExclusiveGroup: """Arguments of which at most one may be given.""" - arguments: tuple[str, ...] # the names of the arguments which exclude each other + # 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 @@ -246,6 +249,37 @@ class Description: error: str | None # why it could not be described; else None +def _without_hidden_subcommands(parser: Cmd2ArgumentParser) -> Cmd2ArgumentParser: + """Return the parser, or a copy to render whose usage and help leave out the subcommands added with help=SUPPRESS. + + argparse leaves no such subcommand out: usage lists it among the choices, and help lists it with ==SUPPRESS== for its + help. The parser itself is never changed. The copy is shallow; its lists of actions and the group which holds the + subcommands are its own, and name a copy of the subcommands' action which knows only the subcommands help shows. + """ + try: + action = parser.get_subparsers_action() + except ValueError: + return parser + # As in _describe_subcommands(), each subcommand added with help= has a pseudo action, named for it, here. + hidden = {id(action.choices[choice.dest]) for choice in action._choices_actions if choice.help == argparse.SUPPRESS} + if not hidden: + return parser + shown = copy.copy(action) + shown.choices = {name: subparser for name, subparser in action.choices.items() if id(subparser) not in hidden} + shown._choices_actions = [choice for choice in action._choices_actions if choice.help != argparse.SUPPRESS] + rendered = copy.copy(parser) + rendered._actions = [shown if each is action else each for each in parser._actions] + rendered._action_groups = [] + for group in parser._action_groups: + if any(each is action for each in group._group_actions): + own = copy.copy(group) + own._group_actions = [shown if each is action else each for each in group._group_actions] + rendered._action_groups.append(own) + else: + rendered._action_groups.append(group) + return rendered + + def _format_at_help_width(parser: Cmd2ArgumentParser) -> tuple[str, str]: """Return the parser's usage and help as plain text, wrapped at HELP_WIDTH whatever the terminal reports. @@ -278,6 +312,11 @@ def _is_described(action: argparse.Action) -> bool: 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 + + def _describe_subcommands( parser: Cmd2ArgumentParser, ) -> tuple[bool, tuple[Subcommand, ...], list[tuple[str, Cmd2ArgumentParser]]]: @@ -312,18 +351,18 @@ def _describe_subcommands( def describe_parser(parser: Cmd2ArgumentParser, path: str, summary: str) -> dict[str, Description]: """Describe a parser under its path, and every subcommand under it at every depth under its own path. - A subcommand's alias is a second key for the same object. + A subcommand is there once, under its name: answer_describe_command() finds one by an alias through its parent. """ # 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(described[id(a)].name for a in group._group_actions if id(a) in described) + members = tuple(_exclusive_name(described[id(a)]) for a in group._group_actions if id(a) in described) if len(members) >= 2: groups.append(ExclusiveGroup(arguments=members, required=bool(group.required))) required, subcommands, children = _describe_subcommands(parser) - usage, help_text = _format_at_help_width(parser) + usage, help_text = _format_at_help_width(_without_hidden_subcommands(parser)) result = { path: Description( path=path, @@ -340,10 +379,7 @@ def describe_parser(parser: Cmd2ArgumentParser, path: str, summary: str) -> dict } for (name, subparser), subcommand in zip(children, subcommands, strict=True): child_path = f"{path} {name}" - found = describe_parser(subparser, child_path, subcommand.summary) - result.update(found) - for alias in subcommand.aliases: - result[f"{path} {alias}"] = found[child_path] + result.update(describe_parser(subparser, child_path, subcommand.summary)) return result @@ -400,7 +436,7 @@ class Snapshot: generation: int built_at: str # local time with its offset, ISO 8601, to the second commands: tuple[Command, ...] # in the order help sorts them - descriptions: Mapping[str, Description] # by path, every depth, alias paths included + 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, ...] @@ -598,18 +634,21 @@ def answer_describe_command(snapshot: Snapshot, command: str) -> CommandDescript """Describe a command or a subcommand, given its path as typed ("server tag add"), or raise UnknownCommandError.""" words = command.split() path = " ".join(words) - description = snapshot.descriptions.get(path) + description = snapshot.descriptions.get(words[0]) if words else None if description is None: - # The longest part of the path which exists says what could have followed it. - for count in range(len(words) - 1, 0, -1): - parent = snapshot.descriptions.get(" ".join(words[:count])) - if parent is not None: - names = ", ".join(subcommand.name for subcommand 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.') names = ", ".join(listed.name for listed in snapshot.commands) raise UnknownCommandError(f'There is no command "{path}". The commands are: {names}.') + # 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 + found = next((sub for sub in parent.subcommands if word == sub.name or word in sub.aliases), None) + description = None if found is None else snapshot.descriptions.get(f"{parent.path} {found.name}") + if description is None: + names = ", ".join(subcommand.name for subcommand 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) @@ -770,6 +809,7 @@ def __init__(self, port: int) -> 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 @@ -1011,21 +1051,22 @@ def _mcp_serve(run: _Run) -> None: 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 it has been stopped already. 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, or leaves that to a worker which is still alive. 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. + 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, or leaves that to a worker which is still alive. 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_requested: + if run.stop_finished: return run.stop_requested = True # from now on run.serving() is false and mcp_url is None - try: 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: @@ -1041,6 +1082,8 @@ def mcp_stop(self) -> None: run.sock.close() # uvicorn closes it too, unless it never took it if worker is None or not worker.is_alive(): run.release_logging() + 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: @@ -1376,12 +1419,12 @@ def do_plugin(self, args: argparse.Namespace) -> None: @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".""" - try: - self.register_command_set(self.backups) - except ValueError: # it is registered already + # 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.") - else: - self.poutput("Loaded the backups plugin: backup, restore.") + 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") @@ -1389,12 +1432,12 @@ def plugin_load(self, _: argparse.Namespace) -> None: @cmd2.as_subcommand_to("plugin", "unload", plugin_unload_parser, help="unload a plugin") def plugin_unload(self, _: argparse.Namespace) -> None: """Unload the backups plugin.""" - try: - self.unregister_command_set(self.backups) - except ValueError: # it is not registered + # 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.") - else: - self.poutput("Unloaded the backups plugin.") + 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") diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 07333cc26..896614a12 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -109,6 +109,7 @@ def _argument(*flags: str, **kwargs: Any) -> Any: (("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), @@ -208,7 +209,7 @@ def server_add(self, _: argparse.Namespace) -> None: 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.") + @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) @@ -293,14 +294,12 @@ def test_parser_subcommands_three_deep_by_path() -> None: assert set(found) == { "server", "server list", - "server ls", "server add", "server tag", "server tag add", "server tag remove", } - assert found["server ls"] is found["server list"] - assert found["server list"].path == "server list" + 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." @@ -329,11 +328,47 @@ def test_parser_leaves_out_a_suppressed_subcommand_with_its_alias() -> None: 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_parser_exclusive_groups() -> None: logs = _descriptions(ParserApp(), "logs")["logs"] - assert logs.exclusive_groups == (ex.ExclusiveGroup(arguments=("follow", "since"), required=False),) + 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),) + 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_leaves_out_a_suppressed_argument() -> None: @@ -544,6 +579,10 @@ def test_answer_describe_command() -> None: # Review Focus 1 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) @@ -554,6 +593,29 @@ def test_answer_describe_command() -> None: # Review Focus 1 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 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") @@ -1183,18 +1245,40 @@ def test_shared_logging_records_are_copied_under_the_handlers_lock() -> None: # --------------------------------------------------------------------------------------------------------------------- -@pytest.fixture -def sdk() -> None: - """Skip a test where the MCP SDK is not installed, unless this run exists to run it.""" +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 # noqa: F401 (a failure here fails the test: the CI job of Task 10 sets the variable) + 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") + 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 @@ -1744,6 +1828,49 @@ def test_status_prefers_a_problem_then_a_failure_then_a_stop_then_how_the_worker 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() + + run.server = Server() + run.sock = socket.socket() + run.take_logging() + run.worker = threading.Thread(target=told.wait, args=(30,), name="mcp-server-test", daemon=True) # ends once told + 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._holds_logging) == (False, False) + assert app.mcp_url is None + finally: + told.set() + run.sock.close() + run.release_logging() + + 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) @@ -2571,7 +2698,7 @@ def test_the_demonstration_has_every_kind_of_thing_to_describe(fleet) -> None: assert deploy["dry_run"].max_values == 0 lines = next(argument for argument in found["logs"].arguments if argument.name == "lines") assert (lines.type, lines.flags) == ("int", ("-n", "--lines")) - assert found["logs"].exclusive_groups == (ex.ExclusiveGroup(arguments=("follow", "since"), required=False),) + assert found["logs"].exclusive_groups == (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) @@ -2590,6 +2717,14 @@ def test_the_demonstration_loads_and_unloads_a_command_set(fleet) -> None: 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} From 8e9c438bda31198b94beccc554cdfb0211281829 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:36:35 -0500 Subject: [PATCH 22/35] Address the second review of the MCP server example - mcp_stop() decides whether to give up on the worker by whether it has recorded how it ended, not by is_alive(). On Python 3.11 and 3.12, a join() which Ctrl-C interrupts leaves is_alive() false while the worker runs on. A worker which started lets go of the logging itself, as its last act; the stop does so only for a start which failed before its worker started. mcp_status() says whether a cancelled worker has ended by the same rule. - Letting go of a run's hold on the logging holds off Ctrl-C until it is done, so that an interrupt cannot leave the hold taken for good. - describe_command splits the path as the prompt splits a command line, so a subcommand whose name has a space in it is found when it is typed quoted. Its path is served quoted. - A required exclusive group of which one member is visible is kept, with that member. - main() asks for mcp.server.mcpserver, which only version 2 of the SDK has, before the console starts. - An argument's name is plain text, as its flags, metavar and help are. --- examples/mcp_server.py | 66 ++++++++++----- tests/test_example_mcp_server.py | 141 ++++++++++++++++++++++++++++++- 2 files changed, 182 insertions(+), 25 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 63a36f362..7ca82355c 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -71,6 +71,8 @@ import cmd2 from cmd2 import Choices, Cmd, Cmd2ArgumentParser from cmd2.constants import INFINITY +from cmd2.parsing import shlex_split +from cmd2.string_utils import quote_if_needed, strip_quotes from cmd2.utils import DEFAULT_STR_SORT_KEY, strip_doc_annotations # --------------------------------------------------------------------------------------------------------------------- @@ -198,7 +200,7 @@ def describe_argument(action: argparse.Action) -> Argument: metavar = " ".join(metavar) help_text = action.help if isinstance(action.help, str) and action.help != argparse.SUPPRESS else "" return Argument( - name=action.dest, + 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), @@ -216,7 +218,7 @@ def describe_argument(action: argparse.Action) -> Argument: @dataclass(frozen=True) class ExclusiveGroup: - """Arguments of which at most one may be given.""" + """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. @@ -348,6 +350,11 @@ def _describe_subcommands( return bool(action.required), tuple(subcommands), primaries +def _subcommand_path(path: str, name: str) -> str: + """A subcommand's path as it is typed: its parent's, then its name, quoted if it has a space in it.""" + return f"{path} {quote_if_needed(name)}" + + def describe_parser(parser: Cmd2ArgumentParser, path: str, summary: str) -> dict[str, Description]: """Describe a parser under its path, and every subcommand under it at every depth under its own path. @@ -359,7 +366,8 @@ def describe_parser(parser: Cmd2ArgumentParser, path: str, summary: str) -> dict 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) - if len(members) >= 2: + # 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, subcommands, children = _describe_subcommands(parser) usage, help_text = _format_at_help_width(_without_hidden_subcommands(parser)) @@ -377,9 +385,8 @@ def describe_parser(parser: Cmd2ArgumentParser, path: str, summary: str) -> dict error=None, ) } - for (name, subparser), subcommand in zip(children, subcommands, strict=True): - child_path = f"{path} {name}" - result.update(describe_parser(subparser, child_path, subcommand.summary)) + for (_, subparser), subcommand in zip(children, subcommands, strict=True): + result.update(describe_parser(subparser, _subcommand_path(path, subcommand.name), subcommand.summary)) return result @@ -631,9 +638,15 @@ def answer_list_commands(snapshot: Snapshot) -> CommandList: 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.""" - words = command.split() - path = " ".join(words) + """Describe a command or a subcommand, given its path as typed ("server tag add"), or raise UnknownCommandError. + + The path is split into words as the prompt splits a command line, so a name with a space in it is typed quoted. + """ + try: + words = [strip_quotes(word) for word in shlex_split(command)] + 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(quote_if_needed(word) for word in words) description = snapshot.descriptions.get(words[0]) if words else None if description is None: names = ", ".join(listed.name for listed in snapshot.commands) @@ -643,9 +656,9 @@ def answer_describe_command(snapshot: Snapshot, command: str) -> CommandDescript for word in words[1:]: parent = description found = next((sub for sub in parent.subcommands if word == sub.name or word in sub.aliases), None) - description = None if found is None else snapshot.descriptions.get(f"{parent.path} {found.name}") + description = None if found is None else snapshot.descriptions.get(_subcommand_path(parent.path, found.name)) if description is None: - names = ", ".join(subcommand.name for subcommand in parent.subcommands) + names = ", ".join(quote_if_needed(subcommand.name) for subcommand 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.') @@ -796,7 +809,7 @@ class _Run: 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 a worker which is still alive only if, under it, the worker has not recorded its outcome yet. mcp_status() + 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. """ @@ -839,8 +852,12 @@ def take_logging(self) -> None: 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.""" - with self.lock: + """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() @@ -1054,8 +1071,9 @@ def mcp_stop(self) -> None: 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, or leaves that to a worker which is still alive. 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. + 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: @@ -1071,17 +1089,19 @@ def mcp_stop(self) -> 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 worker.is_alive() and run.outcome is None: + 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 if run.sock is not None: with contextlib.suppress(OSError): run.sock.close() # uvicorn closes it too, unless it never took it - if worker is None or not worker.is_alive(): - run.release_logging() + 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 @@ -1107,7 +1127,7 @@ def mcp_status(self) -> list[str]: 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 run.worker.is_alive() + 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: @@ -1483,11 +1503,13 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) if not args.no_mcp: try: - importlib.import_module("mcp") + # 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 the MCP SDK: uv run --group examples examples/mcp_server.py " + "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 diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 896614a12..c6d2dd3f1 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -176,7 +176,14 @@ 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", choices=["\x1b[31mred\x1b[0m"], default="\x1b[31mred\x1b[0m", help="\x1b[1mpick\x1b[0m") + 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.default == "red" assert styled.help == "pick" @@ -371,6 +378,20 @@ def test_parser_exclusive_groups_name_options_which_share_a_destination_apart() 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"] @@ -616,6 +637,30 @@ def __getitem__(self, key: str) -> Any: assert all(len(key.split()) <= known + 1 for key in looked_up) +class SpacedApp(cmd2.Cmd): + """An application with subcommands whose names, and an alias, have a space in them.""" + + report_parser = cmd2.Cmd2ArgumentParser() + report_subcommands = report_parser.add_subparsers(title="subcommands") + report_subcommands.add_parser("list all", aliases=["every one"], help="List every report.") + report_subcommands.add_parser("show", help="Show one report.") + + @cmd2.with_argparser(report_parser) + def do_report(self, _: argparse.Namespace) -> None: + pass + + +def test_describing_a_subcommand_whose_name_has_a_space_takes_it_quoted_as_the_prompt_does() -> None: + snapshot = ex.build_snapshot(SpacedApp(), 1) + for typed in ('report "list all"', "report 'list all'", 'report "every one"', '"report" "list all"'): + 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, and so refuses this. The error names the subcommand as it is typed. + with pytest.raises(ex.UnknownCommandError, match='"report" has: "list all", show'): + ex.answer_describe_command(snapshot, "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_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") @@ -1850,10 +1895,14 @@ def should_exit(self, value: bool) -> None: 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() - run.worker = threading.Thread(target=told.wait, args=(30,), name="mcp-server-test", daemon=True) # ends once told + # 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): @@ -1863,7 +1912,7 @@ def should_exit(self, value: bool) -> None: run.worker.join(30) assert not run.worker.is_alive() assert run.sock.fileno() == -1 - assert (run.abandoned, run._holds_logging) == (False, False) + assert (run.abandoned, run.outcome, run._holds_logging) == (False, "stopped", False) assert app.mcp_url is None finally: told.set() @@ -1871,6 +1920,80 @@ def should_exit(self, value: bool) -> None: 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) @@ -2749,6 +2872,18 @@ def test_main_without_the_sdk_says_how_to_install_it() -> None: 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 From 857f0bcb1005083bc7ac6328dc78702b17d4231d Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:18:07 -0500 Subject: [PATCH 23/35] Describe subcommands under their paths as the prompt takes them, quoted where it must be - A subcommand's name is quoted in its path where the prompt would split it or read part of it as syntax: whitespace, a quotation mark, a redirection character, or one of the application's terminators. Every path served can be asked for again. - Its usage and help name it, and the subcommands above it, the same way, rendered from a copy of the parser with that prog; the parser is not changed, and the positionals before a subcommand stay where argparse puts them. - describe_command takes such a name only as it is typed, quoted, as the prompt does. - The first word of a path must be the name of a listed command, unquoted, as at the prompt. --- examples/mcp_server.py | 91 +++++++++++++++++++++++++------- tests/test_example_mcp_server.py | 77 +++++++++++++++++++++++++-- 2 files changed, 145 insertions(+), 23 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 7ca82355c..4b30b523e 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -70,9 +70,9 @@ import cmd2 from cmd2 import Choices, Cmd, Cmd2ArgumentParser -from cmd2.constants import INFINITY +from cmd2.constants import INFINITY, MULTILINE_TERMINATOR, QUOTES, REDIRECTION_CHARS from cmd2.parsing import shlex_split -from cmd2.string_utils import quote_if_needed, strip_quotes +from cmd2.string_utils import is_quoted, quote, strip_quotes from cmd2.utils import DEFAULT_STR_SORT_KEY, strip_doc_annotations # --------------------------------------------------------------------------------------------------------------------- @@ -350,16 +350,60 @@ def _describe_subcommands( return bool(action.required), tuple(subcommands), primaries -def _subcommand_path(path: str, name: str) -> str: - """A subcommand's path as it is typed: its parent's, then its name, quoted if it has a space in it.""" - return f"{path} {quote_if_needed(name)}" +def _as_typed(name: str, terminators: Collection[str]) -> str: + """A subcommand's name as it is typed at the prompt: quoted where the prompt would split it, or read part of it as syntax. + + That is a name with whitespace, a quotation mark, a redirection character or one of the application's terminators. + """ + marks = (*QUOTES, *REDIRECTION_CHARS, *terminators) + if any(char.isspace() for char in name) or any(mark in name for mark in marks): + return quote(name) + return name + + +def _is_typed_as(word: str, name: str, terminators: Collection[str]) -> bool: + """Whether a word of a command line, as the prompt splits it, is the name: as it is typed, or in quotes of any kind.""" + return word == _as_typed(name, terminators) or (is_quoted(word) and strip_quotes(word) == name) -def describe_parser(parser: Cmd2ArgumentParser, path: str, summary: str) -> dict[str, Description]: +def _typed_prog(parent: Cmd2ArgumentParser, typed_parent_prog: str, child: Cmd2ArgumentParser, name: str, typed: str) -> str: + """The prog of a subcommand's parser, for its usage and help, with each name in it as it is typed. + + cmd2 makes a subcommand's prog its parent's prog, then the positionals before the subcommands, then its name, none + of it quoted (Cmd2ArgumentParser.update_prog()). A prog which was made some other way is left as it is. + """ + prog = child.prog + if prog.startswith(parent.prog) and prog.endswith(f" {name}"): + return typed_parent_prog + prog[len(parent.prog) : len(prog) - len(name)] + typed + return prog + + +def _for_rendering(parser: Cmd2ArgumentParser, prog: str) -> Cmd2ArgumentParser: + """Return the parser, or a copy of it to render: with that prog, and without the subcommands which help hides.""" + rendered = _without_hidden_subcommands(parser) + if rendered.prog != prog: + if rendered is parser: + rendered = copy.copy(parser) # never a change to the parser which the prompt uses + rendered.prog = prog + return rendered + + +def describe_parser( + parser: Cmd2ArgumentParser, path: str, summary: str, terminators: Collection[str] = (MULTILINE_TERMINATOR,) +) -> 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 name: answer_describe_command() finds one by an alias through its parent. + A subcommand is there once, under its path as it is typed: its parent's, then its name, quoted where the prompt + would split it or read it as syntax, which the application's terminators help decide. Its usage and help name it + the same way. answer_describe_command() finds one by an alias through its parent. """ + return _describe_parser_as(parser, path, summary, terminators, parser.prog) + + +def _describe_parser_as( + parser: Cmd2ArgumentParser, path: str, summary: str, terminators: Collection[str], prog: str +) -> dict[str, Description]: + """describe_parser(), for a parser whose prog is rendered as the one given.""" # 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} @@ -370,7 +414,7 @@ def describe_parser(parser: Cmd2ArgumentParser, path: str, summary: str) -> dict if len(members) >= 2 or (group.required and members): groups.append(ExclusiveGroup(arguments=members, required=bool(group.required))) required, subcommands, children = _describe_subcommands(parser) - usage, help_text = _format_at_help_width(_without_hidden_subcommands(parser)) + usage, help_text = _format_at_help_width(_for_rendering(parser, prog)) result = { path: Description( path=path, @@ -385,8 +429,10 @@ def describe_parser(parser: Cmd2ArgumentParser, path: str, summary: str) -> dict error=None, ) } - for (_, subparser), subcommand in zip(children, subcommands, strict=True): - result.update(describe_parser(subparser, _subcommand_path(path, subcommand.name), subcommand.summary)) + for (name, subparser), subcommand in zip(children, subcommands, strict=True): + typed = _as_typed(subcommand.name, terminators) + child_prog = _typed_prog(parser, prog, subparser, name, typed) + result.update(_describe_parser_as(subparser, f"{path} {typed}", subcommand.summary, terminators, child_prog)) return result @@ -498,7 +544,7 @@ def _describe_command(app: Cmd, name: str) -> tuple[Command, dict[str, Descripti text = plain_text(inspect.cleandoc(func.__doc__)) if func.__doc__ else "" descriptions = {name: _unparsed_description(name, summary, text, None)} else: - descriptions = describe_parser(parser, name, summary) + descriptions = describe_parser(parser, name, summary, app.statement_parser.terminators) top = descriptions[name] command = Command( name=plain_text(name), @@ -640,14 +686,18 @@ def answer_list_commands(snapshot: Snapshot) -> CommandList: 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. - The path is split into words as the prompt splits a command line, so a name with a space in it is typed quoted. + 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. A subcommand's name which the prompt would split, or read as syntax, is typed quoted, as the + paths served are. """ try: - words = [strip_quotes(word) for word in shlex_split(command)] + 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(quote_if_needed(word) for word in words) - description = snapshot.descriptions.get(words[0]) if words else None + path = " ".join(words) + terminators = snapshot.typing.terminators + 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}.') @@ -655,10 +705,15 @@ def answer_describe_command(snapshot: Snapshot, command: str) -> CommandDescript # 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 - found = next((sub for sub in parent.subcommands if word == sub.name or word in sub.aliases), None) - description = None if found is None else snapshot.descriptions.get(_subcommand_path(parent.path, found.name)) + found = next( + (sub for sub in parent.subcommands if any(_is_typed_as(word, n, terminators) for n in (sub.name, *sub.aliases))), + None, + ) + description = ( + None if found is None else snapshot.descriptions.get(f"{parent.path} {_as_typed(found.name, terminators)}") + ) if description is None: - names = ", ".join(quote_if_needed(subcommand.name) for subcommand in parent.subcommands) + names = ", ".join(_as_typed(subcommand.name, terminators) for subcommand 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.') diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index c6d2dd3f1..9fd53d054 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -638,29 +638,96 @@ def __getitem__(self, key: str) -> Any: class SpacedApp(cmd2.Cmd): - """An application with subcommands whose names, and an alias, have a space in them.""" + """An application with subcommands whose names have in them what the prompt splits a line at, or reads as syntax.""" report_parser = cmd2.Cmd2ArgumentParser() report_subcommands = report_parser.add_subparsers(title="subcommands") report_subcommands.add_parser("list all", aliases=["every one"], help="List every report.") + report_subcommands.add_parser("per|site", help="Report per site.") + report_subcommands.add_parser("a;b", help="Report on a, then on b.") + report_subcommands.add_parser("this&that", help="Report on this and that.") + report_subcommands.add_parser("tab\there", help="Report with a tab.") report_subcommands.add_parser("show", help="Show one report.") + report_list = report_subcommands.add_parser("list", help="List some reports.") + report_list.add_subparsers(title="subcommands").add_parser("all", help="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.") + + def __init__(self) -> None: + super().__init__(terminators=[";", "&"]) @cmd2.with_argparser(report_parser) def do_report(self, _: argparse.Namespace) -> None: pass + @cmd2.with_argparser(owner_parser) + def do_owner(self, _: argparse.Namespace) -> None: + pass + def test_describing_a_subcommand_whose_name_has_a_space_takes_it_quoted_as_the_prompt_does() -> None: snapshot = ex.build_snapshot(SpacedApp(), 1) - for typed in ('report "list all"', "report 'list all'", 'report "every one"', '"report" "list all"'): + 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, and so refuses this. The error names the subcommand as it is typed. - with pytest.raises(ex.UnknownCommandError, match='"report" has: "list all", show'): - ex.answer_describe_command(snapshot, "report list all") + # 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 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", show, list.' in str(raised.value) + + +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]' + # 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") From 69128dc524856ad9f644a04599f5e83b2e96c910 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:19:13 -0500 Subject: [PATCH 24/35] Make the snapshot stress test of the MCP server example 20 rounds instead of 100 It is the slowest test of the suite, since each rebuild describes every command. On a slow macOS runner, 100 rounds took over a minute. With 20, the reader still sees nearly every one of the 41 generations, every core kept busy or not. --- tests/test_example_mcp_server.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 9fd53d054..0ad190c32 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -1221,7 +1221,9 @@ def read() -> None: with ThreadPoolExecutor(max_workers=1) as executor: reading = executor.submit(read) try: - for _ in range(100): + # 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" From 1c1bc048fbdb9b7c161d60ea7fbde413db77b862 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:59:58 -0500 Subject: [PATCH 25/35] Type subcommand names as cmd2 takes them, and keep their tabs in usage and help - A subcommand's name is served as it is where the prompt passes it to argparse unchanged, and quoted otherwise, as cmd2's StatementParser decides with the application's terminators. So today's and a'b"c are served bare, and the empty name as "". A typed word is matched the same way. - A name which no spelling gets through the prompt whole, such as one with both quotation marks and a space, is left out, as a hidden subcommand is: no path served for it could be asked for. - Help makes a tab spaces, so a tab in the prog is rendered as a noncharacter and put back, and a name with a tab no longer has the usage of its sibling with spaces. - The test app's report command has a metavar for its subcommands: 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. --- examples/mcp_server.py | 102 +++++++++++++++++++------------ tests/test_example_mcp_server.py | 96 +++++++++++++++++++++++++---- 2 files changed, 146 insertions(+), 52 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 4b30b523e..3b471a95a 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -70,9 +70,9 @@ import cmd2 from cmd2 import Choices, Cmd, Cmd2ArgumentParser -from cmd2.constants import INFINITY, MULTILINE_TERMINATOR, QUOTES, REDIRECTION_CHARS -from cmd2.parsing import shlex_split -from cmd2.string_utils import is_quoted, quote, strip_quotes +from cmd2.constants import INFINITY, MULTILINE_TERMINATOR +from cmd2.exceptions import Cmd2ShlexError +from cmd2.parsing import StatementParser, shlex_split from cmd2.utils import DEFAULT_STR_SORT_KEY, strip_doc_annotations # --------------------------------------------------------------------------------------------------------------------- @@ -350,20 +350,27 @@ def _describe_subcommands( return bool(action.required), tuple(subcommands), primaries -def _as_typed(name: str, terminators: Collection[str]) -> str: - """A subcommand's name as it is typed at the prompt: quoted where the prompt would split it, or read part of it as syntax. +def _taken_as(word: str, statements: StatementParser) -> str | None: + """The argument which argparse is given for a word typed after a command, or None where the word is not one whole. - That is a name with whitespace, a quotation mark, a redirection character or one of the application's terminators. + The prompt splits a word where it is not quoted at whitespace, a redirection character or a terminator, and takes + off the quotation marks around it, not those inside it. The statements are parsed with the application's + terminators, which is all that a word after the command depends on. """ - marks = (*QUOTES, *REDIRECTION_CHARS, *terminators) - if any(char.isspace() for char in name) or any(mark in name for mark in marks): - return quote(name) - return name + try: + statement = statements.parse(f"command {word}") + except Cmd2ShlexError: # a quotation which is never closed + return None + return statement.argv[1] if statement.args == word and len(statement.argv) == 2 else None + +def _as_typed(name: str, statements: StatementParser) -> str | None: + """A subcommand's name as it is typed at the prompt, or None where the prompt cannot take it whole. -def _is_typed_as(word: str, name: str, terminators: Collection[str]) -> bool: - """Whether a word of a command line, as the prompt splits it, is the name: as it is typed, or in quotes of any kind.""" - return word == _as_typed(name, terminators) or (is_quoted(word) and strip_quotes(word) == name) + 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. + """ + return next((typed for typed in (name, f'"{name}"', f"'{name}'") if _taken_as(typed, statements) == name), None) def _typed_prog(parent: Cmd2ArgumentParser, typed_parent_prog: str, child: Cmd2ArgumentParser, name: str, typed: str) -> str: @@ -378,14 +385,27 @@ def _typed_prog(parent: Cmd2ArgumentParser, typed_parent_prog: str, child: Cmd2A return prog -def _for_rendering(parser: Cmd2ArgumentParser, prog: str) -> Cmd2ArgumentParser: - """Return the parser, or a copy of it to render: with that prog, and without the subcommands which help hides.""" +# 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(parser: Cmd2ArgumentParser, prog: str) -> tuple[str, str]: + """Return the parser's usage and help with that prog, without the subcommands which help hides. + + They are rendered from a copy of the parser where either differs, never from a changed parser. Help makes a tab + spaces, and a name with spaces in place of its tab is another name, so a tab in the prog is rendered as a stand-in + and put back. + """ + rendering = prog if _TAB_STAND_IN in prog else prog.replace("\t", _TAB_STAND_IN) rendered = _without_hidden_subcommands(parser) - if rendered.prog != prog: + if rendered.prog != rendering: if rendered is parser: rendered = copy.copy(parser) # never a change to the parser which the prompt uses - rendered.prog = prog - return rendered + rendered.prog = rendering + usage, help_text = _format_at_help_width(rendered) + if rendering == prog: + return usage, help_text + return usage.replace(_TAB_STAND_IN, "\t"), help_text.replace(_TAB_STAND_IN, "\t") def describe_parser( @@ -393,15 +413,16 @@ def describe_parser( ) -> 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, quoted where the prompt - would split it or read it as syntax, which the application's terminators help decide. Its usage and help name it - the same way. answer_describe_command() finds one by an alias through its parent. + 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 help decide. Its usage and help name it + the same way. One which the prompt cannot take whole has no path which can be typed, and is left out, as a hidden + one is. answer_describe_command() finds one by an alias through its parent. """ - return _describe_parser_as(parser, path, summary, terminators, parser.prog) + return _describe_parser_as(parser, path, summary, StatementParser(terminators=terminators), parser.prog) def _describe_parser_as( - parser: Cmd2ArgumentParser, path: str, summary: str, terminators: Collection[str], prog: str + parser: Cmd2ArgumentParser, path: str, summary: str, statements: StatementParser, prog: str ) -> dict[str, Description]: """describe_parser(), for a parser whose prog is rendered as the one given.""" # argparse has no public way to list a parser's arguments or its mutually exclusive groups. @@ -413,8 +434,15 @@ def _describe_parser_as( # 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, subcommands, children = _describe_subcommands(parser) - usage, help_text = _format_at_help_width(_for_rendering(parser, prog)) + required, all_subcommands, all_children = _describe_subcommands(parser) + typed_names = [_as_typed(subcommand.name, statements) for subcommand in all_subcommands] + kept = [ + (child, subcommand, typed) + for child, subcommand, typed in zip(all_children, all_subcommands, typed_names, strict=True) + if typed is not None + ] + subcommands = tuple(subcommand for _, subcommand, _ in kept) + usage, help_text = _usage_and_help(parser, prog) result = { path: Description( path=path, @@ -429,10 +457,9 @@ def _describe_parser_as( error=None, ) } - for (name, subparser), subcommand in zip(children, subcommands, strict=True): - typed = _as_typed(subcommand.name, terminators) + for (name, subparser), subcommand, typed in kept: child_prog = _typed_prog(parser, prog, subparser, name, typed) - result.update(_describe_parser_as(subparser, f"{path} {typed}", subcommand.summary, terminators, child_prog)) + result.update(_describe_parser_as(subparser, f"{path} {typed}", subcommand.summary, statements, child_prog)) return result @@ -687,15 +714,15 @@ def answer_describe_command(snapshot: Snapshot, command: str) -> CommandDescript """Describe a command or a subcommand, given its path as typed ("server tag add"), or raise UnknownCommandError. 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. A subcommand's name which the prompt would split, or read as syntax, is typed quoted, as the - paths served are. + 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. """ 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) - terminators = snapshot.typing.terminators + statements = StatementParser(terminators=snapshot.typing.terminators) 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: @@ -705,15 +732,12 @@ def answer_describe_command(snapshot: Snapshot, command: str) -> CommandDescript # 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 - found = next( - (sub for sub in parent.subcommands if any(_is_typed_as(word, n, terminators) for n in (sub.name, *sub.aliases))), - None, - ) - description = ( - None if found is None else snapshot.descriptions.get(f"{parent.path} {_as_typed(found.name, terminators)}") - ) + taken = _taken_as(word, statements) + found = next((sub for sub in parent.subcommands if taken in (sub.name, *sub.aliases)), None) + typed = None if found is None else _as_typed(found.name, statements) + description = None if typed is None else snapshot.descriptions.get(f"{parent.path} {typed}") if description is None: - names = ", ".join(_as_typed(subcommand.name, terminators) for subcommand in parent.subcommands) + names = ", ".join(filter(None, (_as_typed(subcommand.name, statements) for subcommand 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.') diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 0ad190c32..ee4b505e7 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -637,19 +637,36 @@ def __getitem__(self, key: str) -> Any: 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.""" + """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() - report_subcommands = report_parser.add_subparsers(title="subcommands") - report_subcommands.add_parser("list all", aliases=["every one"], help="List every report.") - report_subcommands.add_parser("per|site", help="Report per site.") - report_subcommands.add_parser("a;b", help="Report on a, then on b.") - report_subcommands.add_parser("this&that", help="Report on this and that.") - report_subcommands.add_parser("tab\there", help="Report with a tab.") - report_subcommands.add_parser("show", help="Show one report.") - report_list = report_subcommands.add_parser("list", help="List some reports.") - report_list.add_subparsers(title="subcommands").add_parser("all", help="List all of some reports.") + # 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.") + _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") @@ -659,10 +676,11 @@ class SpacedApp(cmd2.Cmd): def __init__(self) -> None: super().__init__(terminators=[";", "&"]) + self.ran: str | None = None @cmd2.with_argparser(report_parser) - def do_report(self, _: argparse.Namespace) -> None: - pass + 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: @@ -688,6 +706,10 @@ def test_a_name_which_the_prompt_would_split_or_read_as_syntax_is_served_quoted_ '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 show", "report list", "report list all", @@ -698,7 +720,48 @@ def test_a_name_which_the_prompt_would_split_or_read_as_syntax_is_served_quoted_ 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", show, list.' in str(raised.value) + assert ( + '"report" has: "list all", "per|site", "a;b", "this&that", "tab\there", "tab here", today\'s, a\'b"c, "", ' + "show, list." in str(raised.value) + ) + + +def test_every_path_served_runs_at_the_prompt_the_subcommand_which_it_describes() -> None: + app = SpacedApp() + snapshot = ex.build_snapshot(app, 1) + for path, description in snapshot.descriptions.items(): + if path.startswith("report "): + app.ran = None + app.onecmd_plus_hooks(path) + 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_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: @@ -709,6 +772,13 @@ def test_usage_and_help_name_each_subcommand_as_it_is_typed() -> None: 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]' From 41dc36f433f31b3ae057168cc7ae77350480a36c Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:47:05 -0500 Subject: [PATCH 26/35] Show each subcommand by the names of it which can be typed, everywhere it is named - A subcommand whose name the prompt cannot take whole is reached by an alias which it can: the alias stands for it in its path, its usage and its parent's list, and its subcommands are described under that path. - A name which cannot be typed is left out wherever it would be named: the structured list of subcommands and aliases, and the parent's usage and help, which are rendered from a copy of the parser that names each subcommand by the same names. --- examples/mcp_server.py | 118 +++++++++++++++++++------------ tests/test_example_mcp_server.py | 35 ++++++++- 2 files changed, 106 insertions(+), 47 deletions(-) diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 3b471a95a..ec7139489 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -60,7 +60,7 @@ import threading import time from collections import deque -from collections.abc import Collection, Iterator, Mapping +from collections.abc import Collection, Iterator, Mapping, Sequence from dataclasses import dataclass from datetime import datetime from types import FrameType @@ -251,31 +251,50 @@ class Description: error: str | None # why it could not be described; else None -def _without_hidden_subcommands(parser: Cmd2ArgumentParser) -> Cmd2ArgumentParser: - """Return the parser, or a copy to render whose usage and help leave out the subcommands added with help=SUPPRESS. +@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 + typed: str # the first of those as it is typed + parser: Cmd2ArgumentParser + subcommand: Subcommand + - argparse leaves no such subcommand out: usage lists it among the choices, and help lists it with ==SUPPRESS== for its - help. The parser itself is never changed. The copy is shallow; its lists of actions and the group which holds the - subcommands are its own, and name a copy of the subcommands' action which knows only the subcommands help shows. +def _with_shown_subcommands(parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcommand]) -> Cmd2ArgumentParser: + """Return the parser, or a copy to render 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. The parser itself is never changed. The copy is shallow; its lists of actions and the group which + holds the subcommands are its own, and name a copy of the subcommands' action which knows only what is shown. """ try: action = parser.get_subparsers_action() except ValueError: return parser - # As in _describe_subcommands(), each subcommand added with help= has a pseudo action, named for it, here. - hidden = {id(action.choices[choice.dest]) for choice in action._choices_actions if choice.help == argparse.SUPPRESS} - if not hidden: + if [name for each in shown for name in each.shown] == list(action.choices): return parser - shown = copy.copy(action) - shown.choices = {name: subparser for name, subparser in action.choices.items() if id(subparser) not in hidden} - shown._choices_actions = [choice for choice in action._choices_actions if choice.help != argparse.SUPPRESS] + # 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) rendered = copy.copy(parser) - rendered._actions = [shown if each is action else each for each in parser._actions] + rendered._actions = [shown_action if each is action else each for each in parser._actions] rendered._action_groups = [] for group in parser._action_groups: if any(each is action for each in group._group_actions): own = copy.copy(group) - own._group_actions = [shown if each is action else each for each in group._group_actions] + own._group_actions = [shown_action if each is action else each for each in group._group_actions] rendered._action_groups.append(own) else: rendered._action_groups.append(group) @@ -319,35 +338,46 @@ def _exclusive_name(argument: Argument) -> str: return argument.flags[0] if argument.flags else argument.name -def _describe_subcommands( - parser: Cmd2ArgumentParser, -) -> tuple[bool, tuple[Subcommand, ...], list[tuple[str, Cmd2ArgumentParser]]]: - """Return whether a subcommand is required, the subcommands, and each one's primary name with its parser. +def _describe_subcommands(parser: Cmd2ArgumentParser, statements: StatementParser) -> tuple[bool, list[_ShownSubcommand]]: + """Return whether a subcommand is required, and each subcommand as its parent's description shows it. - A subcommand added with help=argparse.SUPPRESS is left out, since help leaves it out of its list. + A subcommand added with help=argparse.SUPPRESS is left out, since help leaves it out of its list. So is one which + the prompt cannot take whole by any of its names, since no path to it could be typed. Of the others, a name which + the prompt cannot take whole 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, (), [] + return False, [] # 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) - subcommands: list[Subcommand] = [] - primaries: list[tuple[str, Cmd2ArgumentParser]] = [] + shown: list[_ShownSubcommand] = [] for names in by_parser.values(): - name, *aliases = names # argparse adds the primary name before its aliases - help_text = helps.get(name) + 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 - subparser = action.choices[name] + typable = [(name, typed) for name in names if (typed := _as_typed(plain_text(name), statements)) is not None] + if not typable: + continue + subparser = action.choices[names[0]] summary = _first_line(help_text) or _first_line(subparser.description) - subcommands.append(Subcommand(name=plain_text(name), aliases=tuple(plain_text(a) for a in aliases), summary=summary)) - primaries.append((name, subparser)) - return bool(action.required), tuple(subcommands), primaries + (first, typed), *others = typable + subcommand = Subcommand(name=plain_text(first), aliases=tuple(plain_text(name) for name, _ in others), summary=summary) + shown.append( + _ShownSubcommand( + names=tuple(names), + shown=tuple(name for name, _ in typable), + typed=typed, + parser=subparser, + subcommand=subcommand, + ) + ) + return bool(action.required), shown def _taken_as(word: str, statements: StatementParser) -> str | None: @@ -389,15 +419,15 @@ def _typed_prog(parent: Cmd2ArgumentParser, typed_parent_prog: str, child: Cmd2A _TAB_STAND_IN = "\ufdd0" -def _usage_and_help(parser: Cmd2ArgumentParser, prog: str) -> tuple[str, str]: - """Return the parser's usage and help with that prog, without the subcommands which help hides. +def _usage_and_help(parser: Cmd2ArgumentParser, prog: str, shown: Sequence[_ShownSubcommand]) -> tuple[str, str]: + """Return the parser's usage and help with that prog, naming only the subcommands shown, by the names shown. They are rendered from a copy of the parser where either differs, never from a changed parser. Help makes a tab spaces, and a name with spaces in place of its tab is another name, so a tab in the prog is rendered as a stand-in and put back. """ rendering = prog if _TAB_STAND_IN in prog else prog.replace("\t", _TAB_STAND_IN) - rendered = _without_hidden_subcommands(parser) + rendered = _with_shown_subcommands(parser, shown) if rendered.prog != rendering: if rendered is parser: rendered = copy.copy(parser) # never a change to the parser which the prompt uses @@ -415,8 +445,9 @@ def describe_parser( 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 help decide. Its usage and help name it - the same way. One which the prompt cannot take whole has no path which can be typed, and is left out, as a hidden - one is. answer_describe_command() finds one by an alias through its parent. + 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. """ return _describe_parser_as(parser, path, summary, StatementParser(terminators=terminators), parser.prog) @@ -434,15 +465,8 @@ def _describe_parser_as( # 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, all_subcommands, all_children = _describe_subcommands(parser) - typed_names = [_as_typed(subcommand.name, statements) for subcommand in all_subcommands] - kept = [ - (child, subcommand, typed) - for child, subcommand, typed in zip(all_children, all_subcommands, typed_names, strict=True) - if typed is not None - ] - subcommands = tuple(subcommand for _, subcommand, _ in kept) - usage, help_text = _usage_and_help(parser, prog) + required, shown = _describe_subcommands(parser, statements) + usage, help_text = _usage_and_help(parser, prog, shown) result = { path: Description( path=path, @@ -452,14 +476,16 @@ def _describe_parser_as( has_parser=True, arguments=tuple(described.values()), exclusive_groups=tuple(groups), - subcommands=subcommands, + subcommands=tuple(each.subcommand for each in shown), subcommand_required=required, error=None, ) } - for (name, subparser), subcommand, typed in kept: - child_prog = _typed_prog(parser, prog, subparser, name, typed) - result.update(_describe_parser_as(subparser, f"{path} {typed}", subcommand.summary, statements, child_prog)) + for each in shown: + child_prog = _typed_prog(parser, prog, each.parser, each.names[0], each.typed) + result.update( + _describe_parser_as(each.parser, f"{path} {each.typed}", each.subcommand.summary, statements, child_prog) + ) return result diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index ee4b505e7..3471b978c 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -664,6 +664,9 @@ class SpacedApp(cmd2.Cmd): _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.") @@ -710,6 +713,9 @@ def test_a_name_which_the_prompt_would_split_or_read_as_syntax_is_served_quoted_ "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", @@ -722,7 +728,7 @@ def test_a_name_which_the_prompt_would_split_or_read_as_syntax_is_served_quoted_ 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, "", ' - "show, list." in str(raised.value) + "daily, weekly, show, list." in str(raised.value) ) @@ -751,6 +757,33 @@ def test_a_name_with_quotation_marks_in_it_is_found_as_the_prompt_takes_it() -> 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_a_subcommand_which_no_spelling_gets_through_the_prompt_whole_is_left_out() -> None: app = SpacedApp() snapshot = ex.build_snapshot(app, 1) From 3b84d452f86b57a21670bffeac41494d7549040e Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:42:00 -0500 Subject: [PATCH 27/35] Type a subcommand's name as argparse is given it by a command which keeps its quotes A command made with preserve_quotes=True gives argparse each word with its quotation marks, so the subcommand named "list all", quotes and all, is reached by typing "list all", and no word reaches one named list all without them. The example read every command as if it took its quotes off: it served kept '"list all"', which runs nothing, and gave "list all" to the other subcommand. The example now asks cmd2 for each command's preserve_quotes with Cmd.get_argparse_command_spec(), and reads the words after the command as the prompt gives them to that command's parser, both when it describes the command and when it finds a path. The snapshot records which commands keep their quotes, for the lookup, and does not serve it. --- docs/examples/mcp_server.md | 5 +- examples/mcp_server.py | 103 +++++++++++++++++++------------ tests/test_example_mcp_server.py | 28 ++++++++- 3 files changed, 96 insertions(+), 40 deletions(-) diff --git a/docs/examples/mcp_server.md b/docs/examples/mcp_server.md index 1c3294926..2e0f08f90 100644 --- a/docs/examples/mcp_server.md +++ b/docs/examples/mcp_server.md @@ -20,7 +20,8 @@ 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 the +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: @@ -264,6 +265,8 @@ def build_snapshot(app: Cmd, generation: int, leave_out: Collection[str] = ()) - `_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). diff --git a/examples/mcp_server.py b/examples/mcp_server.py index ec7139489..cf4005556 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -338,7 +338,44 @@ def _exclusive_name(argument: Argument) -> str: return argument.flags[0] if argument.flags else argument.name -def _describe_subcommands(parser: Cmd2ArgumentParser, statements: StatementParser) -> tuple[bool, list[_ShownSubcommand]]: +@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) + + +def _keeps_quotes(app: Cmd, name: str) -> bool: + """Whether argparse is given the command's arguments with their quotation marks: its preserve_quotes.""" + func = app.get_command_func(name) + spec = None if func is None else app.get_argparse_command_spec(func) + return spec is not None and spec.preserve_quotes + + +def _describe_subcommands(parser: Cmd2ArgumentParser, reading: _Reading) -> tuple[bool, list[_ShownSubcommand]]: """Return whether a subcommand is required, and each subcommand as its parent's description shows it. A subcommand added with help=argparse.SUPPRESS is left out, since help leaves it out of its list. So is one which @@ -361,7 +398,7 @@ def _describe_subcommands(parser: Cmd2ArgumentParser, statements: StatementParse 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 = [(name, typed) for name in names if (typed := _as_typed(plain_text(name), statements)) is not None] + typable = [(name, typed) for name in names if (typed := reading.as_typed(plain_text(name))) is not None] if not typable: continue subparser = action.choices[names[0]] @@ -380,29 +417,6 @@ def _describe_subcommands(parser: Cmd2ArgumentParser, statements: StatementParse return bool(action.required), shown -def _taken_as(word: str, statements: StatementParser) -> str | None: - """The argument which argparse is given for a word typed after a command, or None where the word is not one whole. - - The prompt splits a word where it is not quoted at whitespace, a redirection character or a terminator, and takes - off the quotation marks around it, not those inside it. The statements are parsed with the application's - terminators, which is all that a word after the command depends on. - """ - try: - statement = statements.parse(f"command {word}") - except Cmd2ShlexError: # a quotation which is never closed - return None - return statement.argv[1] if statement.args == word and len(statement.argv) == 2 else None - - -def _as_typed(name: str, statements: StatementParser) -> 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. - """ - return next((typed for typed in (name, f'"{name}"', f"'{name}'") if _taken_as(typed, statements) == name), None) - - def _typed_prog(parent: Cmd2ArgumentParser, typed_parent_prog: str, child: Cmd2ArgumentParser, name: str, typed: str) -> str: """The prog of a subcommand's parser, for its usage and help, with each name in it as it is typed. @@ -439,21 +453,28 @@ def _usage_and_help(parser: Cmd2ArgumentParser, prog: str, shown: Sequence[_Show def describe_parser( - parser: Cmd2ArgumentParser, path: str, summary: str, terminators: Collection[str] = (MULTILINE_TERMINATOR,) + 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 help decide. Its usage and help name it + 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. """ - return _describe_parser_as(parser, path, summary, StatementParser(terminators=terminators), parser.prog) + reading = _Reading(StatementParser(terminators=terminators), keeps_quotes) + return _describe_parser_as(parser, path, summary, reading, parser.prog) def _describe_parser_as( - parser: Cmd2ArgumentParser, path: str, summary: str, statements: StatementParser, prog: str + parser: Cmd2ArgumentParser, path: str, summary: str, reading: _Reading, prog: str ) -> dict[str, Description]: """describe_parser(), for a parser whose prog is rendered as the one given.""" # argparse has no public way to list a parser's arguments or its mutually exclusive groups. @@ -465,7 +486,7 @@ def _describe_parser_as( # 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, statements) + required, shown = _describe_subcommands(parser, reading) usage, help_text = _usage_and_help(parser, prog, shown) result = { path: Description( @@ -483,9 +504,7 @@ def _describe_parser_as( } for each in shown: child_prog = _typed_prog(parser, prog, each.parser, each.names[0], each.typed) - result.update( - _describe_parser_as(each.parser, f"{path} {each.typed}", each.subcommand.summary, statements, child_prog) - ) + result.update(_describe_parser_as(each.parser, f"{path} {each.typed}", each.subcommand.summary, reading, child_prog)) return result @@ -548,6 +567,7 @@ class Snapshot: 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 @@ -597,7 +617,8 @@ def _describe_command(app: Cmd, name: str) -> tuple[Command, dict[str, Descripti text = plain_text(inspect.cleandoc(func.__doc__)) if func.__doc__ else "" descriptions = {name: _unparsed_description(name, summary, text, None)} else: - descriptions = describe_parser(parser, name, summary, app.statement_parser.terminators) + terminators = app.statement_parser.terminators + descriptions = describe_parser(parser, name, summary, terminators, keeps_quotes=_keeps_quotes(app, name)) top = descriptions[name] command = Command( name=plain_text(name), @@ -626,6 +647,7 @@ def build_snapshot(app: Cmd, generation: int, leave_out: Collection[str] = ()) - """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() visible = sorted(app.get_visible_commands(), key=DEFAULT_STR_SORT_KEY) for name in visible: if name in leave_out: @@ -634,6 +656,9 @@ def build_snapshot(app: Cmd, generation: int, leave_out: Collection[str] = ()) - command, found = _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(app, name): + quotes_kept.add(command.name) commands.append(command) descriptions.update(found) parser = app.statement_parser @@ -656,6 +681,7 @@ def build_snapshot(app: Cmd, generation: int, leave_out: Collection[str] = ()) - terminators=tuple(plain_text(t) for t in parser.terminators), multiline_commands=tuple(plain_text(c) for c in parser.multiline_commands), ), + quotes_kept=frozenset(quotes_kept), error=None, ) @@ -672,6 +698,7 @@ def failed_snapshot(generation: int, error: str) -> Snapshot: aliases=(), macros=(), typing=TypingRules(allow_redirection=False, terminators=(), multiline_commands=()), + quotes_kept=frozenset(), error=plain_text(error), ) @@ -748,22 +775,22 @@ def answer_describe_command(snapshot: Snapshot, command: str) -> CommandDescript 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) - statements = StatementParser(terminators=snapshot.typing.terminators) 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 = _taken_as(word, statements) + taken = reading.argument_for(word) found = next((sub for sub in parent.subcommands if taken in (sub.name, *sub.aliases)), None) - typed = None if found is None else _as_typed(found.name, statements) + typed = None if found is None else reading.as_typed(found.name) description = None if typed is None else snapshot.descriptions.get(f"{parent.path} {typed}") if description is None: - names = ", ".join(filter(None, (_as_typed(subcommand.name, statements) for subcommand in parent.subcommands))) + names = ", ".join(filter(None, (reading.as_typed(subcommand.name) for subcommand 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.') diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 3471b978c..86aab7aac 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -677,6 +677,13 @@ class SpacedApp(cmd2.Cmd): 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.") + def __init__(self) -> None: super().__init__(terminators=[";", "&"]) self.ran: str | None = None @@ -689,6 +696,10 @@ def do_report(self, args: argparse.Namespace) -> None: 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) + def test_describing_a_subcommand_whose_name_has_a_space_takes_it_quoted_as_the_prompt_does() -> None: snapshot = ex.build_snapshot(SpacedApp(), 1) @@ -736,7 +747,7 @@ def test_every_path_served_runs_at_the_prompt_the_subcommand_which_it_describes( app = SpacedApp() snapshot = ex.build_snapshot(app, 1) for path, description in snapshot.descriptions.items(): - if path.startswith("report "): + if path.startswith(("report ", "kept ")): app.ran = None app.onecmd_plus_hooks(path) assert app.ran == description.summary, path @@ -784,6 +795,21 @@ def test_usage_help_and_aliases_name_a_subcommand_only_by_the_names_which_can_be 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_a_subcommand_which_no_spelling_gets_through_the_prompt_whole_is_left_out() -> None: app = SpacedApp() snapshot = ex.build_snapshot(app, 1) From a560c7d9f673c1a9035d7ea03aa30e21316c7630 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:16:46 -0500 Subject: [PATCH 28/35] Describe nothing from before preloop(), and serve only names which dispatch their subcommand - The first description is built once cmdloop() has run preloop(), before the first line is read, in an override of cmd2's private Cmd._cmdloop(), since cmd2 has no public method there and pre_prompt() never runs when input is a pipe. Until then the server answers that the description has not been built, so a command which preloop() hides is never described. Commands run from inside preloop() publish nothing, and a second cmdloop() does not serve the first one's description while its own preloop() runs. - Choices which are an iterator are not listed, and usage and help are rendered from a copy of the argument without them, so describing a command no longer uses up what argparse checks values against. - A command is described by the name it was asked for, so a synonym such as do_orate = do_speak, which cmd2 gives the other's parser, prog and all, has usage which names it. - A subcommand's name is served only where argparse takes it for the subcommand, not for an option (-h, --, an ambiguous abbreviation) or a file of arguments, and only where plain_text() leaves it as it is, so that a\rb is no longer served as ab, its sibling's path. --- docs/examples/mcp_server.md | 16 ++- examples/mcp_server.py | 168 +++++++++++++++++++------ tests/test_example_mcp_server.py | 203 +++++++++++++++++++++++++++++-- 3 files changed, 338 insertions(+), 49 deletions(-) diff --git a/docs/examples/mcp_server.md b/docs/examples/mcp_server.md index 2e0f08f90..647bb02de 100644 --- a/docs/examples/mcp_server.md +++ b/docs/examples/mcp_server.md @@ -181,10 +181,15 @@ application's `mcp_snapshot` attribute, and it is never changed afterwards. Each The snapshot is rebuilt at three moments, by three methods of [cmd2.Cmd][] which the mixin overrides: -1. When the outermost [cmd2.Cmd.cmdloop][] starts, before the server does, so that there is always - a description to serve. +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 changed while it started up, and what its own `pre_prompt()` changes. + 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 @@ -308,8 +313,9 @@ the secret inside the command instead, or leave the command out with `mcp_leave_ The mixin asks a few things of your application: -- It comes before `cmd2.Cmd` in the bases, so that its `cmdloop()`, `pre_prompt()` and - `onecmd_plus_hooks()` are the ones which are called. +- 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 diff --git a/examples/mcp_server.py b/examples/mcp_server.py index cf4005556..237fda4bf 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -64,7 +64,7 @@ from dataclasses import dataclass from datetime import datetime from types import FrameType -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, NoReturn, TypeVar from rich.console import Console, RenderableType @@ -209,7 +209,10 @@ def describe_argument(action: argparse.Action) -> Argument: max_values=high, takes_rest_of_line=action.nargs in (argparse.REMAINDER, argparse.PARSER), default=_describe_default(action), - choices=None if action.choices is None else tuple(plain_text(str(choice)) for choice in action.choices), + # Choices which are an iterator are not listed: listing them would use up what argparse checks values against. + choices=None + if action.choices is None or isinstance(action.choices, Iterator) + else tuple(plain_text(str(choice)) for choice in action.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), @@ -262,19 +265,17 @@ class _ShownSubcommand: subcommand: Subcommand -def _with_shown_subcommands(parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcommand]) -> Cmd2ArgumentParser: - """Return the parser, or a copy to render whose usage and help name only the subcommands shown, by the names shown. +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. - argparse would list every subcommand by every name: usage among the choices, and help with ==SUPPRESS== for the help - of a hidden one. The parser itself is never changed. The copy is shallow; its lists of actions and the group which - holds the subcommands are its own, and name a copy of the subcommands' action which knows only what is 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 parser + return {} if [name for each in shown for name in each.shown] == list(action.choices): - return parser + 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) @@ -288,17 +289,48 @@ def _with_shown_subcommands(parser: Cmd2ArgumentParser, shown: Sequence[_ShownSu # 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]) -> Cmd2ArgumentParser: + """Return the parser, or a copy to render 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 choices which are an iterator, to list them or to expand %(choices)s in a help, + and use them up, though argparse reads them again to check each value given: an argument whose choices are an + iterator is rendered as one without 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 parser._actions: + if isinstance(action.choices, Iterator): + unlisted = replaced[id(action)] = copy.copy(action) + unlisted.choices = None + if not replaced: + return parser rendered = copy.copy(parser) - rendered._actions = [shown_action if each is action else each for each in parser._actions] - rendered._action_groups = [] - for group in parser._action_groups: - if any(each is action for each in group._group_actions): + 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 = [shown_action if each is action else each for each in group._group_actions] - rendered._action_groups.append(own) + own._group_actions = [replaced.get(id(each), each) for each in group._group_actions] + result.append(own) else: - rendered._action_groups.append(group) - return rendered + result.append(group) + return result def _format_at_help_width(parser: Cmd2ArgumentParser) -> tuple[str, str]: @@ -368,6 +400,33 @@ def as_typed(self, name: str) -> str | None: 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 _reaches_subcommands() asks.""" + + +def _refuse(message: str) -> NoReturn: + raise _NotASubcommandError(message) + + +def _reaches_subcommands(parser: Cmd2ArgumentParser, name: str) -> bool: + """Whether argparse, given the name where the parser's subcommand goes, takes it for the subcommand's name. + + argparse takes a word which begins with one of its prefix characters as an option, such as -h, or --ver beside + --verbose and --version, unless it is that character alone, looks like a negative number, or has a space in it. It + takes "--" for the end of the options, and a word which begins with one of its fromfile prefix characters for a file + of arguments. Whether a word is an option is decided by _parse_optional(), which is private, and is asked of a + shallow copy: on Python 3.11 an ambiguous abbreviation is reported with error(), which prints and exits. + """ + if parser.fromfile_prefix_chars and name.startswith(tuple(parser.fromfile_prefix_chars)): + return False + 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 None + except _NotASubcommandError: + return False + + def _keeps_quotes(app: Cmd, name: str) -> bool: """Whether argparse is given the command's arguments with their quotation marks: its preserve_quotes.""" func = app.get_command_func(name) @@ -379,9 +438,10 @@ def _describe_subcommands(parser: Cmd2ArgumentParser, reading: _Reading) -> tupl """Return whether a subcommand is required, and each subcommand as its parent's description shows it. A subcommand added with help=argparse.SUPPRESS is left out, since help leaves it out of its list. So is one which - the prompt cannot take whole by any of its names, since no path to it could be typed. Of the others, a name which - the prompt cannot take whole is left out; where that is the primary name, the first alias which can be typed - stands for the subcommand. + 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() @@ -398,13 +458,19 @@ def _describe_subcommands(parser: Cmd2ArgumentParser, reading: _Reading) -> tupl 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 = [(name, typed) for name in names if (typed := reading.as_typed(plain_text(name))) is not None] + typable = [ + (name, typed) + for name in names + if plain_text(name) == name # else it would be served as another name, perhaps a sibling's + and _reaches_subcommands(parser, name) + and (typed := reading.as_typed(name)) is not None + ] if not typable: continue subparser = action.choices[names[0]] summary = _first_line(help_text) or _first_line(subparser.description) (first, typed), *others = typable - subcommand = Subcommand(name=plain_text(first), aliases=tuple(plain_text(name) for name, _ in others), summary=summary) + subcommand = Subcommand(name=first, aliases=tuple(name for name, _ in others), summary=summary) shown.append( _ShownSubcommand( names=tuple(names), @@ -436,12 +502,12 @@ def _typed_prog(parent: Cmd2ArgumentParser, typed_parent_prog: str, child: Cmd2A def _usage_and_help(parser: Cmd2ArgumentParser, prog: str, shown: Sequence[_ShownSubcommand]) -> tuple[str, str]: """Return the parser's usage and help with that prog, naming only the subcommands shown, by the names shown. - They are rendered from a copy of the parser where either differs, never from a changed parser. Help makes a tab + They are rendered from a copy of the parser where they would differ, never from a changed parser. Help makes a tab spaces, and a name with spaces in place of its tab is another name, so a tab in the prog is rendered as a stand-in and put back. """ rendering = prog if _TAB_STAND_IN in prog else prog.replace("\t", _TAB_STAND_IN) - rendered = _with_shown_subcommands(parser, shown) + rendered = _to_render(parser, shown) if rendered.prog != rendering: if rendered is parser: rendered = copy.copy(parser) # never a change to the parser which the prompt uses @@ -468,9 +534,12 @@ def describe_parser( 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, parser.prog) + return _describe_parser_as(parser, path, summary, reading, path) def _describe_parser_as( @@ -686,6 +755,10 @@ def build_snapshot(app: Cmd, generation: int, leave_out: Collection[str] = ()) - ) +# 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( @@ -1041,6 +1114,7 @@ class McpServerMixin(_Base): 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_in_cmdloop: bool + _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__( @@ -1061,25 +1135,48 @@ def __init__( self.mcp_port = mcp_port self.mcp_name = mcp_name self.mcp_leave_out = frozenset(mcp_leave_out) - self.mcp_snapshot = failed_snapshot(0, "The description has not been built yet.") + self.mcp_snapshot = failed_snapshot(0, _NOT_BUILT) self.mcp_build_error = None self._mcp_depth = 0 self._mcp_in_cmdloop = False + self._mcp_starting = False self._mcp_run = None def cmdloop(self, intro: RenderableType = "") -> int: - """Build the first description before the loop starts, and stop when the loop ends, however it ends.""" + """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 = not self._mcp_in_cmdloop # False for a call made from inside a command self._mcp_in_cmdloop = True try: if outermost: - self.mcp_start() # the first description, then the server + self._mcp_starting = True + if self.mcp_snapshot.error is None: + self.mcp_snapshot = failed_snapshot(self.mcp_snapshot.generation + 1, _NOT_BUILT) + self.mcp_start() # the server, which serves no description until _cmdloop() builds the first return super().cmdloop(intro) finally: if outermost: self._mcp_in_cmdloop = False + 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 calls this too, and builds nothing. + """ + if self._mcp_starting: + 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() @@ -1097,6 +1194,8 @@ def onecmd_plus_hooks(self, line: str, *args: Any, **kwargs: Any) -> bool: 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. @@ -1337,16 +1436,17 @@ def list_shortcuts_aliases_macros() -> Tables: 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. Never raises an Exception. + """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 each prompt, and at the end of each command. The first build, in mcp_start(), comes before that, - so Ctrl-C there raises KeyboardInterrupt, which leaves the start before it has taken anything. + 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: + if self._mcp_depth != 0 or self._mcp_starting: return with self.sigint_protection: warnings: list[str] = [] @@ -1354,8 +1454,8 @@ def _mcp_rebuild(self) -> None: snapshot = self._mcp_build() except Exception as error: # noqa: BLE001 - a rebuild never raises message = plain_text(f"{type(error).__name__}: {error}") - if self.mcp_snapshot.generation == 0: - self.mcp_snapshot = failed_snapshot(1, message) + if self.mcp_snapshot.error == _NOT_BUILT: + self.mcp_snapshot = failed_snapshot(self.mcp_snapshot.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 diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 86aab7aac..9948751b3 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -684,6 +684,22 @@ class SpacedApp(cmd2.Cmd): _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.") + def __init__(self) -> None: super().__init__(terminators=[";", "&"]) self.ran: str | None = None @@ -700,6 +716,10 @@ def do_owner(self, _: argparse.Namespace) -> None: 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) + def test_describing_a_subcommand_whose_name_has_a_space_takes_it_quoted_as_the_prompt_does() -> None: snapshot = ex.build_snapshot(SpacedApp(), 1) @@ -747,7 +767,7 @@ def test_every_path_served_runs_at_the_prompt_the_subcommand_which_it_describes( app = SpacedApp() snapshot = ex.build_snapshot(app, 1) for path, description in snapshot.descriptions.items(): - if path.startswith(("report ", "kept ")): + if path.startswith(("report ", "kept ", "odd ")): app.ran = None app.onecmd_plus_hooks(path) assert app.ran == description.summary, path @@ -810,6 +830,106 @@ def test_the_subcommands_of_a_command_which_keeps_its_quotes_are_typed_as_argpar assert ex.answer_describe_command(snapshot, "report 'list all'").description.path == 'report "list all"' +def test_a_subcommand_name_which_argparse_takes_as_an_option_is_left_out(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. + assert [(each.name, each.aliases) for each in odd.subcommands] == [ + ("expand", ()), + ("-1", ()), + ("-", ()), + ("- x", ()), + ("ab", ()), + ] + 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 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 + + +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) for each in power.arguments] == [("mode", None), ("fan", None)] + assert power.usage == "Usage: power [-h] [--fan SPEED] MODE" + + def test_a_subcommand_which_no_spelling_gets_through_the_prompt_whole_is_left_out() -> None: app = SpacedApp() snapshot = ex.build_snapshot(app, 1) @@ -1008,28 +1128,32 @@ def test_arguments_are_passed_through_unchanged() -> None: assert len(app.history) == before -@pytest.mark.parametrize("moment", ["mcp_start", "pre_prompt", "the end of a command"]) +@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() + 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") - assert protected == [True] + # 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 -def test_ctrl_c_before_cmd2_has_its_handler_leaves_the_loop_and_still_stops(monkeypatch: pytest.MonkeyPatch) -> None: +@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() - assert (app.starts, app.stops, app._mcp_in_cmdloop) == (1, 1, False) + app.cmdloop() # the first build is in _cmdloop(), after cmd2's cmdloop() has installed its handlers + assert (app.starts, app.stops, app._mcp_in_cmdloop, app._mcp_starting) == (1, 1, False, False) def test_a_build_which_fails_keeps_the_previous_snapshot_and_is_reported_once(monkeypatch, capsys) -> None: @@ -1133,7 +1257,7 @@ def do_inner(self, _: cmd2.Statement) -> None: class PreloopApp(LoopApp): - """Disables help in preloop(): after the first description is built, and before the first prompt.""" + """Disables help in preloop(): after the server has started, and before the first description is built.""" def preloop(self) -> None: super().preloop() @@ -1272,7 +1396,7 @@ def test_nothing_is_published_at_a_continuation_prompt() -> None: 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 mcp_start's generation 1, + 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 @@ -1283,13 +1407,72 @@ def test_a_multiline_command_at_the_top_level_publishes_at_its_end() -> None: 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 mcp_start's generation 1 + 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) + + +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_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() From a4f1a78869b0d57a2582da847a2a9e72a2b0375b Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:14:10 -0500 Subject: [PATCH 29/35] Leave out suppressed subcommand lists, cap listed choices, and say when nothing is described - Subcommands added with add_subparsers(help=argparse.SUPPRESS) are all left out, as help and usage leave them out. - No more than the first 1000 of an argument's choices are read and listed, so choices=range(2**32) no longer takes minutes and gigabytes before the first prompt. Each argument's new more_choices says when some are not listed, which is also so of choices which are an iterator, and usage and help are rendered without such choices. - The mixin counts the calls of cmdloop() in progress, and only the outermost loop's _cmdloop() ends the start, so a loop run inside preloop() publishes nothing before preloop() has returned. - Where there is no description, describe_command says so, with DescriptionUnavailableError, and list_shortcuts_aliases_macros has an error, as list_commands has, in place of answering that the command does not exist or that the tables are empty. - A subcommand's name is checked against the from-file prefixes of every parser above it, since each reads the files in every word it is given. --- docs/examples/mcp_server.md | 20 ++++- examples/mcp_server.py | 106 +++++++++++++++------- tests/test_example_mcp_server.py | 150 +++++++++++++++++++++++++++++-- 3 files changed, 234 insertions(+), 42 deletions(-) diff --git a/docs/examples/mcp_server.md b/docs/examples/mcp_server.md index 647bb02de..d80441e88 100644 --- a/docs/examples/mcp_server.md +++ b/docs/examples/mcp_server.md @@ -226,20 +226,27 @@ The server has three tools. Each one is marked read-only, and each answer carrie - `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. + 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. 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: +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 and the name of its type +- 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 @@ -364,6 +371,11 @@ The mixin asks a few things of your application: - **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 diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 237fda4bf..774fe713b 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -125,7 +125,8 @@ class Argument: max_values: int | None # None when unbounded takes_rest_of_line: bool # nargs=argparse.REMAINDER, or argparse.PARSER, which takes one value first default: Any # None when there is none worth stating - choices: tuple[str, ...] | None # None unless choices= was given + 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 @@ -194,6 +195,7 @@ def _describe_type(action: argparse.Action) -> str | None: 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): @@ -209,16 +211,33 @@ def describe_argument(action: argparse.Action) -> Argument: max_values=high, takes_rest_of_line=action.nargs in (argparse.REMAINDER, argparse.PARSER), default=_describe_default(action), - # Choices which are an iterator are not listed: listing them would use up what argparse checks values against. - choices=None - if action.choices is None or isinstance(action.choices, Iterator) - else tuple(plain_text(str(choice)) for choice in action.choices), + 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.""" @@ -296,16 +315,16 @@ def _to_render(parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcommand]) -> """Return the parser, or a copy to render 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 choices which are an iterator, to list them or to expand %(choices)s in a help, - and use them up, though argparse reads them again to check each value given: an argument whose choices are an - iterator is rendered as one without choices. + 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). An argument with choices which are not all listed is rendered as one without 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 parser._actions: - if isinstance(action.choices, Iterator): + if _listed_choices(action.choices)[1]: unlisted = replaced[id(action)] = copy.copy(action) unlisted.choices = None if not replaced: @@ -408,16 +427,21 @@ def _refuse(message: str) -> NoReturn: raise _NotASubcommandError(message) -def _reaches_subcommands(parser: Cmd2ArgumentParser, name: str) -> bool: +def _reaches_subcommands(parser: Cmd2ArgumentParser, name: str, file_prefixes: str) -> bool: """Whether argparse, given the name where the parser's subcommand goes, takes it for the subcommand's name. argparse takes a word which begins with one of its prefix characters as an option, such as -h, or --ver beside --verbose and --version, unless it is that character alone, looks like a negative number, or has a space in it. It - takes "--" for the end of the options, and a word which begins with one of its fromfile prefix characters for a file - of arguments. Whether a word is an option is decided by _parse_optional(), which is private, and is asked of a - shallow copy: on Python 3.11 an ambiguous abbreviation is reported with error(), which prints and exits. + takes "--" for the end of the options. Whether a word is an option is decided by _parse_optional(), which is private, + and is asked of a shallow copy: on Python 3.11 an ambiguous abbreviation is reported with error(), which prints and + exits. + + A word which begins with a fromfile prefix character is read as a file of arguments, whether the character is the + parser's or that of a parser above it: each reads the files in every word it is given, before it passes on the words + after its subcommand's name. file_prefixes are those of the parsers above it. """ - if parser.fromfile_prefix_chars and name.startswith(tuple(parser.fromfile_prefix_chars)): + prefixes = file_prefixes + (parser.fromfile_prefix_chars or "") + if prefixes and name.startswith(tuple(prefixes)): return False asked = copy.copy(parser) asked.error = _refuse # the copy's own: the parser which the prompt uses is never changed @@ -434,10 +458,13 @@ def _keeps_quotes(app: Cmd, name: str) -> bool: return spec is not None and spec.preserve_quotes -def _describe_subcommands(parser: Cmd2ArgumentParser, reading: _Reading) -> tuple[bool, list[_ShownSubcommand]]: +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. - A subcommand added with help=argparse.SUPPRESS is left out, since help leaves it out of its list. So is one which + 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 @@ -447,6 +474,8 @@ def _describe_subcommands(parser: Cmd2ArgumentParser, reading: _Reading) -> tupl 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} @@ -462,7 +491,7 @@ def _describe_subcommands(parser: Cmd2ArgumentParser, reading: _Reading) -> tupl (name, typed) for name in names if plain_text(name) == name # else it would be served as another name, perhaps a sibling's - and _reaches_subcommands(parser, name) + and _reaches_subcommands(parser, name, file_prefixes) and (typed := reading.as_typed(name)) is not None ] if not typable: @@ -539,13 +568,13 @@ def describe_parser( 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) + return _describe_parser_as(parser, path, summary, reading, path, "") def _describe_parser_as( - parser: Cmd2ArgumentParser, path: str, summary: str, reading: _Reading, prog: str + parser: Cmd2ArgumentParser, path: str, summary: str, reading: _Reading, prog: str, file_prefixes: str ) -> dict[str, Description]: - """describe_parser(), for a parser whose prog is rendered as the one given.""" + """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} @@ -555,7 +584,7 @@ def _describe_parser_as( # 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) + required, shown = _describe_subcommands(parser, reading, file_prefixes) usage, help_text = _usage_and_help(parser, prog, shown) result = { path: Description( @@ -573,7 +602,11 @@ def _describe_parser_as( } for each in shown: child_prog = _typed_prog(parser, prog, each.parser, each.names[0], each.typed) - result.update(_describe_parser_as(each.parser, f"{path} {each.typed}", each.subcommand.summary, reading, child_prog)) + inner_prefixes = file_prefixes + (parser.fromfile_prefix_chars or "") + child_path = f"{path} {each.typed}" + result.update( + _describe_parser_as(each.parser, child_path, each.subcommand.summary, reading, child_prog, inner_prefixes) + ) return result @@ -793,7 +826,7 @@ class CommandList: categories: tuple[Category, ...] # in the order help shows them help_topics: tuple[str, ...] typing: TypingRules - error: str | None + error: str | None # why there is no description to answer from: none has been built yet, or a build failed @dataclass(frozen=True) @@ -814,12 +847,17 @@ class Tables: 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 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.""" by_category: dict[str, list[Command]] = {} @@ -839,10 +877,14 @@ def answer_list_commands(snapshot: Snapshot) -> CommandList: 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 @@ -878,6 +920,7 @@ def answer_tables(snapshot: Snapshot) -> Tables: shortcuts=snapshot.shortcuts, aliases=snapshot.aliases, macros=snapshot.macros, + error=snapshot.error, ) @@ -1113,7 +1156,7 @@ class McpServerMixin(_Base): 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_in_cmdloop: bool + _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 @@ -1138,7 +1181,7 @@ def __init__( self.mcp_snapshot = failed_snapshot(0, _NOT_BUILT) self.mcp_build_error = None self._mcp_depth = 0 - self._mcp_in_cmdloop = False + self._mcp_loops = 0 self._mcp_starting = False self._mcp_run = None @@ -1149,8 +1192,8 @@ def cmdloop(self, intro: RenderableType = "") -> int: 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 = not self._mcp_in_cmdloop # False for a call made from inside a command - self._mcp_in_cmdloop = True + outermost = self._mcp_loops == 0 # False for a call made from inside a command, or from inside preloop() + self._mcp_loops += 1 try: if outermost: self._mcp_starting = True @@ -1159,8 +1202,8 @@ def cmdloop(self, intro: RenderableType = "") -> int: 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_in_cmdloop = False self._mcp_starting = False self.mcp_stop() # safe to call twice, and after a start which failed @@ -1170,9 +1213,10 @@ def _cmdloop(self) -> None: 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 calls this too, and builds nothing. + 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: + if self._mcp_starting and self._mcp_loops == 1: self._mcp_starting = False self._mcp_rebuild() super()._cmdloop() @@ -1424,7 +1468,7 @@ def describe_command(command: str) -> CommandDescription: snapshot = self.mcp_snapshot try: return answer_describe_command(snapshot, command) - except UnknownCommandError as error: + except (UnknownCommandError, DescriptionUnavailableError) as error: raise ToolError(str(error)) from error @server.tool(annotations=read_only) diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 9948751b3..783808289 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -7,6 +7,7 @@ import functools import importlib.util import io +import itertools import json import logging import os @@ -700,6 +701,11 @@ class SpacedApp(cmd2.Cmd): _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 @@ -720,6 +726,10 @@ def do_kept(self, args: argparse.Namespace) -> None: 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) @@ -767,7 +777,7 @@ def test_every_path_served_runs_at_the_prompt_the_subcommand_which_it_describes( app = SpacedApp() snapshot = ex.build_snapshot(app, 1) for path, description in snapshot.descriptions.items(): - if path.startswith(("report ", "kept ", "odd ")): + if path.startswith(("report ", "kept ", "odd ", "files ")): app.ran = None app.onecmd_plus_hooks(path) assert app.ran == description.summary, path @@ -866,6 +876,85 @@ def test_a_subcommand_name_which_is_not_served_as_it_is_is_left_out() -> None: 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 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) + + class SynonymApp(cmd2.Cmd): """Has orate, the function of speak under a second name, which cmd2 gives the parser of speak, prog and all.""" @@ -926,10 +1015,22 @@ def test_describing_choices_which_are_an_iterator_leaves_them_to_argparse() -> N assert app.given is not None assert (app.given.mode, app.given.fan) == ("off", "fast") power = snapshot.descriptions["power"] - assert [(each.name, each.choices) for each in power.arguments] == [("mode", None), ("fan", None)] + assert [(each.name, each.choices, each.more_choices) for each in power.arguments] == [ + ("mode", None, True), + ("fan", None, True), + ] 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) @@ -1153,7 +1254,7 @@ def test_a_keyboard_interrupt_from_the_first_build_leaves_the_loop_and_still_sto 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_in_cmdloop, app._mcp_starting) == (1, 1, False, False) + 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: @@ -1253,7 +1354,7 @@ def do_outer(self, _: cmd2.Statement) -> None: def do_inner(self, _: cmd2.Statement) -> None: """Run a command loop inside this command.""" self.cmdloop() - self.seen["inner loop returned"] = (self._mcp_in_cmdloop, frozenset(_listed(self))) + self.seen["inner loop returned"] = (self._mcp_loops, frozenset(_listed(self))) class PreloopApp(LoopApp): @@ -1440,6 +1541,32 @@ def preloop(self) -> None: 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) @@ -1492,7 +1619,7 @@ def preloop(self) -> None: with pytest.raises(RuntimeError, match="in preloop"): app.cmdloop() assert (app.starts, app.stops) == (1, 1) - assert app._mcp_in_cmdloop is False + assert app._mcp_loops == 0 app.mcp_stop() # again: nothing is raised RebuildApp().mcp_stop() # with no start: nothing is raised @@ -1501,8 +1628,8 @@ 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) - in_cmdloop, listed_then = app.seen["inner loop returned"] - assert in_cmdloop is True + 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" @@ -1907,6 +2034,15 @@ def do_budget(self, args: argparse.Namespace) -> None: 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 From db54d52d1966123a394b816d79377389e1c807d6 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:32:48 -0500 Subject: [PATCH 30/35] Fix MCP help rendering, worker cleanup, and snapshot error reporting Keep subcommand visibility independent of argument choice limits, render formatter-aware summaries, and reject the end-of-options marker in paths. Release the listener when its worker exits and publish the latest failure until a snapshot succeeds. Include both required test matrices when deciding whether to retry an unacquired runner. --- .github/workflows/rerun-unacquired.yml | 3 +- examples/mcp_server.py | 63 +++++++++++++++++------- tests/test_example_mcp_server.py | 66 ++++++++++++++++++++++++-- 3 files changed, 108 insertions(+), 24 deletions(-) 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/examples/mcp_server.py b/examples/mcp_server.py index 774fe713b..1f29a1eed 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -73,6 +73,7 @@ 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 DEFAULT_STR_SORT_KEY, strip_doc_annotations # --------------------------------------------------------------------------------------------------------------------- @@ -311,22 +312,30 @@ def _shown_subcommands(parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcomm return {id(action): shown_action} -def _to_render(parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcommand]) -> Cmd2ArgumentParser: +def _to_render( + parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcommand], omitted: Sequence[argparse.Action] +) -> Cmd2ArgumentParser: """Return the parser, or a copy to render 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). An argument with choices which are not all listed is rendered as one without choices. + 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 parser._actions: - if _listed_choices(action.choices)[1]: - unlisted = replaced[id(action)] = copy.copy(action) - unlisted.choices = None + 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) if not replaced: return parser rendered = copy.copy(parser) @@ -377,6 +386,15 @@ def _first_line(value: object) -> str: 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 = parser._get_formatter() + 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)): @@ -441,7 +459,7 @@ def _reaches_subcommands(parser: Cmd2ArgumentParser, name: str, file_prefixes: s after its subcommand's name. file_prefixes are those of the parsers above it. """ prefixes = file_prefixes + (parser.fromfile_prefix_chars or "") - if prefixes and name.startswith(tuple(prefixes)): + if name == "--" or name.startswith(tuple(prefixes)): return False asked = copy.copy(parser) asked.error = _refuse # the copy's own: the parser which the prompt uses is never changed @@ -497,7 +515,7 @@ def _describe_subcommands( if not typable: continue subparser = action.choices[names[0]] - summary = _first_line(help_text) or _first_line(subparser.description) + summary = _first_line(help_text) or _parser_summary(subparser) (first, typed), *others = typable subcommand = Subcommand(name=first, aliases=tuple(name for name, _ in others), summary=summary) shown.append( @@ -528,7 +546,9 @@ def _typed_prog(parent: Cmd2ArgumentParser, typed_parent_prog: str, child: Cmd2A _TAB_STAND_IN = "\ufdd0" -def _usage_and_help(parser: Cmd2ArgumentParser, prog: str, shown: Sequence[_ShownSubcommand]) -> tuple[str, str]: +def _usage_and_help( + parser: Cmd2ArgumentParser, prog: str, shown: Sequence[_ShownSubcommand], omitted: Sequence[argparse.Action] +) -> tuple[str, str]: """Return the parser's usage and help with that prog, naming only the subcommands shown, by the names shown. They are rendered from a copy of the parser where they would differ, never from a changed parser. Help makes a tab @@ -536,7 +556,7 @@ def _usage_and_help(parser: Cmd2ArgumentParser, prog: str, shown: Sequence[_Show and put back. """ rendering = prog if _TAB_STAND_IN in prog else prog.replace("\t", _TAB_STAND_IN) - rendered = _to_render(parser, shown) + rendered = _to_render(parser, shown, omitted) if rendered.prog != rendering: if rendered is parser: rendered = copy.copy(parser) # never a change to the parser which the prompt uses @@ -585,7 +605,8 @@ def _describe_parser_as( 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) - usage, help_text = _usage_and_help(parser, prog, shown) + omitted = [action for action in actions if described[id(action)].more_choices] + usage, help_text = _usage_and_help(parser, prog, shown, omitted) result = { path: Description( path=path, @@ -687,7 +708,7 @@ def _command_summary(doc: str | None, parser: Cmd2ArgumentParser | None) -> str: # What "help -v" shows. return plain_text(strip_doc_annotations(doc)) if parser is not None: - return _first_line(parser.description) + return _parser_summary(parser) return "" @@ -1078,6 +1099,12 @@ def __init__(self, port: int) -> None: 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. @@ -1337,8 +1364,10 @@ def _mcp_serve(run: _Run) -> None: else: run.outcome = "failed" finally: - # Its last act, with the lock let go of: a worker which was given up on can still log until it ends. - run.release_logging() + 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. @@ -1372,9 +1401,7 @@ def mcp_stop(self) -> 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 - if run.sock is not None: - with contextlib.suppress(OSError): - run.sock.close() # uvicorn closes it too, unless it never took it + run.close_socket() if worker is None: run.release_logging() # a start which failed before its worker started: nobody else will with run.lock: @@ -1498,7 +1525,7 @@ def _mcp_rebuild(self) -> None: snapshot = self._mcp_build() except Exception as error: # noqa: BLE001 - a rebuild never raises message = plain_text(f"{type(error).__name__}: {error}") - if self.mcp_snapshot.error == _NOT_BUILT: + if self.mcp_snapshot.error is not None and self.mcp_snapshot.error != message: self.mcp_snapshot = failed_snapshot(self.mcp_snapshot.generation + 1, message) if message != self.mcp_build_error: warnings.append(f"MCP: the description could not be built: {message}") diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 783808289..043f8c304 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -353,6 +353,34 @@ def test_parser_usage_and_help_leave_out_a_suppressed_subcommand_without_changin 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_end_of_options_is_never_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", "") + assert [child.name for child in found["p"].subcommands] == aliases + assert "p --" not in found + if aliases: + assert parser.parse_args(["end"]) == argparse.Namespace() + assert "p end" in found + + def test_parser_exclusive_groups() -> None: logs = _descriptions(ParserApp(), "logs")["logs"] assert logs.exclusive_groups == (ex.ExclusiveGroup(arguments=("--follow", "--since"), required=False),) @@ -548,6 +576,22 @@ def test_snapshot_summary_from_a_rich_description_when_there_is_no_docstring() - 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) @@ -948,6 +992,7 @@ def test_no_more_choices_are_read_than_are_listed() -> 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") @@ -1019,6 +1064,7 @@ def test_describing_choices_which_are_an_iterator_leaves_them_to_argparse() -> N ("mode", None, True), ("fan", None, True), ] + assert "one of (choices omitted)" in power.help assert power.usage == "Usage: power [-h] [--fan SPEED] MODE" @@ -1295,6 +1341,20 @@ def test_a_first_build_which_fails_publishes_an_empty_snapshot_with_the_error(mo 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") @@ -3198,11 +3258,7 @@ async def fails_once_released(server: Any) -> None: 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)" - if sys.platform != "win32": - # uvicorn did not shut down, and asyncio.run() closed the worker's event loop, which on Unix is a selector loop: - # its close() leaves the listener open, so the port is still taken until the restart undoes this run. On - # Windows uvicorn runs a proactor loop, whose close() cancels its accept loop, which closes the listener. - assert not can_bind(first.port) + 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 From dfb92d47654b9ced83ca33351df355a3a25b2412 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:17:14 -0500 Subject: [PATCH 31/35] Serve usable subcommand paths and bound child help in MCP snapshots Expose the quoted lookup spelling and account for positionals that consume the end-of-options marker. Rebuild capped child prefixes from the display parser, size help formatters locally, and escape surrogate code points before sending JSON. --- docs/examples/mcp_server.md | 14 ++- examples/mcp_server.py | 181 ++++++++++++++++--------------- tests/test_example_mcp_server.py | 82 ++++++++++++++ 3 files changed, 184 insertions(+), 93 deletions(-) diff --git a/docs/examples/mcp_server.md b/docs/examples/mcp_server.md index d80441e88..4bddb6d94 100644 --- a/docs/examples/mcp_server.md +++ b/docs/examples/mcp_server.md @@ -216,13 +216,15 @@ The server has three tools. Each one is marked read-only, and each answer carrie `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 the names of its subcommands. 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. + 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`. A command's subcommands are listed by name and summary, and the assistant asks - again with a longer path to have one of them described. A name which isn't there, including a - hidden or disabled command, is an error which names the commands or subcommands which are. + `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. diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 1f29a1eed..34d513ef5 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -52,7 +52,6 @@ import itertools import json import logging -import os import re import signal import socket @@ -63,6 +62,7 @@ from collections.abc import Collection, Iterator, Mapping, Sequence from dataclasses import dataclass from datetime import datetime +from functools import partial from types import FrameType from typing import TYPE_CHECKING, Any, NoReturn, TypeVar @@ -110,7 +110,8 @@ def plain_text(value: object) -> str: # cmd2.string_utils.strip_style() is not enough here: it leaves hyperlinks. text = _OSC_SEQUENCE.sub("", text) text = _CSI_SEQUENCE.sub("", text) - return _CONTROL_CHARACTERS.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) @@ -254,6 +255,7 @@ 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 @@ -280,7 +282,7 @@ class _ShownSubcommand: 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 - typed: str # the first of those as it is typed + needs_separator: bool # the parent must consume -- before this name parser: Cmd2ArgumentParser subcommand: Subcommand @@ -315,7 +317,7 @@ def _shown_subcommands(parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcomm def _to_render( parser: Cmd2ArgumentParser, shown: Sequence[_ShownSubcommand], omitted: Sequence[argparse.Action] ) -> Cmd2ArgumentParser: - """Return the parser, or a copy to render whose usage and help name only the subcommands shown, by the names shown. + """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, @@ -336,9 +338,10 @@ def _to_render( unlisted.metavar = formatter._get_default_metavar_for_optional(action) else: unlisted.metavar = formatter._get_default_metavar_for_positional(action) - if not replaced: - return parser 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) @@ -361,21 +364,16 @@ def _with_replaced(groups: list[_Group], replaced: Mapping[int, argparse.Action] return result -def _format_at_help_width(parser: Cmd2ArgumentParser) -> tuple[str, str]: - """Return the parser's usage and help as plain text, wrapped at HELP_WIDTH whatever the terminal reports. - - The COLUMNS environment variable overrides the terminal's width, so it is set for the two calls. This is not - thread safe: call it on the main thread only. The newlines which argparse puts at the end of both are left off. - """ - saved = os.environ.get("COLUMNS") - os.environ["COLUMNS"] = str(HELP_WIDTH) - try: - return plain_text(parser.format_usage()).rstrip(), plain_text(parser.format_help()).rstrip() - finally: - if saved is None: - os.environ.pop("COLUMNS", None) - else: - os.environ["COLUMNS"] = saved +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: @@ -389,7 +387,7 @@ def _first_line(value: object) -> str: 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 = parser._get_formatter() + formatter = _snapshot_formatter(parser, parser.prog) formatter.add_text(parser.description) return _first_line(formatter.format_help()) return _first_line(parser.description) @@ -438,35 +436,24 @@ def as_typed(self, name: str) -> str | None: class _NotASubcommandError(Exception): - """Raised in place of argparse's error() by the copy of a parser which _reaches_subcommands() asks.""" + """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 _reaches_subcommands(parser: Cmd2ArgumentParser, name: str, file_prefixes: str) -> bool: - """Whether argparse, given the name where the parser's subcommand goes, takes it for the subcommand's name. - - argparse takes a word which begins with one of its prefix characters as an option, such as -h, or --ver beside - --verbose and --version, unless it is that character alone, looks like a negative number, or has a space in it. It - takes "--" for the end of the options. Whether a word is an option is decided by _parse_optional(), which is private, - and is asked of a shallow copy: on Python 3.11 an ambiguous abbreviation is reported with error(), which prints and - exits. - - A word which begins with a fromfile prefix character is read as a file of arguments, whether the character is the - parser's or that of a parser above it: each reads the files in every word it is given, before it passes on the words - after its subcommand's name. file_prefixes are those of the parsers above it. - """ - prefixes = file_prefixes + (parser.fromfile_prefix_chars or "") - if name == "--" or name.startswith(tuple(prefixes)): - return False +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 None + return asked._parse_optional(name) is not None except _NotASubcommandError: - return False + return True def _keeps_quotes(app: Cmd, name: str) -> bool: @@ -476,6 +463,12 @@ def _keeps_quotes(app: Cmd, name: str) -> bool: return spec is not None and spec.preserve_quotes +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 _describe_subcommands( parser: Cmd2ArgumentParser, reading: _Reading, file_prefixes: str ) -> tuple[bool, list[_ShownSubcommand]]: @@ -500,29 +493,35 @@ def _describe_subcommands( 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 "")) + # A preceding positional can consume --. Without one, argparse hands the marker itself to the subparser action. + can_end_options = "-" not in prefixes and bool(_preceding_positionals(parser)) 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 = [ - (name, typed) - for name in names - if plain_text(name) == name # else it would be served as another name, perhaps a sibling's - and _reaches_subcommands(parser, name, file_prefixes) - and (typed := reading.as_typed(name)) is not None - ] + 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), *others = typable - subcommand = Subcommand(name=first, aliases=tuple(name for name, _ in others), summary=summary) + (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), - typed=typed, + shown=tuple(name for name, _, _ in typable), + needs_separator=needs_separator, parser=subparser, subcommand=subcommand, ) @@ -530,38 +529,36 @@ def _describe_subcommands( return bool(action.required), shown -def _typed_prog(parent: Cmd2ArgumentParser, typed_parent_prog: str, child: Cmd2ArgumentParser, name: str, typed: str) -> str: - """The prog of a subcommand's parser, for its usage and help, with each name in it as it is typed. - - cmd2 makes a subcommand's prog its parent's prog, then the positionals before the subcommands, then its name, none - of it quoted (Cmd2ArgumentParser.update_prog()). A prog which was made some other way is left as it is. - """ - prog = child.prog - if prog.startswith(parent.prog) and prog.endswith(f" {name}"): - return typed_parent_prog + prog[len(parent.prog) : len(prog) - len(name)] + typed - return prog +def _child_prog_prefix(parser: Cmd2ArgumentParser, rendered: Cmd2ArgumentParser, omitted: Sequence[argparse.Action]) -> str: + """Use the displayed parent and positionals for the prefix shared by its child parsers.""" + prefix = parser.get_subparsers_action()._prog_prefix + if prefix == parser.prog: + return rendered.prog + # argparse may wrap the first positional onto the next line when its choices are long. + if not prefix.startswith(parser.prog) or not prefix[len(parser.prog)].isspace(): + return prefix # an application-supplied prefix + if omitted: + positionals = _preceding_positionals(parser) + if any(action in positionals or (action.option_strings and action.required) for action in omitted): + # Newer argparse also includes required options when add_subparsers() builds the prefix. + required = [action for action in rendered._actions if action.option_strings and action.required] + return rendered._build_subparsers_prog_prefix([*required, *_preceding_positionals(rendered)]) + return rendered.prog + prefix[len(parser.prog) :] # 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( - parser: Cmd2ArgumentParser, prog: str, shown: Sequence[_ShownSubcommand], omitted: Sequence[argparse.Action] -) -> tuple[str, str]: - """Return the parser's usage and help with that prog, naming only the subcommands shown, by the names shown. - - They are rendered from a copy of the parser where they would differ, never from a changed parser. Help makes a tab - spaces, and a name with spaces in place of its tab is another name, so a tab in the prog is rendered as a stand-in - and put back. - """ +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) - rendered = _to_render(parser, shown, omitted) - if rendered.prog != rendering: - if rendered is parser: - rendered = copy.copy(parser) # never a change to the parser which the prompt uses + if rendering != prog: + rendered = copy.copy(rendered) rendered.prog = rendering - usage, help_text = _format_at_help_width(rendered) + 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") @@ -606,7 +603,9 @@ def _describe_parser_as( 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] - usage, help_text = _usage_and_help(parser, prog, shown, omitted) + rendered = _to_render(parser, shown, omitted) + rendered.prog = prog + usage, help_text = _usage_and_help(rendered) result = { path: Description( path=path, @@ -621,10 +620,18 @@ def _describe_parser_as( error=None, ) } + if not shown: + return result + prefix = _child_prog_prefix(parser, rendered, omitted) + original_prefix = parser.get_subparsers_action()._prog_prefix + inner_prefixes = file_prefixes + (parser.fromfile_prefix_chars or "") for each in shown: - child_prog = _typed_prog(parser, prog, each.parser, each.names[0], each.typed) - inner_prefixes = file_prefixes + (parser.fromfile_prefix_chars or "") - child_path = f"{path} {each.typed}" + 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) ) @@ -639,7 +646,7 @@ class Command: category: str summary: str has_parser: bool - subcommands: tuple[str, ...] # the names of its first level of subcommands + subcommands: tuple[str, ...] # the typed spellings of its first level of subcommands error: str | None @@ -748,7 +755,7 @@ def _describe_command(app: Cmd, name: str) -> tuple[Command, dict[str, Descripti category=category, summary=summary, has_parser=top.has_parser, - subcommands=tuple(subcommand.name for subcommand in top.subcommands), + subcommands=tuple(subcommand.typed for subcommand in top.subcommands), error=None, ) return command, descriptions @@ -923,10 +930,9 @@ def answer_describe_command(snapshot: Snapshot, command: str) -> CommandDescript parent = description taken = reading.argument_for(word) found = next((sub for sub in parent.subcommands if taken in (sub.name, *sub.aliases)), None) - typed = None if found is None else reading.as_typed(found.name) - description = None if typed is None else snapshot.descriptions.get(f"{parent.path} {typed}") + description = None if found is None else snapshot.descriptions.get(f"{parent.path} {found.typed}") if description is None: - names = ", ".join(filter(None, (reading.as_typed(subcommand.name) for subcommand in parent.subcommands))) + 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.') @@ -1478,7 +1484,7 @@ def _mcp_asgi_app(self) -> Any: def list_commands() -> CommandList: """List the application's commands by category, in the order its help shows them. - Each command comes with its summary, whether a parser checks its arguments, and the names of its subcommands. + 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). """ @@ -1490,7 +1496,8 @@ 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 is described by its own path. + 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. """ snapshot = self.mcp_snapshot try: diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 043f8c304..8da5a5581 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -381,6 +381,57 @@ def test_end_of_options_is_never_a_subcommand_name(aliases) -> None: assert "p end" in found +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 + + +def test_child_help_bounds_required_options_when_argparse_includes_them_in_prog() -> None: + parser = cmd2.Cmd2ArgumentParser(prog="pick") + parser.add_argument("--id", type=int, choices=range(1010), required=True) + parser.add_argument("group") + child = parser.add_subparsers().add_parser("show") + description = ex.describe_parser(parser, "pick", "")["pick show"] + expected = "pick --id ID group show" if "--id" in child.prog else "pick group show" + assert description.usage == f"Usage: {expected} [-h]" + assert description.help.startswith(description.usage) + + +@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_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),) @@ -777,6 +828,12 @@ def do_files(self, args: argparse.Namespace) -> None: def test_describing_a_subcommand_whose_name_has_a_space_takes_it_quoted_as_the_prompt_does() -> None: snapshot = ex.build_snapshot(SpacedApp(), 1) + root = ex.answer_describe_command(snapshot, "report").description + 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". @@ -2094,6 +2151,31 @@ def do_budget(self, args: argparse.Namespace) -> None: 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]["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" From c398626292e50029c6968e5bd8cb71216207ce34 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:49:57 -0500 Subject: [PATCH 32/35] Bound parser prefix formatting and correct MCP snapshot metadata --- cmd2/argparse_utils.py | 27 ++++++++- examples/mcp_server.py | 86 ++++++++++++++------------ tests/test_example_mcp_server.py | 101 +++++++++++++++++++++++++++---- 3 files changed, 160 insertions(+), 54 deletions(-) diff --git a/cmd2/argparse_utils.py b/cmd2/argparse_utils.py index cee16a398..204cbd89f 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 @@ -836,8 +839,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 diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 34d513ef5..443573235 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -74,7 +74,7 @@ from cmd2.exceptions import Cmd2ShlexError from cmd2.parsing import StatementParser, shlex_split from cmd2.rich_utils import HelpFormatterRenderable -from cmd2.utils import DEFAULT_STR_SORT_KEY, strip_doc_annotations +from cmd2.utils import strip_doc_annotations # --------------------------------------------------------------------------------------------------------------------- # Part 1: Describing @@ -126,7 +126,7 @@ class Argument: 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 - default: Any # None when there is none worth stating + 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 @@ -212,7 +212,7 @@ def describe_argument(action: argparse.Action) -> Argument: min_values=low, max_values=high, takes_rest_of_line=action.nargs in (argparse.REMAINDER, argparse.PARSER), - default=_describe_default(action), + 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, @@ -530,20 +530,23 @@ def _describe_subcommands( def _child_prog_prefix(parser: Cmd2ArgumentParser, rendered: Cmd2ArgumentParser, omitted: Sequence[argparse.Action]) -> str: - """Use the displayed parent and positionals for the prefix shared by its child parsers.""" + """Show the parent arguments needed before the child, using their display actions.""" prefix = parser.get_subparsers_action()._prog_prefix - if prefix == parser.prog: - return rendered.prog - # argparse may wrap the first positional onto the next line when its choices are long. - if not prefix.startswith(parser.prog) or not prefix[len(parser.prog)].isspace(): + # Rich may have expanded a tab in the cached name or wrapped the first positional onto a new line. + cached_prog = parser.prog if prefix.startswith(parser.prog) else parser.prog.expandtabs() + if prefix != cached_prog and (not prefix.startswith(cached_prog) or not prefix[len(cached_prog)].isspace()): return prefix # an application-supplied prefix - if omitted: - positionals = _preceding_positionals(parser) - if any(action in positionals or (action.option_strings and action.required) for action in omitted): - # Newer argparse also includes required options when add_subparsers() builds the prefix. - required = [action for action in rendered._actions if action.option_strings and action.required] - return rendered._build_subparsers_prog_prefix([*required, *_preceding_positionals(rendered)]) - return rendered.prog + prefix[len(parser.prog) :] + 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)] + if required or any(action in omitted for action in _preceding_positionals(parser)): + 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_positionals(rendered)], groups, prefix="") + usage = plain_text(formatter.format_help()).strip() + return usage if rendering == prog else usage.replace(_TAB_STAND_IN, "\t") + return rendered.prog + prefix[len(cached_prog) :] # A noncharacter: Unicode keeps these for a program's own use, out of text written for people, such as help. @@ -650,6 +653,14 @@ class Command: 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".""" @@ -691,6 +702,7 @@ class Snapshot: 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, ...] @@ -705,10 +717,6 @@ def _now() -> str: return datetime.now().astimezone().isoformat(timespec="seconds") -def _by_name(item: tuple[str, Any]) -> Any: - return DEFAULT_STR_SORT_KEY(item[0]) - - 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: @@ -778,7 +786,9 @@ def build_snapshot(app: Cmd, generation: int, leave_out: Collection[str] = ()) - commands: list[Command] = [] descriptions: dict[str, Description] = {} quotes_kept: set[str] = set() - visible = sorted(app.get_visible_commands(), key=DEFAULT_STR_SORT_KEY) + sort_key = cmd2.utils.DEFAULT_STR_SORT_KEY + visible = sorted(app.get_visible_commands(), key=sort_key) + by_category: dict[str, list[Command]] = {} for name in visible: if name in leave_out: continue @@ -790,21 +800,27 @@ def build_snapshot(app: Cmd, generation: int, leave_out: Collection[str] = ()) - if _keeps_quotes(app, name): 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=DEFAULT_STR_SORT_KEY) + 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) + 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)), + 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) + 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), @@ -826,6 +842,7 @@ def failed_snapshot(generation: int, error: str) -> Snapshot: generation=generation, built_at=_now(), commands=(), + categories=(), descriptions={}, help_topics=(), shortcuts=(), @@ -837,14 +854,6 @@ def failed_snapshot(generation: int, error: str) -> Snapshot: ) -@dataclass(frozen=True) -class Category: - """The commands of one help category.""" - - name: str - commands: tuple[Command, ...] - - @dataclass(frozen=True) class CommandList: """The answer to "list the commands".""" @@ -888,14 +897,10 @@ class DescriptionUnavailableError(LookupError): def answer_list_commands(snapshot: Snapshot) -> CommandList: """List the commands by category, in the order help shows them.""" - by_category: dict[str, list[Command]] = {} - for command in snapshot.commands: - by_category.setdefault(command.category, []).append(command) - categories = tuple(Category(name, tuple(by_category[name])) for name in sorted(by_category, key=DEFAULT_STR_SORT_KEY)) return CommandList( generation=snapshot.generation, built_at=snapshot.built_at, - categories=categories, + categories=snapshot.categories, help_topics=snapshot.help_topics, typing=snapshot.typing, error=snapshot.error, @@ -1230,8 +1235,9 @@ def cmdloop(self, intro: RenderableType = "") -> int: try: if outermost: self._mcp_starting = True - if self.mcp_snapshot.error is None: + 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: @@ -1453,7 +1459,7 @@ def mcp_status(self) -> list[str]: 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({command.category for command in snapshot.commands})} categories" + 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: @@ -1498,6 +1504,8 @@ def describe_command(command: str) -> CommandDescription: 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: diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 8da5a5581..2b7030270 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -126,27 +126,27 @@ def test_argument_values(flags, kwargs, low, high, rest, required) -> None: 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.default, argument.help) == ("int", 10, "how many") + assert (argument.type, argument.parser_default, argument.help) == ("int", 10, "how many") assert _argument("name").flags == () - assert _argument("name").default is None # none worth stating + 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")).default == repr(Path("out")) + assert _argument("--out", default=Path("out")).parser_default == repr(Path("out")) 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.default == {"tags": ["a", "red"]} + 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).default == repr(value) + assert _argument("--limit", default=value).parser_default == repr(value) def test_argument_choices_are_strings() -> None: @@ -186,7 +186,7 @@ def test_argument_of_an_awkward_shape() -> None: # Review Focus 5 ) assert styled.name == "color" assert styled.choices == ("red",) # Review Focus 3 - assert styled.default == "red" + assert styled.parser_default == "red" assert styled.help == "pick" assert_plain(styled) @@ -397,17 +397,32 @@ def test_child_help_reuses_the_bounded_parent_positionals() -> None: assert child.prog == original -def test_child_help_bounds_required_options_when_argparse_includes_them_in_prog() -> None: +@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) - parser.add_argument("group") - child = parser.add_subparsers().add_parser("show") + 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 "--id" in child.prog else "pick group 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") @@ -689,6 +704,31 @@ def test_answer_list_commands() -> None: 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") @@ -1057,6 +1097,25 @@ def test_no_more_choices_are_read_than_are_listed() -> 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.""" @@ -1707,6 +1766,22 @@ def test_a_second_loop_serves_nothing_from_before_its_own_preloop() -> None: 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() @@ -2146,7 +2221,7 @@ def do_budget(self, args: argparse.Namespace) -> None: result = ask(app.mcp_url, "describe_command", {"command": "budget"}) assert result["is_error"] is False [argument] = result["structured"]["description"]["arguments"] - assert (argument["name"], argument["default"]) == ("limit", "inf") + assert (argument["name"], argument["parser_default"]) == ("limit", "inf") finally: app.mcp_stop() @@ -2169,7 +2244,7 @@ def do_read(self, _: argparse.Namespace) -> None: app.mcp_start() described = ask(app.mcp_url, "describe_command", {"command": "read"}) assert described["is_error"] is False - assert described["structured"]["description"]["arguments"][0]["default"] == expected + 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: @@ -3472,7 +3547,7 @@ def test_the_demonstration_has_every_kind_of_thing_to_describe(fleet) -> None: 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"].default == "dev" + 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")) From 39c4c13804983fe447ce5b9cbe04392b4c3685c5 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:13:18 -0500 Subject: [PATCH 33/35] Cover parser prefix choices and MCP example behavior --- tests/test_argparse_utils.py | 19 +++++ tests/test_example_mcp_server.py | 119 ++++++++++++++++++++++--------- 2 files changed, 103 insertions(+), 35 deletions(-) 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 index 2b7030270..37367dd38 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -16,7 +16,6 @@ import socket import subprocess import sys -import textwrap import threading import urllib.error import urllib.request @@ -397,6 +396,13 @@ def test_child_help_reuses_the_bounded_parent_positionals() -> None: assert child.prog == original +def test_child_help_preserves_an_explicit_subparser_prefix() -> None: + parser = cmd2.Cmd2ArgumentParser(prog="pick") + parser.add_subparsers(prog="custom invocation").add_parser("show") + child = ex.describe_parser(parser, "pick", "")["pick show"] + assert child.usage == "Usage: custom invocation show [-h]" + + @pytest.mark.parametrize("positional", [False, True]) def test_child_help_includes_required_parent_options(positional: bool) -> None: parser = cmd2.Cmd2ArgumentParser(prog="pick") @@ -638,6 +644,25 @@ def test_snapshot_lists_a_command_which_cannot_be_described() -> None: assert snapshot.descriptions["status"].error is None +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." @@ -1482,6 +1507,7 @@ def do_broken(self, _: argparse.Namespace) -> None: 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: @@ -1901,6 +1927,8 @@ def test_shared_logging_makes_its_changes_once_and_puts_them_back() -> None: 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 @@ -2376,40 +2404,18 @@ def test_a_port_which_is_not_a_port_is_a_warning(port: int, sdk, capsys) -> None 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() -> None: - done = run_without_sdk( - textwrap.dedent( - """ - class App(ex.McpServerMixin, cmd2.Cmd): - pass - - - def state(): - loggers = [logging.getLogger(name) for name in ("", "uvicorn", "mcp")] - return [(list(logger.handlers), logger.level, logger.propagate) for logger in loggers] - - - before = state() - app = App(mcp_port=0, allow_cli_args=False) - app.mcp_start() - found = { - "url": app.mcp_url, - "commands": len(app.mcp_snapshot.commands), - "status": app.mcp_status()[0], - "logging as it was": state() == before, - } - print(json.dumps(found)) - """ - ) - ) - assert done.returncode == 0, done.stderr - found = json.loads(done.stdout.splitlines()[-1]) - assert found["url"] is None - assert found["commands"] > 0 - assert done.stderr.count("MCP server not started") == 1 - assert "--group examples" in done.stderr - assert found["status"].startswith("No MCP server") - assert found["logging as it was"] is True +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"]) @@ -3566,6 +3572,8 @@ def test_the_demonstration_loads_and_unloads_a_command_set(fleet) -> None: 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 @@ -3585,6 +3593,47 @@ def test_the_demonstration_disables_and_enables_a_category(fleet) -> None: 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 From 946b28d258afa0a14606aa0492d0181dd1154047 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:44:48 -0500 Subject: [PATCH 34/35] Fix MCP snapshot freshness, subcommand usage, and server ownership Rebuild generated usage from current parser actions and include trailing parent positionals. Preserve custom prefixes and arbitrary parser defaults. Report stale snapshots to clients and keep manually started servers running through embedded command loops. Link the example and setup guide from the README. --- README.md | 5 ++ cmd2/argparse_utils.py | 14 ++++ docs/examples/mcp_server.md | 14 ++-- examples/mcp_server.py | 90 ++++++++++++++++++------- tests/test_example_mcp_server.py | 111 +++++++++++++++++++++++++++++-- 5 files changed, 201 insertions(+), 33 deletions(-) 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 204cbd89f..e61a17dfa 100644 --- a/cmd2/argparse_utils.py +++ b/cmd2/argparse_utils.py @@ -696,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]: @@ -892,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/mcp_server.md b/docs/examples/mcp_server.md index 4bddb6d94..3cb1d2f4b 100644 --- a/docs/examples/mcp_server.md +++ b/docs/examples/mcp_server.md @@ -230,7 +230,10 @@ The server has three tools. Each one is marked read-only, and each answer carrie 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. +`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 @@ -354,11 +357,12 @@ The mixin asks a few things of your application: ## Limits and Safety -- **How fresh the description is.** It is as of the last top-level prompt or the end of the last - outermost command, whichever came later. A change made part of the way through a long command or a +- **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. A change made by another thread shows at the next of those two moments. A command run by - calling `onecmd()` directly, and not through `onecmd_plus_hooks()`, does not refresh it. + 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 diff --git a/examples/mcp_server.py b/examples/mcp_server.py index 443573235..bbda468fe 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -60,7 +60,7 @@ import time from collections import deque from collections.abc import Collection, Iterator, Mapping, Sequence -from dataclasses import dataclass +from dataclasses import dataclass, replace from datetime import datetime from functools import partial from types import FrameType @@ -176,7 +176,7 @@ def _plain_data(value: Any) -> Any: 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 == argparse.SUPPRESS: + 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 @@ -529,24 +529,22 @@ def _describe_subcommands( return bool(action.required), shown -def _child_prog_prefix(parser: Cmd2ArgumentParser, rendered: Cmd2ArgumentParser, omitted: Sequence[argparse.Action]) -> str: +def _child_prog_prefix(rendered: Cmd2ArgumentParser) -> str: """Show the parent arguments needed before the child, using their display actions.""" - prefix = parser.get_subparsers_action()._prog_prefix - # Rich may have expanded a tab in the cached name or wrapped the first positional onto a new line. - cached_prog = parser.prog if prefix.startswith(parser.prog) else parser.prog.expandtabs() - if prefix != cached_prog and (not prefix.startswith(cached_prog) or not prefix[len(cached_prog)].isspace()): - return prefix # an application-supplied prefix + 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)] - if required or any(action in omitted for action in _preceding_positionals(parser)): - 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_positionals(rendered)], groups, prefix="") - usage = plain_text(formatter.format_help()).strip() - return usage if rendering == prog else usage.replace(_TAB_STAND_IN, "\t") - return rendered.prog + prefix[len(cached_prog) :] + 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. @@ -592,7 +590,14 @@ def describe_parser( def _describe_parser_as( - parser: Cmd2ArgumentParser, path: str, summary: str, reading: _Reading, prog: str, file_prefixes: str + 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. @@ -608,6 +613,16 @@ def _describe_parser_as( 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( @@ -625,7 +640,10 @@ def _describe_parser_as( } if not shown: return result - prefix = _child_prog_prefix(parser, rendered, omitted) + prefix = _child_prog_prefix(rendered) + subparsers_index = next(i for i, action in enumerate(rendered._actions) if isinstance(action, argparse._SubParsersAction)) + child_trailing = [action for action in rendered._actions[subparsers_index + 1 :] if not action.option_strings] + 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: @@ -636,7 +654,16 @@ def _describe_parser_as( 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) + _describe_parser_as( + each.parser, + child_path, + each.subcommand.summary, + reading, + child_prog, + inner_prefixes, + child_trailing, + child_groups, + ) ) return result @@ -711,6 +738,7 @@ class Snapshot: 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: @@ -864,6 +892,7 @@ class CommandList: 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) @@ -873,6 +902,7 @@ class CommandDescription: generation: int built_at: str description: Description + stale_reason: str | None = None @dataclass(frozen=True) @@ -885,6 +915,7 @@ class Tables: 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): @@ -904,6 +935,7 @@ def answer_list_commands(snapshot: Snapshot) -> CommandList: help_topics=snapshot.help_topics, typing=snapshot.typing, error=snapshot.error, + stale_reason=snapshot.stale_reason, ) @@ -941,7 +973,9 @@ def answer_describe_command(snapshot: Snapshot, command: str) -> CommandDescript 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) + return CommandDescription( + generation=snapshot.generation, built_at=snapshot.built_at, description=description, stale_reason=snapshot.stale_reason + ) def answer_tables(snapshot: Snapshot) -> Tables: @@ -953,6 +987,7 @@ def answer_tables(snapshot: Snapshot) -> Tables: aliases=snapshot.aliases, macros=snapshot.macros, error=snapshot.error, + stale_reason=snapshot.stale_reason, ) @@ -973,7 +1008,8 @@ def answer_tables(snapshot: Snapshot) -> Tables: 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 may be one command old." + "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." ) @@ -1230,7 +1266,7 @@ def cmdloop(self, intro: RenderableType = "") -> int: 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 # False for a call made from inside a command, or from inside preloop() + outermost = self._mcp_loops == 0 and self._mcp_depth == 0 self._mcp_loops += 1 try: if outermost: @@ -1511,6 +1547,8 @@ def describe_command(command: str) -> CommandDescription: 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) @@ -1540,8 +1578,12 @@ def _mcp_rebuild(self) -> None: snapshot = self._mcp_build() except Exception as error: # noqa: BLE001 - a rebuild never raises message = plain_text(f"{type(error).__name__}: {error}") - if self.mcp_snapshot.error is not None and self.mcp_snapshot.error != message: - self.mcp_snapshot = failed_snapshot(self.mcp_snapshot.generation + 1, message) + 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 diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index 37367dd38..fe386392c 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -135,6 +135,17 @@ 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) @@ -396,13 +407,67 @@ def test_child_help_reuses_the_bounded_parent_positionals() -> None: assert child.prog == original -def test_child_help_preserves_an_explicit_subparser_prefix() -> None: +@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="custom invocation").add_parser("show") + 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("positional", [False, True]) def test_child_help_includes_required_parent_options(positional: bool) -> None: parser = cmd2.Cmd2ArgumentParser(prog="pick") @@ -1451,7 +1516,9 @@ def test_a_build_which_fails_keeps_the_previous_snapshot_and_is_reported_once(mo 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 is previous + 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 @@ -1463,11 +1530,18 @@ def test_a_build_failure_is_kept_until_a_build_succeeds_and_is_reported_again_if build = app._mcp_build monkeypatch.setattr(app, "_mcp_build", mock.Mock(side_effect=RuntimeError("a defect"))) app.onecmd_plus_hooks("help") - assert app.mcp_snapshot is good # the last good one is still served + + 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") @@ -1861,6 +1935,20 @@ def test_cmdloop_twice_starts_and_stops_twice() -> None: 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() @@ -2294,6 +2382,21 @@ def test_describing_an_unknown_command_is_a_tool_error_which_names_what_exists(s 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") From c98238ef00fe63d5540b614b01293329976873c5 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:28:11 -0500 Subject: [PATCH 35/35] Handle early command hooks and align MCP discovery with argparse --- docs/examples/mcp_server.md | 11 +-- examples/mcp_server.py | 73 ++++++++++++++------ tests/test_example_mcp_server.py | 112 ++++++++++++++++++++++++++++--- 3 files changed, 159 insertions(+), 37 deletions(-) diff --git a/docs/examples/mcp_server.md b/docs/examples/mcp_server.md index 3cb1d2f4b..3fb819d7c 100644 --- a/docs/examples/mcp_server.md +++ b/docs/examples/mcp_server.md @@ -267,14 +267,17 @@ docstring: 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) - for name in visible: - if name in leave_out: - continue + included = [name for name in visible if name not in leave_out] + for name in included: try: - command, found = _describe_command(app, name) + 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 diff --git a/examples/mcp_server.py b/examples/mcp_server.py index bbda468fe..589b68fa8 100644 --- a/examples/mcp_server.py +++ b/examples/mcp_server.py @@ -62,7 +62,7 @@ from collections.abc import Collection, Iterator, Mapping, Sequence from dataclasses import dataclass, replace from datetime import datetime -from functools import partial +from functools import cache, partial from types import FrameType from typing import TYPE_CHECKING, Any, NoReturn, TypeVar @@ -456,11 +456,15 @@ def _needs_end_of_options(parser: Cmd2ArgumentParser, name: str) -> bool: return True -def _keeps_quotes(app: Cmd, name: str) -> bool: - """Whether argparse is given the command's arguments with their quotation marks: its preserve_quotes.""" - func = app.get_command_func(name) - spec = None if func is None else app.get_argparse_command_spec(func) - return spec is not None and spec.preserve_quotes +@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]: @@ -469,6 +473,28 @@ def _preceding_positionals(parser: Cmd2ArgumentParser) -> list[argparse.Action]: 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]]: @@ -494,8 +520,7 @@ def _describe_subcommands( for name, subparser in action.choices.items(): by_parser.setdefault(id(subparser), []).append(name) prefixes = tuple(file_prefixes + (parser.fromfile_prefix_chars or "")) - # A preceding positional can consume --. Without one, argparse hands the marker itself to the subparser action. - can_end_options = "-" not in prefixes and bool(_preceding_positionals(parser)) + 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 @@ -641,8 +666,7 @@ def _describe_parser_as( if not shown: return result prefix = _child_prog_prefix(rendered) - subparsers_index = next(i for i, action in enumerate(rendered._actions) if isinstance(action, argparse._SubParsersAction)) - child_trailing = [action for action in rendered._actions[subparsers_index + 1 :] if not action.option_strings] + 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 "") @@ -771,7 +795,7 @@ def _unparsed_description(path: str, summary: str, help_text: str, error: str | ) -def _describe_command(app: Cmd, name: str) -> tuple[Command, dict[str, Description]]: +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: @@ -780,11 +804,14 @@ def _describe_command(app: Cmd, name: str) -> tuple[Command, dict[str, Descripti 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(app, name)) + descriptions = describe_parser(parser, name, summary, terminators, keeps_quotes=keeps_quotes) top = descriptions[name] command = Command( name=plain_text(name), @@ -794,7 +821,7 @@ def _describe_command(app: Cmd, name: str) -> tuple[Command, dict[str, Descripti subcommands=tuple(subcommand.typed for subcommand in top.subcommands), error=None, ) - return command, descriptions + return command, descriptions, keeps_quotes def _failed_command(app: Cmd, name: str, exc: Exception) -> tuple[Command, dict[str, Description]]: @@ -816,16 +843,15 @@ def build_snapshot(app: Cmd, generation: int, leave_out: Collection[str] = ()) - 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 visible: - if name in leave_out: - continue + for name in included: try: - command, found = _describe_command(app, name) + 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(app, name): + if keeps_quotes: quotes_kept.add(command.name) commands.append(command) by_category.setdefault(command.category, []).append(command) @@ -853,7 +879,7 @@ def by_name(item: tuple[str, Any]) -> Any: 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), + multiline_commands=tuple(plain_text(c) for c in parser.multiline_commands if c in included), ), quotes_kept=frozenset(quotes_kept), error=None, @@ -1248,7 +1274,6 @@ def __init__( :param mcp_name: the name the server gives itself to a client :param mcp_leave_out: the names of commands which are never described """ - super().__init__(*args, **kwargs) self.mcp_port = mcp_port self.mcp_name = mcp_name self.mcp_leave_out = frozenset(mcp_leave_out) @@ -1258,6 +1283,10 @@ def __init__( 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. @@ -1266,7 +1295,7 @@ def cmdloop(self, intro: RenderableType = "") -> int: 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 + outermost = self._mcp_loops == 0 and self._mcp_depth == 0 and not self._mcp_initializing self._mcp_loops += 1 try: if outermost: @@ -1570,7 +1599,7 @@ def _mcp_rebuild(self) -> None: 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: + if self._mcp_depth != 0 or self._mcp_starting or self._mcp_initializing: return with self.sigint_protection: warnings: list[str] = [] diff --git a/tests/test_example_mcp_server.py b/tests/test_example_mcp_server.py index fe386392c..d06718292 100644 --- a/tests/test_example_mcp_server.py +++ b/tests/test_example_mcp_server.py @@ -380,15 +380,19 @@ def test_many_subcommand_names_do_not_restore_hidden_help(monkeypatch) -> None: @pytest.mark.parametrize("aliases", [[], ["end"]]) -def test_end_of_options_is_never_a_subcommand_name(aliases) -> None: +def test_literal_end_of_options_as_a_subcommand_name(aliases) -> None: parser = cmd2.Cmd2ArgumentParser(prefix_chars="+") parser.add_subparsers(required=True).add_parser("--", aliases=aliases) found = ex.describe_parser(parser, "p", "") - assert [child.name for child in found["p"].subcommands] == aliases - assert "p --" not in found + 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() - assert "p end" in found def test_child_help_reuses_the_bounded_parent_positionals() -> None: @@ -468,6 +472,23 @@ def test_child_custom_usage_includes_trailing_parent_positional() -> None: 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") @@ -504,6 +525,21 @@ def test_option_like_subcommand_after_a_positional_is_reachable(name) -> None: 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 = [] @@ -709,6 +745,36 @@ def test_snapshot_lists_a_command_which_cannot_be_described() -> 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]: @@ -1004,13 +1070,15 @@ def test_a_name_which_the_prompt_would_split_or_read_as_syntax_is_served_quoted_ ) -def test_every_path_served_runs_at_the_prompt_the_subcommand_which_it_describes() -> None: +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 - app.onecmd_plus_hooks(path) + # 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 @@ -1071,21 +1139,26 @@ def test_the_subcommands_of_a_command_which_keeps_its_quotes_are_typed_as_argpar assert ex.answer_describe_command(snapshot, "report 'list all'").description.path == 'report "list all"' -def test_a_subcommand_name_which_argparse_takes_as_an_option_is_left_out(capsys: pytest.CaptureFixture[str]) -> None: +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] == [ - ("expand", ()), + *expected, ("-1", ()), ("-", ()), ("- x", ()), ("ab", ()), ] - 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 capsys.readouterr().err == "" # Python 3.11 reports an ambiguous abbreviation with error(), which prints @@ -1356,6 +1429,23 @@ 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."""