Cover image
Try Now
2025-04-13

用一行代码将单击CLIS转换为MCP服务器

3 years

Works with Finder

1

Github Watches

0

Github Forks

2

Github Stars

click-mcp

PyPI version License: MIT

A Python library that extends Click applications with Model Context Protocol (MCP) support, allowing AI agents to interact with CLI tools.

Overview

click-mcp provides a simple decorator that converts Click commands into MCP tools. This enables AI agents to discover and interact with your CLI applications programmatically.

The Model Context Protocol (MCP) is an open standard for AI agents to interact with tools and applications in a structured way.

Key Features

  • Simple @click_mcp decorator syntax
  • Automatic conversion of Click commands to MCP tools
  • Support for nested command groups
  • Stdio-based MCP server for easy integration

Installation

pip install click-mcp

Basic Usage

import click
from click_mcp import click_mcp

@click_mcp(server_name="my-cli-app")
@click.group()
def cli():
    """Sample CLI application."""
    pass

@cli.command()
@click.option('--name', required=True, help='Name to greet')
def greet(name):
    """Greet someone."""
    click.echo(f"Hello, {name}!")

if __name__ == '__main__':
    cli()

When you run the MCP server, Click commands are converted into MCP tools:

  • Command greet becomes MCP tool greet
  • Nested commands use dot notation (e.g., users.create)

To invoke a command via MCP, send a request like:

{
  "type": "invoke",
  "tool": "greet",
  "parameters": {
    "name": "World"
  }
}

To start the MCP server:

$ python my_app.py mcp

Advanced Usage

Customizing the MCP Command Name

By default, click-mcp adds an mcp command to your CLI application. You can customize this name using the command_name parameter:

@click_mcp(command_name="start-mcp")
@click.group()
def cli():
    """Sample CLI application with custom MCP command name."""
    pass

With this configuration, you would start the MCP server using:

$ python my_app.py start-mcp

This can be useful when:

  • The name "mcp" conflicts with an existing command
  • You want a more descriptive command name
  • You're integrating with a specific AI agent that expects a certain command name

Customizing the MCP Server Name

You can also customize the name of the MCP server that's reported to clients:

@click_mcp(server_name="my-custom-tool")
@click.group()
def cli():
    """Sample CLI application with custom server name."""
    pass

This can be useful when:

  • You want to provide a more descriptive name for your tool
  • You're integrating with systems that use the server name for identification
  • You want to distinguish between different MCP-enabled applications

Working with Nested Command Groups

click-mcp supports nested command groups. When you have a complex CLI structure with subcommands, all commands are exposed as MCP tools:

@click_mcp
@click.group()
def cli():
    """Main CLI application."""
    pass

@cli.group()
def users():
    """User management commands."""
    pass

@users.command()
@click.option('--username', required=True)
def create(username):
    """Create a new user."""
    click.echo(f"Creating user: {username}")

@users.command()
@click.argument('username')
def delete(username):
    """Delete a user."""
    click.echo(f"Deleting user: {username}")

When exposed as MCP tools, the nested commands will be available with their full path using dot notation (e.g., "users.create" and "users.delete").

Handling Command Errors

When a Click command raises an exception, click-mcp captures the error and returns it as part of the MCP response. This allows AI agents to handle errors gracefully:

@cli.command()
@click.option('--filename', required=True)
def process(filename):
    """Process a file."""
    try:
        with open(filename, 'r') as f:
            content = f.read()
        click.echo(f"Processed file: {filename}")
    except FileNotFoundError:
        raise click.UsageError(f"File not found: {filename}")

If the file doesn't exist, the AI agent will receive an error message that it can present to the user or use to take corrective action.

Development

Setup

Clone the repository and install Hatch:

git clone https://github.com/aws/click-mcp.git
cd click-mcp
pip install hatch

Testing

Run tests with Hatch:

# Run all tests
hatch run test

# Run tests with coverage
hatch run cov

Code Formatting

Format code with Black:

# Format code
hatch run format

# Check formatting
hatch run check-format

Linting

Run linting checks with Ruff:

hatch run lint

Type Checking

Run type checking with MyPy:

hatch run typecheck

Run All Checks

Run all checks (formatting, linting, type checking, and tests):

hatch run check-all

Building

Build the package:

hatch run build

Documentation

Generate documentation:

hatch run docs

Related Resources

License

MIT

相关推荐

  • Joshua Armstrong
  • Confidential guide on numerology and astrology, based of GG33 Public information

  • https://suefel.com
  • Latest advice and best practices for custom GPT development.

  • Alexandru Strujac
  • Efficient thumbnail creator for YouTube videos

  • Emmet Halm
  • Converts Figma frames into front-end code for various mobile frameworks.

  • Elijah Ng Shi Yi
  • Advanced software engineer GPT that excels through nailing the basics.

  • Lists Tailwind CSS classes in monospaced font

  • https://maiplestudio.com
  • Find Exhibitors, Speakers and more

  • lumpenspace
  • Take an adjectivised noun, and create images making it progressively more adjective!

  • https://appia.in
  • Siri Shortcut Finder – your go-to place for discovering amazing Siri Shortcuts with ease

  • Carlos Ferrin
  • Encuentra películas y series en plataformas de streaming.

  • Yusuf Emre Yeşilyurt
  • I find academic articles and books for research and literature reviews.

  • tomoyoshi hirata
  • Sony α7IIIマニュアルアシスタント

  • apappascs
  • 发现市场上最全面,最新的MCP服务器集合。该存储库充当集中式枢纽,提供了广泛的开源和专有MCP服务器目录,并提供功能,文档链接和贡献者。

  • ShrimpingIt
  • MCP系列GPIO Expander的基于Micropython I2C的操作,源自ADAFRUIT_MCP230XX

  • jae-jae
  • MCP服务器使用剧作《无头浏览器》获取网页内容。

  • ravitemer
  • 一个功能强大的Neovim插件,用于管理MCP(模型上下文协议)服务器

  • patruff
  • Ollama和MCP服务器之间的桥梁,使本地LLMS可以使用模型上下文协议工具

  • pontusab
  • 光标与风浪冲浪社区,查找规则和MCP

  • av
  • 毫不费力地使用一个命令运行LLM后端,API,前端和服务。

  • WangRongsheng
  • 🧑‍🚀 llm 资料总结(数据处理、模型训练、模型部署、 o1 模型、mcp 、小语言模型、视觉语言模型)|摘要世界上最好的LLM资源。

  • Mintplex-Labs
  • 带有内置抹布,AI代理,无代理构建器,MCP兼容性等的多合一桌面和Docker AI应用程序。

  • modelcontextprotocol
  • 模型上下文协议服务器

    Reviews

    1 (1)
    Avatar
    user_8TT3lN6j
    2025-04-17

    I've been an avid user of click-mcp and it has significantly streamlined my workflow. The intuitive interface paired with robust functionalities makes it a must-have tool for efficiency. Kudos to crowecawcaw for creating such a stellar product! Highly recommend checking it out at https://github.com/crowecawcaw/click-mcp.