Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
0be9e03
Make a command's help category public as Cmd.get_command_category()
tleonhardt Dec 2, 2026
0e2ee94
Begin the MCP server example: describe one argument of a command
tleonhardt Dec 2, 2026
17df518
Remove C1 control characters and 8-bit escape sequences from describe…
tleonhardt Dec 2, 2026
0a70e0f
Describe a command's parser and its subcommands to any depth
tleonhardt Dec 2, 2026
cb7c695
Build a snapshot of an application's commands, and the answers made f…
tleonhardt Dec 2, 2026
5b87e77
Rebuild the description at the start, before each prompt and after ea…
tleonhardt Dec 2, 2026
75645a0
Own the changes to the server libraries' logging in one place
tleonhardt Dec 2, 2026
7927352
Serve the description over MCP from a worker thread beside the prompt
tleonhardt Dec 2, 2026
72b0e1b
Test the server when it cannot start, and with two runs alive at once
tleonhardt Dec 2, 2026
e86ffc6
Keep the malformed log record of one test from reaching another
tleonhardt Dec 2, 2026
da4296a
Add the fleet console which demonstrates the MCP server, and its comm…
tleonhardt Dec 2, 2026
b1c7b92
Run the MCP server example's tests in CI with the MCP SDK installed
tleonhardt Dec 2, 2026
c27bfe2
Document the MCP server example
tleonhardt Dec 2, 2026
1db209a
Undo a start which Ctrl-C interrupts, decide under a run's lock how i…
tleonhardt Dec 2, 2026
d29c7b1
Give only the stop meant to give up on a worker a short wait in the a…
tleonhardt Dec 2, 2026
8e83ba0
Leave out a subcommand which help hides, warn against a secret as a d…
tleonhardt Dec 2, 2026
95b62be
Show finding a command's category from the visible commands, since a …
tleonhardt Dec 2, 2026
5f056e3
Merge branch 'main' into public-command-category
tleonhardt Dec 2, 2026
9c431d2
Merge branch 'public-command-category' into mcp-server-example
tleonhardt Dec 2, 2026
ec9104f
Merge branch 'main' into mcp-server-example
tleonhardt Dec 2, 2026
7777733
Document connecting Claude Desktop to the MCP server example through …
tleonhardt Dec 2, 2026
2664dcd
Leave off the newlines which argparse ends a command's usage and help…
tleonhardt Dec 3, 2026
23706fd
Say that the MCP server example was tried by hand on Windows, and wit…
tleonhardt Dec 3, 2026
a1526d3
Address the review of the MCP server example
tleonhardt Dec 3, 2026
8e9c438
Address the second review of the MCP server example
tleonhardt Dec 3, 2026
857f0bc
Describe subcommands under their paths as the prompt takes them, quot…
tleonhardt Dec 3, 2026
69128dc
Make the snapshot stress test of the MCP server example 20 rounds ins…
tleonhardt Dec 3, 2026
1c1bc04
Type subcommand names as cmd2 takes them, and keep their tabs in usag…
tleonhardt Dec 3, 2026
d2e68f1
Merge main into mcp-server-example
tleonhardt Dec 3, 2026
41dc36f
Show each subcommand by the names of it which can be typed, everywher…
tleonhardt Dec 3, 2026
e7622e6
Merge remote-tracking branch 'origin/main' into mcp-server-example
tleonhardt Dec 3, 2026
3b84d45
Type a subcommand's name as argparse is given it by a command which k…
tleonhardt Dec 3, 2026
a560c7d
Describe nothing from before preloop(), and serve only names which di…
tleonhardt Dec 3, 2026
b0bc11a
Merge remote-tracking branch 'origin/main' into mcp-server-example
tleonhardt Dec 3, 2026
a4f1a78
Leave out suppressed subcommand lists, cap listed choices, and say wh…
tleonhardt Dec 3, 2026
db54d52
Fix MCP help rendering, worker cleanup, and snapshot error reporting
tleonhardt Dec 3, 2026
dfb92d4
Serve usable subcommand paths and bound child help in MCP snapshots
tleonhardt Dec 3, 2026
5cbac76
Merge branch 'main' into mcp-server-example
tleonhardt Dec 3, 2026
e29d03a
Merge branch 'main' into mcp-server-example
tleonhardt Dec 3, 2026
c398626
Bound parser prefix formatting and correct MCP snapshot metadata
tleonhardt Dec 3, 2026
39c4c13
Cover parser prefix choices and MCP example behavior
tleonhardt Dec 4, 2026
946b28d
Fix MCP snapshot freshness, subcommand usage, and server ownership
tleonhardt Dec 4, 2026
c98238e
Handle early command hooks and align MCP discovery with argparse
tleonhardt Dec 4, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/rerun-unacquired.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
42 changes: 40 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@
cannot be reassigned. A parser given to `@with_argparser` is the spec's `parser_source`
itself, shared by every application which has not built the command's parser yet: to change
one application's parser, change the one which `self.command_parsers.get(func)` returns.
- Added the
[mcp_server.py](https://github.com/python-cmd2/cmd2/blob/main/examples/mcp_server.py) example,
a `cmd2` application which, while its prompt is live, serves a read-only description of its
own commands to an AI assistant over MCP, so that the assistant can work out the command line
for what the person asks. It needs the MCP SDK, which is not a `cmd2` dependency. See
[MCP Server](docs/examples/mcp_server.md) for how to run it, connect an assistant, and use it
in your own application.

## 4.4.5 (2026-12-02)

Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down
41 changes: 39 additions & 2 deletions cmd2/argparse_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ def get_choices(self) -> Choices:

import argparse
import contextlib
import copy
import itertools
import re
import sys
import threading
Expand All @@ -234,6 +236,7 @@ def get_choices(self) -> Choices:
Callable,
Generator,
Iterable,
Iterator,
Sequence,
)
from dataclasses import dataclass
Expand Down Expand Up @@ -693,6 +696,17 @@ class Cmd2ArgumentParser(argparse.ArgumentParser):

# Thread-local storage shared by all parser instances (including subparsers)
_thread_locals: ClassVar[_ParserThreadLocals] = _ParserThreadLocals()
_custom_subparsers_prog: bool = False

# Keep argparse's overloads for callers. At runtime argparse caches both explicit and
# generated prefixes in the same attribute, so remember which came from the application.
if not TYPE_CHECKING:

def add_subparsers(self, **kwargs: Any) -> "argparse._SubParsersAction":
"""Add a subparsers action and remember any explicitly supplied usage prefix."""
action = super().add_subparsers(**kwargs)
self._custom_subparsers_prog = kwargs.get("prog") is not None
return action

@contextlib.contextmanager
def output_to(self, file: IO[str] | None) -> Generator[None]:
Expand Down Expand Up @@ -836,8 +850,28 @@ def _build_subparsers_prog_prefix(self, positionals: list[argparse.Action]) -> s
)

# Inject the current positional state so add_subparsers() has the right context
temp_parser._actions = positionals
temp_parser._mutually_exclusive_groups = self._mutually_exclusive_groups
# Formatting a prefix can otherwise exhaust an iterator used for validation or enumerate
# billions of choices just to name a child parser. Bound the formatter's input without
# changing the actions used to parse commands.
max_prefix_choices = 1000
replacements = {}
for action in positionals:
if action.metavar is not None or action.choices is None:
continue
display = copy.copy(action)
display.choices = None # let the formatter choose its usual metavar
if not isinstance(action.choices, Iterator):
sample = tuple(itertools.islice(action.choices, max_prefix_choices + 1))
if len(sample) <= max_prefix_choices:
display.choices = sample
replacements[id(action)] = display

temp_parser._actions = [replacements.get(id(action), action) for action in positionals]
for group in self._mutually_exclusive_groups:
# argparse matches group members by action identity.
display_group = copy.copy(group)
display_group._group_actions = [replacements.get(id(action), action) for action in group._group_actions]
temp_parser._mutually_exclusive_groups.append(display_group)

# Call add_subparsers() to build _prog_prefix
return temp_parser.add_subparsers()._prog_prefix
Expand Down Expand Up @@ -869,6 +903,9 @@ def update_prog(self, prog: str) -> None:
# Update _prog_prefix. This ensures that any subcommands added later via
# add_parser() will have the correct prog value.
subparsers_action._prog_prefix = self._build_subparsers_prog_prefix(positionals)
self._custom_subparsers_prog = (
type(self)._build_subparsers_prog_prefix is not Cmd2ArgumentParser._build_subparsers_prog_prefix
)

# subparsers_action._name_parser_map includes aliases. Since primary names are inserted
# first, we skip already updated parsers to ensure primary names are used in 'prog'.
Expand Down
1 change: 1 addition & 0 deletions docs/examples/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

<!--intro-end-->
Loading
Loading