click-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Stephen Crowe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ include LICENSE
2
+ include README.md
3
+ recursive-include tests *
4
+ recursive-exclude tests/__pycache__ *
@@ -0,0 +1,236 @@
1
+ Metadata-Version: 2.4
2
+ Name: click-mcp
3
+ Version: 0.1.0
4
+ Summary: Extend Click applications with Model Context Protocol (MCP) support
5
+ Home-page: https://github.com/crowecawcaw/click-mcp
6
+ Author: Stephen Crowe
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/crowecawcaw/click-mcp
9
+ Project-URL: Issues, https://github.com/crowecawcaw/click-mcp/issues
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Operating System :: OS Independent
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: click>=7.0
25
+ Dynamic: home-page
26
+ Dynamic: license-file
27
+ Dynamic: requires-python
28
+
29
+ # click-mcp
30
+
31
+ A Python library that extends Click applications with Model Context Protocol (MCP) support, allowing AI agents to interact with CLI tools.
32
+
33
+ ## Overview
34
+
35
+ `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.
36
+
37
+ The [Model Context Protocol (MCP)](https://github.com/model-context-protocol/mcp) is an open standard for AI agents to interact with tools and applications in a structured way.
38
+
39
+ ## Key Features
40
+
41
+ - Simple `@click_mcp` decorator syntax
42
+ - Automatic conversion of Click commands to MCP tools
43
+ - Support for nested command groups
44
+ - Stdio-based MCP server for easy integration
45
+
46
+ ## Installation
47
+
48
+ ```bash
49
+ pip install click-mcp
50
+ ```
51
+
52
+ ## Basic Usage
53
+
54
+ ```python
55
+ import click
56
+ from click_mcp import click_mcp
57
+
58
+ @click_mcp
59
+ @click.group()
60
+ def cli():
61
+ """Sample CLI application."""
62
+ pass
63
+
64
+ @cli.command()
65
+ @click.option('--name', required=True, help='Name to greet')
66
+ def greet(name):
67
+ """Greet someone."""
68
+ click.echo(f"Hello, {name}!")
69
+
70
+ if __name__ == '__main__':
71
+ cli()
72
+ ```
73
+
74
+ When you run the MCP server, Click commands are converted into MCP tools:
75
+ - Command `greet` becomes MCP tool `greet`
76
+ - Nested commands use dot notation (e.g., `users.create`)
77
+
78
+ To invoke a command via MCP, send a request like:
79
+
80
+ ```json
81
+ {
82
+ "type": "invoke",
83
+ "tool": "greet",
84
+ "parameters": {
85
+ "name": "World"
86
+ }
87
+ }
88
+ ```
89
+
90
+ To start the MCP server:
91
+
92
+ ```bash
93
+ $ python my_app.py mcp
94
+ ```
95
+
96
+ ## Advanced Usage
97
+
98
+ ### Customizing the MCP Command Name
99
+
100
+ By default, `click-mcp` adds an `mcp` command to your CLI application. You can customize this name using the `command_name` parameter:
101
+
102
+ ```python
103
+ @click_mcp(command_name="start-mcp")
104
+ @click.group()
105
+ def cli():
106
+ """Sample CLI application with custom MCP command name."""
107
+ pass
108
+ ```
109
+
110
+ With this configuration, you would start the MCP server using:
111
+
112
+ ```bash
113
+ $ python my_app.py start-mcp
114
+ ```
115
+
116
+ This can be useful when:
117
+ - The name "mcp" conflicts with an existing command
118
+ - You want a more descriptive command name
119
+ - You're integrating with a specific AI agent that expects a certain command name
120
+
121
+ ### Working with Nested Command Groups
122
+
123
+ `click-mcp` supports nested command groups. When you have a complex CLI structure with subcommands, all commands are exposed as MCP tools:
124
+
125
+ ```python
126
+ @click_mcp
127
+ @click.group()
128
+ def cli():
129
+ """Main CLI application."""
130
+ pass
131
+
132
+ @cli.group()
133
+ def users():
134
+ """User management commands."""
135
+ pass
136
+
137
+ @users.command()
138
+ @click.option('--username', required=True)
139
+ def create(username):
140
+ """Create a new user."""
141
+ click.echo(f"Creating user: {username}")
142
+
143
+ @users.command()
144
+ @click.argument('username')
145
+ def delete(username):
146
+ """Delete a user."""
147
+ click.echo(f"Deleting user: {username}")
148
+ ```
149
+
150
+ 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").
151
+
152
+ ### Handling Command Errors
153
+
154
+ 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:
155
+
156
+ ```python
157
+ @cli.command()
158
+ @click.option('--filename', required=True)
159
+ def process(filename):
160
+ """Process a file."""
161
+ try:
162
+ with open(filename, 'r') as f:
163
+ content = f.read()
164
+ click.echo(f"Processed file: {filename}")
165
+ except FileNotFoundError:
166
+ raise click.UsageError(f"File not found: {filename}")
167
+ ```
168
+
169
+ 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.
170
+
171
+ ## Development
172
+
173
+ ### Setup
174
+
175
+ Clone the repository and install development dependencies:
176
+
177
+ ```bash
178
+ git clone https://github.com/aws/click-mcp.git
179
+ cd click-mcp
180
+ pip install -e ".[dev]"
181
+ ```
182
+
183
+ ### Testing
184
+
185
+ Run tests with pytest:
186
+
187
+ ```bash
188
+ pytest
189
+ ```
190
+
191
+ Run tests with coverage:
192
+
193
+ ```bash
194
+ pytest --cov=click_mcp
195
+ ```
196
+
197
+ ### Code Formatting
198
+
199
+ Format code with black:
200
+
201
+ ```bash
202
+ black click_mcp tests
203
+ ```
204
+
205
+ Run linting checks:
206
+
207
+ ```bash
208
+ flake8 click_mcp tests
209
+ ```
210
+
211
+ ### Building
212
+
213
+ Build the package:
214
+
215
+ ```bash
216
+ python -m build
217
+ ```
218
+
219
+ ### Documentation
220
+
221
+ Generate documentation:
222
+
223
+ ```bash
224
+ cd docs
225
+ make html
226
+ ```
227
+
228
+ ## Related Resources
229
+
230
+ - [Model Context Protocol (MCP) Specification](https://github.com/model-context-protocol/mcp)
231
+ - [Click Documentation](https://click.palletsprojects.com/)
232
+ - [MCP Tools Registry](https://github.com/model-context-protocol/registry) - A collection of MCP-compatible tools
233
+
234
+ ## License
235
+
236
+ MIT
@@ -0,0 +1,208 @@
1
+ # click-mcp
2
+
3
+ A Python library that extends Click applications with Model Context Protocol (MCP) support, allowing AI agents to interact with CLI tools.
4
+
5
+ ## Overview
6
+
7
+ `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.
8
+
9
+ The [Model Context Protocol (MCP)](https://github.com/model-context-protocol/mcp) is an open standard for AI agents to interact with tools and applications in a structured way.
10
+
11
+ ## Key Features
12
+
13
+ - Simple `@click_mcp` decorator syntax
14
+ - Automatic conversion of Click commands to MCP tools
15
+ - Support for nested command groups
16
+ - Stdio-based MCP server for easy integration
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip install click-mcp
22
+ ```
23
+
24
+ ## Basic Usage
25
+
26
+ ```python
27
+ import click
28
+ from click_mcp import click_mcp
29
+
30
+ @click_mcp
31
+ @click.group()
32
+ def cli():
33
+ """Sample CLI application."""
34
+ pass
35
+
36
+ @cli.command()
37
+ @click.option('--name', required=True, help='Name to greet')
38
+ def greet(name):
39
+ """Greet someone."""
40
+ click.echo(f"Hello, {name}!")
41
+
42
+ if __name__ == '__main__':
43
+ cli()
44
+ ```
45
+
46
+ When you run the MCP server, Click commands are converted into MCP tools:
47
+ - Command `greet` becomes MCP tool `greet`
48
+ - Nested commands use dot notation (e.g., `users.create`)
49
+
50
+ To invoke a command via MCP, send a request like:
51
+
52
+ ```json
53
+ {
54
+ "type": "invoke",
55
+ "tool": "greet",
56
+ "parameters": {
57
+ "name": "World"
58
+ }
59
+ }
60
+ ```
61
+
62
+ To start the MCP server:
63
+
64
+ ```bash
65
+ $ python my_app.py mcp
66
+ ```
67
+
68
+ ## Advanced Usage
69
+
70
+ ### Customizing the MCP Command Name
71
+
72
+ By default, `click-mcp` adds an `mcp` command to your CLI application. You can customize this name using the `command_name` parameter:
73
+
74
+ ```python
75
+ @click_mcp(command_name="start-mcp")
76
+ @click.group()
77
+ def cli():
78
+ """Sample CLI application with custom MCP command name."""
79
+ pass
80
+ ```
81
+
82
+ With this configuration, you would start the MCP server using:
83
+
84
+ ```bash
85
+ $ python my_app.py start-mcp
86
+ ```
87
+
88
+ This can be useful when:
89
+ - The name "mcp" conflicts with an existing command
90
+ - You want a more descriptive command name
91
+ - You're integrating with a specific AI agent that expects a certain command name
92
+
93
+ ### Working with Nested Command Groups
94
+
95
+ `click-mcp` supports nested command groups. When you have a complex CLI structure with subcommands, all commands are exposed as MCP tools:
96
+
97
+ ```python
98
+ @click_mcp
99
+ @click.group()
100
+ def cli():
101
+ """Main CLI application."""
102
+ pass
103
+
104
+ @cli.group()
105
+ def users():
106
+ """User management commands."""
107
+ pass
108
+
109
+ @users.command()
110
+ @click.option('--username', required=True)
111
+ def create(username):
112
+ """Create a new user."""
113
+ click.echo(f"Creating user: {username}")
114
+
115
+ @users.command()
116
+ @click.argument('username')
117
+ def delete(username):
118
+ """Delete a user."""
119
+ click.echo(f"Deleting user: {username}")
120
+ ```
121
+
122
+ 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").
123
+
124
+ ### Handling Command Errors
125
+
126
+ 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:
127
+
128
+ ```python
129
+ @cli.command()
130
+ @click.option('--filename', required=True)
131
+ def process(filename):
132
+ """Process a file."""
133
+ try:
134
+ with open(filename, 'r') as f:
135
+ content = f.read()
136
+ click.echo(f"Processed file: {filename}")
137
+ except FileNotFoundError:
138
+ raise click.UsageError(f"File not found: {filename}")
139
+ ```
140
+
141
+ 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.
142
+
143
+ ## Development
144
+
145
+ ### Setup
146
+
147
+ Clone the repository and install development dependencies:
148
+
149
+ ```bash
150
+ git clone https://github.com/aws/click-mcp.git
151
+ cd click-mcp
152
+ pip install -e ".[dev]"
153
+ ```
154
+
155
+ ### Testing
156
+
157
+ Run tests with pytest:
158
+
159
+ ```bash
160
+ pytest
161
+ ```
162
+
163
+ Run tests with coverage:
164
+
165
+ ```bash
166
+ pytest --cov=click_mcp
167
+ ```
168
+
169
+ ### Code Formatting
170
+
171
+ Format code with black:
172
+
173
+ ```bash
174
+ black click_mcp tests
175
+ ```
176
+
177
+ Run linting checks:
178
+
179
+ ```bash
180
+ flake8 click_mcp tests
181
+ ```
182
+
183
+ ### Building
184
+
185
+ Build the package:
186
+
187
+ ```bash
188
+ python -m build
189
+ ```
190
+
191
+ ### Documentation
192
+
193
+ Generate documentation:
194
+
195
+ ```bash
196
+ cd docs
197
+ make html
198
+ ```
199
+
200
+ ## Related Resources
201
+
202
+ - [Model Context Protocol (MCP) Specification](https://github.com/model-context-protocol/mcp)
203
+ - [Click Documentation](https://click.palletsprojects.com/)
204
+ - [MCP Tools Registry](https://github.com/model-context-protocol/registry) - A collection of MCP-compatible tools
205
+
206
+ ## License
207
+
208
+ MIT
@@ -0,0 +1,8 @@
1
+ """
2
+ click-mcp: Extends Click applications with Model Context Protocol (MCP) support.
3
+ """
4
+
5
+ from .decorator import click_mcp
6
+
7
+ __version__ = "0.1.0"
8
+ __all__ = ["click_mcp"]
@@ -0,0 +1,167 @@
1
+ """
2
+ Decorator for adding MCP support to Click applications.
3
+ """
4
+
5
+ from typing import Dict, Any, Optional, Callable
6
+
7
+ import click
8
+
9
+
10
+ # Registry to store MCP metadata for commands
11
+ _mcp_registry = {}
12
+
13
+
14
+ def register_mcp_metadata(command_name: str, metadata: Dict[str, Any]):
15
+ """Register MCP metadata for a command."""
16
+ if command_name not in _mcp_registry:
17
+ _mcp_registry[command_name] = {}
18
+
19
+ _mcp_registry[command_name].update(metadata)
20
+
21
+
22
+ def get_mcp_metadata(command_name: str) -> Dict[str, Any]:
23
+ """Get MCP metadata for a command."""
24
+ return _mcp_registry.get(command_name, {})
25
+
26
+
27
+ class CommandDecorator: # pylint: disable=too-few-public-methods
28
+ """Decorator for customizing MCP command behavior."""
29
+
30
+ def __call__(self, include: bool = True, name: Optional[str] = None) -> Callable:
31
+ """
32
+ Decorator for customizing MCP command behavior.
33
+
34
+ Usage:
35
+ @cli.command()
36
+ @click_mcp.command(include=True, name="custom-name")
37
+ def my_command():
38
+ \"\"\"Command with custom MCP settings.\"\"\"
39
+ pass
40
+
41
+ Args:
42
+ include: Whether to include this command in MCP tools (default: True).
43
+ name: Custom name to use for this command in MCP tools.
44
+
45
+ Returns:
46
+ A decorator function.
47
+ """
48
+
49
+ def decorator(f):
50
+ # Store metadata directly in the function object
51
+ if not hasattr(f, "_mcp_metadata"): # pylint: disable=protected-access
52
+ f._mcp_metadata = {} # pylint: disable=protected-access
53
+
54
+ f._mcp_metadata["include"] = include # pylint: disable=protected-access
55
+ if name:
56
+ f._mcp_metadata["name"] = name # pylint: disable=protected-access
57
+
58
+ # Register metadata with the command name
59
+ if hasattr(f, "name"):
60
+ register_mcp_metadata(
61
+ f.name, f._mcp_metadata
62
+ ) # pylint: disable=protected-access
63
+
64
+ # For Click commands, we need to add a callback to register metadata
65
+ # when the command is created
66
+ original_callback = f.callback if hasattr(f, "callback") else None
67
+
68
+ def _register_mcp_metadata(ctx, param, value):
69
+ cmd = ctx.command
70
+ register_mcp_metadata(cmd.name, {"include": include, "name": name})
71
+
72
+ if original_callback:
73
+ return original_callback(ctx, param, value)
74
+ return value
75
+
76
+ f = click.option(
77
+ "--_mcp_register",
78
+ is_flag=True,
79
+ hidden=True,
80
+ expose_value=False,
81
+ callback=_register_mcp_metadata,
82
+ )(f)
83
+
84
+ return f
85
+
86
+ return decorator
87
+
88
+
89
+ # Create a command decorator instance
90
+ command = CommandDecorator()
91
+
92
+
93
+ def click_mcp(
94
+ cli_group=None, command_name: str = "mcp", include_all_commands: bool = True
95
+ ):
96
+ """
97
+ Decorator that adds MCP support to a Click application.
98
+
99
+ Usage:
100
+ @click_mcp
101
+ @click.group()
102
+ def cli():
103
+ \"\"\"Sample CLI application.\"\"\"
104
+ pass
105
+
106
+ # Or with custom command name:
107
+ @click_mcp(command_name="start-mcp")
108
+ @click.group()
109
+ def cli():
110
+ \"\"\"Sample CLI application.\"\"\"
111
+ pass
112
+
113
+ # Or with selective command inclusion:
114
+ @click_mcp(include_all_commands=False)
115
+ @click.group()
116
+ def cli():
117
+ \"\"\"Only expose specific commands as MCP tools.\"\"\"
118
+ pass
119
+
120
+ Args:
121
+ cli_group: A Click Group object to extend with MCP support.
122
+ command_name: Name of the MCP command to add (default: "mcp").
123
+ include_all_commands: Whether to include all commands by default (default: True).
124
+
125
+ Returns:
126
+ The decorated Click group or a decorator function.
127
+ """
128
+ # Add the command decorator to the click_mcp namespace
129
+ click_mcp.command = command # type: ignore
130
+
131
+ # Handle case when used as @click_mcp or @click_mcp(command_name="...")
132
+ if cli_group is None:
133
+ return lambda f: _add_mcp_support(f, command_name, include_all_commands)
134
+
135
+ # Handle case when used as click_mcp(cli_group)
136
+ return _add_mcp_support(cli_group, command_name, include_all_commands)
137
+
138
+
139
+ def _add_mcp_support(cli_group, command_name: str, include_all_commands: bool):
140
+ """Add MCP support to a Click group."""
141
+ if not isinstance(cli_group, (click.Command, click.Group)):
142
+ raise TypeError(
143
+ f"@click_mcp decorator must be applied to a Click command or group. "
144
+ f"Got {type(cli_group).__name__} instead."
145
+ )
146
+
147
+ if not isinstance(cli_group, click.Group):
148
+ raise TypeError(
149
+ f"@click_mcp decorator must be applied to a Click group, not a Click command. "
150
+ f"Got {type(cli_group).__name__} instead."
151
+ )
152
+
153
+ register_mcp_metadata(
154
+ cli_group.name, {"include_all_commands": include_all_commands}
155
+ )
156
+
157
+ @cli_group.command(command_name)
158
+ def mcp_command():
159
+ """Start an MCP server for this CLI application."""
160
+ # Import here to avoid circular imports
161
+ # pylint: disable=import-outside-toplevel,cyclic-import
162
+ from .server import MCPServer
163
+
164
+ mcp_server = MCPServer(cli_group)
165
+ mcp_server.run()
166
+
167
+ return cli_group