import { z } from "zod"; declare const DeviceConfigSchema: unknown; type DeviceConfig = z.infer; declare const MikrotikConfigSchema: unknown; type MikrotikConfig = z.infer; declare function loadConfig(argv?: string[]): MikrotikConfig; import { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; interface ToolContext { /** Correlates this invocation with its result and saved activity record. */ callId?: string; /** Informational progress message. */ info: (message: string) => void; /** Error / failure message. */ error: (message: string) => void; /** * Name of the device this call targets, when the client selected one. * `undefined` means "use the configured default device". */ device?: string; /** * Which transport actually carried the last device command of this call. * * Recorded here rather than in a module-level global because tool calls run * concurrently — a shared "last transport used" would be overwritten by * whichever device answered most recently. One context per call makes this * safe for free. * * A tool that issues several commands reports the LAST one; that is exact for * the single-command majority and representative otherwise. */ transport?: DeviceTransport; /** * Why REST fell back to SSH on the last command, when it did. Present only * for a device with `api: true` that could not use REST — the reason is the * whole diagnostic value, since a silent fallback otherwise looks like REST * simply never being enabled. */ restFallback?: string; /** * Risk preset of the tool that owns this call (set by the registry). The * connector uses it to keep READ tools out of an open Safe Mode shell. * Unset for internal callers (samplers, dashboard routes). */ risk?: "READ" | "WRITE" | "WRITE_IDEMPOTENT" | "DESTRUCTIVE" | "DANGEROUS"; /** * The tools bound to the MCP server this call arrived on (set by the * registry). The tool gateway uses it to run, describe and point at other * tools without a second code path. Unset for internal callers. */ tools?: ToolAccess; /** Set by the registry when this call returned another tool's finished result. */ delegated?: boolean; /** Set by the registry when the handler opted out of the reachability hint line. */ noHint?: boolean; } /** Access to the other tools of the same MCP server, for the tool gateway. */ interface ToolAccess { /** * Run a tool through the SAME pipeline as a direct `tools/call`: device and * `reason` handling, access policy, guards, audit record. `undefined` when * the tool is not available on this server (unknown, read-only mode, * filtered out). */ run(name: string, args: Record): Promise | undefined; /** The Zod shape a direct call is validated against (with `device` / `reason`). */ shape(name: string): Record | undefined; /** The JSON Schema exactly as `tools/list` publishes it for this tool. */ schema(name: string): Record | undefined; /** * True when a hint may tell the client to call the tool by name. In `core` * surface mode that is every listed tool. In `full` mode only the pinned * core set: the rest is listed too, but a host with a large catalog may not * have loaded it, so hints must give an `invoke_tool` call for those. */ direct(name: string): boolean; } /** How a device command was actually carried. */ type DeviceTransport = "ssh" | "rest" | "mac-telnet"; type SendLog = (level: "info" | "error", message: string) => void; import { ClientChannel, SFTPWrapper } from "ssh2"; interface EndpointOptions { /** Evaluated at connect time, not at client construction. */ hosts?: () => string[]; onAttempt?: (host: string, error?: string) => void; onConnected?: (host: string) => () => void; } interface SSHClientOptions extends EndpointOptions { host: string; username: string; password?: string; port?: number; keyFilename?: string; privateKey?: string; /** Passphrase for an encrypted private key. */ keyPassphrase?: string; /** Sign in with an SSH agent: `true` uses `SSH_AUTH_SOCK`, a string is the socket. */ agent?: boolean | string; /** The pinned SHA-256 fingerprint of the host key (`SHA256:…`). */ hostKeySha256?: string; timeoutMs?: number; /** * Optional SSH jump host (bastion / ProxyJump). When set, `connect()` reaches * `host:port` THROUGH this hop: it opens an SSH session to the hop, asks it to * `forwardOut` a TCP channel to the target, then runs the real SSH session * over that channel. So the target never needs a port exposed to the network — * only the bastion is reachable. The hop is itself an SSH endpoint and may * carry its own `jump` for a multi-hop chain (A → B → target). */ jump?: SSHClientOptions; /** Interval (ms) for SSH keepalive packets. 0 disables (default). */ keepAliveInterval?: number; /** Max consecutive keepalive failures before disconnect. Default: 3. */ keepAliveCountMax?: number; } /** Options for one command. `onData` and `signal` serve a live terminal. */ interface RunOptions { /** Stop the command after this long and return what it printed. */ maxMs?: number; /** Receives stdout as it arrives. The full output is still returned. */ onData?: (text: string) => void; /** Aborting stops the command and returns what it printed so far. */ signal?: AbortSignal; } declare class MikroTikSSHClient { private client; /** * Open bastion connections, outermost-first, kept alive for the lifetime of * the session (the target's transport rides a channel on the last one). Closed * in reverse on `disconnect()`. */ private bastions; private releases; private readonly opts; /** Human-readable reason the last `connect()` failed, if it did. */ lastError?: string; connectedHost?: string; get isConnected(): boolean; constructor(opts: SSHClientOptions); /** * Establish the SSH connection — directly, or through one or more jump hosts * when `opts.jump` is set. Resolves `true` on success, `false` on failure * (with the reason on `lastError`). */ connect(): Promise; /** Retry addresses only during connection setup, never after dispatching a command. */ private connectEndpoint; /** * Open one ssh2 connection. When `sock` is given the connection rides that * stream (a forwarded channel from a jump host) instead of dialling the * network directly. Resolves the ready `Client`; rejects with a clear reason. */ private openClient; /** * Ask a connected jump host to open a TCP channel to `host:port` and resolve * the resulting stream (used as the next hop's transport `sock`). * * A RouterOS bastion with SSH TCP forwarding disabled (the default) often * NEVER answers the channel-open request instead of rejecting it cleanly, so * without a timeout this would hang the whole connection (the dashboard sits * forever at "connecting…"). The `timeoutMs` guard turns that silent stall * into a fast, actionable error; an explicit rejection gets the same hint. */ private forwardOut; /** Run a single command on a fresh SSH channel and return its decoded output. */ run(command: string, opts?: RunOptions): Promise; /** * Upload a file's bytes to the device over SFTP — the file-transfer subsystem * RouterOS exposes on its SSH server. `remotePath` is relative to the SFTP * default directory (the flash root), so `config.rsc` lands at the root and * appears in `/file`; a path like `disk1/config.rsc` targets external disk. * Resolves on success; rejects with a clear reason on failure. */ uploadFile(remotePath: string, data: Buffer, limitMs?): Promise; /** * Download a file's bytes from the device over SFTP. `remotePath` is relative * to the SFTP default directory (the flash root). Resolves with the raw file * contents; rejects with a clear reason on failure. */ downloadFile(remotePath: string, limitMs?): Promise; /** * One SFTP transfer that always ends: with its result, when the connection * closes or fails, or after `limitMs`. * * Before this, a transfer waited only for the SFTP callback. A channel that * stalled, or a connection that dropped during the transfer, never called it: * the tool call had no answer and the caller waited until its own host gave up. */ private transfer; /** * Open the SFTP subsystem and keep it open, for callers that list, stream or * rename files (the dashboard Files page). The caller ends it. */ sftp(): Promise; /** Open a persistent interactive shell channel (used by Safe Mode). */ shell(opts?: { term?: string; cols?: number; rows?: number; }): Promise; /** Close the SSH connection (and any jump hosts). Safe to call multiple times. */ disconnect(): void; } /** * Execute a RouterOS command and return its raw text output. * * The target device is taken from `ctx.device` (set by the registry from the * tool call's `device` argument); when unset, the configured default is used. * Safe Mode is tracked per device, so each router has its own session. * * @param command Fully-formed RouterOS CLI command (e.g. `/ip address print`). * @param ctx Per-call context carrying the target device. * @param opts `maxMs` caps the one-shot read for interactive/streaming * commands (ping, bandwidth-test) so they can't hang the tool. */ declare function executeMikrotikCommand(command: string, ctx: ToolContext, opts?: RunOptions): Promise; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { CallToolResult as CallToolResult2, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js"; import { ZodRawShape } from "zod"; /** Links a tool to an MCP App view resource. */ interface UiLink { /** `ui://…` resource URI of the HTML view the host should render. */ resourceUri: string; /** * Where the tool may be invoked from. `"model"` lets the LLM call it; * `"app"` lets the rendered view call it (e.g. polling/refresh helpers). * Defaults to model-visible when omitted. */ visibility?: ("model" | "app")[]; } declare function setConfig(cfg: MikrotikConfig): void; declare function getConfig(): MikrotikConfig; /** Names of every ENABLED configured device, plus which one is the default. */ declare function listDevices(): { names: string[]; default: string; }; /** * Resolve a (possibly undefined) device name to a concrete, existing config key. * Accepts a config key OR a device's free-text label. An omitted name uses the * configured default. * * FAIL-CLOSED: a name that matches no enabled device THROWS. It must never * degrade to the default router — a typo'd or stale device name silently * retargeting a write at whichever device happens to be first is the one bug * class here that can misconfigure the wrong physical device. `getDevice()` * already threw for this, but every caller resolved the name first and then * handed the laundered key to `getDevice`, so that guard could never fire. * * Matching is EXACT (key first, then label) — never fuzzy/substring — so a name * like "Ali Home" can never collapse onto a different device such as "home". */ declare function resolveDeviceName(name?: string): string; /** One row of the human-facing device directory shown in the `device` selector. */ interface DeviceDirectoryEntry { key: string; label?: string; /** Where it connects: `host:port`, or `MAC ` for a MAC-Telnet device. */ target: string; isDefault: boolean; } /** * Return the connection config for a device by key or label (or the default when * `name` is undefined). Throws if an explicit name matches neither a key nor a * label, or if the device is disabled. */ declare function getDevice(name?: string): DeviceConfig; /** Which wireless stack a device actually answers on. */ type WirelessStack = "wifi" | "wireless" | "capsman-legacy" | "none"; /** * What a tool needs from the device. Every field is optional and ANDed; an * absent `requires` means universally available, which is true of the large * majority of the catalog. */ interface ToolRequires { /** Inclusive lower bound, e.g. `"7.13"`. */ minVersion?: string; /** Exclusive upper bound, for menus removed in a later release. */ maxVersion?: string; /** Every named package must be installed AND enabled. */ packages?: string[]; /** The device must answer on one of these wireless stacks. */ wirelessStack?: WirelessStack | WirelessStack[]; /** Board-name test, e.g. `/^CRS3/` for a switch-chip-only menu. */ board?: RegExp; /** A device-mode permission that must be granted. */ deviceMode?: "container" | "scheduler" | "fetch"; /** The device must be a RouterBOARD (excludes CHR and x86). */ routerBoard?: boolean; } /** Options threaded into every tool registration. */ interface RegisterOptions { /** * `full` (default) lists every tool. `core` lists only {@link PINNED_TOOLS} * plus `coreTools`; every other tool still runs, by its own name or through * `invoke_tool`. Use `core` for hosts that load only part of a large list. */ surface?: "full" | "core"; /** Extra tool names to list in `core` surface mode. */ coreTools?: string[]; sendLog?: SendLog; /** Configured device KEYS; when more than one, a `device` selector is injected. */ deviceNames?: string[]; /** * Extra accepted values for the `device` selector — a device's free-text * label (`description`, e.g. "Ali Home") so the AI can target it by the * friendly name as well as its config key. Resolved back to the key by * {@link resolveDeviceName}. Does NOT affect the single-vs-multi decision. */ deviceAliases?: string[]; /** * Human-facing directory of every device (key → label → target), used to make * the `device` selector's description unambiguous so the model can tell * similarly-named routers apart and never substitute one for another. */ deviceDirectory?: DeviceDirectoryEntry[]; /** * Emit MCP App view metadata (`_meta.ui`) on tools. Default true. Set false for * hosts whose tool discovery hides/deprioritises tools that carry App/ * `openai/outputTemplate` metadata — without it, every `list_*`/`get_*` read * tool gains the auto-records view and some clients then surface only the * (metadata-free) write tools. Disabling makes reads plain, surfacing tools. */ appViews?: boolean; /** * Read-only mode: register only tools annotated `readOnlyHint`. Used to * withhold every write/destructive tool from a publicly-exposed surface (e.g. * a ChatGPT Apps connector) until authentication is in place. */ readOnly?: boolean; } /** * A handler may return plain text (the common case — wrapped as the model-facing * result) or a structured payload. `structuredContent` is the data an MCP App * view renders; `text` remains the fallback shown to the model and to text-only * hosts, so UI is always additive. */ interface ToolResult { text: string; structuredContent?: Record; /** Explicit outcome for evidence readers whose successful output can quote historical errors. */ isError?: boolean; /** * A finished result of ANOTHER tool's direct-call pipeline, returned as is. * Only the tool gateway sets it: that call was already guarded, recorded and * given its own Tool call ID, so this call must not record or stamp it again. */ passthrough?: CallToolResult2; /** * `false` = do not append the "not in your tool list" hint line. For a * result whose text already says how to run every tool it names. */ hint?: false; } type HandlerOutput = string | ToolResult; interface ToolDef { /** Stable tool id exposed to MCP clients. */ name: string; /** Short human-readable display name shown in compact tool lists. */ title: string; /** Full description — this is the prompt the model reads to decide when to call. */ description: string; /** One of the risk presets above. */ annotations: ToolAnnotations; /** Zod raw shape describing the tool's parameters. */ inputSchema?: Shape; /** * Optional MCP App view: links this tool to a `ui://…` HTML resource the host * renders inline. When set, the tool should return `structuredContent` for the * view (it still returns `text` for non-UI hosts). */ ui?: UiLink; /** * When true, skip the multi-device `device` selector injection for this tool. * Use for server-introspection tools that never contact a RouterOS device. */ noDevice?: boolean; /** * When true, a write by this tool changes the MCP host only (its memory * database, for one), never the router. The registry then does not read the * router's change log around the call: there is nothing there to confirm, * and the read costs an SSH round trip. */ hostOnly?: boolean; /** * What this tool needs from the device — a RouterOS version floor, a package, * a wireless stack, a board, a device-mode permission. * * Omit it unless the tool genuinely cannot run everywhere; the large majority * of the catalog is universal, and a spurious requirement hides a working tool. * Declaring it does two things: the description is annotated when the device is * known to be unsupported, and the call is guarded so an unsupported invocation * returns a clear reason instead of a RouterOS parser error. */ requires?: ToolRequires; /** * True for `invoke_tool` only. The access policy is then evaluated for the * delegated tool (its own risk and device) instead of for the dispatcher, * so a read-only scope can still read through the gateway and a write is * still judged as the write it is. */ dispatcher?: boolean; /** Handler returning the result shown to the model (text, or text + structured data). */ handler: (args: any, ctx: ToolContext) => Promise | HandlerOutput; } interface RegisterableTool { name: string; title: string; annotations: ToolAnnotations; inputSchema?: ZodRawShape; description: string; /** Server-only tools do not participate in device access checks. */ noDevice?: boolean; /** Present when the tool renders an MCP App view. */ ui?: UiLink; /** Device requirements, if the tool declared any. */ requires?: ToolRequires; /** True for `invoke_tool`: guards apply to the delegated tool. */ dispatcher?: boolean; /** * The raw handler (pre-`device`-injection, pre-validation). Exposed so the * tool-gateway dispatcher (`invoke_tool`) can run any tool by name through its * own Zod schema + handler — the precise alternative to the raw-CLI escape * hatch. Normal registration never touches this; it goes through `register`. */ handler: (args: any, ctx: ToolContext) => Promise | HandlerOutput; register: (server: McpServer, opts?: RegisterOptions) => void; } declare function defineTool(def: ToolDef): RegisterableTool; type ToolModule = RegisterableTool[]; /** Register every tool from every module, returning the total count. */ declare function registerTools(server: McpServer, modules: ToolModule[], opts?: RegisterOptions): number; import { McpServer as McpServer2 } from "@modelcontextprotocol/sdk/server/mcp.js"; interface CreatedServer { server: McpServer2; toolCount: number; promptCount: number; /** Number of MCP App `ui://` views registered as resources. */ uiViewCount: number; /** True when only read-only tools were registered. */ readOnly: boolean; } declare function createServer(opts?: { sendLog?: SendLog; }): CreatedServer; /** * Outcome of {@link SafeModeManager.commit}. `ok` is true ONLY when Safe Mode is * confirmed exited (changes persisted) — callers must check it before telling * the user anything was committed, so a failed commit can never masquerade as a * success that then silently reverts. */ interface CommitResult { ok: boolean; message: string; } declare class SafeModeManager { private readonly deviceName; private ssh; private channel; private active; /** * Set when the persistent shell drops WHILE Safe Mode was active — i.e. the * session died before an explicit commit, with an unverified outcome. * Distinguishes "never enabled / cleanly closed" from * "died with your changes still pending" so commit/status can report the revert * instead of a reassuring false success. Cleared on the next enable(). */ private droppedUnexpectedly; /** Why the last session was closed automatically; shown by status() only. */ private lastClosure; /** Distinguish each mode probe from delayed output of an earlier round trip. */ private probeSequence; /** Serializes channel access so concurrent tool calls don't interleave I/O. */ private queue; private commandTimeoutMs; private idleTimeoutMs; /** Applies to subsequent commands, never extends an already-running command. */ setTimeouts(commandTimeoutMs: number, idleTimeoutMs: number): string; /** The device this Safe Mode session belongs to (a configured device name). */ constructor(deviceName: string); get isActive(): boolean; /** * True after the shell dropped by itself, until that is reported ONCE (by the * next write, commit, rollback or enable). It never blocks reads and never * needs a restart to clear. */ get requiresRecovery(): boolean; /** Close the session after a failure and remember why, for status(). */ private closeAfterFailure; /** Run `fn` exclusively — the persistent channel must not be shared mid-command. */ private lock; /** Open a persistent SSH shell and activate MikroTik Safe Mode. */ enable(): Promise; /** * Execute a command through the safe-mode persistent shell session. * * If the shell never returns a prompt within the timeout, the interactive * Safe-Mode session is wedged — this throws immediately so the caller aborts * instead of issuing more commands that would each also burn the full timeout * (the cumulative effect of which is a multi-minute "hang" to the MCP client). */ execute(command: string): Promise; /** * Send Ctrl+X again to exit Safe Mode and persist all changes. Returns a * structured result so callers NEVER report "committed" on a failed commit — * `ok` is true only when Safe Mode is confirmed exited (changes saved). */ commit(): Promise; /** Close the session to trigger MikroTik's automatic safe-mode revert. */ rollback(): Promise; status(): string; /** * Fired by the persistent shell's `close`/`error` events. Arrow-bound so the * same reference is used for add/removeListener. Acts ONLY when we still think * Safe Mode is active — a drop then means the session died with staged changes * pending and an unverified rollback, so we flag it and tear the zombie * handles down. A close during our own cleanup() (which clears `active` first) * is a no-op: it is an intentional teardown, not a lost session. */ private readonly handleUnexpectedDrop; /** * Read from the channel until `isDone(cleaned)` is satisfied or the shell goes * SILENT. Defaults to "any RouterOS prompt appeared". Mode transitions pass a * stricter predicate so they wait for the prompt that reflects the NEW state * (safe-mode marker present/absent), not merely the first prompt-shaped line. * * The timeout is an IDLE timeout, not a total budget: every data chunk resets * it, so a legitimately slow-but-streaming command (`/terse` on a large * config can emit for tens of seconds) never trips it — only a genuine wedge, * where no byte has arrived for `idleMs`, does. A separate hard cap (`hardCapMs`) * bounds the pathological "dribbles a byte forever" case so the read can't hang * indefinitely. Either expiry resolves with `timedOut: true` so callers can tell * "the prompt appeared" from "the shell stopped answering" — the latter means the * interactive Safe-Mode session is wedged and must abort rather than letting every * subsequent command burn its own timeout. */ private readUntilPrompt; /** * Determine the shell's CURRENT mode definitively by round-tripping a sentinel * command (`:put ""`) and classifying the prompt that follows ITS * output. A real command — not a bare Enter — forces RouterOS to fully process * any pending Ctrl+X and render a prompt that reflects the true mode, so we * never settle on a transient ``→normal redraw and report a commit that * did not actually take. Returns `safe`, `released`, or `unknown` (no prompt). */ private probeMode; private extractOutput; private cleanup; } declare function getSafeModeManager(deviceName: string): SafeModeManager; declare const allToolModules: ToolModule[]; declare const VERSION: string; declare const SERVER_NAME = "mikrotik-mcp"; export { DeviceConfig, DeviceConfigSchema, MikroTikSSHClient, MikrotikConfig, MikrotikConfigSchema, RegisterableTool, SERVER_NAME, SafeModeManager, ToolContext, ToolModule, VERSION, allToolModules, createServer, defineTool, executeMikrotikCommand, getConfig, getDevice, getSafeModeManager, listDevices, loadConfig, registerTools, resolveDeviceName, setConfig };