click-mcp 0.1.0__py3-none-any.whl
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.
- click_mcp/__init__.py +8 -0
- click_mcp/decorator.py +167 -0
- click_mcp/scanner.py +185 -0
- click_mcp/server.py +176 -0
- click_mcp-0.1.0.dist-info/METADATA +236 -0
- click_mcp-0.1.0.dist-info/RECORD +19 -0
- click_mcp-0.1.0.dist-info/WHEEL +5 -0
- click_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
- click_mcp-0.1.0.dist-info/top_level.txt +2 -0
- tests/__init__.py +3 -0
- tests/conftest.py +39 -0
- tests/integration/test_advanced_cli.py +51 -0
- tests/integration/test_cli.py +51 -0
- tests/integration/test_integration.py +218 -0
- tests/test_command_inclusion.py +119 -0
- tests/test_decorator.py +114 -0
- tests/test_name_override.py +100 -0
- tests/test_scanner.py +107 -0
- tests/test_server.py +129 -0
click_mcp/__init__.py
ADDED
click_mcp/decorator.py
ADDED
|
@@ -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
|
click_mcp/scanner.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Scanner for converting Click commands to MCP tools.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Dict, Any, List, Optional
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from .decorator import get_mcp_metadata
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def scan_click_command(command, parent_path: str = "") -> List[Dict[str, Any]]:
|
|
13
|
+
"""
|
|
14
|
+
Scan a Click command or group and convert it to MCP tools.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
command: A Click command or group.
|
|
18
|
+
parent_path: Path of parent commands (for nested commands).
|
|
19
|
+
|
|
20
|
+
Returns:
|
|
21
|
+
A list of MCP tool definitions.
|
|
22
|
+
"""
|
|
23
|
+
tools = []
|
|
24
|
+
|
|
25
|
+
if isinstance(command, click.Group):
|
|
26
|
+
group_metadata = get_mcp_metadata(command.name)
|
|
27
|
+
include_all_commands = group_metadata.get("include_all_commands", True)
|
|
28
|
+
|
|
29
|
+
for name, cmd in command.commands.items(): # pylint: disable=too-many-branches
|
|
30
|
+
# Skip MCP commands
|
|
31
|
+
if name == "mcp" or name.endswith("-mcp") or name == "start-mcp":
|
|
32
|
+
continue
|
|
33
|
+
|
|
34
|
+
# Build command path
|
|
35
|
+
if parent_path:
|
|
36
|
+
cmd_path = f"{parent_path}.{name}"
|
|
37
|
+
else:
|
|
38
|
+
cmd_path = name
|
|
39
|
+
|
|
40
|
+
# Check if command should be included
|
|
41
|
+
should_include = _should_include_command(cmd, include_all_commands)
|
|
42
|
+
if not should_include:
|
|
43
|
+
continue
|
|
44
|
+
|
|
45
|
+
# Get custom name if specified
|
|
46
|
+
custom_name = _get_custom_command_name(cmd)
|
|
47
|
+
if custom_name:
|
|
48
|
+
if parent_path:
|
|
49
|
+
tool_name = f"{parent_path}.{custom_name}"
|
|
50
|
+
else:
|
|
51
|
+
tool_name = custom_name
|
|
52
|
+
else:
|
|
53
|
+
tool_name = cmd_path
|
|
54
|
+
|
|
55
|
+
# Handle nested groups
|
|
56
|
+
if isinstance(cmd, click.Group):
|
|
57
|
+
# Add the group itself as a tool if it has a custom name
|
|
58
|
+
if custom_name:
|
|
59
|
+
group_tool = _create_tool_from_command(cmd, tool_name)
|
|
60
|
+
tools.append(group_tool)
|
|
61
|
+
|
|
62
|
+
# Set new parent path for nested commands
|
|
63
|
+
if parent_path:
|
|
64
|
+
new_parent_path = f"{parent_path}.{custom_name}"
|
|
65
|
+
else:
|
|
66
|
+
new_parent_path = custom_name
|
|
67
|
+
else:
|
|
68
|
+
new_parent_path = cmd_path
|
|
69
|
+
|
|
70
|
+
# Add nested commands
|
|
71
|
+
tools.extend(scan_click_command(cmd, new_parent_path))
|
|
72
|
+
else:
|
|
73
|
+
# Create tool for command
|
|
74
|
+
tool = _create_tool_from_command(cmd, tool_name)
|
|
75
|
+
tools.append(tool)
|
|
76
|
+
|
|
77
|
+
return tools
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _should_include_command(command, default_include: bool) -> bool:
|
|
81
|
+
"""Determine if a command should be included in MCP tools."""
|
|
82
|
+
cmd_metadata = get_mcp_metadata(command.name)
|
|
83
|
+
|
|
84
|
+
# If command has explicit include/exclude setting, use that
|
|
85
|
+
if "include" in cmd_metadata:
|
|
86
|
+
return cmd_metadata["include"]
|
|
87
|
+
|
|
88
|
+
# For Click commands with callback, check if the callback has metadata
|
|
89
|
+
if hasattr(command, "callback") and hasattr(command.callback, "_mcp_metadata"):
|
|
90
|
+
# pylint: disable=protected-access
|
|
91
|
+
metadata = command.callback._mcp_metadata
|
|
92
|
+
if "include" in metadata:
|
|
93
|
+
return metadata["include"]
|
|
94
|
+
|
|
95
|
+
# Otherwise use the default from the parent group
|
|
96
|
+
return default_include
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _get_custom_command_name(command) -> Optional[str]:
|
|
100
|
+
"""Get custom name for a command if specified."""
|
|
101
|
+
# First check command metadata
|
|
102
|
+
cmd_metadata = get_mcp_metadata(command.name)
|
|
103
|
+
if "name" in cmd_metadata:
|
|
104
|
+
return cmd_metadata["name"]
|
|
105
|
+
|
|
106
|
+
# Then check callback metadata
|
|
107
|
+
if hasattr(command, "callback") and hasattr(command.callback, "_mcp_metadata"):
|
|
108
|
+
# pylint: disable=protected-access
|
|
109
|
+
metadata = command.callback._mcp_metadata
|
|
110
|
+
if "name" in metadata:
|
|
111
|
+
return metadata["name"]
|
|
112
|
+
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _create_tool_from_command(command, name: str) -> Dict[str, Any]:
|
|
117
|
+
"""Create an MCP tool definition from a Click command."""
|
|
118
|
+
description = command.help
|
|
119
|
+
|
|
120
|
+
if not description:
|
|
121
|
+
description = f"Execute the {name} command"
|
|
122
|
+
|
|
123
|
+
tool = {
|
|
124
|
+
"name": name,
|
|
125
|
+
"description": description,
|
|
126
|
+
"parameters": _get_parameters_from_command(command),
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return tool
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _get_parameters_from_command(command) -> Dict[str, Any]:
|
|
133
|
+
"""Extract parameters from a Click command."""
|
|
134
|
+
parameters = {}
|
|
135
|
+
|
|
136
|
+
for param in command.params:
|
|
137
|
+
# Skip hidden MCP parameters
|
|
138
|
+
if param.name == "_mcp_register" and param.hidden:
|
|
139
|
+
continue
|
|
140
|
+
|
|
141
|
+
# Get parameter description
|
|
142
|
+
if hasattr(param, "help"):
|
|
143
|
+
description = param.help or f"Parameter {param.name}"
|
|
144
|
+
else:
|
|
145
|
+
description = f"Parameter {param.name}"
|
|
146
|
+
|
|
147
|
+
param_def = {
|
|
148
|
+
"type": _get_param_type(param),
|
|
149
|
+
"description": description,
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
# Add required flag
|
|
153
|
+
if param.required:
|
|
154
|
+
param_def["required"] = True
|
|
155
|
+
|
|
156
|
+
# Add default value if present
|
|
157
|
+
if param.default is not None and param.default != ():
|
|
158
|
+
param_def["default"] = param.default
|
|
159
|
+
|
|
160
|
+
# Add enum values for choices
|
|
161
|
+
if (
|
|
162
|
+
hasattr(param, "type")
|
|
163
|
+
and hasattr(param.type, "choices")
|
|
164
|
+
and param.type.choices
|
|
165
|
+
):
|
|
166
|
+
param_def["enum"] = list(param.type.choices)
|
|
167
|
+
|
|
168
|
+
parameters[param.name] = param_def
|
|
169
|
+
|
|
170
|
+
return parameters
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _get_param_type(param) -> str:
|
|
174
|
+
"""Determine the MCP parameter type from a Click parameter."""
|
|
175
|
+
if hasattr(param, "is_flag") and param.is_flag:
|
|
176
|
+
return "boolean"
|
|
177
|
+
if hasattr(param, "type"):
|
|
178
|
+
if param.type.name == "integer":
|
|
179
|
+
return "integer"
|
|
180
|
+
if param.type.name == "float":
|
|
181
|
+
return "number"
|
|
182
|
+
if param.type.name == "boolean":
|
|
183
|
+
return "boolean"
|
|
184
|
+
|
|
185
|
+
return "string"
|
click_mcp/server.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MCP server implementation for Click applications.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
import io
|
|
8
|
+
import contextlib
|
|
9
|
+
from typing import Dict, Any
|
|
10
|
+
|
|
11
|
+
from .scanner import scan_click_command
|
|
12
|
+
from .decorator import get_mcp_metadata
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MCPServer: # pylint: disable=too-few-public-methods
|
|
16
|
+
"""MCP server for Click applications."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, cli_group):
|
|
19
|
+
"""
|
|
20
|
+
Initialize the MCP server.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
cli_group: A Click group to expose as MCP tools.
|
|
24
|
+
"""
|
|
25
|
+
self.cli_group = cli_group
|
|
26
|
+
self.tools = scan_click_command(cli_group)
|
|
27
|
+
self.tool_map = {tool["name"]: tool for tool in self.tools}
|
|
28
|
+
|
|
29
|
+
def run(self):
|
|
30
|
+
"""Run the MCP server with stdio transport."""
|
|
31
|
+
self._send_response(
|
|
32
|
+
{"type": "server_info", "version": "1.0", "tools": self.tools}
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
for line in sys.stdin:
|
|
36
|
+
try:
|
|
37
|
+
request = json.loads(line)
|
|
38
|
+
|
|
39
|
+
if request["type"] == "invoke":
|
|
40
|
+
self._handle_invoke(request)
|
|
41
|
+
else:
|
|
42
|
+
self._send_error(f"Unknown request type: {request['type']}")
|
|
43
|
+
except json.JSONDecodeError:
|
|
44
|
+
self._send_error("Invalid JSON request")
|
|
45
|
+
except Exception as e: # pylint: disable=broad-except
|
|
46
|
+
self._send_error(f"Error processing request: {str(e)}")
|
|
47
|
+
|
|
48
|
+
def _handle_invoke(self, request):
|
|
49
|
+
try:
|
|
50
|
+
tool_name = request["tool"]
|
|
51
|
+
parameters = request.get("parameters", {})
|
|
52
|
+
|
|
53
|
+
if tool_name not in self.tool_map:
|
|
54
|
+
self._send_error(f"Unknown tool: {tool_name}")
|
|
55
|
+
return
|
|
56
|
+
|
|
57
|
+
result = self._execute_command(tool_name, parameters)
|
|
58
|
+
|
|
59
|
+
self._send_response(
|
|
60
|
+
{"type": "invoke_response", "id": request.get("id"), "result": result}
|
|
61
|
+
)
|
|
62
|
+
except Exception as e: # pylint: disable=broad-except
|
|
63
|
+
self._send_error(f"Error invoking tool {request.get('tool')}: {str(e)}")
|
|
64
|
+
|
|
65
|
+
def _execute_command(
|
|
66
|
+
self, tool_name: str, parameters: Dict[str, Any]
|
|
67
|
+
) -> Dict[str, Any]:
|
|
68
|
+
# pylint: disable=too-many-locals,too-many-branches
|
|
69
|
+
# Parse the tool name to get the command path
|
|
70
|
+
command_path = tool_name.split(".")
|
|
71
|
+
|
|
72
|
+
# Find the command in the CLI group
|
|
73
|
+
command = self._find_command(self.cli_group, command_path)
|
|
74
|
+
|
|
75
|
+
# Build command arguments
|
|
76
|
+
args = []
|
|
77
|
+
positional_args = []
|
|
78
|
+
|
|
79
|
+
# Separate options and arguments
|
|
80
|
+
option_names = set()
|
|
81
|
+
argument_names = set()
|
|
82
|
+
|
|
83
|
+
for param in command.params:
|
|
84
|
+
if hasattr(param, "opts"): # It's an option
|
|
85
|
+
option_names.add(param.name)
|
|
86
|
+
else: # It's an argument
|
|
87
|
+
argument_names.add(param.name)
|
|
88
|
+
|
|
89
|
+
# Process options
|
|
90
|
+
for param_name, param_value in parameters.items():
|
|
91
|
+
if param_name in option_names:
|
|
92
|
+
param = next(p for p in command.params if p.name == param_name)
|
|
93
|
+
|
|
94
|
+
# Handle boolean flags
|
|
95
|
+
if hasattr(param, "is_flag") and param.is_flag:
|
|
96
|
+
if param_value:
|
|
97
|
+
args.append(f"--{param_name}")
|
|
98
|
+
# Handle regular options
|
|
99
|
+
else:
|
|
100
|
+
args.append(f"--{param_name}")
|
|
101
|
+
args.append(str(param_value))
|
|
102
|
+
elif param_name in argument_names:
|
|
103
|
+
# Store arguments separately to add them in the correct order
|
|
104
|
+
positional_args.append((param_name, param_value))
|
|
105
|
+
|
|
106
|
+
# Add positional arguments in the correct order
|
|
107
|
+
for param in command.params:
|
|
108
|
+
if param.name in argument_names:
|
|
109
|
+
for arg_name, arg_value in positional_args:
|
|
110
|
+
if arg_name == param.name:
|
|
111
|
+
args.append(str(arg_value))
|
|
112
|
+
|
|
113
|
+
# Capture the command output
|
|
114
|
+
output = io.StringIO()
|
|
115
|
+
with contextlib.redirect_stdout(output):
|
|
116
|
+
try:
|
|
117
|
+
# Create a new context and invoke the command
|
|
118
|
+
ctx = command.make_context(command.name, args)
|
|
119
|
+
command.invoke(ctx)
|
|
120
|
+
except Exception as e: # pylint: disable=broad-except
|
|
121
|
+
raise ValueError(f"Command execution failed: {str(e)}") from e
|
|
122
|
+
|
|
123
|
+
# Return the captured output
|
|
124
|
+
return {"output": output.getvalue().rstrip()}
|
|
125
|
+
|
|
126
|
+
def _find_command(self, group, path):
|
|
127
|
+
"""Find a command in a group by path."""
|
|
128
|
+
if not path:
|
|
129
|
+
return group
|
|
130
|
+
|
|
131
|
+
current = path[0]
|
|
132
|
+
remaining = path[1:]
|
|
133
|
+
|
|
134
|
+
# Try to find the command by name
|
|
135
|
+
if current in group.commands:
|
|
136
|
+
cmd = group.commands[current]
|
|
137
|
+
else:
|
|
138
|
+
# Try to find a command with a custom name
|
|
139
|
+
cmd = None
|
|
140
|
+
for cmd_name, command in group.commands.items():
|
|
141
|
+
# Check command metadata
|
|
142
|
+
metadata = get_mcp_metadata(cmd_name)
|
|
143
|
+
if metadata.get("name") == current:
|
|
144
|
+
cmd = command
|
|
145
|
+
break
|
|
146
|
+
|
|
147
|
+
# Check callback metadata
|
|
148
|
+
if hasattr(command, "callback") and hasattr(
|
|
149
|
+
command.callback, "_mcp_metadata"
|
|
150
|
+
):
|
|
151
|
+
# pylint: disable=protected-access
|
|
152
|
+
callback_metadata = command.callback._mcp_metadata
|
|
153
|
+
if callback_metadata.get("name") == current:
|
|
154
|
+
cmd = command
|
|
155
|
+
break
|
|
156
|
+
|
|
157
|
+
if cmd is None:
|
|
158
|
+
raise ValueError(f"Command not found: {current}")
|
|
159
|
+
|
|
160
|
+
# If there are more path segments, the command must be a group
|
|
161
|
+
if remaining and not hasattr(cmd, "commands"):
|
|
162
|
+
raise ValueError(f"'{current}' is not a command group")
|
|
163
|
+
|
|
164
|
+
# If this is the last segment, return the command
|
|
165
|
+
if not remaining:
|
|
166
|
+
return cmd
|
|
167
|
+
|
|
168
|
+
# Otherwise, continue searching in the subgroup
|
|
169
|
+
return self._find_command(cmd, remaining)
|
|
170
|
+
|
|
171
|
+
def _send_response(self, response: Dict[str, Any]):
|
|
172
|
+
sys.stdout.write(json.dumps(response) + "\n")
|
|
173
|
+
sys.stdout.flush()
|
|
174
|
+
|
|
175
|
+
def _send_error(self, message: str):
|
|
176
|
+
self._send_response({"type": "error", "message": message})
|