Repository navigation
Add an example which serves a description of its commands over MCP - #1855
Open
tleonhardt wants to merge 43 commits into
Open
tleonhardt wants to merge 43 commits into
tleonhardt wants to merge 43 commits into
Conversation
…t ended, and describe a non-finite default by its repr
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
…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
…disabled command's function is its replacement
…mcp-remote, which was tried
… with, so that a client printing them prints no empty lines
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.
# Conflicts: # CHANGELOG.md
…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 was referenced Dec 4, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Adds
examples/mcp_server.py, acmd2application which serves a description of its own commandsover 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
Cmdwhich are new in 4.5.0, both merged intomain:get_command_category(), which Make a command's help category public as Cmd.get_command_category() #1856 made publicget_argparse_command_spec(), which Make a command's argparse spec public as Cmd.get_argparse_command_spec() #1859 added, so that the example can tell whether a commandgives argparse its arguments with their quotes (
preserve_quotes)What is in it
The example is one file in three parts.
cmd2already holds. They cover commands, arguments (nargsranges, 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.
McpServerMixin, which can be copied into another application.cmdloop(),pre_prompt()andonecmd_plus_hooks(), so it uses no hooks, and_cmdloop(), which is private tocmd2.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.
http://127.0.0.1:8765/mcp, using Uvicorn and the MCP SDK'sMCPServer.list_commands,describe_command(command)andlist_shortcuts_aliases_macros.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.
CommandSetloaded as a plugin, togive the other two parts every kind of command to describe. It takes
--mcp-port PORTand--no-mcp.Also included:
tests/test_example_mcp_server.py. The tests which need the SDK are skipped when itisn't installed.
examplesdependency group withmcp>=2. It isn't indefault-groups, because it bringsin about fifteen packages.
example-tests, which installs that group and runs the example's tests withCMD2_EXAMPLE_TESTS_NEED_SDK=1, so that a skip there is a failure.docs/examples/mcp_server.md, with entries inmkdocs.yml,docs/examples/index.mdandexamples/README.md, and a CHANGELOG entry under 4.5.0. The pagewarns that each argument's default and each command's help text are served as they are.
Testing
dfb92d47on macOS with Python 3.15.2,make check,make test(3426 passed, 3 skipped)and
make docs-testpassed. All 196 SDK-required example tests passed on Python 3.11.18 and 3.15.2.a4f1a788, Windows and Python 3.11 included. The firstrun, at
1db209a4, had failed on two assumptions of the tests: coverage's warning on Python 3.11, and anevent loop which leaves a socket open on Unix but not on Windows.
a4f1a788, the example's tests passed with the SDK: 185 passed, none skipped, on Python 3.15, 3.11 and 3.12. Atearlier commits, they also passed:
8e83ba00: 148 passed, none skipped7777733b: 143 passed, and 5 skipped, which need a pipe for the prompthttp://127.0.0.1address, and gave the expected command linefor each objective tried.
mcp-remotebridge, gave the same command lines, and worked againafter the example was restarted, with nothing done in Desktop. The page has the configuration
which was used.
quitand Ctrl-D end at once, and the port is free at once.8e83ba00, since the commits before itchanged how a run starts and stops.
7777733b, from a Claude Codesession 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.
2664dcdaleaves them off.After review
A first review found eight points. All eight were real, and each is fixed in
a1526d36, with a testwhich failed first:
describe_commandfinds a subcommand by an alias at any depth, such asserver t addwheretaghas the alias
t. Looking up an unknown line stops at its first unknown word, so a long one is nolonger looked up prefix by prefix.
help=argparse.SUPPRESS, as the listof subcommands already did.
cmd2's ownhelpstill shows one, with==SUPPRESS==for its help,since that is how argparse renders it.
can share.
mcp_stop().plugin loadandplugin unloadsay when the plugin is loaded already, or isn't loaded.nargs=argparse.PARSERis described, where before the whole command'sdescription failed.
A second review, at
a1526d36, found six more. All six were real too, and each is fixed in8e9c438b, with a test which failed first:join()which Ctrl-C interrupts leavesis_alive()false while thethread 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 statusfollows the same rule.can't leave the hold taken for good.
(
report "list all"), and its path is served quoted.main()asks for version 2 of the SDK before the console starts.A third review, at
8e9c438b, found three points in how a path with quotes in it is handled, allfrom the quoting just added. All three were real, and each is fixed in
857f0bcb, with a test whichfailed first:
report "list all"hasUsage: report "list all" [-h], and not the usage ofreport list all, which is another command.quotation mark,
|,>, or one of the application's terminators. Every path served can be askedfor again, and such a name is found only when it is typed quoted, as at the prompt.
At
8e9c438b, the macOS 3.11 job ran past its 10-minute limit, and GitHub kept no log of it. Thesame job had taken 8 minutes at
a1526d36, on a runner on which everything ran about 25 timesslower than on an Apple silicon Mac.
69128dc5makes the slowest test of the suite, the snapshotstress 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:report today'sandreport a'b"cas they are. Where a name was quoted for having a quotation mark in it,a'b"cwas served as
'a'b"c', which the prompt splits in two. A name is now served as it is where theprompt passes it to argparse unchanged, and quoted otherwise, as
cmd2'sStatementParserdecides with the application's terminators. A word typed in a path is matched the same way.
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.
report "", was served asreport,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
reporthas a metavar for its subcommands.A fifth review, at
d2e68f1f, found three points. All three were real, and each is fixed with atest which failed first:
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).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).preserve_quotes=Truegives argparse each word with its quotation marks, soits subcommand named
"list all", quotes and all, is typed"list all", and no word reaches onenamed
list all. The example read every command as if it took its quotes off. It now askscmd2for each command'spreserve_quoteswithCmd.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 ina560c7d9, with a test which failed first:cmdloop()ranpreloop(), so acommand which
preloop()hides was described. With input from a pipe,cmd2never callspre_prompt(), and that description stayed until a command had run. The first description is nowbuilt once
preloop()has returned, before the first line is read, and until then the serveranswers that it has not been built yet.
cmd2has no public method at that moment, so the mixinoverrides
cmd2's private_cmdloop(); the docs page says so. Commands run from insidepreloop()publish nothing, and a secondcmdloop()doesn't serve the first one's descriptionwhile its own
preloop()runs.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.
cmd2gives a command which is another's function under a second name, such asdo_orate = do_speak, the other's parser, prog and all, sooratewas described asUsage: speak .... A command is now described by the name it was asked for.-h, with the aliasexpand, was served asreport -h, which prints theparent'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 thatin 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.
a\rbandabwere both served asab, and one hid the other. A name whichplain_text()changes is now left out.A seventh review, at
b0bc11ad, found five points. All five were real, and each is fixed ina4f1a788, with a test which failed first:add_subparsers(help=argparse.SUPPRESS), which help and usage leave outtogether, 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 minutesand 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_choicessays when some are not, which is alsoso of choices which are an iterator. Usage and help are rendered without such choices.
cmdloop()run from inside the outerpreloop()ended the start, so the description waspublished before that
preloop()returned. The mixin now counts the calls ofcmdloop()inprogress, and only the outermost loop's
_cmdloop()ends the start.describe_commandanswered that the command did not exist, andlist_shortcuts_aliases_macrosreturned empty tables.describe_commandnow says why there isnone, and the tables have an
error, aslist_commandshas.is given, so
@allunder a root parser with the prefix@was served, but opened the fileall.A name is now checked against the prefixes of every parser above it.
The eighth review is addressed in
db54d52d:%(choices)sexpands to(choices omitted)when the choices exceed the cap or are an iterator.cmd2.TextGroup.A subcommand named
--appears only under a usable alias, even with custom option prefixes.clients see the latest distinct build error. Later build failures preserve the last good snapshot.
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:wrapped all its choices in the child's original usage prefix.
typedlookup spelling. Clients can distinguishreport "list all"from
report list alldirectly from the parent response.--. The child usageshows the delimiter for the invocation while the MCP lookup path contains only command names.
the SDK in both a default and an alias.
COLUMNS.The checks by hand were done before any of the changes made after review.
Design documents
In the python-cmd2/design repository:
with a record of how it was carried out
the checks by hand, with what was seen