Skip to main content
Glama
network-terminal-mcp

network-terminal-mcp

by evgenyzh

network-terminal-mcp

PyPI CI License: MIT

Локальный MCP-сервер для постоянных интерактивных терминалов. Модель открывает сессию привычной командой ssh, telnet или serial, затем пишет в живой поток команды, ?-подсказки, pager keys и вложенные ssh, а читает только новый вывод.

Статус: 0.5.0 — command-only API, настоящий OpenSSH/Telnet в POSIX PTY, локальный serial, конкретные ошибки, ограниченная по времени запись, метрики простоя и секреты без обязательного pass.

В 0.3.0 ответы MCP стали компактнее; клиенты, использующие удалённые поля ответов 0.2.1, необходимо адаптировать. Полные данные сессии — в session_status.

SSH/Telnet автоматически отвечают на запрос позиции курсора (DSR). Enter отправляет \r; при необходимости точного \n используйте enter=false. Подробности и ограничения — в руководстве.

Открытие сессии

Единственный аргумент:

{"command": "ssh -J operator@bastion.example.net operator@192.0.2.10"}
{"command": "telnet 192.0.2.30 23"}
{"command": "serial /dev/ttyUSB0 115200"}

SSH использует локальные ~/.ssh/config, agent, ключи, ProxyJump, ProxyCommand и любые опции OpenSSH. Аргументы передаются клиенту без фильтрации; shell не используется. ready означает, что процесс запущен, а не что логин завершён: banner и prompt читаются через terminal_read.

Related MCP server: shell-session-mcp

Основной цикл

open_session("ssh operator@192.0.2.10")
terminal_read(session_id)                    # banner / login prompt
terminal_write(session_id, "show version")
terminal_read(session_id)
terminal_write(session_id, "show interface brief")
terminal_read(session_id)
close_session(session_id)
  • terminal_read возвращает только новый вывод и не повторяет историю.

  • При truncated=true продолжайте с next_output_offset через read_output.

  • terminal_write(..., enter=false) отправляет одиночные клавиши и control bytes.

  • Пароли и passphrase вводятся только через terminal_write_secret с одним источником: value, env или file.

Нестабильные соединения

ready означает, что жив локальный процесс клиента, а не что удалённая сторона отвечает. Для SSH добавляйте контроль связи:

ssh -o ConnectTimeout=10 -o ServerAliveInterval=15 -o ServerAliveCountMax=3 operator@192.0.2.10

После сна ноутбука, смены Wi-Fi/VPN или долгой паузы закройте и переоткройте подозрительные сессии: запись в полуразрушенное TCP-соединение может выглядеть успешной. terminal_read ограничен timeout, terminal_write — 10 секундами; session_status показывает last_output_at и idle_seconds. Подробнее: эксплуатация.

Для одноразового ssh host 'command' обычный shell остаётся проще. MCP нужен для живого терминала, pager, нескольких команд с сохранением состояния, password prompts, вложенных переходов и Serial.

Установка

uv tool install network-terminal-mcp
network-terminal-mcp check

Обновление:

uv tool upgrade network-terminal-mcp

Проверка показывает версию, наличие ssh/telnet, pyserial и доступность audit-каталога. Обязательных конфигурационных файлов нет.

OpenCode V2

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "servers": {
      "network-terminal": {
        "type": "local",
        "command": ["/home/USER/.local/bin/network-terminal-mcp"],
        "codemode": false,
        "disabled": false
      }
    }
  }
}

codemode: false оставляет все инструменты, включая open_session, в native tool list. Если ~/.local/bin уже в PATH, достаточно ["network-terminal-mcp"].

Документация

  • Текущая документация — архитектура, эксплуатация, безопасность, тесты и результаты проверок.

  • Инструкция для модели — MCP instructions и ресурс network-terminal://usage.

  • Backlog — только необязательные направления после реальной эксплуатации.

  • История — завершённые планы и реализация 0.1.x, не руководство.

Разработка

Требуются Python 3.12+, uv и POSIX/Linux.

uv sync
uv run ruff check .
uv run mypy src
uv run pytest

Не добавляйте в репозиторий реальные адреса, hostnames, usernames, fingerprints, секреты или production transcripts.

Available Tools

7 tools
close_sessionB

Close the terminal and child process, retaining its final status.

Inputs: session_id (required). Returns: error, state, exit_code

open_sessionA

Open a persistent terminal: ssh, telnet, or serial DEVICE [BAUDRATE].

No shell is involved. SSH uses the local client, config, agent and keys.

Inputs: command (required). Returns: error, state, warnings, session_id

read_outputC

Read buffered output from the default or an independent named cursor.

Inputs: session_id (required), limit, offset, reader_id. Returns: offset, output, truncated, next_offset, +1 more

session_statusC

Return state, command, timestamps, idle time, warnings, and exit status.

Inputs: session_id (required). Returns: Serializable session metadata returned by MCP tools.

terminal_readB

Read only new output until quiet or timeout; no prompt shape required.

If truncated, continue with read_output or next_output_offset.

Inputs: session_id (required), timeout. Returns: output, truncated, next_output_offset

terminal_writeA

Write input, appending a line terminator unless enter=false.

Input is audited after known-secret redaction; use terminal_write_secret for passwords. Timeout fails the session and may mean a partial write.

Inputs: data (required), session_id (required), enter. Returns: ok, state

terminal_write_secretA

Send a secret from exactly one source: value, env, or file.

Prefer env or file; plaintext value remains in client history. The server redacts known secrets and never returns or audits the secret value.

Inputs: session_id (required), env, file, value. Returns: ok, state

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    B3.2/5.0

    Scored across 7 tools

    Disambiguation4/5

    Each tool maps to a distinct operation (open, close, status, write, secret write, read), but terminal_read and read_output both read output and only their descriptions distinguish incremental-vs-buffered semantics. The terminal_read description explicitly redirects to read_output for truncation, which mitigates most of the confusion.

    Naming Consistency3/5

    Most names follow verb_noun, but the set mixes a 'terminal_' prefix (terminal_write, terminal_read, terminal_write_secret) with unprefixed session verbs (open_session, close_session) and an unprefixed read (read_output). session_status breaks the verb_noun pattern entirely, though all names remain readable and domain-specific.

    Tool Count5/5

    Seven tools is well-scoped for persistent terminal session management: lifecycle, I/O, secret-safe input, and status each earn a slot with no filler.

    Completeness4/5

    The session lifecycle (open, write, read, status, close) is fully covered, including a thoughtful secret-handling path. Gaps are minor: no explicit signal/interrupt or resize operation, and no way to enumerate multiple concurrent sessions even though named read cursors are supported.

    Maintenance

    ActivityMaintained
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Terminal-first SSH access for MCP clients and AI agents, enabling interactive remote sessions, file uploads, and stateful workflows.
      18 npm
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides persistent interactive shell sessions via pseudo-terminals for MCP agents, enabling bidirectional communication, incremental reads, and stateful command execution across steps.
      9 npm
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to have persistent, fully interactive SSH sessions into remote hosts, behaving like a local terminal.
      15 npm
      2
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI agents to interact with real terminal sessions across local and remote hosts, driving multi-turn interactive programs like TUIs, REPLs, and SSH prompts through MCP.
      68
      MIT