click2mcp
# click2mcp
`click2mcp` turns a [Click](https://click.palletsprojects.com/) CLI into a typed
MCP server. At startup it walks the command tree and creates one MCP tool per leaf
command, using the command's parameter names, types, defaults, and allowed values.
The JSON Schema comes from a function signature. `MCPServer.add_tool` and
`Tool.from_function` build it with pydantic and do not accept a hand-written
`inputSchema`, so `click2mcp` gives each command a function whose `__signature__`
and `__annotations__` are the Click parameters themselves.
## Install
```bash
pip install click2mcp
```
## Quickstart
Add an adapter module to your CLI package:
```python
# src/mycli/mcp/server.py
from click2mcp import ClickMCP
from mycli.main import main as cli
bridge = ClickMCP(app="mycli", cli=cli, module="mycli.main")
mcp = bridge.server
def main() -> None:
bridge.run()
```
Expose it as a console script and an optional dependency:
```toml
[project.scripts]
mycli-mcp = "mycli.mcp.server:main"
[project.optional-dependencies]
mcp = ["click2mcp>=0.1.0"]
```
Install the extra, register the server with an MCP client, and run it over stdio.
For Claude Code:
```bash
claude mcp add mycli -- mycli-mcp
```
To serve it over Streamable HTTP instead — for a remote client or one shared
across sessions — select the transport and the endpoint:
```bash
mycli-mcp --transport streamable-http --port 8000
claude mcp add --transport http mycli http://127.0.0.1:8000/mcp
```
`cli` can also be a zero-argument callable that returns the root command or `None`.
It is resolved once. If it raises, the server still starts with only the escape
hatches. `module="mycli.main"` is the fallback launcher used when no installed
`mycli` executable can be found.
## Configuration
| Parameter | Default | Meaning |
| --- | --- | --- |
| `app` | required | CLI executable name, MCP server name, and `{app}-mcp` program name. |
| `cli` | required | Root `click.Command` (a group or a single command), zero-arg callable returning one, or `None`. |
| `module` | `None` | Module passed to `python -m` when no executable is found. Required if `app` is not installed and no `launcher` is given. |
| `instructions` | generic template | MCP server instructions; used verbatim when supplied. |
| `exclude` | `frozenset()` | Command paths omitted from the typed tools and refused by `{app}_run`. |
| `include` | `None` | Command path prefixes to expose; `None` exposes every leaf outside `exclude`. |
| `include_hidden` | `False` | Also expose commands and groups marked `hidden=True`; a hidden group takes its whole subtree with it. |
| `escape_hatches` | `True` | Register `{app}_help` and `{app}_run`. |
| `help_description` | generic | Description override for `{app}_help`. |
| `run_description` | generic | Description override for `{app}_run`. |
| `inherit_group_options` | `True` | Expose options declared on ancestor groups on every leaf tool below them. |
| `tool_prefix` | `""` | Prefix for generated typed tool names: `""` (the default) names them after the command path alone, `None` keeps `{app}_`, any other value is normalized (`-`/space to `_`, trailing `_` added). Must form a Python identifier. `{app}_help`/`{app}_run` keep their prefix regardless. |
| `transport` | `"stdio"` | Default MCP transport for `run()`: `"stdio"` or `"streamable-http"`. |
| `host` | `"127.0.0.1"` | Default Streamable HTTP bind address. |
| `port` | `8000` | Default Streamable HTTP TCP port. |
| `path` | `"/mcp"` | Default Streamable HTTP endpoint path; a leading `/` is added when missing. |
| `stateless` | `False` | Default for Streamable HTTP: serve each request without a session. |
| `json_response` | `False` | Default for Streamable HTTP: reply with a plain JSON body instead of an SSE stream. |
| `allowed_hosts` | `None` | Host header values accepted when serving Streamable HTTP; required for a non-loopback `host`. A bare name also allows any port on it. |
| `launcher` | `None` | Explicit argv prefix used to run the CLI. |
| `env` | `None` | Extra child environment variables, merged over the defaults. |
| `invoke` | `None` | Custom `(tokens) -> CompletedProcess[str]` runner; shared by typed tools and escape hatches. |
The launcher is resolved once, in this order: `launcher` verbatim, the console
script next to the running interpreter, `shutil.which(app)`, then
`[sys.executable, "-m", module]`. If none of them exist, construction raises
`RuntimeError`. The child process gets `NO_COLOR=1`, `TERM=dumb`, and
`PYTHONIOENCODING=utf-8`, merged over `os.environ` and then over `env`.
## Behavior notes
**Tool generation.** Every leaf command becomes one tool. Spaces and hyphens in the
command path turn into `_`, so `mycli browse following users` is
`browse_following_users` (see `tool_prefix` to add a prefix), and the description
ends with the exact CLI spelling. `--groups` restricts the typed tools to the named
subtrees, written with dots or spaces. An empty entry is rejected. Commands and
groups marked `hidden=True` are skipped, subtree included, unless `include_hidden`
is set (or `--include-hidden` is passed to `run()`); a `chain=True` group still
yields one tool per subcommand. A plain `click.Command` works as the root too, and
then the root command's parameters become the tool named after the app.
**Click semantics.** Tuple options (`type=(int, int)`) and positionals with
`nargs > 1` are exposed as fixed-length tuples, heterogeneous element types
included, and spelled back as `--point=1 2`. `count=True` options are integers and
emit one bare flag per increment, never `--verbose=3`. Non-clamping
`IntRange`/`FloatRange` bounds become `minimum`/`maximum` (or the exclusive
equivalents); clamping ranges accept out-of-range input, so they carry no schema
bounds and a "Clamped to ..." description instead, since click clamps the value.
`Path` and `DateTime` types add a description naming their constraints and accepted
formats, and a case-insensitive `Choice` is exposed as a plain string with its
allowed values listed rather than a `Literal` that would reject another casing.
**Tool names and client namespacing.** Typed tools are named after the command path
alone (`browse_following_users`) by default, because clients such as Claude Code
already namespace them as `mcp__<server>__<tool>`, and a `{app}_` prefix would
therefore repeat the server name on screen. Set `tool_prefix=None` for the
historical `mycli_browse_following_users` name, for clients that show a flat list
of tools with no other context; any other value replaces the prefix, normalized
like a command path. This applies to the generated typed tools only: `{app}_help` and
`{app}_run` always keep the `{app}_` prefix, because `help` and `run` are generic
verbs that would collide with real subcommands of the same name.
**Escape hatches and inherited options.** `{app}_help(path)` runs `--help`, and
`{app}_run(args)` runs an arbitrary command line. Set `escape_hatches=False` to omit
both. Only `ToolError` text reaches the client. Typed tools also expose the options
of their ancestor groups, and the generated argv puts each option before the
subcommand it belongs to: `{app} --verbose sub --profile=x run -- n`. A leaf
parameter shadows a group option with the same name, the innermost group wins over
outer ones, and eager options such as `--help` and `--version` are skipped. Set
`inherit_group_options=False` to disable the inheritance.
**Prompts and failures.** An option declared with `prompt=` is exposed as required,
because the child's stdin is `/dev/null` and a prompt can never be answered over
MCP, even when Click does not mark the option required. A leaf whose parameters
cannot be turned into a signature, or whose tool name collides with another
command's, is logged and skipped. The rest of the server still starts.
**JSON output.** Output that is a single JSON object or array is returned as data:
the tool result carries a real JSON value in its structured content, so a client
does not receive the document as an escaped JSON string. A bare JSON scalar is
returned compact when re-serialization shortens it. This applies to both the typed
tools and `{app}_run`. Help text, logs, JSON Lines, and anything else that is not
one complete JSON document passes through exactly as the CLI wrote it, and key
order is preserved.
**Runtime and exclusions.** A call returns when the child exits. There is no
server-side timeout, and the child's stdin is `/dev/null`, so it cannot read the
JSON-RPC stream; deciding when to give up is the MCP client's job. Options are
passed as one token, `--long=value`, never `--long value`, and repeated options are
repeated. A multi-value option keeps its first value glued to the `=`, with the
remaining values following as separate tokens (`--point=1 2`), so negatives
survive. Positionals follow an end-of-options `--` in declaration order, so values
that begin with `-` survive. Full-screen TUIs and endless streams cannot work over
MCP. List them in `exclude`, because nothing here kills a subprocess and
`{app}_run` refuses excluded paths before spawning.
**Transports.** `run()` serves MCP over stdio by default. Pass `--transport
streamable-http` (or set `transport=` on the constructor) to serve Streamable HTTP
instead. `--host`, `--port`, `--path`, `--stateless`, `--json-response`, and
`--allow-host` tune the endpoint, and the constructor's `host`, `port`, `path`,
`stateless`, `json_response`, and `allowed_hosts` supply their defaults. Command-line
flags override those defaults, with `--no-stateless` and `--no-json-response`
turning a baked-in boolean off. `--groups` applies to both transports. The SDK's
`sse` transport is not offered; Streamable HTTP supersedes it in the MCP spec.
An HTTP bind is reachable from the network, so DNS-rebinding protection matters.
The SDK applies its own loopback allowlist (`127.0.0.1:*`, `localhost:*`,
`[::1]:*`) only when the bind address is loopback; binding anywhere else requires
`--allow-host` (repeatable), and the server refuses to start without it rather than
accepting every `Host` header. A bare name such as `example.com` allows any port on
that name, since the `Host` header carries the port. Origins are not allowlisted: a
request that carries an `Origin` header (a browser) is rejected, while non-browser
clients normally send none.
## License
MIT
TDQS
Scored across 3 tools
demo_help and demo_run are clearly distinct (help vs execution), but `hello` has a useless description and could be mistaken for a test/echo or another command invocation. The boundary between hello and demo_run is unclear without knowing the CLI semantics.
Two tools follow a demo_* noun/verb pattern (demo_help, demo_run), but `hello` breaks the convention and has no domain prefix. The set is still readable, but the mixed style is noticeable.
Three tools is reasonable for a minimal CLI bridge: help, run, and a sample hello. The count is well-scoped, though `hello` feels like demo filler rather than a core operation.
For a CLI bridge, demo_help and demo_run together cover discovery and execution well. Minor gaps exist around structured output or error handling, but the core lifecycle is present.