Skip to content

Add an example which serves a description of its commands over MCP - #1855

Open
tleonhardt wants to merge 43 commits into
mainfrom
mcp-server-example
Open

tleonhardt wants to merge 43 commits into
mainfrom
mcp-server-example

Conversation

@tleonhardt

@tleonhardt tleonhardt commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Adds examples/mcp_server.py, a cmd2 application which serves a description of its own commands
over the Model Context Protocol while its prompt is live. An
assistant connected to it, such as Claude Code, can turn an objective stated in plain English into
the command line for that application. The server never runs a command. It only describes the
commands, and the person types the command line which the assistant gives.

Closes #1852

Built on #1856 and #1859

The example needs two methods of Cmd which are new in 4.5.0, both merged into main:

What is in it

The example is one file in three parts.

  1. Describing an application as plain data. Frozen dataclasses built from the parsers which
    cmd2 already holds. They cover commands, arguments (nargs ranges, choices, defaults, types),
    subcommands to any depth, shortcuts, aliases and macros. Hidden commands, disabled commands and
    subcommands which help hides are left out. No more than the first 1000 of an argument's choices
    are listed. This part imports nothing from the MCP SDK. All text
    served is stripped of escape sequences and control characters.
  2. McpServerMixin, which can be copied into another application.
    • It overrides cmdloop(), pre_prompt() and onecmd_plus_hooks(), so it uses no hooks, and
      _cmdloop(), which is private to cmd2.
    • It rebuilds the description on the main thread at three moments: once preloop() has returned,
      before the first line is read; before each top-level prompt; and after each outermost command.
      Until the first, the server answers that the description has not been built yet. Nothing is
      published while a command is in progress.
    • It serves the latest description from a worker thread, over HTTP at
      http://127.0.0.1:8765/mcp, using Uvicorn and the MCP SDK's MCPServer.
    • The three tools are read-only: list_commands, describe_command(command) and
      list_shortcuts_aliases_macros.
    • Each run of the server is one object, which owns its socket, its thread and a hold on the server
      libraries' logging. Each is released exactly once on every path. That includes Ctrl-C during a
      start, which SIGINT is deferred around while a start takes what it owns, and a worker which
      won't stop in time. Under the run's lock, a stop decides whether a worker finished or was given
      up on.
  3. A pretend "fleet console" with servers, deployments and a CommandSet loaded as a plugin, to
    give the other two parts every kind of command to describe. It takes --mcp-port PORT and
    --no-mcp.

Also included:

  • The tests, in tests/test_example_mcp_server.py. The tests which need the SDK are skipped when it
    isn't installed.
  • A new examples dependency group with mcp>=2. It isn't in default-groups, because it brings
    in about fifteen packages.
  • A new CI job, example-tests, which installs that group and runs the example's tests with
    CMD2_EXAMPLE_TESTS_NEED_SDK=1, so that a skip there is a failure.
  • A docs page, docs/examples/mcp_server.md, with entries in mkdocs.yml,
    docs/examples/index.md and examples/README.md, and a CHANGELOG entry under 4.5.0. The page
    warns that each argument's default and each command's help text are served as they are.

Testing

  • At dfb92d47 on macOS with Python 3.15.2, make check, make test (3426 passed, 3 skipped)
    and make docs-test passed. All 196 SDK-required example tests passed on Python 3.11.18 and 3.15.2.
  • CI: all 32 checks passed at a4f1a788, Windows and Python 3.11 included. The first
    run, at 1db209a4, had failed on two assumptions of the tests: coverage's warning on Python 3.11, and an
    event loop which leaves a socket open on Unix but not on Windows.
  • At a4f1a788, the example's tests passed with the SDK: 185 passed, none skipped, on Python 3.15, 3.11 and 3.12. At
    earlier commits, they also passed:
    • on Python 3.11 with coverage on, with the SDK and without it
    • on Linux in a container, at 8e83ba00: 148 passed, none skipped
    • on Windows 11, at 7777733b: 143 passed, and 5 skipped, which need a pipe for the prompt
    • on free-threaded 3.15 with the GIL off
    • 40 times in a row, and 5 times with every processor kept busy (at an earlier commit)
  • By hand on macOS (iTerm2):
    • The MCP Inspector lists the three tools.
    • Claude Code connects to the plain http://127.0.0.1 address, and gave the expected command line
      for each objective tried.
    • Claude Desktop, through the mcp-remote bridge, gave the same command lines, and worked again
      after the example was restarted, with nothing done in Desktop. The page has the configuration
      which was used.
    • The prompt is undisturbed while a client calls in a loop.
    • quit and Ctrl-D end at once, and the port is free at once.
    • A second copy on the same port warns and carries on without a server.
    • A client which stays connected works again after a restart.
  • By hand on Linux (tmux in a container), the same behavior checks, with the SDK's own client.
  • The last three checks were done again on both systems at 8e83ba00, since the commits before it
    changed how a run starts and stops.
  • By hand on Windows 11 (Windows Terminal, PowerShell 5.1), at 7777733b, from a Claude Code
    session there, with the MCP Inspector, Claude Code and the SDK's own client. The same checks as on
    macOS passed, but for Claude Desktop, which was not tried. A second copy cannot take the port
    (error 10048), and a restart at once gets it, even with a client's connection open at the quit.
    The run found one cosmetic point on every platform: the served usage and help kept the newlines
    which argparse ends them with. 2664dcda leaves them off.

After review

A first review found eight points. All eight were real, and each is fixed in a1526d36, with a test
which failed first:

  • describe_command finds a subcommand by an alias at any depth, such as server t add where tag
    has the alias t. Looking up an unknown line stops at its first unknown word, so a long one is no
    longer looked up prefix by prefix.
  • The usage and help served leave out a subcommand added with help=argparse.SUPPRESS, as the list
    of subcommands already did. cmd2's own help still shows one, with ==SUPPRESS== for its help,
    since that is how argparse renders it.
  • An exclusive group names an option by its first flag, not by its destination, which two options
    can share.
  • A stop which Ctrl-C cut short is finished by the next mcp_stop().
  • plugin load and plugin unload say when the plugin is loaded already, or isn't loaded.
  • An argument with nargs=argparse.PARSER is described, where before the whole command's
    description failed.
  • The tests which need the SDK are skipped where only its version 1 is installed.

A second review, at a1526d36, found six more. All six were real too, and each is fixed in
8e9c438b, with a test which failed first:

  • On Python 3.11 and 3.12, a join() which Ctrl-C interrupts leaves is_alive() false while the
    thread runs on, so a stop could let go of the logging while its worker still ran. The stop now
    judges the worker by the outcome it records, and a worker which started always lets go of the
    logging itself. mcp status follows 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
    can't leave the hold taken for good.
  • A subcommand whose name has a space in it is found when it is typed quoted, as at the prompt
    (report "list all"), and its path is served quoted.
  • A required exclusive group of which only one member is visible is kept, with that member.
  • main() asks for version 2 of the SDK before the console starts.
  • An argument's name is plain text, as its flags, metavar and help are.

A third review, at 8e9c438b, found three points in how a path with quotes in it is handled, all
from the quoting just added. All three were real, and each is fixed in 857f0bcb, with a test which
failed first:

  • A subcommand's usage and help name it as its path does, so report "list all" has
    Usage: report "list all" [-h], and not the usage of report list all, which is another command.
  • A name is quoted where the prompt would split it or read part of it as syntax: whitespace, a
    quotation mark, |, >, or one of the application's terminators. Every path served can be asked
    for again, and such a name is found only when it is typed quoted, as at the prompt.
  • The first word of a path must be the name of a command, unquoted, as at the prompt.

At 8e9c438b, the macOS 3.11 job ran past its 10-minute limit, and GitHub kept no log of it. The
same job had taken 8 minutes at a1526d36, on a runner on which everything ran about 25 times
slower than on an Apple silicon Mac. 69128dc5 makes the slowest test of the suite, the snapshot
stress test, 20 rounds instead of 100. The reader still sees nearly every generation.

A fourth review, at 69128dc5, found three more points in how names are typed. All three were real,
and each is fixed in 1c1bc048, with a test which failed first:

  • A quotation mark inside a word is part of it at the prompt, which runs report today's and
    report a'b"c as they are. Where a name was quoted for having a quotation mark in it, a'b"c
    was served as 'a'b"c', which the prompt splits in two. A name is now 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. A word typed in a path is matched the same way.
  • Help makes a tab spaces, so report "tab<TAB>here" had the usage of its sibling with six spaces.
    A tab in the prog is now rendered as a noncharacter and put back.
  • The empty name, which argparse takes and the prompt runs as report "", was served as report ,
    which is the parent. It is now report "".

A name which no spelling gets through the prompt whole, such as one with both quotation marks and a
space, is now left out, as a hidden subcommand is, since no path served for it could be asked for. A
new test runs every path served at the prompt and checks that it runs the subcommand it describes.
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, so the test app's report has a metavar for its subcommands.

A fifth review, at d2e68f1f, found three points. All three were real, and each is fixed with a
test which failed first:

  • A subcommand whose name the prompt cannot take whole was left out, even when it had an alias which
    the prompt can take. It is now reached by that alias, which stands for it in its path, its usage
    and its parent's list, and its own subcommands are described under that path (41dc36f4).
  • A name left out of the list of subcommands was still in its parent's usage and help, which named
    every subcommand by every name. They are now rendered from a copy of the parser which names each
    subcommand only by the names which can be typed (41dc36f4).
  • A command made with preserve_quotes=True gives argparse each word with its quotation marks, so
    its subcommand named "list all", quotes and all, is typed "list all", and no word reaches one
    named list all. The example read every command as if it took its quotes off. It now asks
    cmd2 for each command's preserve_quotes with Cmd.get_argparse_command_spec(), from Make a command's argparse spec public as Cmd.get_argparse_command_spec() #1859,
    and reads the words after the command as that command's parser is given them (3b84d452).

A sixth review, at 3b84d452, found five points. All five were real, and each is fixed in
a560c7d9, with a test which failed first:

  • The first description was built when the server started, before cmdloop() ran preloop(), so a
    command which preloop() hides was described. With input from a pipe, cmd2 never calls
    pre_prompt(), and that description stayed until a command had run. The first description is now
    built once preloop() has returned, before the first line is read, and until then the server
    answers that it has not been built yet. cmd2 has no public method at that moment, so the mixin
    overrides cmd2's private _cmdloop(); the docs page says so. Commands run from inside
    preloop() publish nothing, and a second cmdloop() doesn't serve the first one's description
    while its own preloop() runs.
  • Describing an argument whose choices are an iterator used it up, so that argparse then rejected a
    value which it had accepted before. Such choices are no longer listed, and usage and help are
    rendered from a copy of the argument without them.
  • cmd2 gives a command which is another's function under a second name, such as
    do_orate = do_speak, the other's parser, prog and all, so orate was described as
    Usage: speak .... A command is now described by the name it was asked for.
  • A subcommand named -h, with the alias expand, was served as report -h, which prints the
    parent's help. A name is now served only where argparse takes it for the subcommand, not for an
    option (-h, --, an ambiguous abbreviation) or for a file of arguments. argparse decides that
    in a private method, which is asked of a copy of the parser: on Python 3.11 it reports an
    ambiguous abbreviation by printing an error and exiting. On 3.11, 3.12 and 3.15 its answer matches
    what the prompt dispatches.
  • Sibling subcommands a\rb and ab were both served as ab, and one hid the other. A name which
    plain_text() changes is now left out.

A seventh review, at b0bc11ad, found five points. All five were real, and each is fixed in
a4f1a788, with a test which failed first:

  • Subcommands added with add_subparsers(help=argparse.SUPPRESS), which help and usage leave out
    together, were served. They are now all left out.
  • choices=range(2**32) with a metavar is checked at once by argparse, but listing it took minutes
    and gigabytes on the main thread before the first prompt. No more than the first 1000 choices are
    now read and listed, and each argument's new more_choices says when some are not, which is also
    so of choices which are an iterator. Usage and help are rendered without such choices.
  • A cmdloop() run from inside the outer preloop() ended the start, so the description was
    published before that preloop() returned. The mixin now counts the calls of cmdloop() in
    progress, and only the outermost loop's _cmdloop() ends the start.
  • Where there was no description, describe_command answered that the command did not exist, and
    list_shortcuts_aliases_macros returned empty tables. describe_command now says why there is
    none, and the tables have an error, as list_commands has.
  • argparse reads files of arguments, with each parser's from-file prefixes, in every word the parser
    is given, so @all under a root parser with the prefix @ was served, but opened the file all.
    A name is now checked against the prefixes of every parser above it.

The eighth review is addressed in db54d52d:

  • The argument choice cap preserves the parent's filtered subcommands in help and usage.
    %(choices)s expands to (choices omitted) when the choices exceed the cap or are an iterator.
  • Command and subcommand summaries render formatter-aware descriptions such as cmd2.TextGroup.
    A subcommand named -- appears only under a usable alias, even with custom option prefixes.
  • A worker that exits releases its listener immediately. Until the first successful snapshot,
    clients see the latest distinct build error. Later build failures preserve the last good snapshot.
  • Runner retries count both required test matrices. The selector was checked locally against a
    missing example runner, a mix of a missing runner and a test failure, two missing runners, and
    passing matrices with an unrelated failure. The workflow takes effect after merge to main.

The five findings from the ninth review are addressed in dfb92d47:

  • Child and grandchild help use a bounded argument's metavar even when argparse embedded and
    wrapped all its choices in the child's original usage prefix.
  • Subcommands expose their typed lookup spelling. Clients can distinguish report "list all"
    from report list all directly from the parent response.
  • An option-looking subcommand can be reached after a positional consumes --. The child usage
    shows the delimiter for the invocation while the MCP lookup path contains only command names.
  • Snapshot text escapes lone surrogates. Tests round-trip an undecodable filesystem byte through
    the SDK in both a default and an alias.
  • Help formatting sets the width on the formatter and its Rich console without changing COLUMNS.

The checks by hand were done before any of the changes made after review.

Design documents

In the python-cmd2/design repository:

@codecov

codecov Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.76%. Comparing base (fe09282) to head (c98238e).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1855   +/-   ##
=======================================
  Coverage   99.76%   99.76%           
=======================================
  Files          23       23           
  Lines        6777     6801   +24     
=======================================
+ Hits         6761     6785   +24     
  Misses         16       16           
Flag Coverage Δ
unittests 99.76% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

…bandonment test, and join the replacement's worker too
…efault, say where the example was tried, and fix its tests on Python 3.11 with coverage and on Windows
@tleonhardt
tleonhardt changed the base branch from main to public-command-category December 2, 2026 16:50
Base automatically changed from public-command-category to main December 2, 2026 19:53
@tleonhardt
tleonhardt marked this pull request as ready for review December 3, 2026 02:14
- 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.
- 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.
…ed 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.
…tead 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.
…e 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.
…e 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.
tleonhardt added a commit that referenced this pull request Dec 3, 2026
…c() (#1859)

* Make a command's argparse spec public as Cmd.get_argparse_command_spec()

@with_argparser and @with_annotated record an ArgparseCommandSpec on the command function: the
source of its parser, and whether argparse is given the command's arguments with their quotes. It
was readable only through a private attribute. Code which describes an application's commands, as
the MCP server example in #1855 does, needs preserve_quotes to say how a subcommand is typed.

- Cmd.get_argparse_command_spec(func) returns the spec, or None for a command which neither
  decorator made. A disabled command's stand-in carries its spec.
- CommandParsers.get() and argparse completion use it in place of the private attribute.
- docs/features/argument_processing.md shows how to ask, and CHANGELOG.md has an entry under
  4.5.0.

* Freeze ArgparseCommandSpec, and give get_argparse_command_spec() only bound methods

- ArgparseCommandSpec is frozen. Through the getter, one application could change the spec which
  every application shares, so that it and completion reported what the command did not do.
- CommandParsers.get() reads the spec directly again. The argparse decorators pass it their own
  function, which is not bound, and the public accessor takes a bound method; calling it from
  there also called an override of it during Cmd.__init__().

* Say that a frozen ArgparseCommandSpec still shares its parser source

Freezing the spec stops its fields being reassigned, not a change to the parser which
@with_argparser was given: that is the spec's parser_source itself, and each application copies it
when it builds the command's parser. The changelog entry and the docstring of
get_argparse_command_spec() now say so, and send a reader who wants to change one application's
parser to self.command_parsers.get(func).

* Say what parser_source is for each argparse decorator

@with_argparser records the parser or factory it was given. @with_annotated records a factory
which cmd2 makes from the command's type hints, so its parser_source is not the command's
function. The docstring of get_argparse_command_spec() now names each case.
…eeps 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.
…spatch 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.
…en 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.
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.
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.
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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Example: a cmd2 application with a built-in MCP server which describes its commands and arguments

1 participant