Repository navigation
Support an opt-in read-only MCP server via cmd2[mcp] - #1866
Open
tleonhardt wants to merge 49 commits into
Open
tleonhardt wants to merge 49 commits into
tleonhardt wants to merge 49 commits into
Conversation
…t ended, and describe a non-finite default by its repr
…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
- 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.
# 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.
Let Cmd own listener startup, shutdown, and snapshot refresh at its command and prompt boundaries. Keep the SDK optional and make the fleet console a consumer of the supported API. Exercise default installations and real MCP clients separately in CI.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1866 +/- ##
==========================================
+ Coverage 99.76% 99.79% +0.02%
==========================================
Files 23 25 +2
Lines 6785 7738 +953
==========================================
+ Hits 6769 7722 +953
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. |
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.
Alternative solution for #1852. This PR adds a supported, opt-in MCP server to
cmd2.Cmdand includes a Fleet console example that uses its public API. An MCP client can inspect the running application’s commands and suggest a command line for the person at the prompt to review and run.Both this PR and #1855 target
mainand can be reviewed independently. #1855 packages discovery as a reusable example mixin. This PR ships it incmd2behind thecmd2[mcp]extra and explicit activation. The branch comparison shows what changes between the two implementations. Compare the two approaches. See the design tradeoffs in #1852.Usage
Install
cmd2[mcp]and select a port when constructing the application.A client can then connect to
http://127.0.0.1:8765/mcp. Port0requests an available port. The defaultNoneleaves MCP disabled, with no SDK import, snapshot work, or listener.Behavior
mcp_start()andmcp_stop()and inspectmcp_urlormcp_status().list_commands,describe_command, andlist_shortcuts_aliases_macros. Command execution stays at the prompt.Verification
0a8f47d8passedmake check,make test(3,474 passed, 5 skipped), andmake docs-test.