Skip to main content
Glama
SprutHub MCP Server

SprutHub MCP Server

by pikerr

SprutHubCTL

MIT License Python 3.10+

Высокоуровневая интеграция SprutHub для LLM-ассистентов (Antigravity, Claude Desktop, Cursor, Claude Code, Cline и др.) и системных администраторов.

Предоставляет два формата работы в одном пакете:

  1. On-Demand CLI (spruthubctl / sprut) + Skill — ультралегковесный запуск по требованию для терминала и AI-агентов (Antigravity, Claude Code) с нулевым оверхедом по RAM и контекстному окну (~80 мс на запрос, 0 байт RAM в простое).

  2. MCP Server (spruthub-mcp) — стандартный сервер Model Context Protocol (для клиентов без доступа к терминалу, например Claude Desktop).


Ключевые особенности

  • ⚡ Прямой локальный WebSocket: прямое подключение к хабу в локальной сети (ws://<IP>/spruthub), нулевые задержки (< 5 мс), полная автономность без зависимости от облака.

  • 🧠 Семантический фасад вместо сырого RPC: сервер берет на себя нормализацию данных, фильтрацию служебного мусора и разрешение сервисов, позволяя LLM работать за 1 шаг.

  • 🛡️ Автоматическая нормализация типов: упаковка базовых типов (bool, int, float, str) в структуры SprutHub (boolValue, intValue и др.).

  • 💡 Умное переключение (switch): вам не нужно знать точный service_id или characteristic_id реле — система автоматически найдёт целевую службу Switch/Lightbulb/Outlet.

  • 🔒 Безопасная аутентификация: работа по локальному паролю (токену) без необходимости хранить мастер-пароль от аккаунта.

  • 🚀 Нулевой оверхед (Hybrid Architecture): поддержка работы как в виде фонового MCP-сервера, так и через легковесный CLI.


Related MCP server: MCP-HASS

⚡ Быстрая установка (Prompt-ready)

Если вы используете AI-агента (Antigravity, Claude Code, Cursor, Cline):

Просто отправьте вашему ассистенту сообщение со ссылкой на репозиторий:

«Установи SprutHub из https://github.com/pikerr/spruthubctl. Мой хост: 192.168.1.100, локальный пароль: ВАШ_ПАРОЛЬ»

Агент прочитает AGENTS.md и выполнит всё сам за один шаг.

Установка вручную в терминале:

uvx --from git+https://github.com/pikerr/spruthubctl spruthubctl install --host 192.168.1.100 --token ВАШ_ПАРОЛЬ

(Для регистрации MCP-сервера в Claude Desktop / Cursor добавьте флаг --mcp).

Команда автоматически:

  1. Сохраняет конфигурацию в ~/.config/spruthubctl/config.json (chmod 600).

  2. Устанавливает готовый Agent Skill в директории ~/.gemini/ и ~/.claude/.

  3. Проверяет связь с вашим контроллером SprutHub.


Архитектура: Двойной интерфейс (CLI + MCP)

flowchart TD
    subgraph Clients["Клиенты и Ассистенты"]
        Claude["Claude Desktop / Cursor<br/>(клиенты без терминала)"]
        Terminal["Antigravity / Claude Code / Терминал<br/>(on-demand агенты)"]
    end

    subgraph Package["Пакет spruthubctl"]
        CLI["CLI & Skill (cli.py)<br/>spruthubctl / sprut<br/>On-Demand (80ms, 0 RAM)"]
        MCP["MCP Server (server.py)<br/>spruthub-mcp<br/>Stdio JSON-RPC daemon"]
        Core["SprutHubClient<br/>Семантический фасад & нормализация типов"]
    end

    Hub[("SprutHub Controller<br/>ws://IP/spruthub")]

    Terminal -->|uvx / CLI| CLI
    Claude -->|MCP Protocol| MCP
    CLI --> Core
    MCP --> Core
    Core -->|Локальный WebSocket| Hub

Инструменты и команды

(Команда spruthubctl также доступна по короткому алиасу sprut и совместимому spruthub-cli).

Категория

Команда CLI

MCP Tool

Описание

Хаб и система

spruthubctl summary

sprut_get_summary

Комплексная сводка: статус хаба, аккаунт, комнаты с устройствами, расширения, статистика.

spruthubctl info

sprut_get_hub_info

Краткая информация о контроллере (имя, модель, серийник, версия ПО, онлайн-статус).

spruthubctl restart [--yes]

sprut_restart_hub

Перезагрузка контроллера / службы SprutHub.

Комнаты

spruthubctl rooms

sprut_list_rooms

Список комнат со сводкой датчиков в реальном времени.

spruthubctl room create <name>

sprut_create_room

Создание новой комнаты.

spruthubctl room rename <id> <name>

sprut_update_room

Переименование существующей комнаты.

spruthubctl room delete <id> [--yes]

sprut_delete_room

Удаление комнаты (с подтверждением).

Устройства

spruthubctl devices [--room ID] [-s query]

sprut_list_devices

Список устройств и их текущих состояний (с фильтрацией).

spruthubctl device <ID>

sprut_get_device

Полная развернутая структура аксессуара (сервисы, характеристики, метаданные).

spruthubctl switch <ID> <on/off>

sprut_set_switch

Быстрое включение/выключение любого реле, выключателя, розетки или лампы.

spruthubctl set <aId> <sId> <cId> <val>

sprut_set_characteristic

Установка любого значения характеристики (яркость, температура, режим).

История и датчики

spruthubctl history <ID> [char] [--days N]

sprut_get_history

Выгрузка временных рядов, расчет аналитики (min/max/avg/delta) и дневных сводок.

Сценарии

spruthubctl scenarios [-s query]

sprut_list_scenarios

Список настроенных сценариев автоматизации и их статус.

spruthubctl scenario run <name_or_idx>

sprut_run_scenario

Запуск сценария автоматизации по имени или индексу.

Диагностика

spruthubctl logs [--count N] [--level LVL]

sprut_get_logs

Просмотр системных логов контроллера и ошибок драйверов.

spruthubctl extensions

sprut_list_extensions

Статус всех протокольных расширений (Zigbee, BLE, HomeKit, MQTT и др.).

Каталог шаблонов

spruthubctl catalog list [-s query]

sprut_list_catalog

Поиск и просмотр шаблонов поддерживаемых устройств в каталоге.

spruthubctl catalog get <model_or_file>

sprut_get_catalog_template

Получение схемы и маппинга сервисов конкретного шаблона оборудования.

📖 Полная документация низкоуровневого протокола: docs/SPRUTHUB_API.md — карта всех 18 модулей и 62 RPC-методов ядра SprutHub.


Где взять токен (локальный пароль)?

Всё настраивается за 10 секунд прямо из веб-интерфейса SprutHub:

  1. В браузере откройте веб-интерфейс хаба (http://<IP_ХАБА>).

  2. Перейдите в Настройки → Пользователи → откройте карточку вашего пользователя (Владелец).

  3. Скопируйте значение из поля «Локальный пароль» (при необходимости можно сгенерировать новый кнопкой «Сгенерировать новый пароль»).


Конфигурация

Для работы требуется всего два параметра: IP-адрес (или хост) хаба и локальный пароль.

Конфигурация автоматически определяется по цепочке:

  1. Переменные окружения (SPRUTHUBCTL_HOST / SPRUTHUB_HOST и SPRUTHUBCTL_TOKEN / SPRUTHUB_TOKEN).

  2. Системный файл конфигурации:

    • Linux / macOS: ~/.config/spruthubctl/config.json (или ~/.config/spruthub/config.json)

    • Windows: %APPDATA%\spruthubctl\config.json (или %APPDATA%\spruthub\config.json)

  3. Локальный файл ./config.json в рабочей директории.

Пример config.json:

{
  "host": "192.168.1.100",
  "token": "ВАШ_ЛОКАЛЬНЫЙ_ПАРОЛЬ"
}

(Также поддерживается указание домена, например "host": "spruthub.local" или полного WebSocket URL, если у вас нестандартный порт или реверс-прокси).


Варианты использования

Режим 1: Skill для Antigravity / Claude Code (Рекомендуется)

Идеальный режим: 0 байт RAM в простое, 0 лишних токенов в контексте.

Ничего вручную копировать не нужно:

uvx --from git+https://github.com/pikerr/spruthubctl spruthubctl install --host 192.168.1.100 --token ВАШ_ПАРОЛЬ

Команда автоматически:

  1. Сохранит данные в ~/.config/spruthubctl/config.json с правами доступа 600.

  2. Установит скилл в ~/.gemini/config/skills/spruthub/ (и ~/.claude/skills/).

  3. Проверит соединение с вашим хабом.

После этого агент готов к управлению («выключи свет в спальне», «какая температура в кабинете»).


Режим 2: MCP Server (для Claude Desktop / Cursor)

Автоматическая регистрация (Рекомендуется):

Одной командой зарегистрирует сервер в Claude Desktop и/или Cursor (с сохранением резервной копии старого конфига):

uvx --from git+https://github.com/pikerr/spruthubctl spruthubctl install-mcp --host 192.168.1.100 --token ВАШ_ПАРОЛЬ

(Либо передайте флаг --mcp при первой установке: spruthubctl install --mcp, и утилита настроит и Skill, и Claude Desktop сразу).

Ручная настройка:

Если вы предпочитаете прописать конфиг вручную в claude_desktop_config.json:

{
  "mcpServers": {
    "spruthub": {
      "command": "uvx",
      "args": ["--from", "git+https://github.com/pikerr/spruthubctl[mcp]", "spruthub-mcp"],
      "env": {
        "SPRUTHUB_HOST": "192.168.1.100",
        "SPRUTHUB_TOKEN": "ВАШ_ЛОКАЛЬНЫЙ_ПАРОЛЬ"
      }
    }
  }
}

Лицензия

MIT

Available Tools

18 tools
sprut_create_roomC

Create a new room in the smart home.

Args: name: Name for the new room.

Inputs: name (required). Returns: result

sprut_delete_roomC

Delete a room from the smart home.

Args: room_id: ID of the room to delete.

Inputs: room_id (required). Returns: result

sprut_get_catalog_templateB

Get full device template and definition from catalog.

Args: file_or_model: Template file path or model name. store: Optional catalog store (default MAIN). controller: Optional controller (e.g. zigbee).

Inputs: file_or_model (required), store, controller. Returns: result

sprut_get_deviceC

Get complete details and all characteristics of a specific accessory.

Args: accessory_id: The ID of the accessory (e.g. 1155).

Inputs: accessory_id (required). Returns: result

sprut_get_historyC

Retrieve historical telemetry data and statistics for sensor or accessory characteristics.

Args: accessory_id: ID of the accessory. service_id: Optional Service ID (sId). characteristic_id: Optional Characteristic ID (cId). days: Optional time window in days (e.g. 7). hours: Optional time window in hours (e.g. 24). limit: Optional maximum number of records to retrieve.

Inputs: accessory_id (required), days, hours, limit, +2 more. Returns: result

sprut_get_hub_infoA

Get general information about the SprutHub controller (name, model, firmware version, online status).

Inputs: no named parameters. Returns: result

sprut_get_logsC

Get recent system and driver logs from SprutHub.

Args: count: Number of log entries to retrieve (default 50). level: Optional filter by log level (e.g. ERROR, WARN, INFO).

Inputs: count, level. Returns: result

sprut_get_summaryB

Get a comprehensive smart home dashboard summary (hub info, users, room counts, device breakdown, extensions, scenarios).

Inputs: no named parameters. Returns: result

sprut_list_catalogA

List or search device templates in the SprutHub catalog.

Args: search: Optional query to search by model or manufacturer (e.g. Aubess, TS000F). limit: Max number of templates to return.

Inputs: limit, search. Returns: result

sprut_list_devicesA

List smart home accessories / devices with their controllable services and current values.

Args: room_id: Optional filter to list devices only in a specific room.

Inputs: room_id. Returns: result

sprut_list_extensionsA

List installed protocols and extensions (Zigbee, BLE, HomeKit, MQTT, etc.) and their status.

Inputs: no named parameters. Returns: result

sprut_list_roomsA

List all rooms in the smart home with their IDs, names, and sensor summary.

Inputs: no named parameters. Returns: result

sprut_list_scenariosA

List all automation scenarios configured in SprutHub.

Inputs: no named parameters. Returns: result

sprut_restart_hubB

Restart the SprutHub controller service.

Inputs: no named parameters. Returns: result

sprut_run_scenarioB

Trigger / execute an automation scenario by index.

Args: index: The index of the scenario (from sprut_list_scenarios).

Inputs: index (required). Returns: result

sprut_set_characteristicC

Set any characteristic on an accessory (brightness, temperature, mode, etc.).

Args: accessory_id: The ID of the accessory. service_id: The ID of the service (sId). characteristic_id: The ID of the characteristic (cId). value: The target value to set (boolean, integer, float, or string).

Inputs: value (required), service_id (required), accessory_id (required), characteristic_id (required). Returns: result

sprut_set_switchB

Turn a switch, light, or relay ON or OFF.

Args: accessory_id: The ID of the accessory (e.g. 1155). on: True to turn ON, False to turn OFF. service_id: Optional service ID if the accessory has multiple switches. If omitted, the first Switch service is used automatically.

Inputs: on (required), accessory_id (required), service_id. Returns: result

sprut_update_roomC

Update or rename an existing room.

Args: room_id: ID of the room to update. name: Optional new name for the room.

Inputs: room_id (required), name. Returns: result

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    B3.4/5.0

    Scored across 18 tools

    Disambiguation4/5

    Most tools target a distinct resource+action (list_rooms, get_device, set_characteristic, restart_hub, etc.), so an agent can pick the right one. Minor overlap exists: sprut_get_summary aggregates hub info, rooms, devices, extensions, and scenarios already covered by dedicated list tools, and sprut_set_switch is a convenience wrapper over sprut_set_characteristic for switch services.

    Naming Consistency5/5

    Every tool uses the sprut_ prefix followed by a consistent verb_noun pattern (list_catalog, get_device, set_switch, run_scenario, create_room, update_room, delete_room). Naming is uniform and predictable across the whole set.

    Tool Count4/5

    18 tools is slightly on the heavy side but each maps to a real smart-home operation, so it is not bloated. It earns most of its places, with only sprut_get_summary arguably redundant against the individual list tools.

    Completeness4/5

    Rooms have full CRUD, devices have list/get/set coverage, and telemetry, logs, catalog, scenarios, and extensions are all reachable. Gaps remain around scenario lifecycle (list/run only, no create/update/delete) and extensions (read-only), but agents can cover the core workflows.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to interact with Home Assistant smart home devices through natural language. Control devices, manage automations, query entity states, and retrieve historical data across your home automation system.
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Connects AI assistants to Home Assistant, enabling them to discover and control smart home entities, services, areas, devices, and cameras via the Model Context Protocol.
      4
      BSD 3-Clause
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables LLMs to control Home Assistant devices, including lights, switches, and climate devices, through natural language commands.
      -