cl

cli-mcp-server

Command line interface with secure execution and customizable security policies

Publishercli-mcp-server
Submitted date4/13/2025

Secure CLI Execution with LLMs: An Expert Guide to the Model Context Protocol (MCP) Server


This document details a robust and secure implementation of a Model Context Protocol (MCP) server, designed to facilitate controlled command-line operations within Large Language Model (LLM) applications. It emphasizes security best practices and provides a comprehensive guide for configuration, usage, and development.

Python Version MCP Protocol smithery badge


Table of Contents

  1. Introduction: Bridging LLMs and the Command Line
  2. Key Features: A Security-First Approach
  3. Configuration Deep Dive: Environment Variables and Security Policies
  4. Tooling: Exposing Functionality to LLMs
  5. Integration with Claude Desktop: A Practical Example
  6. Security Architecture: Hardening Against Exploits
  7. Error Handling: Providing Informative Feedback
  8. Development Workflow: Building and Contributing
  9. Conclusion: Empowering LLMs with Secure CLI Access

Introduction: Bridging LLMs and the Command Line

The integration of Large Language Models (LLMs) with external tools and data sources is crucial for building sophisticated AI applications. The Model Context Protocol (MCP) provides a standardized framework for this integration. This document focuses on a specific MCP server implementation that enables LLMs to securely interact with the command-line interface (CLI). This server is designed with security as a paramount concern, implementing multiple layers of protection to prevent malicious command execution and unauthorized access.

Key Features: A Security-First Approach

This MCP server offers a range of features designed to ensure secure command-line execution:

  • Strict Command Whitelisting: Only pre-approved commands can be executed, significantly reducing the attack surface. The 'all' option provides flexibility but should be used with extreme caution in production environments.
  • Configurable Flag Whitelisting: Similar to command whitelisting, this feature restricts the flags that can be used with allowed commands, preventing potentially harmful modifications to command behavior.
  • Path Traversal Prevention: All file paths are rigorously validated to ensure they remain within the designated ALLOWED_DIR, preventing access to sensitive areas of the file system. Path normalization is performed to further mitigate traversal attempts.
  • Shell Operator Injection Protection: The server actively blocks the use of shell operators (e.g., &&, |, >, >>) to prevent command chaining and redirection, which could be exploited to execute arbitrary code.
  • Execution Timeouts and Length Limits: Commands are subject to both a maximum length and a timeout, preventing denial-of-service attacks and resource exhaustion.
  • Detailed Error Reporting: The server provides informative error messages that aid in debugging and troubleshooting, while also providing insights into potential security violations.
  • Asynchronous Operation Support: The server supports asynchronous command execution, allowing LLMs to perform other tasks while waiting for command completion.
  • Working Directory Restriction: Command execution is confined to a specific working directory, further limiting the potential impact of malicious commands.
  • Symlink Resolution and Validation: Symlinks are resolved and validated to ensure they point within the allowed directory, preventing symlink-based attacks.

Configuration Deep Dive: Environment Variables and Security Policies

The server's behavior is controlled through environment variables, allowing for flexible and secure configuration. Understanding these variables is critical for maintaining a secure environment.

| Variable | Description of the most important aspects of this server.

Recommendation: Prioritize security audits and penetration testing to identify and address potential vulnerabilities. Regularly update dependencies and review the configuration to ensure it aligns with the latest security best practices.

Tooling: Exposing Functionality to LLMs

The server exposes two primary tools to LLMs: run_command and show_security_rules.

run_command: Secure Command Execution

This tool allows LLMs to execute pre-approved CLI commands within the confines of the ALLOWED_DIR.

Input Schema:

{ "command": { "type": "string", "description": "Single command to execute (e.g., 'ls -l' or 'cat file.txt')" } }

Security Considerations:

  • Command Injection: The server actively prevents command injection by blocking shell operators and validating all input.
  • Privilege Escalation: The server should be run with the least privilege necessary to perform its intended functions.
  • Data Exfiltration: Carefully consider the commands that are whitelisted to prevent the exfiltration of sensitive data.

show_security_rules: Auditing Security Posture

This tool provides LLMs (and administrators) with the ability to inspect the server's current security configuration.

Output:

The tool displays the following information:

  • Working directory (ALLOWED_DIR)
  • Allowed commands (ALLOWED_COMMANDS)
  • Allowed flags (ALLOWED_FLAGS)
  • Security limits (max command length and timeout)

This information is invaluable for auditing the server's security posture and ensuring that it aligns with the organization's security policies.

Integration with Claude Desktop: A Practical Example

The following examples demonstrate how to integrate this MCP server with Claude Desktop.

Development/Unpublished Servers: Local Testing

This configuration is suitable for local development and testing.

{ "mcpServers": { "cli-mcp-server": { "command": "uv", "args": [ "--directory", "<path/to/the/repo>/cli-mcp-server", "run", "cli-mcp-server" ], "env": { "ALLOWED_DIR": "</your/desired/dir>", "ALLOWED_COMMANDS": "ls,cat,pwd,echo", "ALLOWED_FLAGS": "-l,-a,--help,--version", "MAX_COMMAND_LENGTH": "1024", "COMMAND_TIMEOUT": "30" } } } }

Note: Replace <path/to/the/repo>/cli-mcp-server with the actual path to the server's source code.

Published Servers: Production Deployment

This configuration is intended for production deployments.

{ "mcpServers": { "cli-mcp-server": { "command": "uvx", "args": [ "cli-mcp-server" ], "env": { "ALLOWED_DIR": "</your/desired/dir>", "ALLOWED_COMMANDS": "ls,cat,pwd,echo", "ALLOWED_FLAGS": "-l,-a,--help,--version", "MAX_COMMAND_LENGTH": "1024", "COMMAND_TIMEOUT": "30" } } } }

Important: Ensure that the server is properly packaged and deployed before using this configuration. Clearing the cache via uv clean may be necessary if the server is not functioning as expected.

Security Architecture: Hardening Against Exploits

The server's security architecture is designed to mitigate a wide range of potential attacks. Key security features include:

  • Input Validation: All input is rigorously validated to prevent command injection, path traversal, and other exploits.
  • Principle of Least Privilege: The server should be run with the minimum privileges required to perform its intended functions.
  • Regular Security Audits: Regularly audit the server's configuration and code to identify and address potential vulnerabilities.
  • Dependency Management: Keep all dependencies up-to-date to patch known security vulnerabilities.
  • Monitoring and Logging: Implement robust monitoring and logging to detect and respond to suspicious activity.

Error Handling: Providing Informative Feedback

The server provides detailed error messages to aid in debugging and troubleshooting. These error messages can also provide valuable insights into potential security violations.

Error Types:

  • CommandSecurityError: Indicates a security violation, such as an attempt to execute a non-whitelisted command or use a non-whitelisted flag.
  • CommandTimeoutError: Indicates that a command exceeded the maximum execution time.
  • InvalidCommandFormat: Indicates that the command format is invalid.
  • PathSecurityViolation: Indicates an attempt to access a file or directory outside of the allowed directory.
  • CommandExecutionError: Indicates a general error during command execution.
  • CommandError: Indicates a generic command error.

Development Workflow: Building and Contributing

The following sections outline the development workflow for this MCP server.

Prerequisites: Setting Up Your Environment

  • Python 3.10+: Ensure that you have Python 3.10 or a later version installed.
  • MCP Protocol Library: Install the necessary MCP protocol library.

Building and Publishing: Packaging for Distribution

  1. Sync Dependencies and Update Lockfile:

    uv sync
  2. Build Package Distributions:

    uv build

    This will create source and wheel distributions in the dist/ directory.

  3. Publish to PyPI:

    uv publish --token {{YOUR_PYPI_API_TOKEN}}

Debugging: Leveraging the MCP Inspector

Debugging MCP servers can be challenging due to their reliance on standard input and output. The MCP Inspector provides a valuable tool for debugging.

Launching the MCP Inspector:

npx @modelcontextprotocol/inspector uv --directory {{your source code local directory}}/cli-mcp-server run cli-mcp-server

The Inspector will provide a URL that you can access in your browser to begin debugging.

Conclusion: Empowering LLMs with Secure CLI Access

This MCP server provides a secure and reliable way to integrate LLMs with the command-line interface. By implementing robust security measures and providing detailed error reporting, this server enables developers to build sophisticated AI applications while minimizing the risk of security vulnerabilities. Continuous monitoring, regular security audits, and adherence to the principle of least privilege are essential for maintaining a secure environment.

Visit More

View All