Skip to main content
Glama
MladenSU
by MladenSU

Servidor CLI MCP


Una implementación de servidor de Protocolo de contexto de modelo (MCP) seguro para ejecutar operaciones de línea de comandos controladas con funciones de seguridad integrales.

LicenciaVersión de PythonProtocolo MCP insignia de herrería Pruebas de Python


Tabla de contenido

  1. Descripción general

  2. Características

  3. Configuración

  4. Herramientas disponibles

  5. Uso con Claude Desktop

  6. Características de seguridad

  7. Manejo de errores

  8. Desarrollo

  9. Licencia


Descripción general

Este servidor MCP permite la ejecución segura de la línea de comandos con sólidas medidas de seguridad, como la creación de listas blancas de comandos, la validación de rutas y los controles de ejecución. Es perfecto para proporcionar acceso CLI controlado a aplicaciones LLM, manteniendo la seguridad.

Related MCP server: Windows CLI MCP Server

Características

  • 🔒 Ejecución segura de comandos con validación estricta

  • ⚙️ Lista blanca de comandos y banderas configurables con opción "todos"

  • 🛡️ Prevención y validación de recorridos de ruta

  • Protección contra inyecciones del operador de Shell

  • ⏱️ Tiempos de espera de ejecución y límites de longitud

  • 📝 Informe detallado de errores

  • 🔄 Soporte para operaciones asíncronas

  • 🎯 Restricción y validación del directorio de trabajo

Configuración

Configurar el servidor usando variables de entorno:

Variable

Descripción

Por defecto

ALLOWED_DIR

Directorio base para la ejecución de comandos (obligatorio)

Ninguno (obligatorio)

ALLOWED_COMMANDS

Lista separada por comas de comandos permitidos o 'todos'

ls,cat,pwd

ALLOWED_FLAGS

Lista separada por comas de banderas permitidas o 'todas'

-l,-a,--help

MAX_COMMAND_LENGTH

Longitud máxima de la cadena de comandos

1024

COMMAND_TIMEOUT

Tiempo de espera de ejecución del comando (segundos)

30

ALLOW_SHELL_OPERATORS

Permitir operadores de shell (&&,

Nota: Establecer ALLOWED_COMMANDS o ALLOWED_FLAGS en 'all' permitirá cualquier comando o bandera respectivamente.

Instalación

Para instalar CLI MCP Server para Claude Desktop automáticamente a través de Smithery :

npx @smithery/cli install cli-mcp-server --client claude

Herramientas disponibles

comando_ejecutar

Ejecuta comandos CLI incluidos en la lista blanca dentro de directorios permitidos.

Esquema de entrada:

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

Notas de seguridad:

  • Los operadores de shell (&&, |, >, >>) no son compatibles de forma predeterminada, pero se pueden habilitar con ALLOW_SHELL_OPERATORS=true

  • Los comandos deben estar en la lista blanca a menos que ALLOWED_COMMANDS='all'

  • Las banderas deben estar en la lista blanca a menos que ALLOWED_FLAGS='all'

  • Se validan todas las rutas para que estén dentro de ALLOWED_DIR

mostrar_reglas_de_seguridad

Muestra la configuración de seguridad actual y las restricciones, incluidas:

  • Directorio de trabajo

  • Comandos permitidos

  • Banderas permitidas

  • Límites de seguridad (longitud máxima del comando y tiempo de espera)

Uso con Claude Desktop

Agregue a su ~/Library/Application\ Support/Claude/claude_desktop_config.json :

Configuración de servidores no publicados/desarrollo

{
  "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",
        "ALLOW_SHELL_OPERATORS": "false"
      }
    }
  }
}

Configuración de servidores publicados

{
  "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",
        "ALLOW_SHELL_OPERATORS": "false"
      }
    }
  }
}

En caso de que no funcione o no se muestre en la interfaz de usuario, borre su caché mediante uv clean .

Características de seguridad

  • ✅ Implementación de la lista blanca de comandos con la opción "todos"

  • ✅ Validación de bandera con opción 'todas'

  • ✅ Prevención y normalización de recorridos de ruta

  • ✅ Bloqueo del operador de Shell (con soporte opt-in a través de ALLOW_SHELL_OPERATORS=true )

  • ✅ Límites de longitud de comandos

  • ✅ Tiempos de espera de ejecución

  • ✅ Restricciones del directorio de trabajo

  • ✅ Resolución y validación de enlaces simbólicos

Manejo de errores

El servidor proporciona mensajes de error detallados para:

  • Violaciones de seguridad (CommandSecurityError)

  • Tiempos de espera de comandos (CommandTimeoutError)

  • Formatos de comando no válidos

  • Violaciones de seguridad de ruta

  • Errores de ejecución (CommandExecutionError)

  • Errores de comando generales (CommandError)

Desarrollo

Prerrequisitos

  • Python 3.10+

  • Biblioteca de protocolos MCP

Construcción y publicación

Para preparar el paquete para su distribución:

  1. Sincronizar dependencias y actualizar el archivo de bloqueo:

    uv sync
  2. Distribuciones de paquetes de compilación:

    uv build

    Esto creará distribuciones de origen y de rueda en el directorio dist/ .

  3. Publicar en PyPI:

    uv publish --token {{YOUR_PYPI_API_TOKEN}}

Depuración

Dado que los servidores MCP se ejecutan en stdio, la depuración puede ser complicada. Para una experiencia óptima, recomendamos usar el Inspector MCP .

Puede iniciar el Inspector MCP a través de npm con este comando:

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

Al iniciarse, el Inspector mostrará una URL a la que podrá acceder en su navegador para comenzar a depurar.

Licencia

Este proyecto está licenciado bajo la licencia MIT: consulte el archivo de LICENCIA para obtener más detalles.


Para obtener más información o ayuda, abra un problema en el repositorio del proyecto.

Available Tools

2 tools
run_commandA

Allows command (CLI) execution in the directory: /app

Available commands: pwd, ls, cat Available flags: -l, --help, -a

Shell operators (&&, ||, |, >, >>, <, <<, ;) are not supported. Set ALLOW_SHELL_OPERATORS=true to enable.

ParametersJSON Schema
NameRequiredDescriptionDefault
commandYesSingle command to execute (example: 'ls -l' or 'cat file.txt')

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden and does well by disclosing: execution directory constraint (/app), available commands (pwd, ls, cat), available flags (-l, --help, -a), shell operator restrictions, and how to enable operators. It doesn't mention security implications, permission requirements, or output format details.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Four sentences with zero waste - each provides essential information: purpose, available commands/flags, restrictions, and how to lift restrictions. The structure is front-loaded with the core purpose first, followed by operational details.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a single-parameter command execution tool with no annotations and no output schema, the description provides substantial context: execution environment, command/flag constraints, and operator restrictions. It doesn't describe return values or error behavior, but given the tool's relative simplicity, this is reasonably complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100% with the parameter 'command' well-documented in the schema. The description adds context about what constitutes valid commands (specific examples and restrictions), but doesn't provide additional parameter-specific semantics beyond what the schema already covers. Baseline 3 is appropriate when schema does heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description explicitly states 'Allows command (CLI) execution in the directory: /app' - a specific verb ('execute') with clear resource ('command/CLI') and location constraint ('/app'). It distinguishes from the only sibling tool 'show_security_rules' which appears unrelated to command execution.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context about what commands and flags are available, and when shell operators are/aren't supported. However, it doesn't explicitly state when to use this tool versus alternatives (though the sibling tool appears unrelated) or provide exclusion guidance beyond the shell operator limitation.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

show_security_rulesB

Show what commands and operations are allowed in this environment.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

B3.1/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It implies a read-only operation ('show'), but doesn't specify if it requires authentication, returns structured data, has rate limits, or details output format. For a tool with zero annotation coverage, this is a significant gap in behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose without any fluff. It's front-loaded and wastes no words, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of security rules and lack of annotations or output schema, the description is incomplete. It doesn't explain what the output looks like (e.g., list, structured data), how to interpret 'allowed,' or any prerequisites. This leaves the agent with insufficient context for effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has 0 parameters with 100% schema description coverage, so the schema fully documents the lack of inputs. The description doesn't add parameter details, which is appropriate here, but it could hint at implicit context like environment scope. Baseline is 4 for zero parameters, as no compensation is needed.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Show what commands and operations are allowed in this environment.' It specifies the verb 'show' and the resource 'commands and operations' with their context 'in this environment.' However, it doesn't explicitly differentiate from its sibling 'run_command,' which likely executes commands rather than showing allowed ones.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention the sibling tool 'run_command' or any context for usage, such as checking permissions before execution or troubleshooting. This leaves the agent without explicit direction on tool selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 2 tool updatesv1.0.0
    • First observedrun_command
    • First observedshow_security_rules

TDQS

B3.4/5.0

Scored across 2 tools

Disambiguation5/5

The two tools have completely distinct purposes: run_command executes CLI commands with specific constraints, while show_security_rules displays allowed operations and permissions. There is no overlap or ambiguity between these functions.

Naming Consistency4/5

Both tools follow a clear verb_noun pattern (run_command, show_security_rules), which is consistent and readable. The minor deviation is that 'run' and 'show' are different verbs, but this is appropriate given their distinct actions.

Tool Count2/5

With only 2 tools, the server feels thin for a CLI server that presumably handles command execution and environment management. A typical CLI server would benefit from more tools (e.g., for file operations, process management, or configuration), making this count insufficient for the apparent scope.

Completeness2/5

The tool surface is severely incomplete for a CLI server. It lacks basic operations like file creation, deletion, editing, process monitoring, or environment configuration. The run_command tool is limited to a few commands, and there are no tools for managing the CLI environment beyond showing security rules, creating significant gaps for agent workflows.

Maintenance

ActivityInactive
ResponsivenessUnresponsive

Related MCP Connectors

Related MCP Servers

  • F
    license
    B
    quality
    D
    maintenance
    Enables safe execution of system shell commands with real-time streaming output and rich metadata capture. Provides configurable command execution with timeout controls, environment management, and extensible plugin architecture for monitoring command lifecycles.
    4
    -
  • A
    license
    A
    quality
    B
    maintenance
    Enables secure command-line interactions on Windows systems with support for PowerShell, CMD, Git Bash, and WSL shells, providing controlled file access, command execution, and configurable security restrictions.
    6
    43 npm
    4
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    Provides a secure environment for executing shell commands with restricted directory access and timeout enforcement. It includes tools for running commands, managing execution history, and isolating environment variables.
    24 npm
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    A security-focused tool that implements least-privilege credential injection for Claude Code by intercepting Bash and MCP tool calls to swap in minimum-privilege tokens. It enables secure execution of CLI commands and MCP operations by matching tool arguments against declarative YAML policies to prevent unauthorized access.
    -