Skip to main content
Glama

MCPilot

MCP-агентный диагностический ассистент для Linux — отвечает на вопросы на естественном языке, например «почему мой ноутбук тормозит», позволяя Gemini выбирать и вызывать типизированные, изолированные инструменты, предоставляемые пользовательским MCP-сервером, и итерируя через конечный автомат LangGraph, пока не соберёт достаточно доказательств для диагноза.

Только локально · Ubuntu · CLI · Без произвольного shell · Человек в цикле для изменений


Архитектура

                         USER
                           │
                           ▼
                    CLI Interface (rich)
                           │
                           ▼
                 ┌─────────────────┐
                 │    LangGraph    │
                 │ Diagnostic Agent│◄──── Gemini (function calling)
                 └────────┬────────┘
                          │
                     MCP Client (stdio)
                          │
                    MCP Protocol
                          │
                          ▼
                 ┌─────────────────┐
                 │ MCPilot Server  │  (MCPServer, subprocess-launched)
                 └────────┬────────┘
                          │
          ┌───────────────┼────────────────┐
          │               │                │
          ▼               ▼                ▼
      System          Filesystem          Git
      /proc, psutil   POSIX APIs,       Git CLI via
      systemd,        path allow-list   controlled
      journalctl                        subprocess

Правило уровней: MCP-декораторы вызывают базовый слой абстракции Linux; они сами никогда не содержат логику ОС.

server/tools/system.py   →  server/core/linux.py    →  /proc, psutil, uname
server/tools/services.py →  server/core/systemd.py  →  systemctl, journalctl
server/tools/filesystem.py → server/core/fs.py      →  pathlib / POSIX APIs
server/tools/git.py      →  server/core/git.py      →  git CLI (controlled subprocess)

Related MCP server: mcp-linux-ops

Каталог инструментов (18 инструментов)

Инструмент

Модуль

Возвращает

Риск

get_system_info

system

SystemInfo

READ_ONLY

get_cpu_usage

system

CpuUsage

READ_ONLY

get_memory_usage

system

MemoryUsage

READ_ONLY

get_disk_usage

system

list[DiskUsageEntry]

READ_ONLY

list_processes

system

list[ProcessSummary]

READ_ONLY

get_process_info

system

ProcessDetail | ToolError

READ_ONLY

get_service_status

services

ServiceStatus | ToolError

READ_ONLY

get_service_logs

services

ServiceLogs | ToolError

READ_ONLY

get_listening_ports

services

list[ListeningPort]

READ_ONLY

restart_service

services

ServiceStatus | ToolError

APPROVAL_REQUIRED

list_directory

filesystem

list[DirectoryEntry] | ToolError

READ_ONLY

get_file_metadata

filesystem

FileMetadata | ToolError

READ_ONLY

search_files

filesystem

SearchResult | ToolError

READ_ONLY

read_file

filesystem

str | ToolError

READ_ONLY

git_status

git

GitStatus | ToolError

READ_ONLY

git_diff

git

GitDiff | ToolError

READ_ONLY

git_log

git

list[GitLogEntry] | ToolError

READ_ONLY

run_tests

git

TestRunResult | ToolError

READ_ONLY

Намеренно нет delete_file, sudo_command или универсального shell-инструмента.


Модель безопасности

История безопасности MCPilot — это защита в глубину на четырёх уровнях:

  1. Нет произвольного shell-инструмента — Каждая возможность представляет собой конкретную, узконаправленную функцию Python с фиксированным списком аргументов subprocess. Никогда shell=True, никогда команды с интерполяцией строк.

  2. Ограничение путей — Все файловые и Git-инструменты проверяют пути на соответствие явному списку разрешённых (~/Projects, ~/Documents). Разрешаются символические ссылки, проверка через is_relative_to(). См. server/core/fs.py::validate_path.

  3. Предотвращение инъекций в имя службы — Строгое регулярное выражение (^[a-zA-Z0-9@_.\-]+$) отклоняет ;, |, &, $, обратные кавычки, пробелы и разделители путей. См. server/core/systemd.py::validate_service_name.

  4. Классификация рисков + одобрение человека — Каждый инструмент имеет уровень риска (READ_ONLY, APPROVAL_REQUIRED, DENIED). Неизвестные инструменты по умолчанию получают DENIED (отказ по умолчанию). Единственный изменяющий инструмент (restart_service) приостанавливается для явного подтверждения y.

  5. Журналирование аудита — Каждый вызов инструмента записывается в logs/audit.jsonl с временной меткой, инструментом, аргументами, риском, статусом одобрения и результатом.

  6. Безопасный запуск подпроцессов — Все вызовы subprocess проходят через единую функцию run_safe(): всегда shell=False, всегда список аргументов, всегда с таймаутом.

Полная модель угроз: docs/security.md


Быстрый старт

# Prerequisites: Ubuntu, Python 3.12+, uv
git clone <repo-url> && cd mcpilot

# Install dependencies
uv sync

# Set Gemini API key
cp .env.example .env
# Edit .env and add your GEMINI_API_KEY

# Run tests (44 tests, all layers)
PYTHONPATH="" uv run python -m pytest tests/ -v --override-ini="asyncio_mode=auto"

# Interactive mode
uv run python -m cli.main

# One-shot mode
uv run python -m cli.main "Why is my system slow?"

Примеры трассировок

Диагностика системы

You: Why is my system slow?
[Agent] Analyzing request...
[MCP]  get_cpu_usage()
[MCP]  get_memory_usage()
[MCP]  list_processes(limit=20)
[MCP]  get_disk_usage()
[Agent] Evaluating evidence...
[Agent] Generating diagnosis...

Diagnosis: Memory pressure (92% used, 70% swap) driven by firefox.
Confidence: HIGH.

Диагностика службы

You: Why isn't PostgreSQL working?
[Agent] Analyzing request...
[MCP]  get_service_status(service='postgresql')
[MCP]  get_service_logs(service='postgresql')
[MCP]  get_listening_ports()
[MCP]  list_processes(limit=20)
[Agent] Evaluating evidence...
[Agent] Generating diagnosis...

Diagnosis: systemd shows failed; journal shows "address already in use";
port 5432 is held by PID <n> (<process>). Confidence: HIGH.

Демонстрация безопасности

You: Restart PostgreSQL
[Agent] Analyzing request...

┌──────────────────────────────┐
│ MCPilot requests action      │
├──────────────────────────────┤
│ Tool: restart_service        │
│ Service: postgresql          │
│                              │
│ Reason: service action       │
│ requested by diagnostic agent│
│                              │
│ Approve? [y/N]               │
└──────────────────────────────┘

Набор тестов

Слой

Тесты

Что покрывает

Слой 1 — Ядро Linux

8

/proc, psutil, информация о процессах, ограничение вывода

Слой 2 — Протокол MCP

4

18 инструментов зарегистрировано, схемы, описания

Слой 3 — Безопасность

24

Обход путей, инъекции в службы, неизвестные инструменты, ограничения вывода

Слой 4 — Агент

8

Политики, предел итераций, отклонение одобрения, целостность состояния

Итого

44


Метки уверенности

Уверенность — это дискретная, объяснимая метка, а не калиброванная статистическая оценка:

  • HIGH: ≥3 независимых наблюдения указывают на одну и ту же причину

  • MEDIUM: Есть некоторые подтверждающие доказательства, но не хватает подтверждающего наблюдения

  • LOW: Доказательств мало, достигнут предел итераций или наблюдения противоречат друг другу


Структура проекта

mcpilot/
├── server/
│   ├── main.py                 # MCPServer app, registers all 18 tools
│   ├── tools/                  # MCP tool wrappers (thin, no OS logic)
│   │   ├── system.py           # 6 system tools
│   │   ├── services.py         # 4 service tools (incl. restart_service)
│   │   ├── filesystem.py       # 4 filesystem tools
│   │   └── git.py              # 4 git tools
│   ├── core/                   # Linux abstraction layer
│   │   ├── linux.py            # /proc + psutil parsing
│   │   ├── systemd.py          # systemctl/journalctl wrappers
│   │   ├── fs.py               # path validation + file ops
│   │   ├── git.py              # git subprocess wrappers
│   │   └── command.py          # shared safe-subprocess runner
│   ├── policies.py             # risk classification map
│   ├── schemas.py              # all Pydantic models
│   └── audit.py                # JSONL audit logger
├── client/
│   └── mcp_client.py           # MCP stdio client
├── agent/
│   ├── state.py                # DiagnosticState TypedDict
│   ├── graph.py                # LangGraph wiring
│   ├── nodes.py                # 4 LangGraph nodes
│   ├── prompts.py              # LLM prompt templates
│   └── tool_adapter.py         # MCP → Gemini function declarations
├── cli/
│   └── main.py                 # CLI entrypoint, rich output, approval UI
├── tests/                      # 44 tests across 4 layers
│   ├── server/                 # Layer 1+2 tests
│   ├── agent/                  # Layer 4 tests
│   └── security/               # Layer 3 tests (interview demo suite)
├── docs/                       # Architecture, security, MCP docs
├── examples/                   # Captured diagnostic transcripts
└── logs/                       # audit.jsonl (gitignored)

Лицензия

MIT

Install Server
F
license - not found
A
quality
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • A
    license
    A
    quality
    A
    maintenance
    Enables AI assistants to perform controlled Linux system administration tasks like reading logs, managing services, cron jobs, WordPress, and executing sandboxed Python code, with strict security constraints.
    29
    2
    GPL 2.0
  • F
    license
    B
    quality
    D
    maintenance
    Enables LLMs to execute shell commands and perform file operations on a Linux system, exposing tools like execute_command, read_file, write_file, and more.
    10
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables AI agents to diagnose Linux server incidents by collecting and structuring system diagnostics from multiple servers via SSH, with tools for finding incident clusters, gathering context (memory, CPU, swap, etc.), and running arbitrary commands.

View all related MCP servers

Related MCP Connectors

  • Operate Linux, macOS and Windows from your LLM. Every action runs through an auditable allowlist.

  • Let AI operate servers without SSH. Choose actions, approve risky changes, and audit every step.

  • Runtime permission, approval, and audit layer for AI agent tool execution.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Ronit-k/MCPilot'

If you have feedback or need assistance with the MCP directory API, please join our Discord server