Skip to main content

Crate clap_mcp

Crate clap_mcp 

Source
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 Hash of the deserialized value for the topic segment (after JSON parse succeeds).
impl_serialize_topic_serde_eq
Uses serde JSON of the deserialized value for the topic segment (semantic equality when Eq matches serde’s encoding).
output_schema_one_of
Builds a JSON schema with oneOf for the given types. Used by the derive macro when #[clap_mcp_output_one_of = "T1, T2, T3"] is set. Requires the output-schema feature and each type must implement schemars::JsonSchema.

Structs§

AsStructured
Wrapper for structured (JSON) output when using #[clap_mcp_output_from]. Use when your run function returns a type that implements Serialize but is not String/&str.
ClapArg
Serializable representation of a clap argument.
ClapArgGroup
One clap ArgGroup visible on a single command node at schema extraction.
ClapCommand
A command or subcommand in the schema.
ClapMcpBuiltinFlags
User-facing long names for clap-mcp builtin global flags (stdio, HTTP, export-skills).
ClapMcpConfig
Configuration for execution safety when exposing a CLI over MCP.
ClapMcpErrorData
Error information for JSON-RPC error responses.
ClapMcpRunOptions
Derive-path and imperative MCP run options (execution config + serve behavior).
ClapMcpSchemaMetadata
Metadata for filtering and adjusting the MCP schema.
ClapMcpServeOptions
Optional configuration for MCP serve behavior (logging, etc.).
ClapMcpToolError
Error produced when a tool’s run function returns Err(e) (e.g. Result<O, E>).
ClapSchema
Serializable schema extracted from a clap Command. Used to build MCP tools and invoke the CLI.
ServeMcp
Bundled MCP serve parameters, produced by ServeMcpBuilder::build.
ServeMcpBuilder
Fluent builder for imperative MCP embedder serve.

Enums§

ClapMcpError
Errors that can occur when running the MCP server.
ClapMcpSerializeScope
ClapMcpToolOutput
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_long is 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 instructions when 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§

ClapMcpConfigProvider
Provides MCP execution safety configuration from #[clap_mcp(...)] attributes. Implemented by the #[derive(ClapMcp)] macro.
ClapMcpFlattenArgsTopics
Serialize-topic bindings contributed by a flattened clap::Args helper type.
ClapMcpRunnable
Produces the output string for a parsed CLI value. Used for in-process MCP tool execution when reinvocation_safe is true. Implemented by the #[derive(ClapMcp)] macro via the blanket impl for ClapMcpToolExecutor.
ClapMcpSchemaMetadataProvider
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.
ClapMcpSerializeTopic
Optional typed topical lock segments for arg-scoped serialization.
ClapMcpToolExecutor
Produces MCP tool output (text or structured) for a parsed CLI value.
ClapMcpToolExecutorWithState
In-process MCP tool execution with session state shared across tools/call invocations.
IntoClapMcpResult
Converts the return value of a run function (used with #[clap_mcp_output_from]) into MCP tool output or error.
IntoClapMcpToolError
Converts an error type from a run function into ClapMcpToolError. Used when run returns Result<O, E> and the Err branch is taken.
ParseOrServeMcp
Canonical entrypoint for derive-based CLIs: parse (or serve if --mcp) and return self.
ParseOrServeMcpWithState
Parse CLI or serve MCP with shared session state when --mcp is 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 the http feature is enabled.
command_with_export_skills_flag
Adds a root-level --export-skills flag (optional value for output directory) to a clap::Command.
command_with_export_skills_flag_with_flags
Like command_with_export_skills_flag but uses flags.export_skills_long.
command_with_mcp_and_export_skills_flags
Adds both --mcp and --export-skills flags 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_flags with custom builtin long names.
command_with_mcp_flag
Adds a root-level --mcp flag to a clap::Command (imperative clap usage).
command_with_mcp_flag_with_flags
Like command_with_mcp_flag but uses flags.stdio_long for 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_mcp with 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_config with 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-augmented cmd.get_matches() when argv does not request clap-mcp entry.
in_process_tool_handler_for
Builds an in-process tool handler for type T when using ServeMcpBuilder, serve_mcp, or serve_mcp_blocking with reinvocation_safe. ServeMcpBuilder::for_cli sets this automatically when appropriate.
output_schema_for_type
parse_or_serve_mcp_preserve_cli_with
Like parse_or_serve_mcp_with but uses clap::Parser::parse when 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_with but captures state in the in-process tool handler for the MCP server lifetime.
parse_or_serve_mcp_with_state_preserve_cli
Like parse_or_serve_mcp_with_state but uses clap::Parser::parse when argv does not request clap-mcp entry.
run_async_tool
Runs an async future for MCP tool execution, respecting share_runtime in config.
run_or_serve_mcp
Run parsed CLI through a closure, or serve MCP if --mcp / --mcp-http is 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::Command with MCP metadata applied.
serve_mcp
Async MCP server for embedders: stdio or Streamable HTTP (http feature).
serve_mcp_blocking
Blocking MCP server for embedders: stdio or Streamable HTTP (http feature).
tools_from_schema_with_metadata
Builds MCP tools from a clap schema with execution config and metadata.

Type Aliases§

InProcessToolHandler
Type for in-process tool execution handler.
SerializeTopicSegmentFn
Computes one arg’s contribution to a topical lock key from MCP JSON.

Derive Macros§

ClapMcp
Derive macro for ClapMcpConfigProvider and ClapMcpToolExecutor.