Expand description
§clap-mcp
Expose your clap CLI as an MCP (Model Context Protocol) server over stdio.
§Quick start
Prefer a single run function with #[clap_mcp_output_from = "run"] so CLI and MCP
share one implementation (no duplicated logic).
ⓘ
use clap::Parser;
use clap_mcp::ClapMcp;
#[derive(Parser, ClapMcp)]
#[clap_mcp(reinvocation_safe, parallel_safe = false)]
#[clap_mcp_output_from = "run"]
enum Cli {
Greet { #[arg(long)] name: Option<String> },
}
fn run(cmd: Cli) -> String {
match cmd {
Cli::Greet { name } => format!("Hello, {}!", name.as_deref().unwrap_or("world")),
}
}
fn main() {
let cli = Cli::parse_or_serve_mcp();
println!("{}", run(cli));
}Run with --mcp to start the MCP server instead of executing the CLI.
Modules§
- content
- Custom MCP resources and prompts, and skill export. Custom MCP resources, prompts, and agent skills export.
- logging
- Logging integration for clap-mcp.
Macros§
- clap_
mcp_ main - Convenience macro for struct root + subcommand CLIs: parse root then run.
- impl_
serialize_ topic_ hash_ eq - Uses
Hashof the deserialized value for the topic segment (after JSON parse succeeds). - impl_
serialize_ topic_ serde_ eq - Uses
serdeJSON of the deserialized value for the topic segment (semantic equality whenEqmatches serde’s encoding). - output_
schema_ one_ of - Builds a JSON schema with
oneOffor the given types. Used by the derive macro when#[clap_mcp_output_one_of = "T1, T2, T3"]is set. Requires theoutput-schemafeature and each type must implementschemars::JsonSchema.
Structs§
- AsStructured
- Wrapper for structured (JSON) output when using
#[clap_mcp_output_from]. Use when yourrunfunction returns a type that implementsSerializebut is notString/&str. - ClapArg
- Serializable representation of a clap argument.
- Clap
ArgGroup - One clap
ArgGroupvisible on a single command node at schema extraction. - Clap
Command - A command or subcommand in the schema.
- Clap
McpBuiltin Flags - User-facing long names for clap-mcp builtin global flags (stdio, HTTP, export-skills).
- Clap
McpConfig - Configuration for execution safety when exposing a CLI over MCP.
- Clap
McpError Data - Error information for JSON-RPC error responses.
- Clap
McpRun Options - Derive-path and imperative MCP run options (execution config + serve behavior).
- Clap
McpSchema Metadata - Metadata for filtering and adjusting the MCP schema.
- Clap
McpServe Options - Optional configuration for MCP serve behavior (logging, etc.).
- Clap
McpTool Error - Error produced when a tool’s
runfunction returnsErr(e)(e.g.Result<O, E>). - Clap
Schema - Serializable schema extracted from a clap
Command. Used to build MCP tools and invoke the CLI. - Serve
Mcp - Bundled MCP serve parameters, produced by
ServeMcpBuilder::build. - Serve
McpBuilder - Fluent builder for imperative MCP embedder serve.
Enums§
- Clap
McpError - Errors that can occur when running the MCP server.
- Clap
McpSerialize Scope - Clap
McpTool Output - Output produced by a CLI command for MCP tool results.
- McpListen
- MCP transport listen target for low-level embedders.
Constants§
- CLAP_
MCP_ EXPORT_ SKILLS_ FLAG_ ID - Stable clap arg id for the export-skills flag.
- CLAP_
MCP_ STDIO_ FLAG_ ID - Stable clap arg id for the stdio MCP flag (internal;
ClapMcpBuiltinFlags::stdio_longis user-facing). - EXPORT_
SKILLS_ FLAG_ LONG - Long flag that triggers Agent Skills export (generates SKILL.md). Add via
command_with_export_skills_flag. - LOGGING_
GUIDE_ CONTENT - Full content for the logging guide prompt (returned when clients request
PROMPT_LOGGING_GUIDE). - LOG_
INTERPRETATION_ INSTRUCTIONS - Log interpretation hint for MCP clients (included in
instructionswhen logging is enabled). - MCP_
FLAG_ LONG - Long flag that triggers MCP server mode. Add to your CLI via
command_with_mcp_flag. - MCP_
RESOURCE_ URI_ SCHEMA - URI for the clap schema resource exposed by the MCP server.
- PROMPT_
LOGGING_ GUIDE - Name of the logging guide prompt.
Traits§
- Clap
McpConfig Provider - Provides MCP execution safety configuration from
#[clap_mcp(...)]attributes. Implemented by the#[derive(ClapMcp)]macro. - Clap
McpFlatten Args Topics - Serialize-topic bindings contributed by a flattened
clap::Argshelper type. - Clap
McpRunnable - Produces the output string for a parsed CLI value.
Used for in-process MCP tool execution when
reinvocation_safeis true. Implemented by the#[derive(ClapMcp)]macro via the blanket impl forClapMcpToolExecutor. - Clap
McpSchema Metadata Provider - Provides MCP schema metadata (skip, requires, task tools, serialize) from
#[clap_mcp(skip)],#[clap_mcp(requires = "arg_name")], optional#[clap_mcp(task)], and#[clap_mcp(serialized)]on variants. - Clap
McpSerialize Topic - Optional typed topical lock segments for arg-scoped serialization.
- Clap
McpTool Executor - Produces MCP tool output (text or structured) for a parsed CLI value.
- Clap
McpTool Executor With State - In-process MCP tool execution with session state shared across
tools/callinvocations. - Into
Clap McpResult - Converts the return value of a
runfunction (used with#[clap_mcp_output_from]) into MCP tool output or error. - Into
Clap McpTool Error - Converts an error type from a
runfunction intoClapMcpToolError. Used whenrunreturnsResult<O, E>and theErrbranch is taken. - Parse
OrServe Mcp - Canonical entrypoint for derive-based CLIs: parse (or serve if
--mcp) and return self. - Parse
OrServe McpWith State - Parse CLI or serve MCP with shared session state when
--mcpis present.
Functions§
- argv_
before_ end_ of_ opts - Arg prefix before the first standalone
--(clap end-of-options). Passthrough tokens after--are excluded. - argv_
contains_ clap_ mcp_ flags - Returns true when argv (before
--) contains a clap-mcp builtin entry flag: stdio MCP (--mcp), export-skills, or HTTP MCP when thehttpfeature is enabled. - command_
with_ export_ skills_ flag - Adds a root-level
--export-skillsflag (optional value for output directory) to aclap::Command. - command_
with_ export_ skills_ flag_ with_ flags - Like
command_with_export_skills_flagbut usesflags.export_skills_long. - command_
with_ mcp_ and_ export_ skills_ flags - Adds both
--mcpand--export-skillsflags to the command. Use this so schema extraction omits both; check for export-skills before mcp in the parse flow. - command_
with_ mcp_ and_ export_ skills_ flags_ with_ flags - Like
command_with_mcp_and_export_skills_flagswith custom builtin long names. - command_
with_ mcp_ flag - Adds a root-level
--mcpflag to aclap::Command(imperative clap usage). - command_
with_ mcp_ flag_ with_ flags - Like
command_with_mcp_flagbut usesflags.stdio_longfor the user-facing long name. - get_
matches_ or_ serve_ mcp - Imperative clap entrypoint.
- get_
matches_ or_ serve_ mcp_ with_ config - Imperative clap entrypoint with execution safety configuration.
- get_
matches_ or_ serve_ mcp_ with_ config_ and_ metadata - Imperative clap entrypoint with execution safety configuration and schema metadata.
- get_
matches_ preserve_ cli_ or_ serve_ mcp - Like
get_matches_or_serve_mcpwith native CLI parse when argv has no clap-mcp flags. - get_
matches_ preserve_ cli_ or_ serve_ mcp_ with_ config - Like
get_matches_or_serve_mcp_with_configwith native CLI parse when argv has no clap-mcp flags. - get_
matches_ preserve_ cli_ or_ serve_ mcp_ with_ config_ and_ metadata - Imperative entrypoint like
get_matches_or_serve_mcp_with_config_and_metadata, but uses un-augmentedcmd.get_matches()when argv does not request clap-mcp entry. - in_
process_ tool_ handler_ for - Builds an in-process tool handler for type
Twhen usingServeMcpBuilder,serve_mcp, orserve_mcp_blockingwithreinvocation_safe.ServeMcpBuilder::for_clisets this automatically when appropriate. - output_
schema_ for_ type - parse_
or_ serve_ mcp_ preserve_ cli_ with - Like
parse_or_serve_mcp_withbut usesclap::Parser::parsewhen argv does not request clap-mcp entry, preserving native clap error formatting for normal shell invocations. - parse_
or_ serve_ mcp_ with - Derive-based entrypoint: parse CLI or start MCP server (stdio or HTTP) and exit.
- parse_
or_ serve_ mcp_ with_ state - Stateful derive entrypoint: like
parse_or_serve_mcp_withbut capturesstatein the in-process tool handler for the MCP server lifetime. - parse_
or_ serve_ mcp_ with_ state_ preserve_ cli - Like
parse_or_serve_mcp_with_statebut usesclap::Parser::parsewhen argv does not request clap-mcp entry. - run_
async_ tool - Runs an async future for MCP tool execution, respecting
share_runtimein config. - run_
or_ serve_ mcp - Run parsed CLI through a closure, or serve MCP if
--mcp/--mcp-httpis present. - schema_
from_ command - Extracts a serializable schema from a
clap::Command(imperative clap usage). - schema_
from_ command_ with_ metadata - Extracts a schema from a
clap::Commandwith MCP metadata applied. - serve_
mcp - Async MCP server for embedders: stdio or Streamable HTTP (
httpfeature). - serve_
mcp_ blocking - Blocking MCP server for embedders: stdio or Streamable HTTP (
httpfeature). - tools_
from_ schema_ with_ metadata - Builds MCP tools from a clap schema with execution config and metadata.
Type Aliases§
- InProcess
Tool Handler - Type for in-process tool execution handler.
- Serialize
Topic Segment Fn - Computes one arg’s contribution to a topical lock key from MCP JSON.
Derive Macros§
- ClapMcp
- Derive macro for
ClapMcpConfigProviderandClapMcpToolExecutor.