cli-mcp-server 0.2.3__py3-none-any.whl → 0.2.4__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.
cli_mcp_server/server.py CHANGED
@@ -49,6 +49,7 @@ class SecurityConfig:
49
49
  command_timeout: int
50
50
  allow_all_commands: bool = False
51
51
  allow_all_flags: bool = False
52
+ allow_shell_operators: bool = False
52
53
 
53
54
 
54
55
  class CommandExecutor:
@@ -87,29 +88,103 @@ class CommandExecutor:
87
88
  """
88
89
  Validates and parses a command string for security and formatting.
89
90
 
90
- Checks the command string for unsupported shell operators and splits it into
91
- command and arguments. Only single commands without shell operators are allowed.
91
+ Checks if the command string contains shell operators. If it does, splits the command
92
+ by operators and validates each part individually. If all parts are valid, returns
93
+ the original command string to be executed with shell=True.
94
+
95
+ For commands without shell operators, splits into command and arguments and validates
96
+ each part according to security rules.
92
97
 
93
98
  Args:
94
99
  command_string (str): The command string to validate and parse.
95
100
 
96
101
  Returns:
97
102
  tuple[str, List[str]]: A tuple containing:
98
- - The command name (str)
99
- - List of command arguments (List[str])
103
+ - For regular commands: The command name (str) and list of arguments (List[str])
104
+ - For commands with shell operators: The full command string and empty args list
100
105
 
101
106
  Raises:
102
- CommandSecurityError: If the command contains unsupported shell operators.
107
+ CommandSecurityError: If any part of the command fails security validation.
103
108
  """
104
109
 
105
- # Check for shell operators that we don't support
110
+ # Define shell operators
106
111
  shell_operators = ["&&", "||", "|", ">", ">>", "<", "<<", ";"]
107
- for operator in shell_operators:
108
- if operator in command_string:
109
- raise CommandSecurityError(
110
- f"Shell operator '{operator}' is not supported"
111
- )
112
112
 
113
+ # Check if command contains shell operators
114
+ contains_shell_operator = any(
115
+ operator in command_string for operator in shell_operators
116
+ )
117
+
118
+ if contains_shell_operator:
119
+ # Check if shell operators are allowed
120
+ if not self.security_config.allow_shell_operators:
121
+ # If shell operators are not allowed, raise an error
122
+ for operator in shell_operators:
123
+ if operator in command_string:
124
+ raise CommandSecurityError(
125
+ f"Shell operator '{operator}' is not supported. Set ALLOW_SHELL_OPERATORS=true to enable."
126
+ )
127
+
128
+ # Split the command by shell operators and validate each part
129
+ return self._validate_command_with_operators(
130
+ command_string, shell_operators
131
+ )
132
+
133
+ # Process single command without shell operators
134
+ return self._validate_single_command(command_string)
135
+
136
+ def _is_url_path(self, path: str) -> bool:
137
+ """
138
+ Checks if a given path is a URL of type http or https.
139
+
140
+ Args:
141
+ path (str): The path to check.
142
+
143
+ Returns:
144
+ bool: True if the path is a URL, False otherwise.
145
+ """
146
+ url_pattern = re.compile(r"^https?://")
147
+ return bool(url_pattern.match(path))
148
+
149
+ def _is_path_safe(self, path: str) -> bool:
150
+ """
151
+ Checks if a given path is safe to access within allowed directory boundaries.
152
+
153
+ Validates that the absolute resolved path is within the allowed directory
154
+ to prevent directory traversal attacks.
155
+
156
+ Args:
157
+ path (str): The path to validate.
158
+
159
+ Returns:
160
+ bool: True if path is within allowed directory, False otherwise.
161
+ Returns False if path resolution fails for any reason.
162
+
163
+ Private method intended for internal use only.
164
+ """
165
+ try:
166
+ # Resolve any symlinks and get absolute path
167
+ real_path = os.path.abspath(os.path.realpath(path))
168
+ allowed_dir_real = os.path.abspath(os.path.realpath(self.allowed_dir))
169
+
170
+ # Check if the path starts with allowed_dir
171
+ return real_path.startswith(allowed_dir_real)
172
+ except Exception:
173
+ return False
174
+
175
+ def _validate_single_command(self, command_string: str) -> tuple[str, List[str]]:
176
+ """
177
+ Validates a single command without shell operators.
178
+
179
+ Args:
180
+ command_string (str): The command string to validate.
181
+
182
+ Returns:
183
+ tuple[str, List[str]]: A tuple containing the command and validated arguments.
184
+
185
+ Raises:
186
+ CommandSecurityError: If the command fails validation.
187
+ """
113
188
  try:
114
189
  parts = shlex.split(command_string)
115
190
  if not parts:
@@ -154,44 +229,69 @@ class CommandExecutor:
154
229
  except ValueError as e:
155
230
  raise CommandSecurityError(f"Invalid command format: {str(e)}")
156
231
 
157
- def _is_url_path(self, path: str) -> bool:
158
- """
159
- Checks if a given path is a URL of type http or https.
160
-
161
- Args:
162
- path (str): The path to check.
163
-
164
- Returns:
165
- bool: True if the path is a URL, False otherwise.
166
- """
167
- url_pattern = re.compile(r"^https?://")
168
- return bool(url_pattern.match(path))
169
-
170
- def _is_path_safe(self, path: str) -> bool:
232
+ def _validate_command_with_operators(
233
+ self, command_string: str, shell_operators: List[str]
234
+ ) -> tuple[str, List[str]]:
171
235
  """
172
- Checks if a given path is safe to access within allowed directory boundaries.
236
+ Validates a command string that contains shell operators.
173
237
 
174
- Validates that the absolute resolved path is within the allowed directory
175
- to prevent directory traversal attacks.
238
+ Splits the command string by shell operators and validates each part individually.
239
+ If all parts are valid, returns the original command to be executed with shell=True.
176
240
 
177
241
  Args:
178
- path (str): The path to validate.
242
+ command_string (str): The command string containing shell operators.
243
+ shell_operators (List[str]): List of shell operators to split by.
179
244
 
180
245
  Returns:
181
- bool: True if path is within allowed directory, False otherwise.
182
- Returns False if path resolution fails for any reason.
246
+ tuple[str, List[str]]: A tuple containing the command and empty args list
247
+ (since the command will be executed with shell=True)
183
248
 
184
- Private method intended for internal use only.
249
+ Raises:
250
+ CommandSecurityError: If any part of the command fails validation.
185
251
  """
186
- try:
187
- # Resolve any symlinks and get absolute path
188
- real_path = os.path.abspath(os.path.realpath(path))
189
- allowed_dir_real = os.path.abspath(os.path.realpath(self.allowed_dir))
252
+ # Create a regex pattern to split by any of the shell operators
253
+ # We need to escape special regex characters in the operators
254
+ escaped_operators = [re.escape(op) for op in shell_operators]
255
+ pattern = "|".join(escaped_operators)
256
+
257
+ # Split the command string by shell operators, keeping the operators
258
+ parts = re.split(f"({pattern})", command_string)
259
+
260
+ # Filter out empty parts and whitespace-only parts
261
+ parts = [part.strip() for part in parts if part.strip()]
262
+
263
+ # Group commands and operators
264
+ commands = []
265
+ i = 0
266
+ while i < len(parts):
267
+ if i + 1 < len(parts) and parts[i + 1] in shell_operators:
268
+ # If next part is an operator, current part is a command
269
+ if parts[i]: # Skip empty commands
270
+ commands.append(parts[i])
271
+ i += 2 # Skip the operator
272
+ else:
273
+ # If no operator follows, this is the last command
274
+ if (
275
+ parts[i] and parts[i] not in shell_operators
276
+ ): # Skip if it's an operator
277
+ commands.append(parts[i])
278
+ i += 1
279
+
280
+ # Validate each command individually
281
+ for cmd in commands:
282
+ try:
283
+ # Use the extracted validation method for each command
284
+ self._validate_single_command(cmd)
285
+ except CommandSecurityError as e:
286
+ raise CommandSecurityError(f"Invalid command part '{cmd}': {str(e)}")
287
+ except ValueError as e:
288
+ raise CommandSecurityError(
289
+ f"Invalid command format in '{cmd}': {str(e)}"
290
+ )
190
291
 
191
- # Check if the path starts with allowed_dir
192
- return real_path.startswith(allowed_dir_real)
193
- except Exception:
194
- return False
292
+ # If we get here, all commands passed validation
293
+ # Return the original command string to be executed with shell=True
294
+ return command_string, []
195
295
 
196
296
  def execute(self, command_string: str) -> subprocess.CompletedProcess:
197
297
  """
@@ -210,12 +310,11 @@ class CommandExecutor:
210
310
  Raises:
211
311
  CommandSecurityError: If the command:
212
312
  - Exceeds maximum length
213
- - Contains invalid shell operators
214
313
  - Fails security validation
215
314
  - Fails during execution
216
315
 
217
316
  Notes:
218
- - Executes with shell=False for security
317
+ - Uses shell=True for commands with shell operators, shell=False otherwise
219
318
  - Uses timeout and working directory constraints
220
319
  - Captures both stdout and stderr
221
320
  """
@@ -227,14 +326,38 @@ class CommandExecutor:
227
326
  try:
228
327
  command, args = self.validate_command(command_string)
229
328
 
230
- return subprocess.run(
231
- [command] + args,
232
- shell=False,
233
- text=True,
234
- capture_output=True,
235
- timeout=self.security_config.command_timeout,
236
- cwd=self.allowed_dir,
237
- )
329
+ # Check if this is a command with shell operators
330
+ shell_operators = ["&&", "||", "|", ">", ">>", "<", "<<", ";"]
331
+ use_shell = any(operator in command_string for operator in shell_operators)
332
+
333
+ # Double-check that shell operators are allowed if they are present
334
+ if use_shell and not self.security_config.allow_shell_operators:
335
+ for operator in shell_operators:
336
+ if operator in command_string:
337
+ raise CommandSecurityError(
338
+ f"Shell operator '{operator}' is not supported. Set ALLOW_SHELL_OPERATORS=true to enable."
339
+ )
340
+
341
+ if use_shell:
342
+ # For commands with shell operators, execute with shell=True
343
+ return subprocess.run(
344
+ command, # command is the full command string in this case
345
+ shell=True,
346
+ text=True,
347
+ capture_output=True,
348
+ timeout=self.security_config.command_timeout,
349
+ cwd=self.allowed_dir,
350
+ )
351
+ else:
352
+ # For regular commands, execute with shell=False
353
+ return subprocess.run(
354
+ [command] + args,
355
+ shell=False,
356
+ text=True,
357
+ capture_output=True,
358
+ timeout=self.security_config.command_timeout,
359
+ cwd=self.allowed_dir,
360
+ )
238
361
  except subprocess.TimeoutExpired:
239
362
  raise CommandTimeoutError(
240
363
  f"Command timed out after {self.security_config.command_timeout} seconds"
@@ -262,18 +385,23 @@ def load_security_config() -> SecurityConfig:
262
385
  - command_timeout: Maximum execution time in seconds
263
386
  - allow_all_commands: Whether all commands are allowed
264
387
  - allow_all_flags: Whether all flags are allowed
388
+ - allow_shell_operators: Whether shell operators (&&, ||, |, etc.) are allowed
265
389
 
266
390
  Environment Variables:
267
391
  ALLOWED_COMMANDS: Comma-separated list of allowed commands or 'all' (default: "ls,cat,pwd")
268
392
  ALLOWED_FLAGS: Comma-separated list of allowed flags or 'all' (default: "-l,-a,--help")
269
393
  MAX_COMMAND_LENGTH: Maximum command string length (default: 1024)
270
394
  COMMAND_TIMEOUT: Command timeout in seconds (default: 30)
395
+ ALLOW_SHELL_OPERATORS: Whether to allow shell operators like &&, ||, |, >, etc. (default: false)
396
+ Set to "true" or "1" to enable, any other value to disable.
271
397
  """
272
398
  allowed_commands = os.getenv("ALLOWED_COMMANDS", "ls,cat,pwd")
273
399
  allowed_flags = os.getenv("ALLOWED_FLAGS", "-l,-a,--help")
400
+ allow_shell_operators_env = os.getenv("ALLOW_SHELL_OPERATORS", "false")
274
401
 
275
402
  allow_all_commands = allowed_commands.lower() == "all"
276
403
  allow_all_flags = allowed_flags.lower() == "all"
404
+ allow_shell_operators = allow_shell_operators_env.lower() in ("true", "1")
277
405
 
278
406
  return SecurityConfig(
279
407
  allowed_commands=(
@@ -284,6 +412,7 @@ def load_security_config() -> SecurityConfig:
284
412
  command_timeout=int(os.getenv("COMMAND_TIMEOUT", "30")),
285
413
  allow_all_commands=allow_all_commands,
286
414
  allow_all_flags=allow_all_flags,
415
+ allow_shell_operators=allow_shell_operators,
287
416
  )
288
417
 
289
418
 
@@ -312,7 +441,7 @@ async def handle_list_tools() -> list[types.Tool]:
312
441
  f"Allows command (CLI) execution in the directory: {executor.allowed_dir}\n\n"
313
442
  f"Available commands: {commands_desc}\n"
314
443
  f"Available flags: {flags_desc}\n\n"
315
- "Note: Shell operators (&&, |, >, >>) are not supported."
444
+ f"Shell operators (&&, ||, |, >, >>, <, <<, ;) are {'supported' if executor.security_config.allow_shell_operators else 'not supported'}. Set ALLOW_SHELL_OPERATORS=true to enable."
316
445
  ),
317
446
  inputSchema={
318
447
  "type": "object",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cli-mcp-server
3
- Version: 0.2.3
3
+ Version: 0.2.4
4
4
  Summary: Command line interface for MCP clients with secure execution and customizable security policies
5
5
  Project-URL: Homepage, https://github.com/MladenSU/cli-mcp-server
6
6
  Project-URL: Documentation, https://github.com/MladenSU/cli-mcp-server#readme
@@ -23,6 +23,7 @@ comprehensive security features.
23
23
  ![Python Version](https://img.shields.io/badge/python-3.10%2B-blue)
24
24
  ![MCP Protocol](https://img.shields.io/badge/MCP-Compatible-green)
25
25
  [![smithery badge](https://smithery.ai/badge/cli-mcp-server)](https://smithery.ai/protocol/cli-mcp-server)
26
+ [![Python Tests](https://github.com/MladenSU/cli-mcp-server/actions/workflows/python-tests.yml/badge.svg)](https://github.com/MladenSU/cli-mcp-server/actions/workflows/python-tests.yml)
26
27
 
27
28
  <a href="https://glama.ai/mcp/servers/q89277vzl1"><img width="380" height="200" src="https://glama.ai/mcp/servers/q89277vzl1/badge" /></a>
28
29
 
@@ -76,6 +77,7 @@ Configure the server using environment variables:
76
77
  | `ALLOWED_FLAGS` | Comma-separated list of allowed flags or 'all' | `-l,-a,--help` |
77
78
  | `MAX_COMMAND_LENGTH`| Maximum command string length | `1024` |
78
79
  | `COMMAND_TIMEOUT` | Command execution timeout (seconds) | `30` |
80
+ | `ALLOW_SHELL_OPERATORS` | Allow shell operators (&&, \|\|, \|, >, etc.) | `false` |
79
81
 
80
82
  Note: Setting `ALLOWED_COMMANDS` or `ALLOWED_FLAGS` to 'all' will allow any command or flag respectively.
81
83
 
@@ -104,7 +106,7 @@ Executes whitelisted CLI commands within allowed directories.
104
106
  ```
105
107
 
106
108
  **Security Notes:**
107
- - Shell operators (&&, |, >, >>) are not supported
109
+ - Shell operators (&&, |, >, >>) are not supported by default, but can be enabled with `ALLOW_SHELL_OPERATORS=true`
108
110
  - Commands must be whitelisted unless ALLOWED_COMMANDS='all'
109
111
  - Flags must be whitelisted unless ALLOWED_FLAGS='all'
110
112
  - All paths are validated to be within ALLOWED_DIR
@@ -139,7 +141,8 @@ Add to your `~/Library/Application\ Support/Claude/claude_desktop_config.json`:
139
141
  "ALLOWED_COMMANDS": "ls,cat,pwd,echo",
140
142
  "ALLOWED_FLAGS": "-l,-a,--help,--version",
141
143
  "MAX_COMMAND_LENGTH": "1024",
142
- "COMMAND_TIMEOUT": "30"
144
+ "COMMAND_TIMEOUT": "30",
145
+ "ALLOW_SHELL_OPERATORS": "false"
143
146
  }
144
147
  }
145
148
  }
@@ -161,7 +164,8 @@ Add to your `~/Library/Application\ Support/Claude/claude_desktop_config.json`:
161
164
  "ALLOWED_COMMANDS": "ls,cat,pwd,echo",
162
165
  "ALLOWED_FLAGS": "-l,-a,--help,--version",
163
166
  "MAX_COMMAND_LENGTH": "1024",
164
- "COMMAND_TIMEOUT": "30"
167
+ "COMMAND_TIMEOUT": "30",
168
+ "ALLOW_SHELL_OPERATORS": "false"
165
169
  }
166
170
  }
167
171
  }
@@ -174,7 +178,7 @@ Add to your `~/Library/Application\ Support/Claude/claude_desktop_config.json`:
174
178
  - ✅ Command whitelist enforcement with 'all' option
175
179
  - ✅ Flag validation with 'all' option
176
180
  - ✅ Path traversal prevention and normalization
177
- - ✅ Shell operator blocking
181
+ - ✅ Shell operator blocking (with opt-in support via `ALLOW_SHELL_OPERATORS=true`)
178
182
  - ✅ Command length limits
179
183
  - ✅ Execution timeouts
180
184
  - ✅ Working directory restrictions
@@ -0,0 +1,7 @@
1
+ cli_mcp_server/__init__.py,sha256=bGLiX7XuhVsS-PJdoRIWXiilZ3NTAQ7fb9_8kkNzLlM,216
2
+ cli_mcp_server/server.py,sha256=MCjBmXutf4CZCy32e67-3tDI_AF2b_9qzq49ZkUR2qM,21288
3
+ cli_mcp_server-0.2.4.dist-info/METADATA,sha256=eJFjLeByTc-sUtiDlDyN4HB_NtmrgAyNSZ8kxg7TlqE,7860
4
+ cli_mcp_server-0.2.4.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ cli_mcp_server-0.2.4.dist-info/entry_points.txt,sha256=07bDmJJSXg-6VCFEFTOlsGoxI-0faJafT1yEEjUdN-U,55
6
+ cli_mcp_server-0.2.4.dist-info/licenses/LICENSE,sha256=85rOR_IMpb2VzXBA4VCRZh_KWlaO1Rly8HDYDwGgMWk,1062
7
+ cli_mcp_server-0.2.4.dist-info/RECORD,,
@@ -1,7 +0,0 @@
1
- cli_mcp_server/__init__.py,sha256=bGLiX7XuhVsS-PJdoRIWXiilZ3NTAQ7fb9_8kkNzLlM,216
2
- cli_mcp_server/server.py,sha256=CHP2x_FDx1Rz79ZnmznE6J7-9EHdafK-UibrVTvQx7k,15124
3
- cli_mcp_server-0.2.3.dist-info/METADATA,sha256=EiU10rdnN39XiTq2m0UjTrZDR0-1AEei9NFNf-6NBfk,7371
4
- cli_mcp_server-0.2.3.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
- cli_mcp_server-0.2.3.dist-info/entry_points.txt,sha256=07bDmJJSXg-6VCFEFTOlsGoxI-0faJafT1yEEjUdN-U,55
6
- cli_mcp_server-0.2.3.dist-info/licenses/LICENSE,sha256=85rOR_IMpb2VzXBA4VCRZh_KWlaO1Rly8HDYDwGgMWk,1062
7
- cli_mcp_server-0.2.3.dist-info/RECORD,,